如何在负载均衡器后面正确设置 AspNet Core 2 身份验证?

How to correctly set up AspNet Core 2 authentication behind a load balancer?

我已经成功设置了 AspNet Core 2 身份验证,但现在想让它在负载平衡器后面工作。

因为负载均衡器地址与我的应用程序地址不同,所以我正在 startup.cs ConfigureServices 中更改重定向 URI,如下所示...

options.Events.OnRedirectToIdentityProvider = async n =>
     {                        
        n.ProtocolMessage.RedirectUri = "https://frontfacingaddress.com";
        await Task.FromResult(0);
     };

这很好用,我成功地进行了身份验证,身份服务器的回调调用 https://frontfacingaddress.com/signin-oidc。这是正确处理和处理 OnTokenResponseReceived 显示我成功收到令牌。

问题是:它随后再次调用身份服务器,但这次调用的是应用程序的实际(非负载平衡)地址。当它返回时,它会给出一个错误:AspNetCore.Correlation.OpenIdConnect cookie not found.

所以 Fiddler 跟踪看起来像这样:

302 HTTPS  frontfacingaddress.com   /account/signin
200 HTTPS  identity.serveraddress.com /connect/authorize/callback etc...
302 HTTPS  frontfacingaddress.com   /signin-oidc
-- this is where I successfully receive the code, but then:
302 HTTPS  actualwebaddress.com     /account/signin
200 HTTPS  identity.serveraddress.com /connect/authorize/callback etc...
400 HTTPS  frontfacingaddress.com   /signin-oidc
-- this is the 400 cookie not found error

为什么认证成功后,从真实地址再次触发,失败?

解决方案是修改 ReturnUri 以在收到票时使用 front-facing 地址:

options.Events.OnTicketReceived = async context =>
{
    var host = context.HttpContext.Request.Host.Host;
    var forwardedHost = context.HttpContext.Request.Headers["X-Forwarded-Host"].ToString();
    context.ReturnUri = context.ReturnUri.Replace(host, forwardedHost);                        
    await Task.FromResult(0);
};