'.NET core - Configure JWT Authentication at runtime

I have an ASP.NET Core 2 Web Application and I am using the [Authorize] attribute on the controllers that require authentication. As authentication mechanism, I am using JWT which I could configure in the Startup class using

.AddJwtBearer(options => {
    options.Audience = "....";
    options.Authority = "....";
});

This would work great. My problem is that I don't have the information for audience and authority at startup and I need to configure this at runtime.

Is there any way to do this?



Solution 1:[1]

You can try :

  1. Register multi jwt authentication schema and dynamically choose the needed schema based on parameter/reqeust header value in request . Click here for code sample .

  2. Config and replace your ISecurityTokenValidator. Use DI to inject IHttpContextAccessor to read data from request .Click here and here for code sample .

  3. Manually validating a JWT token with JwtSecurityTokenHandler . Click here for code sample .

Solution 2:[2]

It is worth understanding the extensibility points also, since Microsoft provide a customizable framework. Some people (including myself) prefer a library based approach to dealing with JWTs.

This is possible via a CustomAuthenticationHandler, and its implementation can use a JWT library. My code example uses jose-jwt via this handler class.

This enables you to validate JWTs however you like and take closer control over behaviour. Hopefully it provides an idea or two for your own solution. Further details in this blog post.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nan Yu
Solution 2 Gary Archer