NuhRuqa
NuhRuqa

Reputation: 21

.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?

Upvotes: 2

Views: 1869

Answers (2)

Gary Archer
Gary Archer

Reputation: 29243

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.

Upvotes: 0

Nan Yu
Nan Yu

Reputation: 27538

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 .

Upvotes: 1

Related Questions