首页 > 解决方案 > 带有 AddCookie 的 AddAuthentication 重定向到 http 而不是 https

问题描述

我们有一个 ASP.Net Core 网站,并在用户未登录时使用 AddAuthentication 和 AddCookie 将用户重定向到 OAuth 登录提供程序。我们可以使用 LoginPath 提供登录操作的相对路径。这必须是相对路径;完整路径会导致异常。问题是我们的网站位于负载均衡器后面。到负载均衡器的流量是 https,但从那里它变成了到 Web 服务器的 http。这会导致重定向 url 是 http,而不是 https。我们如何控制 LoginPath 使用 https 作为重定向?

标签: asp.net-core

解决方案


我在@GabrielLuci 推荐的帖子中找到了答案。

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

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;
        }
    };
});

推荐阅读