ASP.NET Core CookieAuthenticationOptions.LoginPath在不同的域上

Raz*_*zie 5 asp.net-core

CookieAuthenticationOptions用于在.NET Core应用程序中配置身份验证,但是我的登录页面位于其他域上。但是,该LoginPath属性仅允许内部路径,而不允许完整的URI。所以下面的代码:

var cookieOptions = new CookieAuthenticationOptions()
{
    AuthenticationScheme = "Cookies",
    LoginPath = new PathString("https://externaldomain.com/login"),
    CookieName = string.Format("myCookie"),
};

app.UseCookieAuthentication(cookieOptions);
Run Code Online (Sandbox Code Playgroud)

... 是无效的。这应该相当简单,还是我在这里遗漏了一些东西?我不希望在应用程序内部处理此问题,而自己进行实际的重定向。那有点la脚。

ade*_*lin 9

使用OnRedirectToLogin

var cookieOptions = new CookieAuthenticationOptions()
{
    AuthenticationScheme = "Cookies",
    CookieName = string.Format("myCookie"),
    Events = new CookieAuthenticationEvents()
    {
          OnRedirectToLogin = async (context) =>
          {
              context.HttpContext.Response.Redirect("https://externaldomain.com/login");
          };
    }
}
Run Code Online (Sandbox Code Playgroud)


Luc*_*iro 5

可接受的答案适用于.NET Core1.x。对于任何想在.NET Core 2.x上实现它的人,请在Startup.cs的ConfigureServices内部使用以下内容:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(o =>
    {
        o.Cookie.Name = "myCookie";
        o.Events = new CookieAuthenticationEvents()
        {
            OnRedirectToLogin = (context) =>
            {
                context.HttpContext.Response.Redirect("https://externaldomain.com/login");
                return Task.CompletedTask;
            }
        };
    });
Run Code Online (Sandbox Code Playgroud)