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

应用从App Service迁移到AKS后,/signin-oidc回调出现Correlation失败错误

问题描述

我的ASP.NET Core应用在回调到/signin-oidc时出现500错误。
应用部署在Azure应用网关后的App Service中时,登录功能正常;但部署到AKS容器中、通过同一网关访问时,出现此错误。

容器日志如下:

warn: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[15]
      '.AspNetCore.Correlation.__PrN2tAGsRBPSGlBe4wQzX7rdufN534NuCeqjwUUEU' cookie not found.
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]
      An unhandled exception has occurred while executing the request.
      System.Exception: An error was encountered while handling the remote login.
       ---> System.Exception: Correlation failed.
         --- End of inner exception stack trace ---
         at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync()
         at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
         at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context)
         at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)

核心错误是“Correlation failed”,伴随关联Cookie未找到的警告。由于网关在App Service场景下正常工作,推测问题出在AKS或Ingress控制器上。

应用通过默认策略强制所有路由认证,使用AddMicrosoftIdentityWebAppAuthentication处理核心认证逻辑:

// 配置AAD登录
services.AddMicrosoftIdentityWebAppAuthentication(config);
services.AddAuthorization(options =>
{
    options.FallbackPolicy = options.DefaultPolicy;
    AuthorizationPolicies.Configure(options);
});
// 生产环境下运行在应用网关之后
// 需要覆盖RedirectUri指向正确的URL
// 因为应用在网关后无法感知自身的外部URL
if (!environment.IsDevelopment())
{
    services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
    {
        options.Events = new OpenIdConnectEvents
        {
            OnRedirectToIdentityProvider = ctxt => {
                ctxt.ProtocolMessage.RedirectUri = cfg.RedirectUri;
                return Task.CompletedTask;
            }
        };
    });
}
...
app.UsePathBase("/ssp-pls");

我也曾尝试修改Cookie配置,但未解决问题:

app.UseCookiePolicy(new CookiePolicyOptions
{
    // HttpOnly =  HttpOnlyPolicy.Always,
    MinimumSameSitePolicy = SameSiteMode.None,
    Secure = CookieSecurePolicy.Always
    // MinimumSameSitePolicy = SameSiteMode.Lax
});

Ingress配置如下:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ssp-ing
  annotations:
    nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
    nginx.ingress.kubernetes.io/affinity: cookie
spec:
  tls:
    - hosts:
        - selfserviceportal.beans.ca
  rules:
  - host: selfserviceportal.beans.ca
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: ssp-svc
            port:
              number: 80
  ingressClassName: nginx

解决方案

1. 对齐Ingress路径与应用PathBase

应用设置了app.UsePathBase("/ssp-pls"),但Ingress路径为/,会导致Cookie路径不匹配,关联Cookie无法被正确携带到回调地址。修改Ingress配置:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ssp-ing
  annotations:
    nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
    nginx.ingress.kubernetes.io/affinity: cookie
    nginx.ingress.kubernetes.io/rewrite-target: /$2
spec:
  tls:
    - hosts:
        - selfserviceportal.beans.ca
  rules:
  - host: selfserviceportal.beans.ca
    http:
      paths:
      - path: /ssp-pls(/|$)(.*)
        pathType: ImplementationSpecific
        backend:
          service:
            name: ssp-svc
            port:
              number: 80
  ingressClassName: nginx

2. 显式设置关联Cookie路径

在OpenIdConnect配置中指定关联Cookie的路径为应用的PathBase,避免路径不匹配:

if (!environment.IsDevelopment())
{
    services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
    {
        options.Events = new OpenIdConnectEvents
        {
            OnRedirectToIdentityProvider = ctxt => {
                ctxt.ProtocolMessage.RedirectUri = cfg.RedirectUri;
                return Task.CompletedTask;
            }
        };
        // 设置关联Cookie路径
        options.CorrelationCookie.Path = "/ssp-pls";
    });
    // 同步设置认证Cookie路径
    services.Configure<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme, options =>
    {
        options.Cookie.Path = "/ssp-pls";
    });
}

3. 配置Ingress转发正确请求头

ASP.NET Core需要正确的转发头识别外部URL和协议,添加Ingress注解:

metadata:
  annotations:
    # 已有注解保留,新增以下内容
    nginx.ingress.kubernetes.io/forwarded-for-header: "X-Forwarded-For"
    nginx.ingress.kubernetes.io/proxy-set-header: "X-Forwarded-Proto $scheme"
    nginx.ingress.kubernetes.io/proxy-set-header: "X-Forwarded-Host $host"

同时在Program.cs中启用转发头中间件(放在UseAuthentication之前):

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});

4. 调整会话亲和性Cookie路径

确保Ingress会话亲和性Cookie的路径与应用PathBase一致,避免请求分发到不同Pod导致Cookie丢失:

nginx.ingress.kubernetes.io/session-cookie-path: "/ssp-pls/"
nginx.ingress.kubernetes.io/session-cookie-name: "INGRESS-AFFINITY"

5. 优化Cookie策略兼容性

生产环境下保持Secure = CookieSecurePolicy.Always,可尝试调整SameSite模式:

app.UseCookiePolicy(new CookiePolicyOptions
{
    MinimumSameSitePolicy = SameSiteMode.Lax,
    Secure = CookieSecurePolicy.Always,
    HttpOnly = HttpOnlyPolicy.Always
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 15:45:34