OAuth - Hades2323/DockerCore GitHub Wiki

What is OAuth?

OAuth is an open standard for access delegation, commonly used as a way for Internet users to grant websites or applications access to their information on other websites but without giving them the passwords. This mechanism is used by companies such as Amazon, Google, Facebook, Microsoft, and Twitter to permit users to share information about their accounts with third-party applications or websites.” - Wikipedia

Why Traefik Google OAuth2 for Docker Services?

Adding the basic authentication that Traefik provides is the simplest way to protect your docker and non-docker services.

For a single service, this can be useful, but I found it quickly became inconvenient and tedious once I had to sign-in to multiple services and for every browser session.

Google OAuth2 enables you to use your Google account to sign in to your services. Using Google OAuth with Traefik will allow you to whitelist accounts, implement Google’s 2FA, as well as provide a Single Sign-On (SSO) to your services. This not only offers the convenience of not having to sign in frequently but also improves security.

Traefik Forward Auth Alternatives

The thomseddon/traefik-forward-auth image provides Google OAuth authentication. If you prefer other generic OIDC providers, then a good options is the mesosphere/traefik-forward-auth Docker image.

How does Google OAuth2 with Traefik work?

Before configuring Traefik Forward Auth with Google OAuth2, let us see how it all fits together.

Google OAuth login and authentication for Traefik acts like a gatekeeper for your services, allowing or denying access after checking for an authorized cookie in your browser. To sum it up, the process goes something like this:

  1. A request is made for our Host ( e.g.: https://traefik.example.com)
  2. The request is routed by our DNS provider to our WAN IP, where ports 80 and 443 are forwarded to the Traefik container.
  3. Traefik sees the incoming request and recognizes that Forward Auth is defined in the labels for that Host, therefore the request is forwarded to the Traefik Forward Auth container.
  4. The container then checks to see if the browser already has an authorized cookie. If there's no cookie, the request is sent to Google's OAuth2 Authorization Server.
  5. After successfully logging in to Google, the request is sent to the redirect URI identified for the Web Application (https://oauth.example.com/\_oauth).
  6. An authorized cookie is then saved in the browser, and the user is sent to the backend service.

The next time that this browser tries to access a service protected by OAuth-based login and authentication, the cookie will be recognized and the user will be taken to their service, without being prompted to sign in!

Traefik Forward Auth with Google OAuth - Process Flow

This process happens very quickly, and once your browser receives the cookie, you'll forget you've even enabled Google OAuth with Traefik!

Note: The Traefik Forward Auth image uses OpenID Connect (OIDC), which is an authentication layer on top of the OAuth 2.0 protocol. The docker image presented in this guide supports Google and also other OIDC providers.

With the basics taken care of let's move on to setting Google OAuth Traefik forward authentication for our Docker services.

Setting Up Google OAuth with Traefik Forward Authentication

Setting up Google OAuth for Docker using Traefik, involves 3 steps: 1) creating DNS records, 2) configuring Google OAuth2 Service, and 2) modifying Docker compose files and adding the Traefik labels to activate forward authentication.

Let's set up all of the prerequisites now:

Step 1: Create DNS Records

Start by creating a new CNAME DNS record for our OAuth service (Google will redirect to this address after authentication).

If you have a wildcard CNAME (*) set then you do not have to create one specific for OAuth. You may then skip this step.

For clarity, throughout this guide we'll use the domain name example.com.

Set the DNS record as oauth.example.com. The pictures below show a screenshot from Cloudflare. Depending on your DNS provider, things may look different for you but essentially have the same content.

Create DNS Records for Google OAuth2

Create DNS Records for Google OAuth2

Note that DNS records can take several hours to propagate and become active.

Step 2: Configure Google OAuth2 Service

With the DNS records created, let us move on the configuring Google OAuth.

Step 2a: Create a Google Project

We need to create a Google Project that will contain our Web App, Consent Screen, and Credentials.

Navigate to the Google Cloud Developers Console and make sure that you are signed into the correct Google account that you want to use (This will normally be your e-mail address).

Note: Sign out of other active Google accounts to make sure that the correct account is used at each step.

If prompted, you'll need to agree to the Google Cloud Platform Terms of Service to use their API:

Google Terms of Service

Google Terms of Service

It's free to use Google's OAuth service, so we can Dismiss the free trial for now. Click on Select a project and New project.

Create a new Project for OAuth

Create a new Project for OAuth

Enter a unique name to identify the project, such as Traefik Forward Auth. Click Create.

Google Console - Create a New Project

Google Console - Create a New Project

Step 2b: Configure the Consent Screen

Once you click OAuth Client ID, you will see the note to configure the consent screen as shown below. A configuring a consent screen is required before proceeding.

If you're not automatically prompted, select the OAuth consent screen from the left panel.

Choose External for User Type and click Create.

OAuth Consent Screen - External App

OAuth Consent Screen - External App

Choose a name for your app, such as Traefik Auth.

OAuth Consent Screen - App Information

OAuth Consent Screen - App Information

Then, under the Authorized domains section enter your domain, for instance, simplehomelab.com. You may even add multiple domains if you plan to use the same for authentication on multiple domains.

OAuth Consent Screen - Authorized Domains

OAuth Consent Screen - Authorized Domains

Make sure that you press Enter to add it, and then click Save.

Nothing to add or change under Scopes. So Save and Continue.

OAuth Consent Screen - Scope

OAuth Consent Screen - Scope

Again, nothing to add or change for Test Users. So Save and Continue.

OAuth Consent Screen - Test Users

OAuth Consent Screen - Test Users

Finally for the OAuth Consent Screen, check the app registration details and hit Back to Dashboard at the end.

OAuth Consent Screen - App Registration

OAuth Consent Screen - App Registration

On the OAuth Consent Screen Dashboard, Publish the app and confirm Push to production.

OAuth Consent Screen - Publish App to Production

OAuth Consent Screen - Publish App to Production

Step 2c: Create OAuth Credentials

Next, we need to create a client ID and client secret to authenticate with Google. Choose our Traefik Forward Auth project, and under the Navigation menu select APIs & Services > Credentials. Click on Create Credentials > OAuth client ID.

Create OAuth Client ID

Create OAuth Client ID

Step 2d: Create the OAuth client ID

Now select the Web Application type and enter a name for your web application, such as Traefik OAuth.

OAuth Client ID - Application Type (Web)

OAuth Client ID - Application Type (Web)

In addition, you'll need to enter your Authorized redirect URI as https://oauth.simplehomelab.com/\_oauth (or multiple redirect URIs as shown below).

Note: You are only allowed to add redirect URIs that direct to your Authorized Domains (described above). Return to the OAuth consent screen if you need to edit them.

Client ID Web Application Redirect URIs

Client ID Web Application Redirect URIs

Make sure that you press Enter to add it, and then click Save.

The credentials for our Single Sign-on for Docker have been created! Copy and save the client ID and client secret; we'll need to use them in the next step.

Google OAuth Client Credentials (keep it safe!!!)

Google OAuth Client Credentials (keep it safe!!!)

Step 3: Setup Traefik Forward Authentication with OAuth2

Now that the OAuth credentials have been configured, the last thing to do is set up the OAuth container. Sign-in to your local machine

Step 3a: Create Traefik Auth Middleware

Let us now specify a Traefik auth middleware for OAuth2. All authentication will be forwarded to this middleware. Create a file called middlewares-oauth.yml in your Traefik rules folder and add the following contents to it:

the rules folder will be /opt/docker/core/appdata/traefik3/rules/udms**, where udms is the hostname.

http:

  middlewares:

    middlewares-oauth:

      forwardAuth:

        address: "http://oauth:4181" # Make sure you have the OAuth service in docker-compose.yml

        trustForwardHeader: true

        authResponseHeaders:

          - "X-Forwarded-User"

Nothing to customize in the YML above.

Step 3b: Create Traefik OAuth Middleware Chain

We will reuse a few of the middlewares from the Traefik guide: middlewares-rate-limit and middlewares-secure-headers.

Create a file called chain-oauth.yml in your Traefik rules folder and add the following contents to it:

http:

  middlewares:

    chain-oauth:

      chain:

        middlewares:

          - middlewares-rate-limit

          - middlewares-secure-headers

          - middlewares-oauth

In short, we are rate limit and specifying security headers, which are both security measures. Then we are including OAuth2 authentication in the chain (the middleware we created in the previous step). Save the files and exit editing.

Step 3b: Add Traefik Forward Auth Secrets

But, instead of creating multiple secrets, we are going to create one single secret file for Traefik forward auth that contains all the credentials.

Create Secrets Folder

If you haven't already done so, create a folder called secrets in a known location. If you have been following the first install, this would be /opt/docker/core/secrets**. The folder must be owned by root:root and have 600 permission as shown below.

Docker Secrets Folder Permissions

Docker Secrets Folder Permissions

Note that you will have to gain root privileges to navigate or see contents of the secrets folder.

Create Forward auth Secrets

Create a file called oauth_secrets inside the secrets folder and add the following content to it:

providers.google.client-``id``=yourGOOGLEclientID

providers.google.client-secret=yourCLIENTsecret

secret=yourOAUTHsecret

whitelist=yourEMAILaddress1

whitelist=yourEMAILaddress2

