private async Task <string> GetUserTokenAsync(AppUser user, TokenScheme scheme = TokenScheme.Default) { async Task <ClaimsPrincipal> GetPrincipalAsync(string loginProvider = null) { if (scheme == TokenScheme.Default) { return(await _signInManager.CreateUserPrincipalAsync(user)); } var authType = scheme == TokenScheme.TwoFactor ? JwtIssuerOptions.TwoFactorScheme : IdentityConstants.TwoFactorRememberMeScheme; var identity = new ClaimsIdentity(authType); identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName)); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id)); if (scheme == TokenScheme.TwoFactorRememberMe && _userManager.SupportsUserSecurityStamp) { var stamp = await _userManager.GetSecurityStampAsync(user); identity.AddClaim(new Claim(_signInManager.Options.ClaimsIdentity.SecurityStampClaimType, stamp)); } return(new ClaimsPrincipal(identity)); } var principal = await GetPrincipalAsync(); return(await Tokens.GenerateJwtAsync(principal, _jwtFactory, scheme)); }
public async Task <string> CreateTokenAsync(ClaimsPrincipal principal, TokenScheme scheme = TokenScheme.Default) { var claims = new List <Claim>(principal.Claims) { new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()), new Claim(JwtRegisteredClaimNames.Iat, new DateTimeOffset(_jwtOptions.IssuedAt).ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64) }; SigningCredentials credentials; switch (scheme) { case TokenScheme.TwoFactor: // Create a JWT that can be used only for two-factor authentication //claims.Add(new Claim(ClaimTypes.AuthenticationMethod, IdentityConstants.TwoFactorUserIdScheme)); claims.Add(new Claim(ClaimTypes.AuthenticationMethod, JwtIssuerOptions.TwoFactorScheme)); credentials = _jwtOptions.JwtTwoFactorSigningCredentials; break; case TokenScheme.TwoFactorRememberMe: claims.Add(new Claim(ClaimTypes.AuthenticationMethod, IdentityConstants.TwoFactorRememberMeScheme)); credentials = _jwtOptions.JwtTwoFactorSigningCredentials; break; default: credentials = _jwtOptions.JwtSigningCredentials; break; } var jwt = new JwtSecurityToken( issuer: _jwtOptions.Issuer, audience: _jwtOptions.Audience, claims: claims, notBefore: _jwtOptions.NotBefore, expires: _jwtOptions.Expiration, signingCredentials: credentials ); return(new JwtSecurityTokenHandler().WriteToken(jwt)); }
public static async Task <string> GenerateJwtAsync(ClaimsPrincipal principal, IJwtFactory jwtFactory, TokenScheme scheme = TokenScheme.Default, JsonSerializerSettings serializerSettings = null) { var response = new { id = principal.FindFirstValue(ClaimTypes.NameIdentifier), auth_token = await jwtFactory.CreateTokenAsync(principal, scheme), expires_in = (int)jwtFactory.GetExpiration() }; return(JsonConvert.SerializeObject(response, serializerSettings ?? new JsonSerializerSettings { Formatting = Formatting.Indented })); }