如何在负载均衡器后面配置UseCookieAuthentication

san*_*ndy 5 c# openid-connect identityserver3 identityserver4

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

我在启动中包含了以下代码

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" },
});
Run Code Online (Sandbox Code Playgroud)

该应用程序托管在ECS中运行的docker中的AWS上。它在侦听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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

Dav*_*idG 3

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

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
Run Code Online (Sandbox Code Playgroud)

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