【问题标题】:DefaultAuthenticateScheme Is Ignored and Controller Returns UnauthorizedDefaultAuthenticateScheme 被忽略,控制器返回 Unauthorized
【发布时间】:2020-11-23 02:22:43
【问题描述】:

我使用的是JWT Bearer Authentication,并将其设置为默认值如下:

// Authentication setup
services
    .AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        ...
    });

以下是我必须在我的控制器上使用授权:

[Authorize]
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase {
    ...
}

不幸的是,这不起作用,我必须改用以下方法:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase {
    ...
}

谁能解释我如何避免将 AuthenticationScheme 添加到每个控制器?

【问题讨论】:

    标签: asp.net asp.net-core jwt authorization


    【解决方案1】:

    经过几个小时的搜索,这实际上很容易。您唯一需要做的就是将管道切换到以下内容:

    app.UseRouting();
    
    app.UseAuthentication();
    app.UseAuthorization();
    
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
    

    UseAuthentication之前UseAuthorization很重要。

    【讨论】:

    • 感谢您回答自己的问题。这正是我的问题和解决方案。
    猜你喜欢
    • 2021-01-13
    • 2021-08-26
    • 2021-10-03
    • 1970-01-01
    • 2014-04-24
    • 2020-03-23
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    相关资源
    最近更新 更多