Traefik can add a simple authentication to your services with a login/password. Indeed, some applications don't have an authentication mechanism, and expose these services can lead to security problems.

Version Date Comments
1 05/2022 Post creation
1.1 08/2023 Update versions, paths and some formulations

Goal : Use basic authentication (HTTP basic auth) with Traefik

Environment : Debian 12, Docker 24.x, docker compose (plugin) 2.20.x, Traefik 2.10.

Execution context :

jho@vmi866042:/opt/docker/dc$ tree
.
├── conf
│   ├── acme.json
│   ├── traefik.yml
│   ├── traefikdynamic
│   │   ├── general.yml
│   │   ├── routersservices.yml
├── docker-compose.yml
└── logs
    ├── traefikAccess.log
    ├── traefik.log
  • path where are every folder and files : /opt/docker/dc
  • path of the principal configuration file for Traefik : /opt/docker/dc/conf/traefik.yml
  • folder where are every dynamic configuration files : /opt/docker/dc/conf/traefikdynamic
  • path of the file which is used to store SSL certificates for let's encrypt (or other provider) : /opt/docker/dc/conf/acme.json
  • folder to store logs : /opt/docker/dc/logs/

To do it, I'm using "dynamic configuration" (more information here)

We will use a "middleware", which execute an operation before accessing the service called. There are some types listed here :

traefik middlewares architecture
Schéma récapitulatif de l'utilisation des middleware dans Traefik

Hash of passwords for Traefik basic authentication is done with MD5, SHA1 or BCrypt. Here, I'm using BCrypt with the website "bcrypt.fr" to generate hashes. You can also use the command htpasswd (it needs the package apache2-utils).

Basic authentication is a login and a password. Only the password needs to be hashed (bcrypt here). Let's add the middleware and let's configure Traefik dashboard with it in the dynamic configuration file (in my example : /opt/docker/traefik/conf/traefikdynamic/dynamic.yml) :

http:
  middlewares:
    authentification:
      basicAuth:
        users: # admin / admin
        - admin:$2y$10$KbBxnjLyBfFi355gJKhgJuXzGUaWbSRvNnvB2R9WDKpLFG1NEdcdi

  routers:
    rt-traefik:
      entryPoints:
      - websecure
      middlewares:
      - authentification
      service: api@internal
      rule: Host (`traefik.rezo.net`)

The user created (admin) have the password "admin". Because of the Traefik dynamic configuration, no need to restart containers. Basic authentication is a very low level of security, this will not replace other security mechanisms.

This middleware can be used on every resource (routers) of your Traefik. Remember to add the name of the middleware in the definitions of your routers to protect.

Partager l'article