private async Task <AuthenticationResult> GenerateAuthenticationResultForUser(IdentityUser user) { var jwtClaims = new List <Claim>() { new Claim(JwtRegisteredClaimNames.Sub, user.Email), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Email, user.Email), new Claim("id", user.Id) }; var userClaims = await userManager.GetClaimsAsync(user); // Merge jwtClaims and userClaims to add them all in token jwtClaims.AddRange(userClaims); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(jwtClaims), Expires = DateTime.UtcNow.Add(jwtOptions.TokenLifeTime), SigningCredentials = new SigningCredentials(key: new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtOptions.Secret)), algorithm: SecurityAlgorithms.HmacSha256), Audience = "Barratson", Issuer = "ChapsasAPI", }; var handler = new JwtSecurityTokenHandler(); SecurityToken token = handler.CreateToken(tokenDescriptor); var refreshToken = new RefreshToken() { JwtId = token.Id, UserId = user.Id, CreationDate = DateTime.UtcNow, ExpirationDate = DateTime.UtcNow.AddMonths(6) }; await context.RefreshTokens.AddAsync(refreshToken); // !!!! // Or you can use JwtSecurityToken with all claims and SignInCredentials in it and pass it in below method string jwt = handler.WriteToken(token); return(AuthenticationResult.SuccessResult(jwt, refreshToken.Token)); }
private async Task <AuthenticationResult> GenerateAuthenticationResultAsync(AppUser user) { // return UserClaims var claims = await GenerateJwtClaimsAsync(user); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.UtcNow.Add(jwtOptions.TokenLifeTime), SigningCredentials = new SigningCredentials(key: new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtOptions.Secret)), algorithm: SecurityAlgorithms.HmacSha256), Issuer = "Benzeine", IssuedAt = DateTime.UtcNow }; var handler = new JwtSecurityTokenHandler(); SecurityToken token = handler.CreateToken(tokenDescriptor); string jwt = handler.WriteToken(token); return(AuthenticationResult.SuccessResult(jwt, claims.ToDictionary())); #region Local Method // Local method for generating JWTClaims async Task <IEnumerable <Claim> > GenerateJwtClaimsAsync(AppUser _user) { var userRoles = await userManager.GetRolesAsync(_user); var role = userRoles.FirstOrDefault(); var jwtClaims = new List <Claim> { new Claim("Email", _user.Email), new Claim("UserID", _user.Id.ToString()), new Claim("Role", role) }; return(jwtClaims); } #endregion }