调用Product API时Swagger返回401未授权错误排查请求
401未授权问题排查与解决步骤
1. 先验证Token本身是否有效
拿你从quickbite.Web获取的access_token,用JWT解析工具(本地就能用的离线解析器就行)拆开看关键字段:
- 检查
aud(受众):必须包含quickbite.Services.ProductAPI,如果ProductAPI配置的受众和token里的不匹配,直接会被拒绝 - 检查
iss(签发者):要和你的IdentityServer地址完全一致(包括HTTPS、端口号),比如https://localhost:xxxx,必须和ProductAPI配置的权威地址对上 - 检查
exp(过期时间):确认token还没过期,过期的token会直接返回401 - 检查
scope(权限范围):里面要有ProductAPI要求的权限,比如productapi.read这类,要是没包含对应scope,调用接口肯定过不了
2. 核对ProductAPI的Program.cs认证配置
重点看认证服务的配置,必须确保以下几点:
builder.Services.AddAuthentication("Bearer") .AddJwtBearer("Bearer", options => { options.Authority = "https://localhost:xxxxx"; // 这里填你的IdentityServer地址,要和token的iss完全一致 options.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = true, ValidAudience = "quickbite.Services.ProductAPI", // 必须和IdentityServer里注册的ProductAPI资源名一致 ValidateIssuer = true, ValidIssuer = "https://localhost:xxxxx", // 和上面的Authority保持一致 ValidateLifetime = true }; }); // 这两行中间件不能少,而且顺序不能错:先认证再授权,放在UseRouting之后、UseEndpoints之前 app.UseAuthentication(); app.UseAuthorization();
- 确认
Authority的地址、端口没写错 ValidAudience要和IdentityServer中定义的ProductAPI资源名称一模一样
3. 检查IdentityServer的资源与客户端配置
在IdentityServer的Program.cs里,必须正确注册ProductAPI的ApiResource:
builder.Services.AddIdentityServer() .AddInMemoryApiResources(new List<ApiResource> { new ApiResource("quickbite.Services.ProductAPI", "Product API") { Scopes = { "productapi.read", "productapi.write" } // 这里定义的scope要和客户端请求的一致 } }) // 其他配置(身份资源、客户端等)...
同时,quickbite.Web对应的Client配置里,必须包含ProductAPI的scope:
.AddInMemoryClients(new List<Client> { new Client { ClientId = "quickbite.web", // 其他客户端配置(ClientSecrets、GrantType等)... AllowedScopes = { "openid", "profile", "productapi.read" } // 一定要加ProductAPI的scope,不然token里不会带这个权限 } })
4. 确认Swagger请求头格式正确
在Swagger里调用接口时,Authorization头的格式必须是:
Bearer {你的access_token}
注意Bearer后面有个空格,拼写错(比如小写bearer)或者没空格,都会导致401
5. 排查HTTPS与端口问题
- 确保IdentityServer和ProductAPI都用HTTPS运行,token的
iss是HTTPS地址,ProductAPI的Authority也必须是HTTPS,混着HTTP/HTTPS会直接验证失败 - 确认请求URL
https://localhost:7028/api/Products的端口7028和ProductAPI实际运行的端口一致
6. 开日志找具体原因
在ProductAPI的appsettings.json里加日志配置,开启认证授权的Debug日志:
{ "Logging": { "LogLevel": { "Microsoft.AspNetCore.Authentication": "Debug", "Microsoft.AspNetCore.Authorization": "Debug" } } }
运行项目后看控制台日志,里面会明确告诉你token验证失败的具体原因(比如受众不匹配、签发者错误、scope缺失等)
内容的提问来源于stack exchange,提问作者Muzammil
相关产品推荐
相关产品推荐

