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 Comment
1 05/2022 Post creation

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

Environment : Debian 11.2 (bullseye), Docker 20.10.x, docker-compose 2.4.x, Traefik 2.6

To do it, I'm using "dynamic configuration" (more information on this site 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