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

.NET Core中LoginPath未触发,直接跳转SSO问题排查

问题描述

我按标准方式配置了AddAuthentication和AddCookie,各项功能正常,但指定的LoginPath从未被触发。当未认证用户访问带有AuthorizeFilter的路由时,应用直接跳转到配置的OpenIdConnect单点登录(SSO)站点。我希望在跳转至SSO前手动执行一些操作,请问是什么原因导致LoginPath未生效?

配置代码如下:

builder.Services.AddAuthentication("SecondaryScheme")
            .AddCookie(options =>
            {
                options.LoginPath = "/Home/Login";

            });

在Owin应用中,我可以通过将AuthenticationMode设置为Passive而非Active来控制此行为,但在.NET Core中找不到类似选项。


原因分析

核心问题在于认证方案的优先级与默认挑战逻辑:

  1. 若你的应用同时注册了OpenIdConnect认证方案,且该方案被设为默认挑战方案,ASP.NET Core会优先触发它的跳转逻辑,直接导向SSO站点,跳过Cookie方案的LoginPath配置。
  2. .NET Core已移除Owin的AuthenticationMode概念,改为通过方案优先级配置和显式指定挑战/认证方案来控制行为。

解决方案

方案1:在授权特性中显式指定Cookie方案

在需要触发自定义前置操作的路由上,用[Authorize]特性指定使用你的Cookie认证方案:

[Authorize(AuthenticationSchemes = "SecondaryScheme")]

此时未认证用户访问该路由时,会触发/Home/Login跳转,你可在此完成前置操作后,手动引导用户跳转到SSO站点。

方案2:全局设置默认挑战方案为Cookie

修改认证配置,将默认挑战方案设为你的Cookie方案,全局优先触发自定义登录逻辑:

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = "SecondaryScheme";
    options.DefaultChallengeScheme = "SecondaryScheme"; // 设置默认挑战方案
})
.AddCookie("SecondaryScheme", options =>
{
    options.LoginPath = "/Home/Login";
})
.AddOpenIdConnect("OidcScheme", options =>
{
    // 你的OpenIdConnect配置
});

然后在/Home/Login的Action中执行前置操作,再手动触发OpenIdConnect挑战:

public IActionResult Login(string returnUrl)
{
    // 执行前置操作:记录日志、设置临时数据等
    return Challenge(new AuthenticationProperties { RedirectUri = returnUrl }, "OidcScheme");
}

方案3:通过Cookie事件插入自定义逻辑

利用Cookie认证的OnRedirectToLogin事件,在跳转前执行自定义操作,再手动转向SSO:

builder.Services.AddAuthentication("SecondaryScheme")
.AddCookie(options =>
{
    options.LoginPath = "/Home/Login";
    options.Events = new CookieAuthenticationEvents
    {
        OnRedirectToLogin = context =>
        {
            // 执行你的前置操作
            // 手动跳转至触发OpenIdConnect挑战的端点
            context.Response.Redirect("/Account/ChallengeOidc?returnUrl=" + Uri.EscapeDataString(context.RedirectUri));
            return Task.CompletedTask;
        }
    };
});

新增ChallengeOidc Action触发SSO挑战:

public IActionResult ChallengeOidc(string returnUrl)
{
    return Challenge(new AuthenticationProperties { RedirectUri = returnUrl }, "OidcScheme");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 06:22:11