user704772
user704772

Reputation: 319

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

I've set up AspNet Core 2 authentication successfully, but now would like to get it working behind a load balancer.

Because the load balancer address is different from my app address I'm changing the redirect Uri in my startup.cs ConfigureServices like this...

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

This works fine and I successfully authenticate and the callback from the identity server calls https://frontfacingaddress.com/signin-oidc. That is correctly handled and handling OnTokenResponseReceived shows that I successfully recieve the token.

The problem is: it is then making another call to the identity server but this time to the app's actual (not load balancing) address. When that comes back it gives an error of: AspNetCore.Correlation.OpenIdConnect cookie not found.

So the Fiddler trace looks like this:

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

Why, after successfully authenticating, is it then firing again from the actual address and failing?

Upvotes: 1

Views: 689

Answers (1)

user704772
user704772

Reputation: 319

The solution was to modify the ReturnUri to use the front-facing address when the ticket was received:

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);
};

Upvotes: 1

Related Questions