You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 6 Identity Server 4刷新登录令牌遇CORS异常求助

问题描述

在.NET 6 Web应用中搭建了Identity Server 4,Web UI作为该身份服务器的客户端应用,用户访问受保护页面/API时能正确跳转登录,登录流程正常。解决方案中还有其他微服务也配置为使用IS作为OIDC服务。

问题:长时间未刷新页面后,调用WebAPI时出现认证失败。排查发现,调用WebAPI的主请求前,会向IS发起请求,但该请求因CORS异常被拒绝。

已配置的IS CORS代码:

builder.Services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy",
        builder => builder.AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader());
});

随后添加了中间件:

app.UseCors("CorsPolicy");

但上述配置未解决问题。

解决方案

以下是你可能遗漏的关键点:

1. 调整中间件注册顺序

.NET 6中中间件的执行顺序直接影响功能生效,UseCors必须在UseIdentityServer、UseAuthentication和UseAuthorization之前注册。因为IdentityServer的端点(如令牌刷新端点/connect/token)需要先经过CORS中间件的校验,否则跨域请求会被直接拦截。

正确的中间件顺序示例:

app.UseCors("CorsPolicy");
app.UseIdentityServer();
app.UseAuthentication();
app.UseAuthorization();
// 其他中间件(如UseEndpoints)

2. 配置IdentityServer4客户端的跨域源

IdentityServer4内置了独立的CORS处理机制,它会优先使用客户端配置中的AllowedCorsOrigins来校验跨域请求,而非完全依赖全局ASP.NET Core CORS配置。你需要在IS的客户端配置中,添加Web UI和所有微服务的域名到允许列表。

示例(在IS的Config.cs或配置文件中):

new Client
{
    ClientId = "web_ui_client",
    ClientName = "Web UI Client",
    // 其他客户端配置(如授权类型、重定向URI等)
    AllowedCorsOrigins = { 
        "https://your-web-ui-domain.com", 
        "https://microservice-1-domain.com",
        "https://microservice-2-domain.com"
    }
}

3. 确保启用IdentityServer的CORS策略服务

在注册IdentityServer服务时,需明确添加CORS策略服务支持,确保IS能正确读取客户端配置中的跨域规则。示例代码:

builder.Services.AddIdentityServer()
    .AddDeveloperSigningCredential() // 生产环境请替换为正式签名凭证
    .AddInMemoryApiResources(Config.GetApiResources())
    .AddInMemoryClients(Config.GetClients())
    .AddCorsPolicyService<DefaultCorsPolicyService>(); // 启用内置CORS策略服务

4. 避免AllowAnyOrigin的冲突问题

如果你的跨域请求携带凭证(如Cookie),浏览器会禁止同时使用AllowAnyOrigin和AllowCredentials。此时应避免使用AllowAnyOrigin,改为明确指定所有允许的源,同时添加AllowCredentials()配置:

builder.Services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy",
        builder => builder.WithOrigins("https://your-web-ui-domain.com", "https://your-microservice-domains.com")
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials());
});

内容的提问来源于stack exchange,提问作者Andreas Müller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 07:01:09