/Google OIDC Auth

Google OIDC Auth

29
v0.5.0

Traefik Google OIDC Auth Middleware

This is a Traefik middleware plugin that authenticates users with Google OpenID Connect, and then checks that their email address or Google Workspace domain is authorized.

Requirements

  • Setup a new project in the Google API console to obtain a client ID and client secret. See the Google developer docs.
  • Install the plugin to Traefik using static config.
  • Configure the middleware in dynamic config.
  • Associate a service to the middleware.
  • Allow Traefik to make outbound HTTPS requests to oauth2.googleapis.com and www.googleapis.com. The middleware exchanges the login code at the first host. It downloads Google's public signing keys from the second host to verify each ID token, and caches the keys for the lifetime that Google states. Logins fail if either host is not reachable.

Configuration

OptionDefaultRequiredDescription
oidc.clientIDXOAuth client ID
oidc.clientSecret**OAuth client secret. Not recommended. Traefik shows this value in clear text in its dashboard, API, and debug log. Use oidc.clientSecretFile.
oidc.clientSecretFile**Recommended. Path to a file that contains the OAuth client secret. See Reading secrets from files.
oidc.callbackPath/oidc/callbackThe path where the OIDC provider will redirect the user after authenticating.
oidc.redirectHostOptional host override for the OIDC redirect URI. Use this to configure a single, central redirect URI for multiple subdomains (e.g., auth.example.com). Requires cookie.domain to be set for cookie sharing.
oidc.returnURLOriginsOptional list of sites that users can be sent back to after login. It applies only when oidc.redirectHost is set. If the list is empty, any site at cookie.domain or one of its subdomains is allowed. If the list is set, only the listed sites are allowed. Write each entry as scheme and host, plus the port if it is not the default, e.g., ["https://app1.example.com", "https://app2.example.com:8443"]. Do not add a path, wildcard, or trailing slash. http:// entries require cookie.insecure to be true. See Post-login return URLs.
oidc.promptA space-delimited, case-sensitive list of prompts to present the user. Possible values are: none, consent, select_account. See Google's docs for more info.
cookie.nameoidc_authName of the cookie. It can be customized to avoid collisions when running multiple instances of the middleware.
cookie.path/You can use this to limit the scope of the cookie to a specific path. Defaults to '/'.
cookie.secret**The HMAC key for cookie signing, which gives integrity protection to cookies. Not recommended. Traefik shows this value in clear text in its dashboard, API, and debug log. Use cookie.secretFile.
cookie.secretFile**Recommended. Path to a file that contains the HMAC key for cookie signing, which gives integrity protection to cookies. See Reading secrets from files.
cookie.duration24hValidity period for new cookies. Users are granted access for this length of time regardless of changes to user's account in the OIDC provider. Removing a user in Google does not invalidate an existing cookie, so keep this short relative to how quickly you need access revoked. Uses the Go time.Duration format.
cookie.insecurefalseSet to true to omit the Secure attribute from cookies.
cookie.sameSiteLaxSameSite attribute for cookies. Options: Strict, Lax, None. Lax provides CSRF protection while allowing cookies on top-level navigation.
cookie.domainDomain attribute for cookies. Use this to share cookies across subdomains (e.g., .example.com). Must start with a dot. Required when using oidc.redirectHost.
authorized.emails*List of allowed email addresses.
authorized.domains*List of allowed domains. This is matched against the hd claim of the user's Google Workspace account.
authorized.allowAllAuthenticatedUsersfalse*Grant access to any user who can authenticate with the OAuth client, without checking authorized.emails or authorized.domains. Cannot be combined with those options. See Allowing all authenticated users.
debugfalseEnable debug logging to stdout.

* One of authorized.emails, authorized.domains, or authorized.allowAllAuthenticatedUsers must be set. emails and domains can be used together. allowAllAuthenticatedUsers cannot be used with either list. The middleware will not start if none of them is set.

** Each secret is required. Set the file option (recommended) or the inline option, not both. See Reading secrets from files.

Post-login return URLs

After a user signs in with Google, the middleware sends them back to the page they first asked for. The middleware limits where that return trip can go, so that a login cannot be used to send a user to a site you do not control.

Without oidc.redirectHost

There is nothing to configure. The user always returns to the same site where the login started. The middleware remembers only the path and query of the original page (for example, /reports?year=2026) and never a host name, so the X-Forwarded-Host header cannot change the destination.

With oidc.redirectHost (central callback)

The login finishes on one host, such as auth.example.com, and the user must then be sent to a different host, such as app1.example.com. The middleware decides which hosts are acceptable in one of two ways:

