【问题标题】:How to disable the default authentication scheme, when non-default schema is provided提供非默认架构时如何禁用默认身份验证方案
【发布时间】:2020-03-31 18:27:53
【问题描述】:

我的应用中有两个身份验证方案

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

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

我使用 net core 2.2,但考虑迁移到 3.1。

【问题讨论】:

    标签: c# authentication asp.net-core


    【解决方案1】:

    我发现解决方案不是提供默认的身份验证方法,而是提供默认的授权策略。

    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")] 都正常工作,只调用其中一种身份验证方案。

    【讨论】:

    • 这让我在我的问题上找到了新的方向!感谢您转过身来输入您发现的内容!
    • 这对我有帮助
    猜你喜欢
    • 2018-07-24
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    相关资源
    最近更新 更多