DefaultAuthenticateScheme 被忽略并且控制器 Returns 未经授权

DefaultAuthenticateScheme Is Ignored and Controller Returns Unauthorized

我使用 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 添加到每个控制器吗?

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

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

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

重要的是 UseAuthentication UseAuthorization 之前