Allow access from one IP, require basic auth from all other sources

Hello!

I'd like to allow access to Traefik from one IP and require basic auth from all other sources; Is there any way to skip basic auth if the IP matches?

In Apache htaccess we could do something like this

AuthType Basic
AuthName "Password Required"
AuthUserFile "/path/to/.htpasswd"
Require valid-user
Require expr %{REMOTE_ADDR} = "123.123.123.123"

This would allow access from any user that can authenticate against the .htpasswd file or requests coming from 123.123.123.123.

Is there anything like this in Traefik?

Thanks in advance!

Hello @kevingimbel,

One simple use case, could be:

version: '3.6'

services:
  traefik:
    image: traefik:v2.6
    command:
      - --providers.docker
    ports:
      - "80:80"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock

  whoami:
    image: traefik/whoami
    labels:
      traefik.http.routers.whoami-ip.rule: Host(`whoami.localhost`) && ClientIP(`127.0.0.1`)

      traefik.http.routers.whoami-auth.rule: Host(`whoami.localhost`)
      traefik.http.routers.whoami-auth.middlewares: test-auth

      traefik.http.middlewares.test-auth.basicauth.users: root:$$apr1$$J.oefIGs$$HnlqmKtI8B6xKYYA1WbEc. #root:root

Here, I define 2 routers.
The first one filters IP and match only a given IP. So, requests coming from this IP will have to be authenticated.
The second one, with a lower priority, will match all other requests going to this service. This second router uses the test-auth middleware that ensure that requests are authenticated to be served.

Hope it helps :slight_smile:

1 Like

Thank you a lot, this looks exactly like what I needed! I'll test this on our infra and then mark as solution once I verify it works! :tada:

1 Like

I was finally able to test this and it works! We had some issues with the basic auth which was defined for the entrypoint instead of the routes, but after reconfiguring that it worked.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.