Customize the above using the information below:

  • yourGOOGLEclientID and yourCLIENTsecret: Obtained previously in this Traefik Oauth2 guide.

  • yourOAUTHsecret: This is used to sign the cookie and should be random. Generate a random secret with:

    1

    openssl rand -hex 16

    Alternatively, you may use an online service like this one, to generate your random secret.

    08 random oauth secret | SimpleHomelab

    Random OAuth Secret

  • yourEMAILaddress1: Google email ID which will be used to authenticate. Optionally, you may add additional email addresses that are allowed to authenticate (e.g. yourEMAILaddress2; remove this line if you only want to allow one email ID).

Save and exit.

Secret Permissions

Next, let's ensure proper permissions for those using the following command:

sudo chown root:root /home/anand/docker/secrets/oauth_secrets

sudo chmod 600 /home/anand/docker/secrets/oauth_secrets

Next, let us setup the OAuth Forwarder container.

Add OAuth Secrets to Master Docker Compose

Open your master docker compose file for editing. If you have been following the Ultimate docker server series, this might be docker-compose-udms.yml (or whatever you named it to be).

Under secrets section, ensure you define the three secrets we created above:

########################### SECRETS

secrets:

...

  oauth_secrets:

    file: $DOCKERDIR/secrets/oauth_secrets

...

Note that, $DOCKERDIR is the environment variable defined in .env file

Step 4. OAuth Docker Compose

Now that all the configuration part is done. Let us add the Traefik Forward Auth docker compose service.

Just a reminder that Traefik should be up and running at this point.

Create OAuth Docker Compose File

Let's create the OAuth Docker compose file. Head over to the [compose folder] Find the compose file for OAuth and copy the contents.

Create a file called oauth.yml inside $DOCKERDIR/compose/udms. Copy-paste the contents into oauth.yml compose file (pay attention to blank spaces at the beginning of each line).

services:

  # Google OAuth - Single Sign On using OAuth 2.0

  # https://www.simplehomelab.com/google-oauth-with-traefik-docker/

  oauth:

    container_name: oauth

    image: thomseddon/traefik-forward-auth``:``latest

    # image: thomseddon/traefik-forward-auth:2.1-arm # Use this image with Raspberry Pi

    security_opt:

      - no-new-privileges``:``true

    restart: unless-stopped

    # profiles: ["core", "all"]

    networks:

      - t3_proxy

    environment:

      - CONFIG=/config

      - COOKIE_DOMAIN=$DOMAINNAME_00

      - INSECURE_COOKIE=``false

      - AUTH_HOST=oauth.$DOMAINNAME_00

      - URL_PATH=/_oauth

      - LOG_LEVEL=warn # set to trace while testing bypass rules

      - LOG_FORMAT=text

      - LIFETIME=86400 # 1 day

      - DEFAULT_ACTION=auth

      - DEFAULT_PROVIDER=google

    secrets:

      - source``: oauth_secrets

        target: /config

    labels:

      - "traefik.enable=true"

      # HTTP Routers

      - "traefik.http.routers.oauth-rtr.tls=true"

      - "traefik.http.routers.oauth-rtr.entrypoints=websecure"

      - "traefik.http.routers.oauth-rtr.rule=Host(`oauth.$DOMAINNAME_00`)"

      # Middlewares

      - "traefik.http.routers.oauth-rtr.middlewares=chain-oauth@file"

      # HTTP Services

      - "traefik.http.routers.oauth-rtr.service=oauth-svc"

      - "traefik.http.services.oauth-svc.loadbalancer.server.port=4181"

