Skip to content

Instantly share code, notes, and snippets.

@kavin-1103
Last active July 26, 2023 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kavin-1103/474a12875bcae54a6c8b4e6f1baf6b01 to your computer and use it in GitHub Desktop.
Save kavin-1103/474a12875bcae54a6c8b4e6f1baf6b01 to your computer and use it in GitHub Desktop.
public async Task<string> CreateJwtToken(ApplicationUser user)
{
//Create Claims
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.NameId , user.Id.ToString()),
new Claim(JwtRegisteredClaimNames.UniqueName ,user.UserName ),
new Claim(ClaimTypes.Email, user.Email)
};
var roles = await _userManager.GetRolesAsync(user);
claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));
claims.AddRange(roles.Select(role => new Claim("Roles", role)));
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: _configuration["Jwt:Issuer"],
audience: _configuration["Jwt:Audience"],
claims: claims,
expires: DateTime.Now.AddDays(7),
signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment