Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core - change JWT SecurityKey during runtime

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.

like image 795
loodakrawa Avatar asked Jan 13 '19 09:01

loodakrawa


1 Answers

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 };
                }

            };

        });
like image 84
Amey Avatar answered Oct 19 '22 14:10

Amey