Reputation: 82361
Currently, for every call that comes to my ASP.NET Core MVC Application, I do the following in the OnValidatePrincipal
event of the cookie:
id_token
out of the cookie via a call to GetTokenValue
.JwtSecurityTokenHandler
's ValidateToken to turn the token into json.ValidTo
property out of the json.It seems a bit excessive to me to do this on each an every call. I am wondering if there is someway I can just store the ValidTo value in the cookie itself. That way I would not have to parse out the json to check for expiration on each call.
Is there a way I can get the id_token
's ValidTo
stored such that a call like this could give me the expiration: GetTokenValue("id_token_valid_to")
?
Upvotes: 5
Views: 19485
Reputation: 895
This is just an idea.
Do you think it is possible for you to set a Claim to the that is the same value of the JWT ExpiryDateTime. In the AttributeClass where you demand the token as a requirement you can have code that will read the Claims from the given Token, seek the claim pertaining to the DateTime Expiry and do a basic DateTime comparison against that?
Upvotes: 0
Reputation: 43890
Check this link: https://www.c-sharpcorner.com/article/jwt-json-web-token-authentication-in-asp-net-core/
But in a couple of words you have to add something like this in your startup file:
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKey = key,
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
ValidateIssuer = false,
ValidAudience =Configuration["Tokens:Audience"] ,
ValidateAudience = true
};
});
and after this you can check User.Identity.IsAuthenticated in you base controler or authorization filter . If token is expired this is false. After this you can expirary date if you neeed.
Upvotes: 6