lucaslorentz / caddy-docker-proxy

Caddy as a reverse proxy for Docker
MIT License
2.86k stars 168 forks source link

Featurerequest in Readme: How to use basic auth? #550

Closed sowinski closed 10 months ago

sowinski commented 10 months ago

Hi,

I googled and was not able to setup basic auth with labels.

This is how i created the hash:

sudo docker compose exec caddy sh
/ # caddy hash-password -plaintext 'mypassword'
$2a$14$0tdA.I8OovfY83LSDmx2kOuocKBZRCdPurhXWuP/hoIvOE7YFkTjG

This is my label section. It is important to escape $ with $$ otherwise it will interpret the values as a variable.

 28     labels:
 29       caddy: www.example.com
 30       caddy.reverse_proxy: "{{upstreams 8000}}"
 31       caddy.basicauth: "/ mylogin $$2a$$14$$a1uIxM6xLMepH44EMy0zDOCtuKmxTMWHL2R7r5aiLYqOvmriYawUK"

Unfortunately this is not working. Caddy log is saying: caddy-caddy-1 | {"level":"info","ts":1701242346.0044415,"logger":"docker-proxy","msg":"Process Caddyfile","logs":"[ERROR] Removing invalid block: parsing caddyfile tokens for 'basicauth': unrecognized hash algorithm: mylogin, at Caddyfile:2\nwww.example.com {\n\tbasicauth / mylogin $2a$14$a1uIxM6xLMepH44EMy0zDOCtuKmxTMWHL2R7r5aiLYqOvmriYawUK\n\treverse_proxy :8000\n}\n\n"}

What I am doing wrong?

francislavoie commented 10 months ago

basicauth doesn't support single-line syntax with a username/password on the same line as the directives, you need to use a block instead. So do caddy.basicauth.mylogin: <password>

sowinski commented 10 months ago

great this works! But my password is not accepted. Is the way how I created the password correct?

But how can I just protect a specific folder or several folders like /admin/ and /cms/

francislavoie commented 10 months ago

Use the user/pass example here to confirm https://caddyserver.com/docs/caddyfile/directives/basicauth#examples, if that works then the problem isn't with how you're setting up the config but rather with the password you generated.

Simple path matching:

caddy.basicauth: /admin/*
caddy.basicauth.mylogin: <password>

But if you need to match multiple paths you'll need to use a named matcher. See the README for examples.

sowinski commented 10 months ago

My docker-compose line looks like that:

caddy.basicauth.Bob: "$2a$14$Zkx19XLiW6VYouLHR5NmfOFU0z2GTNmpkT/5qqR7hx4IjWJPDhjvG" But I can not login with user: Bob pw: hiccup

Do I have to restart caddy or do something else?

I just restart my docker compose every time I change a line?

EDIT: Escaping is necessary $ => $$ and just canceling was not enough. I use docker compose stop and down and then up and it worked.

What would be the correct way to reload the labels?

francislavoie commented 10 months ago

up -d should be enough to make Docker Compose recognize the labels changed and recreate the relevant containers. You shouldn't need to down.