Welcome to new things

[Technical] [Electronic work] [Gadget] [Game] memo writing

How to use Google Authentication instead of Basic Authentication just by setting up a web server

Basic authentication is an easy way to restrict access to a site.

Basic authentication is convenient, but it is problematic because the browser does not remember the ID and password and you have to enter them each time, or anyone can access the system if they know the ID and password.

I would like to include more proper authentication, but I don't want to go through the trouble of creating an authentication system...

So, I tried to use Google Authentication instead of Basic Authentication just to configure the web server so that only specified Gmail accounts can access the site.

summary

The web server is Nginx, and a reverse proxy called oauth2_proxy is used to handle the authentication process.

When Nginx is accessed, Nginx asks oauth2_proxy if the user is valid, and if the user is valid, the next process, i.e., site display, is performed. If the user is invalid, oauth2_proxy displays an error page.

If a user is not logged in, oauth2_proxy will also perform the tedious login-related tasks, from displaying the login screen to completing the login.

install

  • Since oauth2_proxy is distributed in binary form, download the oauth2_proxy file from the following link.

  • Place "oauth2_proxy" in "/usr/sbin" on the Nginx server and pass it through.

Google Authentication Client Registration

oauth2_proxy uses the Google API to obtain the email address of the user who is logging in, and checks whether that address is the specified user.

To use the Google API, you must register your site with Google as a client to use the Google API.

  1. Create a project with Project Page
  2. [Navigation Menu]-[APIs and Services]-[Authentication Information]
  3. Set "Application Name" in the [OAuth Consent Screen] tab and save
  4. On the [Authentication Information] tab, click [Create Authentication Information] - [OAuth Client ID].
  5. Create it by setting the following on the [Create OAuth Client ID] screen

    • Select "Web Application" under "Application Type."
    • Set "Approved JavaScript Generator" to https://<site domain name>.
    • Set "approved redirect URI" to https://<site domain name>/oauth2/callback.
  6. Note down the "Client ID" and "Client Secret" as they are issued.

Configuration of oauth2_proxy

There are two ways to configure oauth2_proxy: by command line arguments or by a configuration file, but this time we have prepared a configuration file "oauth2_proxy.cfg".

  • Prepare a file "authenticated_emails_file" with a list of email addresses to be allowed access.
  • E-mail addresses can be specified not only individually using files, but also collectively by domain using the "email_domains" setting.
  • Even if you do not transfer (upstream) to other servers, an error will occur if "upstreams" is not registered in some way, so register an appropriate value.

oauth2_proxy.cfg

## <addr>:<port> to listen on for HTTP/HTTPS clients
http_address = "127.0.0.1:4180"

## the OAuth Redirect URL.
redirect_url = "https://<サイトドメイン>/oauth2/callback"

## the http url(s) of the upstream endpoint. If multiple, routing is based on path
upstreams = [
    "http://127.0.0.1:8080/"
]

## The OAuth Client ID, Secret
client_id = "<クライアントID>"
client_secret = "<クライアントシークレット>"

## Email Domains to allow authentication for (this authorizes any email on this domain)
## for more granular authorization use `authenticated_emails_file`
## To authorize any email addresses use "*"
#email_domains = [
#    "<Allowed Address Domain>"
#]

## Authenticated Email Addresses File (one email per line)
authenticated_emails_file = "/etc/nginx/authenticated_emails_file"

## Cookie Settings
## Name     - the cookie name
## Secret   - the seed string for secure cookies; should be 16, 24, or 32 bytes
##            for use with an AES cipher when cookie_refresh or pass_access_token
##            is set
## Domain   - (optional) cookie domain to force cookies to (ie: .yourcompany.com)
## Expire   - (duration) expire timeframe for cookie
## Refresh  - (duration) refresh the cookie when duration has elapsed after cookie was initially set.
##            Should be less than cookie_expire; set to 0 to disable.
##            On refresh, OAuth token is re-validated.
##            (ie: 1h means tokens are refreshed on request 1hr+ after it was set)
## Secure   - secure cookies are only sent by the browser of a HTTPS connection (recommended)
## HttpOnly - httponly cookies are not readable by javascript (recommended)
cookie_name = "_oauth2_proxy"
cookie_secret = "0123456789abcdef"

Nginx configuration

well-known

The "default.conf" that displays the "default.conf" is shown below.

  • At the very beginning of the display process, "auth_request /oauth2/auth" is put in to query "oauth2_proxy" for authorized users before displaying them.
  • If the inquiry results in NG, an error page and login page are displayed.
  • If the query result is OK, the next process is continued, i.e., the display process.

default.conf

server {
    listen 443 default ssl;
    ssl_certificate /etc/nginx/server.crt;
    ssl_certificate_key /etc/nginx/server.key;

    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;
        # nginx auth_request includes headers but not body
        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;

        # if you enabled --cookie-refresh, this is needed for it to work with auth_request
#        auth_request_set $auth_cookie $upstream_http_set_cookie;
#        add_header Set-Cookie $auth_cookie;

        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
}

The above is a static page, so nothing special is done. However, if the page is upstream to another server or dynamic, you may need to configure "auth_request_set" and other settings that are commented out. Please refer to oauth2_proxy website for details.

launch

Docker was used to configure and start the system.

Executing the oauth2_proxy binary is persistent, so I run the shell scripts [Nginx] -> [oauth2_proxy] in that order.

The Dockerfile and shell script will look like the following

Dockerfile

FROM nginx:alpine

RUN apk update
RUN apk add bash
RUN apk add ca-certificates
RUN rm -rf /var/cache/apk/*

COPY default.conf /etc/nginx/conf.d/
COPY server.crt /etc/nginx/
COPY server.key /etc/nginx/

COPY oauth2_proxy /usr/sbin/
COPY oauth2_proxy.cfg /etc/nginx/
COPY authenticated_emails_file /etc/nginx/

COPY start.sh /root/
CMD ["/root/start.sh"]

start.sh

#!/bin/bash

nginx
oauth2_proxy -config=/etc/nginx/oauth2_proxy.cfg

After that, you can launch Nginx with Docker, and your access-restricted site with Google authentication is complete.

When you access the site for the first time, you will see the login page as shown below.

button will forward you to the Google login screen, and "Welcome to nginx!" will appear after login.

Other

The default authentication for oaut2_proxy is Google, but it also supports Office365 (Azure), Facebook, GitHub, etc.

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com

www.ekwbtblog.com