/// <summary> /// Формирует AccessToken с указанными Claims. /// </summary> public string GenerateAccessToken(IEnumerable <Claim> claims) { var token = new JwtSecurityToken( issuer: _authSettings.Issuer, audience: _authSettings.Audience, claims: claims, expires: DateTime.UtcNow.AddMinutes(_authSettings.LifetimeMinutes), signingCredentials: new SigningCredentials(_authSettings.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256)); var encodedToken = new JwtSecurityTokenHandler().WriteToken(token); return(encodedToken); }
private ClaimsPrincipal GetPrincipalFromExpiredToken(string token) { var tokenValidationParameters = new TokenValidationParameters { ValidateAudience = false, //you might want to validate the audience and issuer depending on your use case ValidateIssuer = false, ValidateIssuerSigningKey = true, IssuerSigningKey = _authSettings.GetSymmetricSecurityKey(), ValidateLifetime = false //here we are saying that we don't care about the token's expiration date }; var tokenHandler = new JwtSecurityTokenHandler(); SecurityToken securityToken; var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out securityToken); var jwtSecurityToken = securityToken as JwtSecurityToken; if (jwtSecurityToken == null || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase)) { throw new SecurityTokenException("Invalid token"); } return(principal); }