【问题标题】:Why I need to specify AuthenticationSchemes although I have set the defaultScheme?为什么我设置了 defaultScheme 却需要指定 AuthenticationSchemes?
【发布时间】:2022-02-04 21:23:47
【问题描述】:

我正在 .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] 属性。

提前致谢。

【问题讨论】:

    标签: jwt .net-6.0


    【解决方案1】:

    试试这个!

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

    【讨论】:

    • 非常感谢!成功了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-21
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    • 2016-02-14
    • 1970-01-01
    相关资源
    最近更新 更多