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

标签 c# identityserver3 identityserver4 openid-connect

我正在配置 .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-ForX-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/

相关文章:

asp.net-mvc - IdentityServer 4、OpenIdConnect 重定向到外部登录 url

c# - 无法使用我的身份服务器从 native 应用程序调用 API

c# - 将字典<string,string>序列化/反序列化为XML

c# - lambda表达式的生命范围是什么?

c# - Startup中IdentityServer3.Admin的配置

asp.net - IdentityServer混合流-用户成功登录后访问 token 为空

asp.net-core - 通过托管 IdentityServer 的单独微服务使用 OATH 保护 WebApi 的集成测试

c# - 如何在泛型方法中获取枚举的数据值?

时间:2019-03-17 标签:c#dynamiccompare

asp.net - 身份服务器 - 不记名 token 身份验证 - 如何跟踪失败的授权?