为什么我已经设置了 defaultScheme 但还需要指定 AuthenticationSchemes?

Why I need to specify AuthenticationSchemes although I have set the defaultScheme?

我正在 .NET 6 中开发 Web-Api,我正在尝试使用 JWT 进行身份验证。

在我的 Program.cs 文件中,我添加了如下身份验证:

builder.Services
    .AddAuthentication(defaultScheme: JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options => options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = builder.Configuration["JwtSettings:Issuer"],
        ValidAudience = builder.Configuration["JwtSettings:Audience"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JwtSettings:SigningKey"])),
    });

并且我在要保护的方法上使用 [Authorize] 属性。

这仅在我指定如下身份验证方案时有效: [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

我在设置默认身份验证方案时做错了什么,所以我可以按原样使用 [Authorize] 属性。

提前致谢。

试试这个!

需要在program.cs中添加app.UseAuthentication(),因为现在没有认证中间件。