public ClaimsPrincipal GetPrincipalFromExpiredToken(string token) { TokenValidationParameters tokenValidationParameters = new TokenValidationParameters { ValidateAudience = false, ValidateIssuer = false, ValidateIssuerSigningKey = true, IssuerSigningKey = AccessTokenParameters.GetSymmetricSecurityKey(), ValidateLifetime = false }; SecurityToken securityToken; JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); ClaimsPrincipal principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out securityToken); JwtSecurityToken jwtSecurityToken = securityToken as JwtSecurityToken; if (jwtSecurityToken == null || !jwtSecurityToken.Header.Alg.Equals( SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase)) { throw new SecurityTokenException("Invalid token"); } return(principal); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer( options => { options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = AccessTokenParameters.ISSUER, ValidateAudience = true, ValidAudience = AccessTokenParameters.AUDIENCE, ValidateLifetime = true, IssuerSigningKey = AccessTokenParameters.GetSymmetricSecurityKey(), ValidateIssuerSigningKey = true }; }); services. AddControllers(). AddNewtonsoftJson(options => { options.SerializerSettings.Converters.Add( new Newtonsoft.Json.Converters.StringEnumConverter()); }); BusinessConfiguration.ConfigureServices(services, Configuration); // In production, the React files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/build"; }); }
public string GenerateAccessToken(IEnumerable <Claim> claims) { SymmetricSecurityKey secretKey = AccessTokenParameters.GetSymmetricSecurityKey(); SigningCredentials signingCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); JwtSecurityToken tokenOptions = new JwtSecurityToken( issuer: AccessTokenParameters.ISSUER, audience: AccessTokenParameters.AUDIENCE, claims: claims, expires: DateTime.Now.AddMinutes(AccessTokenParameters.LIFETIME), signingCredentials: signingCredentials ); string tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOptions); return(tokenString); }