Skip to main content

Using Basic Auth in Traefik conditionally

· 2 min read
Stephan Hochdörfer
Head of IT Business Operations

Can we conditionally use Traefik Basic Auth? I don't want to use Basic Auth for requests coming from the same server due to solving an issue with a third-party tool that was not able to deal with URLs containing basic auth credentials.

Usually, it is quite simple: Add the basic auth credentials to your URL like this: http://username:password@hostname - many tools have no issue with this. But this specific tool we had to use in a customer project could not deal with such URLs.

The alternative is to whitelist local requests and give them access without Basic Auth credentials. Since I have never done that with Traefik, I was unsure how to accomplish that task. At first, I thought a more complex rule definition would help, but that did not work the way I needed it.

In the end, the solution is simple: Use two router rules for the same service.

[http.routers.example]
rule = "Host(`example.com`)"
entryPoints = ["web", "websecure"]
service = "nginx"
middlewares = ["basic-auth-middleware"]
priority = 1

[http.routers.example-whitlist]
rule = "Host(`example.com`) && ClientIP(`192.168.1.2`)"
entryPoints = ["web", "websecure"]
service = "nginx"
priority = 2

The rules are sorted by length in descending order by default, with longer rules having the highest priority. Although in this particular case, I could have skipped manually setting the priority, I decided to do so to help me understand the process better in the future.