Single Sign-on with Nginx

Fri, Jul 20, 2018 One-minute read

In this post i’ll show how to use nginx as a reverse proxy to use single sign-on by Google oAuth2.

First of all we need to get github/bitly/oauth2Proxy thats will become our authenticator for communicating google api.

After that we need to create oAuth2 api from google console.

After that we get our client id and secret key.

Now we need to configure our nginx for act reverse proxy so our service become request -> nginx -> sso – > backend.

server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /usr/share/nginx/html;
location /oauth2/ {
    proxy_pass       http://127.0.0.1:4180;
    proxy_set_header Host                    $host;
    proxy_set_header X-Real-IP               $remote_addr;
    proxy_set_header X-Scheme                $scheme;
    proxy_set_header X-Auth-Request-Redirect $request_uri;
  }
  location = /oauth2/auth {
    proxy_pass       http://127.0.0.1:4180;
    proxy_set_header Host             $host;
    proxy_set_header X-Real-IP        $remote_addr;
    proxy_set_header X-Scheme         $scheme;
    proxy_set_header Content-Length   "";
    proxy_pass_request_body           off;
  }

    location / {
    
    auth_request /oauth2/auth;
    error_page 401 = /oauth2/sign_in;
    auth_request_set $user   $upstream_http_x_auth_request_user;
    auth_request_set $email  $upstream_http_x_auth_request_email;
    proxy_set_header X-User  $user;
    proxy_set_header X-Email $email;

    auth_request_set $auth_cookie $upstream_http_set_cookie;
    add_header Set-Cookie $auth_cookie;

    proxy_pass http://127.0.0.1:8080/; #assume our backend service at localhost 8080 port
  }

After that configuration is done we should start our proxy with keys and ids.

./oauth2_proxy \
   --email-domain="webischia.com"  \
   --upstream=http://127.0.0.1:80/ \
   --cookie-secure=true \
   --client-id=*** \
   --client-secret=***

Thats it now you can join with your email-domain to your website.