ModeHow to select itWhere users can be sent after login
Domain-based (default)Leave oidc.returnURLOrigins unsetcookie.domain and any of its subdomains. With .example.com, that is example.com, app1.example.com, a.b.example.com, and so on.
Exact listSet oidc.returnURLOriginsOnly the sites in the list.

Domain-based is the convenient choice. A new application on the domain works without a change to the middleware configuration. Use it only if you trust every host under cookie.domain. A host does not have to be protected by this middleware to receive a redirect, so an abandoned or third-party-hosted subdomain is also a valid destination.

Exact list is the strict choice. The list replaces the domain-based rule, so you must add every site you protect, and update the list each time you add a site. Include the callback host itself if it also serves protected pages.

How to write an entry in oidc.returnURLOrigins

Each entry is an origin: the scheme, the host, and the port if it is not the default one. The middleware compares entries to the browser's address as exact text. A browser sends the host in lowercase and leaves out the default port, so an entry must do the same.

EntryAcceptedReason
https://app1.example.comYes
https://app1.example.com:8443YesA non-default port must be included.
https://app1.example.com/NoNo trailing slash.
https://app1.example.com/adminNoNo paths. The whole site is allowed or it is not.
https://*.example.comNoNo wildcards. Use the domain-based mode instead.
https://App1.Example.comNoThe host must be lowercase.
https://app1.example.com:443NoLeave out the default port (443 for https, 80 for http).
http://app1.example.comNoAccepted only when cookie.insecure is true.

In both modes, http destinations are allowed only when cookie.insecure is true. The middleware will not start if an entry is not valid.

What users see when a destination is rejected

  • If the destination is not allowed, the middleware responds with 400 Invalid return URL and does not start the login. It does the same for a request path that a browser could read as another host. Such a path starts with // or /\. With debug enabled, the log shows the rejected host and the reason.
  • The middleware checks the destination a second time when the user comes back from Google. If that check fails, the response is 401 Not authorized.
  • A login that was in progress while you upgraded to this version can fail the second check. The user only has to open the page again.

What these checks do not cover

  • Both modes look only at the host name. Neither one confirms that the host is actually behind this middleware. Attach the middleware only to the Traefik routers you intend to protect.
  • The destination is built from the X-Forwarded-Proto and X-Forwarded-Host headers that Traefik sets. If Traefik is configured to trust these headers from another proxy, that proxy must set them correctly.
  • Register only the callback URLs you use with the OIDC provider.

Headers

X-Forwarded-User

When the middleware proxies a request it adds an X-Forwarded-User header containing the user's email address. This can be used by the downstream service to identify the authenticated user.

If you want your JSON access logs to include the user's email address then configure the access log to retain the X-Forwarded-User header. Here is a CLI example:

# Adding X-Forwarded-User to JSON access logs.
--accesslog
--accesslog.format=json
--accesslog.fields.headers.names.X-Forwarded-User=keep

The resulting access log will contain a request_X-Forwarded-User field.

"request_X-Forwarded-User": "[email protected]"

See Limiting the Fields/Including Headers for more details.

Example config

Static config

# traefik.yml
experimental:
plugins:
google-oidc-auth-middleware:
moduleName: "github.com/andrewkroh/google-oidc-auth-middleware"
# Populate this with the latest release tag.
version: vX.Y.Z

Dynamic config

# dynamic.yml
http:
middlewares:
oidc-auth:
plugin:
google-oidc-auth-middleware:
oidc:
clientID: example.apps.googleusercontent.com
clientSecretFile: /run/secrets/oidc_client_secret
cookie:
secretFile: /run/secrets/oidc_cookie_secret
authorized:
emails:
domains:
- example.com
routers:
my-router:
rule: host(`localhost`)
service: service-foo
entryPoints:
- web
middlewares:
- oidc-auth

Reading secrets from files

We recommend that you always use oidc.clientSecretFile and cookie.secretFile. The inline oidc.clientSecret and cookie.secret options continue to work for existing configurations, but they are not safe. Traefik does not treat plugin configuration as secret, and it shows the inline values in clear text in:

  • the Traefik dashboard and API (for example /api/http/middlewares and /api/rawdata),
  • the Traefik log at the DEBUG level, which prints the dynamic configuration,
  • the place where the configuration is kept, for example the container labels that docker inspect shows.

A person who has the cookie secret can make a valid cookie for any email address. With the file options, Traefik shows only the paths.

The files must be readable by the Traefik process. With Kubernetes, mount them from a Secret volume. With Docker Compose, use secrets:

# docker-compose.yml
secrets:
oidc_client_secret:
file: ./secrets/oidc_client_secret
oidc_cookie_secret:
file: ./secrets/oidc_cookie_secret
services:
traefik:
image: traefik:v3
secrets:
- oidc_client_secret
- oidc_cookie_secret

