Issue
In my web application I want to perform all the default lifetime checks (not before, expires, ...), plus perform one additional check (lifetime < 2 hours).
First I tried this:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, o => {
o.TokenValidationParameters = new TokenValidationParameters()
{
ValidateLifetime = true,
LifetimeValidator = (DateTime? notBefore, DateTime? expires, SecurityToken securityToken, TokenValidationParameters validationParameters) => {
// --> my custom check <--
}
};
});
This will perform my custom check, but it will skip the default implementation, so all the regular checks (not before, expires, ...) are no longer performed.
Then I call the default implementation from within my handler, like this:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, o => {
o.TokenValidationParameters = new TokenValidationParameters()
{
ValidateLifetime = true,
LifetimeValidator = (DateTime? notBefore, DateTime? expires, SecurityToken securityToken, TokenValidationParameters validationParameters) => {
Microsoft.IdentityModel.Tokens.Validators.ValidateLifetime(notBefore, expires, securityToken, validationParameters);
// --> my custom check <--
}
};
});
But this will recursively call my handler and eventually crash my application.
So... what's the correct way to extend the default lifetime validator?
Solution
You can do this:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, o => {
o.TokenValidationParameters = new TokenValidationParameters()
{
ValidateLifetime = true,
LifetimeValidator = (DateTime? notBefore, DateTime? expires, SecurityToken securityToken, TokenValidationParameters validationParameters) => {
var clonedParameters = validationParameters.Clone();
clonedParameters.LifetimeValidator = null;
bool valid = Microsoft.IdentityModel.Tokens.Validators.ValidateLifetime(notBefore, expires, securityToken, clonedParameters);
// --> my custom check <--
}
};
});
So we copy the TokenValidationParameters
and set the lifetime validator reference to null so it prevents the recursive call and doesn't modify the actual instance where you registered the validator.
Answered By - juunas Answer Checked By - Pedro (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.