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

.NET 8升级后Identity Server4出现Correlation failed问题求助

.NET 6升级到.NET 8后Identity Server4出现Correlation failed错误的解决方案

将环境从.NET 6升级到.NET 8后,Identity Server4出现Correlation failed错误,此前.NET 6环境下运行一切正常。以下是客户端配置、Identity Server配置以及当前CookiePolicy配置:

客户端配置

JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

services.AddAuthentication(options =>
{
    options.DefaultScheme = "Cookies";
    options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
    options.SignInScheme = "Cookies";
    options.Authority = configuration["IdentityUrl"];
    options.RequireHttpsMetadata = false;

    options.ClientId = configuration["ClientId"];
    options.ClientSecret = configuration["ClientSecret"];
    options.ResponseType = "code";

    options.TokenValidationParameters = new TokenValidationParameters 
    { 
        NameClaimType = ClaimTypes.Name,
        RoleClaimType = JwtClaimTypes.Role
    };
    options.SaveTokens = true;

    options.Scope.Add(IdentityServerConstants.StandardScopes.OpenId);
    options.Scope.Add(IdentityServerConstants.StandardScopes.Profile);
    options.Scope.Add(IdentityServerConstants.StandardScopes.Email);
    options.Scope.Add(AccountConstants.Scopes.All);
    options.Scope.Add(AccountConstants.Scopes.Roles);

    options.ClaimActions.MapJsonKey(JwtClaimTypes.Role, JwtClaimTypes.Role, JwtClaimTypes.Role);

    options.Events.OnRedirectToIdentityProvider = context =>
    {
        if (string.Equals(context.Request.Query["X-Requested-With"], "XMLHttpRequest", StringComparison.Ordinal) ||
            string.Equals(context.Request.Headers["X-Requested-With"], "XMLHttpRequest", StringComparison.Ordinal))
        {
            context.Response.Clear();
            context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            context.Response.Headers["Location"] = "/Accounts/Account/SignOutNow";
            context.Properties.RedirectUri = $"{context.Request.Scheme}://{context.Request.Host}";
        }
        else
        {
            context.Properties.RedirectUri = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.PathBase}";
            context.Properties.Items.Add(OpenIdConnectDefaults.RedirectUriForCodePropertiesKey, context.ProtocolMessage.RedirectUri);
            context.ProtocolMessage.State = options.StateDataFormat.Protect(context.Properties);
            context.Response.StatusCode = (int)HttpStatusCode.Redirect;
            context.Response.Headers["Location"] = context.ProtocolMessage.CreateAuthenticationRequestUrl();
        }

        context.HandleResponse();

        return Task.CompletedTask;
    };
});

Identity Server配置

services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<IdentityContext>()
.AddDefaultTokenProviders();

var builder = services.AddIdentityServer(options => {

    options.IssuerUri = "null";
    options.UserInteraction.LoginUrl = "/Accounts/SignIn";
    options.UserInteraction.LogoutUrl = "/Accounts/SignOut";
    options.Events.RaiseErrorEvents = true;
    options.Events.RaiseInformationEvents = true;
    options.Events.RaiseFailureEvents = true;
    options.Events.RaiseSuccessEvents = true;
})
.AddInMemoryIdentityResources(IdentityServerConfig.Ids)
.AddInMemoryApiScopes(IdentityServerConfig.ApiScopes)
.AddInMemoryApiResources(IdentityServerConfig.Apis)
.AddInMemoryClients(IdentityServerConfig.GetClients(configuration))
.AddAspNetIdentity<ApplicationUser>();

builder.Services.AddScoped<IProfileService, ProfileService>();

if (isProduction)
{
    var client = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(async (authority, resource, scope) =>
    {
        var context = new AuthenticationContext(authority);
        var credentials = new ClientCredential(configuration.GetValue<string>("AzureKeyVaultClientId"), configuration.GetValue<string>("AzureKeyVaultClientSecret"));
        var authenticationResult = await context.AcquireTokenAsync(resource, credentials);
        return authenticationResult.AccessToken;
    }));

    builder.AddSigningCredential(new X509Certificate2(Convert.FromBase64String(client.GetSecretAsync(configuration.GetValue<string>("AzureKeyVaultIdentityServer4Certificate")).Result.Value), configuration.GetValue<string>("AzureKeyVaultIdentityServer4CertificatePassword")));
}
else
{
    builder.AddDeveloperSigningCredential();
}

services.AddAuthentication()
    .AddIdentityServerAuthentication("IsToken", options =>
    {
        options.Authority = configuration.GetValue<string>("IdentityUrl");
        options.RequireHttpsMetadata = false;
        options.ApiName = AccountConstants.ApiNames.All;
    });

当前CookiePolicy配置

if (app.Environment.EnvironmentName == EnvironmentConstants.DevelopmentEnvironmentName)
{
    app.UseCookiePolicy(new CookiePolicyOptions
    {
        MinimumSameSitePolicy = SameSiteMode.Lax
    });
}
else
{
    app.UseCookiePolicy(new CookiePolicyOptions
    {
        MinimumSameSitePolicy = SameSiteMode.None,
        Secure = CookieSecurePolicy.Always
    });
}

已尝试修改UseCookiePolicy()但未解决问题,寻求有效的解决方案。

内容的提问来源于stack exchange,提问作者Sebastian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 07:20:24