How to Enable Basic Auth and Whitelists in Traefik
Introduction
BasicAuth allows you to protect your services with a simple username and password prompt. IPAllowList restricts access to specific IP addresses or ranges. Both can be defined entirely through Docker labels.
Basic Auth
Traefik expects credentials in htpasswd format. You can generate them with the htpasswd utility:
htpasswd -nB username
You will then be prompted to enter a password. This outputs a string like username:$2y$05$hash....
In Docker Compose labels, dollar signs need to be escaped by doubling them ($$). Store this hash
as an environment variable. BASIC_AUTH_USER_PASS is used in this example.
To apply basic auth to a service, define the middleware and attach it to the router using Docker labels:
labels:
- "traefik.enable=true"
- "traefik.http.routers.myservice.rule=Host(`myservice.example.com`)"
- "traefik.http.routers.myservice.entrypoints=websecure"
- "traefik.http.routers.myservice.tls=true"
- "traefik.http.routers.myservice.tls.certresolver=cloudflare"
# Define the basic auth middleware
- "traefik.http.middlewares.myservice-auth.basicauth.users=${BASIC_AUTH_USER_PASS}"
# Attach middleware to the router
- "traefik.http.routers.myservice.middlewares=myservice-auth@docker"
The basicauth.users label accepts a comma-separated list if you need multiple users.
You can also add basicauth.headerField=X-Remote-User to forward the authenticated
username to the backend service as a header.
IP Whitelists
The IPAllowList middleware restricts access to a service based on the client's IP address.
labels:
- "traefik.http.middlewares.local-only.ipallowlist.sourcerange=192.168.1.0/24"
If Traefik is behind a load balancer or CDN, the client IP seen by Traefik will be the proxy's address rather than the real client. To handle this, configure the entrypoint to trust forwarded headers from your upstream proxy:
command:
- "--entrypoints.websecure.forwardedheaders.trustedips=127.0.0.1"
This tells Traefik to read the real client IP from the X-Forwarded-For header when the
request comes from a trusted source. Without this, the whitelist would match against the proxy's IP
and either allow or block all traffic.
Combining Middlewares
labels:
- "traefik.http.middlewares.myservice-auth.basicauth.users=${BASIC_AUTH_USER_PASS}"
- "traefik.http.middlewares.local-only.ipallowlist.sourcerange=192.168.1.0/24"
- "traefik.http.routers.myservice.middlewares=local-only@docker,myservice-auth@docker"
Traefik evaluates middlewares in the order they are listed. In this case, the IP check runs first — if the request is from an IP outside the allowed range, it is rejected before the auth prompt is reached.