Snippet for Anne Staff
unknown
csharp
3 years ago
1.1 kB
2
Indexable
public class JwtGenerator : IGenerator { private const string TOKEN_KEY = "TokenKey"; private const int DAYS_NUMBER = 7; private readonly SymmetricSecurityKey key; public Generator(IConfiguration config) { this.key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config[TOKEN_KEY])); } public string CreateToken(AppUser user) { var claims = new List<Claim> { new Claim(RegisteredClaimNames.NameId, user.UserName) }; var credentials = new SigningCredentials(this.key, SecurityAlgorithms.HmacSha512Signature); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.Now.AddDays(DAYS_NUMBER), SigningCredentials = credentials }; var tokenHandler = new SecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); }
Editor is loading...