2022-05-19 13:50:10 -07:00
|
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
|
|
using System.Security.Claims;
|
|
|
|
using System.Text;
|
|
|
|
using Core.Entities.Identity;
|
|
|
|
using Core.Interfaces;
|
|
|
|
using Microsoft.Extensions.Configuration;
|
|
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
|
|
|
|
namespace Infrastructure.Services
|
|
|
|
{
|
|
|
|
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["Token:Key"]));
|
|
|
|
}
|
|
|
|
|
|
|
|
public string CreateToken(AppUser user)
|
|
|
|
{
|
|
|
|
var claims = new List<Claim>
|
|
|
|
{
|
2022-05-19 15:47:12 -07:00
|
|
|
new Claim(JwtRegisteredClaimNames.Email, user.Email),
|
|
|
|
new Claim(JwtRegisteredClaimNames.GivenName, user.DisplayName)
|
2022-05-19 13:50:10 -07:00
|
|
|
};
|
|
|
|
|
|
|
|
var creds = new SigningCredentials(_key, SecurityAlgorithms.HmacSha512Signature);
|
|
|
|
var tokenDescriptor = new SecurityTokenDescriptor
|
|
|
|
{
|
|
|
|
Subject = new ClaimsIdentity(claims),
|
|
|
|
Expires = DateTime.Now.AddDays(7),
|
|
|
|
SigningCredentials = creds,
|
|
|
|
Issuer = _config["Token:Issuer"]
|
|
|
|
};
|
|
|
|
|
|
|
|
var tokenHandler = new JwtSecurityTokenHandler();
|
|
|
|
var token = tokenHandler.CreateToken(tokenDescriptor);
|
|
|
|
return tokenHandler.WriteToken(token);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|