I have two authentication schemes in my app
services.AddAuthentication("default")
.AddJwtBearer("default", options =>
{
// some options
})
.AddJwtBearer("non-default", options =>
{
// some other options
});
The idea is to use the default for most of the controllers, and when the non-default is needed, to explicitly mention the needed schema with [Authorize(AuthenticationSchemes = "non-default")]
. The problem is, the default schema is always being called, even when the non-default is set. It runs and fails, and after that the correct schema runs and succeeds. But this results in the log full of "Failed to validate the token" messages. Is there a way to disable the default schema?
I use net core 2.2, but considering to move to 3.1.
I found the solution in providing not the default authentication method, but rather the default authorization policy.
services.AddAuthentication()
.AddJwtBearer("defaultScheme", options =>
{
// some options
})
.AddJwtBearer("nonDefaultScheme", options =>
{
// some other options
});
services.AddAuthorization(opts =>
{
opts.DefaultPolicy = new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes("defaultScheme")
.RequireAuthenticatedUser()
.Build();
opts.AddPolicy("non-default", policy => policy
.AddAuthenticationSchemes("nonDefaultScheme")
.RequireAuthenticatedUser());
});
After this both [Authorize]
and [Authorize("non-default")]
work normally, only calling one of the authentication schemes.
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