Compose mounts each secret at /run/secrets/<name>, which are the paths in the example config.

  • A file option and its inline option cannot be set together. An inline value that is left in the configuration stays visible, so the middleware does not start and the error names the option to remove.
  • White space at the start and the end of the file content is removed, so a file that ends with a newline works.
  • The middleware does not start if a file is missing, cannot be read, is empty, or is larger than 64 KiB.
  • The files are read when Traefik creates the middleware. A change to a file has no effect on a middleware that is in operation. Restart Traefik after you change a secret.

Allowing all authenticated users

Set authorized.allowAllAuthenticatedUsers: true to grant access to any user who can complete the OAuth flow with your OAuth client. The middleware does not check an allowlist in this mode.

Use this option only when the OAuth client itself restricts who can authenticate. For example, a Google OAuth client whose user type is set to Internal lets only members of your Google Workspace organization sign in. If the client is External, this option gives access to every Google account on the internet.

Authentication is not changed by this option. Users still need a valid, signed, unexpired cookie, Google must report the email address as verified, and the X-Forwarded-User header is still set.

When the option is enabled, the middleware always writes a warning to the Traefik log at startup, even when debug is false.

We still recommend that you set authorized.domains instead of this option when you can, as defense in depth. You can change the client's audience from Internal to External with one setting in the Google Cloud console, and that change leaves no trace in your Traefik configuration. A domain allowlist continues to protect you if that happens.

If your Workspace organization has secondary domains, note that Google sets a different hd claim for each domain. You must list each domain in authorized.domains.

# dynamic.yml
http:
middlewares:
oidc-auth:
plugin:
google-oidc-auth-middleware:
oidc:
# This OAuth client must be restricted to an internal audience.
clientID: example.apps.googleusercontent.com
clientSecretFile: /run/secrets/oidc_client_secret
cookie:
secretFile: /run/secrets/oidc_cookie_secret
authorized:
allowAllAuthenticatedUsers: true

Multi-Subdomain Configuration

When protecting multiple subdomains (e.g., app1.example.com, app2.example.com, app3.example.com) under the same parent domain, you can configure a single central redirect URI instead of registering each subdomain individually with your OAuth provider.

Configuration

This feature requires two settings:

  1. oidc.redirectHost: Set this to a central host that will handle all OIDC callbacks (e.g., auth.example.com)
  2. cookie.domain: Set this to share cookies across all subdomains (e.g., .example.com)

Optionally set oidc.returnURLOrigins to limit users to an exact list of return origins rather than any host within cookie.domain.

Example

# dynamic.yml
http:
middlewares:
oidc-auth:
plugin:
google-oidc-auth-middleware:
oidc:
clientID: example.apps.googleusercontent.com
clientSecretFile: /run/secrets/oidc_client_secret
redirectHost: auth.example.com # Central callback host
# Optional: restrict post-login redirects to these exact origins.
# Without this list, any host within .example.com is allowed.
# returnURLOrigins:
# - https://app1.example.com
# - https://app2.example.com
# - https://app3.example.com
callbackPath: /oidc/callback
cookie:
secretFile: /run/secrets/oidc_cookie_secret
domain: .example.com # Share cookies across *.example.com
authorized:
emails:
domains:
- example.com
routers:
# Router for the central callback host
auth-callback:
rule: Host(`auth.example.com`) && Path(`/oidc/callback`)
service: noop@internal
entryPoints:
- web
middlewares:
- oidc-auth
#tls: ...
# Routers for protected subdomains
app1:
rule: Host(`app1.example.com`)
service: service-app1
entryPoints:
- web
middlewares:
- oidc-auth
app2:
rule: Host(`app2.example.com`)
service: service-app2
entryPoints:
- web
middlewares:
- oidc-auth
app3:
rule: Host(`app3.example.com`)
service: service-app3
entryPoints:
- web
middlewares:
- oidc-auth

Google OAuth Setup

In your Google OAuth console, you only need to register one authorized redirect URI:

https://auth.example.com/oidc/callback

Instead of having to register:

  • https://app1.example.com/oidc/callback
  • https://app2.example.com/oidc/callback
  • https://app3.example.com/oidc/callback

How It Works

  1. User visits https://app1.example.com
  2. Middleware redirects to Google OAuth with redirect_uri=https://auth.example.com/oidc/callback
  3. User authenticates with Google
  4. Google redirects to https://auth.example.com/oidc/callback
  5. Middleware sets a cookie with Domain=.example.com (shared across all subdomains)
  6. Middleware redirects user back to original URL: https://app1.example.com
  7. User can now access any subdomain without re-authenticating (cookie is shared)

Requirements

  • All protected sites must be under the same eTLD+1 (e.g., *.example.com)
  • Sharing cookies across different apex domains (e.g., example.com vs example.org) is not supported