Adding basic authentication to secure a service with Traefik
A dding authentication to a service that does not support it by default can be done easily by using Traefik. This way you gain an additional layer of security and you can leverage other features of Traefik like domain names.
In this article I will show you how to secure a service in Traefik reverse proxy using basic authentication. You could use the authentication for example to secure your Traefik dashboard. The example can be executed locally which allows simple adjustment to your own needs. Technologies used are only docker and docker-compose. For the purpose of simpler declaration I will not make use of configuration files, but only use docker labels.
A minimalist configuration of Traefik can be seen in the code block below.
80 is exposed end assigned to the
All incoming traffic is now routed through this specific entrypoint.
To keep it simple we use the
whoami image from containous, the company behind Traefik.
We set it up to hook to the just specified entrypoint and tell it to listen to the domain
This way we can easily access it locally.
To secure this service you have to add a middleware of type
auth. With another label we can add basic authentication and specify user credentials. Username and password are separated by a simple colon. You can add multiple users by separating them via semicolon.
For password creation have a look at the next chapter.
This example resolves to the credentials with both username and password
If you now start the service and navigate to
whoami.localhost you will be prompted to type in the credentials.
After successfull login you should be able to access the containers content.
Traefik supports different hash algorithms to secure your services. Most of these hash algorithms like MD5 or SHA-1 are considered unsafe and not recommended for production use. That is why you should stick to brypt.
To create a hashed passphrase you can make use of an online generator. Twelve is the default number of rounds for bcrypt, though Traefik is able to handle any number of rounds. A higher number increases the complexity of encryption which results in a safer hash, but may impact your latency. You can try some numbers to find your sweet spot or simply stick to the default. Make sure to replace all single dollar chars in your hashed password with double ones for escaping.
As always you can check the full source code on GitHub.