-
-
Save juanvan/0b3b0f6345a4733a8d6249ef2fcbf9d9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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