Added Main
This commit is contained in:
44
noteApi/Service/TokenService.cs
Normal file
44
noteApi/Service/TokenService.cs
Normal file
@@ -0,0 +1,44 @@
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using noteApi.Interfaces;
|
||||
using noteApi.Models;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
|
||||
namespace noteApi.Service
|
||||
{
|
||||
public class TokenService : ITokenService
|
||||
{
|
||||
private readonly IConfiguration _config;
|
||||
private readonly SymmetricSecurityKey _key;
|
||||
public TokenService(IConfiguration config)
|
||||
{
|
||||
_config = config;
|
||||
_key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["JWT:SigningKey"]));
|
||||
}
|
||||
public string CreateToken(AppUser user)
|
||||
{
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new Claim(JwtRegisteredClaimNames.Email, user.Email),
|
||||
new Claim(JwtRegisteredClaimNames.GivenName, user.UserName)
|
||||
};
|
||||
|
||||
var creds = new SigningCredentials(_key, SecurityAlgorithms.HmacSha256Signature);
|
||||
var tokenDescriptor = new SecurityTokenDescriptor
|
||||
{
|
||||
Subject = new ClaimsIdentity(claims),
|
||||
Expires = DateTime.Now.AddDays(14),
|
||||
SigningCredentials = creds,
|
||||
Issuer = _config["JWT:Issuer"],
|
||||
Audience = _config["JWT:Audience"]
|
||||
};
|
||||
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
|
||||
var token = tokenHandler.CreateToken(tokenDescriptor);
|
||||
|
||||
return tokenHandler.WriteToken(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user