OpenIddict配置API令牌验证时连接身份服务器失败问题求助
问题描述
参考OpenIddict的Zirku.Api1示例,在.NET 6.0中实现基于自省的令牌验证以访问API端点,身份服务器与API不在同一解决方案中。直接请求身份服务器响应正常,但请求API时始终失败。
配置代码
ConfigureServices 方法
services.AddOpenIddict() .AddValidation(options => { options.SetIssuer("https://localhost:6001/"); // 配置验证处理器使用自省,注册与远程自省端点通信的客户端凭据 options.UseIntrospection() .SetClientId("testapp") .SetClientSecret("6da97943-865d-41c4-970b-5a2670b7e347"); // 注册System.Net.Http集成 options.UseSystemNetHttp(); // 注册ASP.NET Core主机 options.UseAspNetCore(); }); services.AddAuthentication(OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme);
Configure 方法
app.UseEndpoints(endpoints => { endpoints.MapGet("/api", async context => { var user = context.User; if (user.Identity?.IsAuthenticated == true) { await context.Response.WriteAsync($"{user.Identity.Name} is allowed to access Api1."); } else { context.Response.StatusCode = StatusCodes.Status401Unauthorized; await context.Response.WriteAsync("Unauthorized"); } }).RequireAuthorization(); // 要求授权 endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapRazorPages(); endpoints.MapHub<HubServer>("/hub"); });
控制器代码
[HttpGet] [Authorize(AuthenticationSchemes = OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme)] public async Task<Utils.HttpResponse> listAll(int page = 1, int itemsPerPage = 10, string search = "") {...//更多代码
错误信息
请求API时,程序尝试连接身份服务器的https://localhost:6001/.well-known/openid-configuration端点失败,错误日志如下:
OpenIddict.Validation.OpenIddictValidationDispatcher[0] The response was successfully returned as a challenge response: { "error": "server_error", "error_description": "The remote authorization server is currently unavailable or returned an invalid configuration.", "error_uri": "https://documentation.openiddict.com/errors/ID2170" }.
解决方案
1. 验证元数据端点可用性
直接在浏览器或调试工具中访问https://localhost:6001/.well-known/openid-configuration,确认能返回合法的JSON格式配置。如果身份服务器使用自签名证书,需在API项目中添加证书信任配置(仅开发环境使用):
services.AddHttpClient().ConfigurePrimaryHttpMessageHandler(() => { return new HttpClientHandler { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator }; });
2. 跳过元数据发现,显式指定自省端点
若元数据端点无法访问,可跳过自动发现流程,直接配置自省端点地址:
options.UseIntrospection() .SetClientId("testapp") .SetClientSecret("6da97943-865d-41c4-970b-5a2670b7e347") .SetIntrospectionEndpoint("https://localhost:6001/connect/introspect");
3. 检查身份服务器CORS配置
确保身份服务器允许API域名发起自省请求,在身份服务器中添加CORS规则:
services.AddCors(options => { options.AddPolicy("AllowApi", policy => { policy.WithOrigins("https://localhost:你的API端口") .AllowAnyHeader() .AllowAnyMethod(); }); });
4. 确认客户端权限与凭据正确性
检查testapp客户端在身份服务器中已启用自省权限(AllowIntrospection),且客户端密钥与API配置完全一致。
5. 修正中间件顺序
确保中间件加载顺序正确,UseAuthentication必须在UseAuthorization和UseEndpoints之前:
app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { // 端点配置代码 });
内容的提问来源于stack exchange,提问作者Joanny Benejam
相关产品推荐
相关产品推荐

