Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable the default authentication scheme, when non-default schema is provided

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.

like image 683
Morse Avatar asked Mar 31 '20 18:03

Morse


Video Answer


1 Answers

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.

like image 55
Morse Avatar answered Oct 12 '22 03:10

Morse