2017-04-06 52 views
4

我正在配置.netcore应用程序以使用OIDC身份验证(由IdentityServer提供)。如何在负载平衡器后配置UseCookieAuthentication

我已经包含下面的代码在我的启动

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运行的泊坞窗内。它运行在监听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重定向,我有什么其他选择?

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

+0

你能解决这个问题吗?我遇到了相同的情况,并且,当您评论@davidg提供的答案时,添加中间件似乎没有效果。 –

回答

3

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

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

尽早将它放置在您的管道中。

+1

这似乎对.net核心OIDC中间件没有任何影响。是否还有其他步骤? – TreeAndLeaf