Tired of all your docker services having their authentication system? For those that don't, do you hate Traefik's basic auth? Then, read on to setup up Google OAuth2 with Traefik Forward Auth. Enjoy the convenience of a secure single-sign-on for your Docker services.
In fact, on all my services, I prefer Google OAuth over Authelia just because I am usually signed into the Google ecosystem for various things. This means significantly fewer login prompts for me. This guide is an updated version of my previous Traefik OAuth guides published in 2019, 2020, and 2022.
As you may know, I am a big fan of Docker and Traefik. I have covered this in detail in my Ultimate Docker Server series:
Ultimate Docker Server Series:
This post is part of the Docker Server Tutorial Series, which includes the following individual chapters/parts:- Ultimate Docker Server: Getting Started with OS Preparation [VIDEO] [2024]
- Docker Media Server Ubuntu/Debian with 60+ Awesome Apps [VIDEO] [2024]
- ZeroTier VPN Ubuntu, Docker, Synology, Windows: Secure on-the-go access [coming soon]
- Nginx Proxy Manager Docker Compose Guide: Simplest Reverse Proxy [coming soon]
- Traefik Reverse Proxy
- Authelia Docker Compose Guide: Secure 2-Factor Authentication [VIDEO] [2024]
- Google OAuth Docker Compose Guide: Multi-Factor Authentication [VIDEO] [2024]
- Docker Security Practices for Homelab: Secrets, Firewall, and more
- Cloudflare Settings for Docker Traefik Stacks
- Implementing a Backup System for Docker Traefik Stack [coming soon]
- Automate Homelab Setup Deployarr: 60+ Apps in Minutes
If you're already running Docker-based Media Server behind a Traefik reverse proxy, then this is a logical next step. [Read: Podman vs Docker: 6 Reasons why I am HAPPY I switched]
Table of Contents
- What is OAuth?
- Setting Up Google OAuth with Traefik Forward Authentication
- Authentication and Conditional Bypassing
- OAuth and Security Headers
- Membership Required
- FAQs
- Final Thoughts Traefik Forward Authentication
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
If you prefer a private self-hosted (rather than relying on Google) multi-factor authentication system, then look into Authelia. I use Authelia for certain services.
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.
In addition, there are more alternatives such as Keycloak and Authentik.
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:
- A request is made for our Host ( e.g.: https://traefik.simplehomelab.com)
- The request is routed by our DNS provider to our WAN IP, where ports 80 and 443 are forwarded to the Traefik container.
- 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.
- 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.
- After successfully logging in to Google, the request is sent to the redirect URI identified for the Web Application (https://oauth.simplehomelab.com/_oauth).
- 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!
This process happens very quickly, and once your browser receives the cookie, you'll forget you've even enabled Google OAuth with Traefik!
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
If you prefer to follow a video guide instead, check out my YouTube video:
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).
For clarity, throughout this guide we'll use the domain name simplehomelab.com.
Set the DNS record as oauth.simplehomelab.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.
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. This process is very similar to what is described in our guide on setting up Google Assistant for Home Assistant.
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).
If prompted, you'll need to agree to the Google Cloud Platform Terms of Service to use their API:
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.
Enter a unique name to identify the project, such as Traefik Forward Auth. Click Create.
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.
Choose a name for your app, such as Traefik Auth.
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.
Make sure that you press Enter to add it, and then click Save.
Nothing to add or change under Scopes. So Save and Continue.
Again, nothing to add or change for Test Users. So Save and Continue.
Finally for the OAuth Consent Screen, check the app registration details and hit Back to Dashboard at the end.
On the OAuth Consent Screen Dashboard, Publish the app and confirm Push 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.
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.
In addition, you'll need to enter your Authorized redirect URI as https://oauth.simplehomelab.com/_oauth (or multiple redirect URIs as shown below).
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.
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, or use one of the several awesome SSH clients to sign in remotely.
Be the 1 in 200,000. Help us sustain what we do.Join Us (starting from just $1.67/month)
The assumption is that you have already read and followed most of my Traefik 2 guide and are reading this post just to implement Google OAuth.
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:
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
Again, building on my Traefik guide, let's build the middleware chain for OAuth.
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
If you do not understand what this does, then I suggest reading my Traefik guide.
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
With revision and as with my Ultimate Docker Guide 2024, I am taking secure approach from the beginning. So, let's pass sensitive information as Docker 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 my guides, this would be /home/anand/docker/secrets. The folder must be owned by root:root and have 600 permission as shown below.
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:
openssl rand -hex 16
Alternatively, you may use an online service like this one, to generate your random 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 to represent /home/anand/docker.
If you have any questions on where exactly this is added, check out the compose files in my GitHub Repo.
We have now completed 2 of the 4 steps in adding secrets. We will perform the remaining 2 steps when we create the OAuth Docker Compose file.
Step 4. OAuth Docker Compose
Now that all the configuration part is done. Let us add the Traefik Forward Auth docker compose service.
Create OAuth Docker Compose File
Let's create the OAuth Docker compose file. Head over to the compose folder in my Github Repository, and then into any of the host folders. Find the compose file for OAuth and copy the contents.
Create a file called oauth.yml inside /home/anand/docker/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.smarthomebeginner.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_HS - INSECURE_COOKIE=false - AUTH_HOST=oauth.$DOMAINNAME_HS - 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_HS`)" # 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 (see my Docker guide for how I use profiles).
- 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/udms/oauth.yml) file under the include block, as shown below:
... ... include: ... - compose/$HOSTNAME/oauth.yml ...
$HOSTNAME here will be replaced with udms automatically (as defined in the .env file).
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 /home/anand/docker/docker-compose-udms.yml up -d sudo docker compose -f /home/anand/docker/docker-compose-udms.yml logs -tf --tail="50" oauth
You should see confirmation that OAuth Docker container started successfully. [Read: Dozzle Docker Compose: Simple Docker Logs Viewer]
Now that OAuth Docker container is up and running. Let us test it out by visiting https://oauth.simplehomelab.com. You should now be redirected to Google's login and authentication page before reaching the service.
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. As always, check the docker-compose files in GitHub repo for working examples.
Putting Non-Docker Services behind OAuth
Adding non-docker apps or apps from docker host or external hosts is also quite simple using file providers, as previously explained in my Traefik guide.
Let's take the same example of Adguard Home running on Raspberry Pi, as in my Traefik guide.
Previously, we had AdGuard 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_HS"}}`)" entryPoints: - websecure middlewares: - chain-oauth service: adguard-svc tls: certResolver: dns-cloudflare options: tls-opts@file services: adguard-svc: loadBalancer: servers: - url: "http://192.168.1.225: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. For these, be sure to refer to my guide on putting HTTPS apps behind Traefik.
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 NZB360 app on Android and 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.simplehomelab.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.
Identifying Bypass Rule
How can we figure out what specific rules to use?
This can be quite tricky. As discussed in the link below, a generic way to bypass authentication would be using the path. For example, NZB360 app requests have /api in the path. You may disable authentication for all those requests.
But this can loosen the security and I recommend setting specific rules. For example, if the request header contains the SABnzbd API key then bypass authentication.
Then the next question, how did I know to look for SABnzbd API key? This requires some trial and error.
First, ensure SABNzbd is behind OAuth. Then set the OAuth container's log level to trace in the environmental variable:
LOG_LEVEL: trace
Then check the docker logs for the OAuth container (Basic Docker Commands). This will spit out pretty much everything going on in that container, which can be overwhelming. You can trim this down to your app of interest by piping in the grep sabnzbd command.
sudo docker-compose -f ~/docker/docker-compose-t2.yml logs sabnzbd logs -tf --tail="50"
Now when I try to open SABnzbd through the app of interest, in my case NZB360, it creates an OAuth log entry like the one below.
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`)"
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`)"
For the full docker-compose, check my GitHub Repo. All the above codes assume that you followed my previous Traefik guide and that the API keys are defined correctly in your .env file. Otherwise, the above rules won't work.
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.
Alternative Bypass Methods
Although OAuth Forwarder allows bypassing, I do not use the above method (hence why all the OAuth bypass rules are commented out in the compose files in my GitHub repo). I leverage custom headers to let Traefik handle the bypassing instead of the authentication service.
Traefik has built-in mechanisms for conditional bypassing. Depending on certain conditions, I can specify a different middleware or a middleware chain. This is explained in detail in my separate guide on Traefik Auth bypass.
Several apps in my GitHub repo have auth bypasses set based on certain conditions.
OAuth and Security Headers
One thing to note about using the Traefik OAuth2 service is your security headers. If the service is behind OAuth and you’re trying to check whether your security headers are applied, you will probably receive a lower rating.
FAQs
What is traefik-forward-auth-provider?
Traefik forward auth is as service that integrates with a third-party authentication provider (e.g. Google, Microsoft, Authelia, etc.) to secure your services and web applications.
Is traefik-forward-auth-provider popular?
Yes, Traefik forward auth provider is popular among Traefik and Docker enthusiasts. It makes securing applications with strong authentication system, very easy.
What is the difference between OIDC and OAuth?
OIDC or OpenID Connect (OIDC) is a protocol for authentication. It is a set of specifications based on OAuth 2.0, which adds extra features. In essence, OIDC is the authentical protocol while OAuth is the set of specifications for resource access and sharing.
Are there other (more private) alternatives to Google OAuth?
How do I sign out of my services that use Google OAuth2?
If you need to logout, sign out from your google services in any other tab/window and your OAuth for services will be invalidated.
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! If you have any questions feel free to leave a comment below.