dotnet8 jwt验证BUG

一次需要写个web api 进行 jwt验证,本以为水到渠成,非常简单的事情,洋洋洒洒写完login,返回token,然后去需要权限认证的接口进行请求,结果swagger调试的时候,一直提示无效token。日志也没出现记录,看不到具体错误。于是在配置里开启日志,在“appsettings.json”配置文件添加 "Microsoft.AspNetCore.Authentication": "Information"。
"Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning", "Microsoft.AspNetCore.Authentication": "Information" } },

这个时候再次请求api,结果提示报错,Authentication failed: IDX14100: JWT is not well formed, there are no dots (.). 好吧,自我怀疑下,于是去jwt 在线解析了下。能正常解析,证明格式是对的。然后AI一顿搜索没找出解决方案。继续在网上搜了一圈,有个可怜人跟我一样的问题。这个IDX14100是假提示。于是按他的解决方案 添加了options.UseSecurityTokenValidators = true;
.AddJwtBearer(options => { options.UseSecurityTokenValidators = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, //ValidateIssuerSigningKey = true, ValidIssuer = builder.Configuration["Jwt:Issuer"], ValidAudience = builder.Configuration["Jwt:Audience"], IssuerSigningKey = new SymmetricSecurityKey(key), ClockSkew = TimeSpan.Zero }; });

继续请求api,这个时候日志提示错误IDX10206: Unable to validate audience. The 'audiences' parameter is empty。真无语。明明我的token复核JWT标准。还是这样的提示,最后找了一圈在GitHub上找到了,发现原来是net8 bug,Microsoft.IdentityModel.Tokens" Version="8.8.0"和Microsoft.AspNetCore.Authentication.JwtBearer 冲突,这个问题一直延伸到最新的8.8还是老样子。解决方案需要添加引用Microsoft.IdentityModel.JsonWebTokens,System.IdentityModel.Tokens.Jwt就可以解决,保证版本一致即可。再次请求api,认证通过。卡了我一天多,坑人的微软。收工。

posted @ 2025-04-24 10:30  Rifleman  阅读(121)  评论(0)    收藏  举报