net core中使用jwt时,提示DenyAnonymousAuthorizationRequirement: Requires an authenticated user

客户端请求是401,控制台提示

info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
Authorization failed. These requirements were not met:
DenyAnonymousAuthorizationRequirement: Requires an authenticated user.


翻遍了资料,也查不到原因,快绝望的时候,gpt给了个提示

 原来这个的顺序很重要,以前都不知道,拿过来就用,没考虑过这个,从来没认为这个东西会有顺序,但是确实存在

复制代码
//这里的顺序是错误的
//这里的顺序是错误的
//这里的顺序是错误的

app.UseRouting(); app.UseAuthorization(); app.UseAuthentication();
复制代码

 

复制代码
//这里是正确的
app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllerRoute( name:
"default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
复制代码

这个是Program.cs中的配置

复制代码
// 配置 JWT 认证
var key = Encoding.UTF8.GetBytes(AppSettingsHelper.GetSection("Jwt:Jwtkey"));
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = AppSettingsHelper.GetSection("Jwt:Issuer"),
        ValidAudience = AppSettingsHelper.GetSection("Jwt:Audience"),
        IssuerSigningKey = new SymmetricSecurityKey(key)
    };
});
builder.Services.AddAuthorization();
复制代码

 

posted @   拼博之路  阅读(120)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· 地球OL攻略 —— 某应届生求职总结
点击右上角即可分享
微信分享提示