提供非默认架构时如何禁用默认身份验证方案 [英] How to disable the default authentication scheme, when non-default schema is provided

查看:68
本文介绍了提供非默认架构时如何禁用默认身份验证方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有两种身份验证方案

I have two authentication schemes in my app

services.AddAuthentication("default")
    .AddJwtBearer("default", options =>
    {
        // some options
    })
    .AddJwtBearer("non-default", options =>
    {
        // some other options
    });

该想法是对大多数控制器使用默认值,并且当需要非默认值时,使用 [Authorize(AuthenticationSchemes ="non-default")] .问题是,即使设置了非默认模式,也始终会调用默认模式.它运行并失败,然后正确的架构运行并成功.但这会导致日志中充满无法验证令牌"消息.有没有办法禁用默认架构?

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?

我使用的是net core 2.2,但考虑升级到3.1.

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());
});

此后, [Authorize] [Authorize("non-default")] 都正常工作,仅调用一种身份验证方案.

After this both [Authorize] and [Authorize("non-default")] work normally, only calling one of the authentication schemes.

这篇关于提供非默认架构时如何禁用默认身份验证方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