Having a configuration similar to this:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(x =>
{
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Convert.FromBase64String(config.JwtSecret)),
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
});
Is there a proper way of changing the IssuerSigningKey during runtime?
Ideas that come to mind:
keep a reference to TokenValidationParameters and just replace the IssuerSigningKey
extend SymmetricSecurityKey and do something similar as in the previous point
Both of these ways seem too hacky. I assume there is some kind of mechanism to achieve this the right way, I just couldn't find it.
I know this an old thread, but posting my answer anyway because I stumbled upon this thread while searching for the same scenario and I think it might be useful for others.
There is a delegate IssuerSigningKeyResolver, in the TokenValidationParameters, that you can set while configuring the other options. On every request authentication, your delegate will be executed. You can dynamically return the the SecurityKey.
For example:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
//ValidIssuer = jwtSettings.ValidIssuer,
//ValidAudience = jwtSettings.ValidAudience,
//IssuerSigningKey = issuerSigningKey,
IssuerSigningKeyResolver = (token, secutiryToken, kid, validationParameters) =>
{
SecurityKey issuerSigningKey = null;
// Set issuerSigningKey as per your logic.
// This delegate will be executed for eahc request.
return new List<SecurityKey>() { issuerSigningKey };
}
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With