客户端请求是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();
标签:core,顺序,authenticated,Requires,app,jwt,GetSection,Jwt,true From: https://www.cnblogs.com/icejd/p/18313556