问题
In order to generate JWT token I am using the following code:
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_consumerConfiguration.SecretKey);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, "ConsumerId")
}),
Expires = DateTime.Now.AddMinutes(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
This is my code in RegisterServices
var appSettingsSection = configuration.GetSection("ConsumerConfiguration");
services.Configure<ConsumerConfiguration>(appSettingsSection);
var appSettings = appSettingsSection.Get<ConsumerConfiguration>();
var key = Encoding.ASCII.GetBytes(appSettings.SecretKey);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddScoped<Microsoft.AspNetCore.Authorization.IAuthorizationHandler, ConsumerAuthorizationHandler>();
I using this as a filter to register the custom authorization handler globally in the application:
var policy = new AuthorizationPolicyBuilder().RequireCustomClaim(ClaimTypes.Name).
AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme).Build();
options.Filters.Add(new AuthorizeFilter(policy));
})
and this is my custom authorization handler
#region constructor
public ConsumerAuthorizationHandler(IOptions<ConsumerConfiguration> consumerConfiguration)
{
_consumerConfiguration = consumerConfiguration.Value;
}
#endregion
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CustomRequireClaim requirement)
{
if (!_consumerConfiguration.EnableAuthorizationFilter)
context.Succeed(requirement);
var hasClaim = context.User.Claims.Any(x => x.Type == requirement.ClaimType);
if (hasClaim)
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
public static class AuthorizationPolicyBuilderExtensions
{
public static AuthorizationPolicyBuilder RequireCustomClaim(this AuthorizationPolicyBuilder builder, string claimType)
{
return builder.AddRequirements(new CustomRequireClaim(claimType));
}
}
The problem is: How can I check if the JWT is expired? The token seems not to expire. What code do I have to add that it will check if the token is expired?
回答1:
The authentication flow handles this for you by default. It happens even before you hit your authorization layers.
来源:https://stackoverflow.com/questions/62289715/need-to-check-of-jwt-token-is-valid-expired-in-asp-net-core