Here are some notes about the Traefik OAuth Docker Compose:

  • We are using the thomseddon/traefik-forward-auth:latest. Use the correct image for your system's architecture. For example, Raspberry Pi has a different image tag.

    Note: This image has not been updated in about 3 years, at the time of writing this guide. It still works. But other developers have forked this image and incorporated some improvements via pull requests. One recently updated image tag appears to be this one: ghcr.io/jordemort/traefik-forward-auth. Feel free to try this one in place of thomseddon/traefik-forward-auth

    .

  • Docker profiles is commented out as explained previously

  • networks: We added OAuth to t3_proxy network.

  • You may also change the duration (LIFETIME) for which the authentication is valid from 1 day specified in seconds to another duration.

  • Initially, set the LOG_LEVEL to trace or debug. Once everything works, you may change it to warn.

  • Optionally, the rest of the environment variables defined for the oauth can be configured to your liking (if you know what you are doing).

  • With the labels, we are specifying that OAuth will use the websecure entrypoint and chain-oauth file provider we created previously.

  • Traefik forward auth listens on port 4181. So, we point oauth-rtr.service to a service name oauth-svc and in the next line, we define where that service is listening at (oauth-svc.loadbalancer.server.port=4181.

Add OAuth to the Docker Stack

We created the oauth.yml file. Now we need to add it to our master docker-compose-udms.yml file. To do so, add the path to the oauth.yml (compose/$HOSTNAME/oauth.yml) file under the include block, as shown below:

...

...

include:

...

  - compose/$HOSTNAME/oauth.yml

...

Save the Master Docker Compose file.

Step 5: Starting OAuth Container

Recreate the stack and follow OAuth container logs using the following commands:

sudo docker compose -f /opt/docker/core/docker-compose-($hostname).yml up -d

sudo docker compose -f /opt/docker/core/docker-compose-($hostname).yml logs -tf --``tail``=``"50" oauth

You should see confirmation that OAuth Docker container started successfully.

Now that OAuth Docker container is up and running. Let us test it out by visiting https://oauth.example.com. You should now be redirected to Google's login and authentication page before reaching the service.

Google OAuth Login for Docker Services

Google OAuth Login for Docker Services

This is confirmation that everything works they should!

Authentication and Conditional Bypassing

Now that we have Google OAuth working with Traefik Forward Auth, let's look at ways to protect apps and also some ways to conditionally bypass authentication.

Putting Docker Services behind OAuth

If you created the OAuth Traefik middleware and middleware chain discussed above, then putting docker services behind Google OAuth 2 authentication is simple. All you need to do is add the following middleware (chain-oauth) to docker-compose labels:

## Middlewares

- "traefik.http.routers.service-rtr.middlewares=chain-oauth@file"

service-rtr could be different for different services.

Putting Non-Docker Services behind OAuth

Home with no Traefik authentication (chain-no-auth). Putting it behind OAuth is as simple as changing the middleware from chain-no-auth to chain-oauth, as shown below:

http:

  routers:

    adguard-rtr:

      rule: "Host(`ag.{{env "```DOMAINNAME_00```"}}`)"

      entryPoints:

        - websecure

      middlewares:

        - chain-oauth

      service: adguard-svc

      tls:

        certResolver: dns-cloudflare

        options: tls-opts@file

  services:

    adguard-svc:

      loadBalancer:

        servers:

          - url``: "http://0.0.0.0:80"

Note that [AdGuard]Home is listening on a non-SSL port. Some services (e.g. NextCloud, UniFi controller, Proxmox etc.) tend to be available via HTTPS protocol with a self-signed certificate.

Since the rules directory is dynamic, simply by adding this file to that directory we have created the route. You should be able to connect to AdGuard Home behind OAuth, without restarting Traefik!

Bypassing OAuth / Selective Authentication

I use the app LunaSea on iOS for remotely managing SABnzbd, Sonarr, Radarr, etc. When these apps are behind OAuth, I could not use these apps remotely using a fully qualified domain name (e.g. https://sonarr.example.com). These apps have no way to authenticate themselves and pass through OAuth.

But, you can bypass authentication based on specific keys in the request Headers, regular expressions, host, path, query, and more.

Note: By using an incorrectly specified rule, you can easily disable authentication when you do not intend to. Therefore, I strongly recommend specific and narrow rules for bypassing authentication.

Identifying Bypass Rule
Specifying OAuth Bypass Rule

Notice the uri in the above log screenshot contains the SABnzbd API key. So you can set the bypass use based on this, as follows:

command: --rule.sabnzbd.action=allow --rule.sabnzbd.rule=```"HeaderRegexp(X-Forwarded-Uri, $SABNZBD_API_KEY`)"``

OAuth Log for Radarr access via NZB360 App

OAuth Log for Radarr access via NZB360 App

For Radarr, Sonarr, Lidarr, etc, you may use the following rule (should work for NZB360 or similar apps):

command: --rule.radarr.action=allow --rule.radarr.rule=```"Header(X-Api-Key, $RADARR_API_KEY`)"``

Restart the OAuth container and try to access SABnzbd now via the app and browser. The browser should present the OAuth login and the App should take you to the service directly.

There are several more ways to specify rules. Check out OAuth Forwarders to GitHub page for all available options.

Final Thoughts Traefik Forward Authentication

Implementing Google OAuth2 with Traefik forward authentication has been one of the easiest and most secure ways for me to protect my docker services. By whitelisting accounts and implementing Google’s 2FA, I have confidence that I will be the only one that's able to access those services.

In addition, I now have an authentication service that allows me to access many of my services with just one login.

As said previously, if you prefer a self-hosted alternative that is more private then [Authelia] is a great option. In fact, in a multi-user environment, it might be easier and more secure to use Authelia. Unlike Traefik Forward Auth with Google OAuth2, Authelia is email-agnostic (not everyone has a Google account).

I hope you enjoyed learning about Google OAuth with Traefik for Docker services!