【问题标题】:How to configure UseCookieAuthentication behind a load balancer如何在负载均衡器后面配置 UseCookieAuthentication
【发布时间】:2019-04-05 07:19:08
【问题描述】:

我正在配置一个 .netcore 应用程序以使用 OIDC 身份验证(由 IdentityServer 提供)。

我在 StartUp 中包含以下代码

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationScheme = "Cookies",
    AutomaticAuthenticate = true,
    ExpireTimeSpan = TimeSpan.FromMinutes(60)
});

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
    AuthenticationScheme = "oidc",
    SignInScheme = "Cookies",

    Authority = "https://myauthority",
    ClientId = "myclient",
    CallbackPath = "/",
    ResponseType = "id_token token",
    Scope = { "openid", "profile", "email" },
});

应用程序托管在 AWS 上,位于 ECS 中运行的 docker 中。它运行在监听 https 的应用负载均衡器后面。

我发现因为我的应用程序本身没有使用 https(因为 https 被负载均衡器终止),所以 OIDC 中间件在重定向到 OIDC 服务器时生成了错误的返回 URL - 它生成的 URL 以 http 开头: //.

返回 URL 由 AuthenticationHandler 基类中名为 BuildRedirectUri 的方法生成。它只是使用它收到请求的协议——似乎没有任何方法可以覆盖它。

protected string BuildRedirectUri(string targetPath)
{
    return this.Request.Scheme + "://" + this.Request.Host + this.OriginalPathBase + targetPath;
}

因此,鉴于似乎无法配置中间件来强制进行 HTTP 重定向,我还有哪些其他选择?

我是否应该编写一个“更高”的中间件组件来监听重定向请求并修改协议?或者有没有更好的方法来解决这个问题?

【问题讨论】:

  • 你能解决这个问题吗?我遇到了同样的情况,正如您对@davidg 提供的答案所评论的那样,添加中间件似乎没有效果。

标签: c# identityserver3 identityserver4 openid-connect


【解决方案1】:

当使用代理时(例如将 IIS 放在 Kestrel 之前,或者在您的情况下,负载平衡器),代理应该发送 X-Forwarded-ForX-Forwarded-Proto HTTP 标头。是后者传递了所请求的原始协议。幸运的是,有一个解决方案,那就是使用 Microsoft.AspNetCore.HttpOverrides 包中的 ForwardedHeaders 中间件。所以添加那个包,然后把这段代码添加到你的中间件管道中:

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

尽早将其放入您的管道中。

【讨论】:

  • 这似乎对 .net 核心 OIDC 中间件没有任何影响。是否涉及其他步骤?
【解决方案2】:

对我来说,添加 ForwarededHeaders 是不够的。我还必须添加以清除网络和代理(如 on the ASP.NET Core Docs repo 所述)。

并尽早在Configure

 var options = new ForwardedHeadersOptions
        {
            ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
        };
 options.KnownNetworks.Clear();
 options.KnownProxies.Clear();
 app.UseForwardedHeaders(options);

如果所有其他方法都失败了,您也可以使用发布在https://leastprivilege.com/2017/10/09/new-in-identityserver4-v2-simplified-configuration-behind-load-balancers-or-reverse-proxies/ 的解决方案来避免这一切。这也有效(但不适用于我的多租户环境):

services.AddIdentityServer(options =>
            {
                ...
               options.PublicOrigin = "https://whatever.domain.com";
                ...
            })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 2016-04-17
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 2015-07-11
    • 2018-11-05
    相关资源
    最近更新 更多