Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force an HTTPS callback using Microsoft.AspNetCore.Authentication.Google?

I am creating an AspNetCore application with Google authentication. I am deploying this app behind an nginx reverse proxy on an Ubuntu server. Almost everything is working, but I am having trouble with the callback url.

In the Google developer console, I have http://localhost:5000/signin-google set as an authorized redirect URI. This works as expected and allows me to use Google authentication when running from my workstation.

For production, I have https://myserver/signin-google set as an authorized redirect URI. However, when I try to use it, I get an error from accounts.google.com that http://myserver/signin-google (notice the missing s) is not authorized. That's true; it shouldn't be authorized and my server doesn't even respond to port 80 requests.

How can I tell the authentication middleware that I need it to use HTTPS for the callback URL?

like image 806
Fizzbuzz97 Avatar asked Jul 01 '16 19:07

Fizzbuzz97


1 Answers

I finally figured it out.

Step 1: Make sure Nginx is sending the necessary forwarding headers, for example:

server {
    # other stuff ...
    location / {
        # other stuff ...
        proxy_set_header X-Forwarded-Proto $scheme;
        # you could also just hardcode this to https if you only accept https
    }
}

Step 2: By default, AspNetCore will ignore these headers. Install the middleware that processes it:

PM> Install-Package Microsoft.AspNetCore.HttpOverrides

Step 3: in your Configure function, apply the middleware.

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

This should correctly change the Context.Request.Scheme value to https, which will cause the authentication middleware to generate the correct redirect_uri.

like image 181
Fizzbuzz97 Avatar answered Sep 17 '22 22:09

Fizzbuzz97