我正在配置 .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 的方法生成。它仅使用接收请求时所依据的协议(protocol) - 似乎没有任何方法可以覆盖它。
protected string BuildRedirectUri(string targetPath)
{
return this.Request.Scheme + "://" + this.Request.Host + this.OriginalPathBase + targetPath;
}
鉴于似乎无法配置中间件来强制进行 HTTP 重定向,我还有哪些其他选择?
我是否应该编写一个“高级”中间件组件来监听重定向请求并修改协议(protocol)?或者有没有更好的方法来解决这个问题?
最佳答案
当使用代理时(例如将 IIS 放在 Kestrel 前面或在您的情况下是负载平衡器),代理应该发送 X-Forwarded-For
和 X-Forwarded-Proto
HTTP header 。后者传递了所请求的原始协议(protocol)。幸运的是有一个解决方案,那就是使用 Microsoft.AspNetCore.HttpOverrides
中的 ForwardedHeaders
中间件。包裹。因此,添加该包,然后将此代码添加到您的中间件管道中:
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
尽早将其放入管道中。
关于c# - 如何在负载均衡器后面配置 UseCookieAuthentication,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43267113/