Basic HTTP Auth with Traefik

banner-http-auth-traefik-1
banner-http-auth-traefik-1

No way, two posts on one day!

Starting up a container with Docker, and exposing it via a hostname using Traefik is something that a lot of us are familiar with, however something that I myself did not realise, is that you can actually do basic HTTP auth on frontends that are registered with Traefik.

Why would you want to do this? I realise that there are much better ways to do auth apart from HTTP auth, however in a situation where you simply need to make sure that a user has some sort of password prompt before being given access to a service, (such as a web interface to something) then HTTP auth can be very effective.

How would you go about this? Well, you simply start your service in Docker, and in your service create tags, you establish your HTTP auth, let me show you an example below and go through it line by line:

docker service create \ --network traefik \ - attaches the service to the traefik network --name httpd \ - names the service --label "traefik.port=80" \ - exposes the frontend on port 80 --label "traefik.frontend.rule=Host:authtest.devinsmith.co.za" \ - attaches this specific hostname to the traefik service. --label "traefik.docker.network=traefik" \ - tells traefik to use the traefik network --label"traefik.frontend.auth.basic= "blogvisitor:\$apr1\$reTMWX1Z\$UZ6OO5PRvHVta9uWR97ui/"" \ - establishes the frontend basic http auth that I am describing in this post httpd:latest

Things to note:

  • The password for the frontend auth is encoded using htpasswd, the command I used to encode it on my Mac is htpasswd -nb blogvisitor:blog123. The format for passing the authentication to traefik is User:Pass.
  • I had to escape the $ characters in the password using \ in order for things to work correctly.

As you can see from the command above, I published this service here and I will leave it up so that you can visit that and see how it works.

The test authentication details are in the htpasswd encode command that I used ;).

I should be expanding this post in future to encompass timeout and other details on the authentication, however for the moment, check out the example and let me know what you think.

–Devin

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy