Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting JwtBearerOptions into a controller

In Startup.cs I enable JWT auth, which works perfectly across my app.

b.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, o =>
{
    o.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = key,
        ValidateIssuer = true,
        ValidIssuer = JwtConstants.Issuer,
        ValidateAudience = true,
        ValidAudience = JwtConstants.Audience,
        ValidateLifetime = true,
        ClockSkew = TimeSpan.Zero
    };
});

In one of my controllers, I would like to get a handle on the TokenValidationParameters that are set in the Startup.cs config. I thought I would be able to do this by providing my controller constructor with IOptions<JwtBearerOptions> options and reading options.Value.TokenValidationParameters, however, when injected the properties do not match the values set in Startup.cs.

My ultimate goal is to manually validate a JWT token, like below.

var handler = new JwtSecurityTokenHandler();
var user = handler.ValidateToken(token, validationParameters, out var validatedToken);
like image 415
Alex Avatar asked Apr 26 '26 06:04

Alex


1 Answers

To get the options you registered with your authentication scheme during startup, you'll have to use the IOptionsMonitor to extract the named options.

In your controller, inject it like this

public YourController(IOptionsMonitor<JwtBearerOptions> jwtOptions, ...) { ... }

Then when you want to get the instance of the options, you get it with the same name as you used to register the authentication scheme. Like this in your case:

var yourOptions = _jwtOptions.Get(JwtBearerDefaults.AuthenticationScheme);

You can read more about the options pattern in aspnet core here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-2.2

like image 183
Fredrik Lundin Avatar answered Apr 27 '26 23:04

Fredrik Lundin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!