Traefik & Grafana: auto-login based on source IP

If you want to automatically (or force a specific) login requests to Grafana coming from a given source IP with Traefik, you can do it with a separate router and a middleware. This requires basic authentication to be enabled on grafana (it is by default).

Suppose you start with a default Traefik configuration exposing your grafana to anyone on

      - "traefik.enable=true"
      - "traefik.http.routers.grafana.rule=Host(``)"
      - "traefik.http.routers.grafana.service=grafana"
      - "traefik.http.routers.grafana.tls=true"
      - "traefik.http.routers.grafana.tls.certresolver=myresolver"
      - "traefik.http.routers.grafana.entrypoints=websecure"
      - ""

To force requests coming from the IP to be authenticated as the foobar user, add the following labels after enabling traefik and before the router grafana:

      - "traefik.http.routers.grafana-1_1_1_1.rule=Host(``) && ClientIP(``)"
      - "traefik.http.routers.grafana-1_1_1_1.service=grafana"
      - "traefik.http.routers.grafana-1_1_1_1.middlewares=grafana-1_1_1_1-autologin"
      - "traefik.http.routers.grafana-1_1_1_1.tls=true"
      - "traefik.http.routers.grafana-1_1_1_1.tls.certresolver=letsencrypt"
      - "traefik.http.routers.grafana-1_1_1_1.entrypoints=websecure"
      - "traefik.http.middlewares.grafana-1_1_1_1-autologin.headers.customrequestheaders.Authorization=Basic Zm9vYmFyOnBhc3N3b3Jk"

A quick explanation: this new router grafana-1_1_1_1 is used if the requested hostname is and the source IP is . If it is used, we use the middleware grafana-1_1_1_1-autologin which adds a header to all requests. The username/password is hardcoded and uses basic auth. The rest of the configuration is identical to the default router.

If the source IP is not, then the default router grafana is used and the header is not added and the users need to go authenticate as usual.

This entry was posted in Computer, Docker, Linux. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.