Skip to content

Instantly share code, notes, and snippets.

@juanvan
Created July 20, 2020 17:51
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 juanvan/0b3b0f6345a4733a8d6249ef2fcbf9d9 to your computer and use it in GitHub Desktop.
Save juanvan/0b3b0f6345a4733a8d6249ef2fcbf9d9 to your computer and use it in GitHub Desktop.
private async Task<dynamic> GenerateToken(string username)
{
var user = await _userManager.FindByEmailAsync(username);
var roles = from ur in _context.UserRoles
join r in _context.Roles on ur.RoleId equals r.Id
where ur.UserId == user.Id
select new { ur.UserId, ur.RoleId, r.Name };
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, username),
new Claim(ClaimTypes.NameIdentifier, user.Id),
new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()),
new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddMinutes(1)).ToUnixTimeSeconds().ToString())
};
foreach (var role in roles)
{
claims.Add(new Claim(ClaimTypes.Role, role.Name));
}
//Pull Key from Config File
string configKey = _configuration.GetValue<string>("Secrets:SecurityKey");
var token = new JwtSecurityToken(
new JwtHeader(
new SigningCredentials(
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configKey)),
SecurityAlgorithms.HmacSha256)),
new JwtPayload(claims));
var output = new
{
Access_Token = new JwtSecurityTokenHandler().WriteToken(token),
UserName = username
};
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment