2017-04-06 40 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