aspnet / AspNetKatana

Microsoft's OWIN implementation, the Katana project
Apache License 2.0
967 stars 334 forks source link

Google middleware doesn't generate proper redirect_uri when using a load balancer #102

Closed RobSiklos closed 4 years ago

RobSiklos commented 7 years ago

I have an application which uses the Microsoft.Owin.Security.Google middleware for federated authentication.

Everything works fine, until I add a load balancer into the mix.

The load balancer is configured such that incoming connections are HTTPS, but backend connections (i.e. between the load balancer and the ASP.NET application) are HTTP.

In this configuration, I get a redirect_uri_mismatch error from Google during the authentication sequence, because the redirect_uri parameter provided by the middleware specifies HTTP instead of HTTPS.

I think the offending line of code is https://github.com/aspnet/AspNetKatana/blob/dev/src/Microsoft.Owin.Security.Google/GoogleOAuth2AuthenticationHandler.cs#L158, where the baseUri variable is using the scheme from the request.

There should be some way to override this behaviour, so that I can specify what scheme should actually be used.

Tratcher commented 7 years ago

The recommended approach is to have the load balancer forward the scheme as a header (e.g. x-forwarded-proto), and have a middleware that reads the header and updates the OwinContext.Request.Scheme accordingly. This addresses the issue not just for one auth component, but for all urls generated in the application.

RobSiklos commented 7 years ago

@Tratcher Thanks! I actually have the header in the request already. Any pointers on how to create the middleware which updates the Request object?

Tratcher commented 7 years ago

The basics are:

app.Use((context, next) =>
{
  var forwardedScheme = context.Request.Headrs["x-forwarded-proto"];
  context.Request.Scheme = forwardedScheme;
  return next();
});

Plus lots of validation code.

RobSiklos commented 7 years ago

@Tratcher Got it working - many thanks!!