How to use basicauth with filters

Trying out caddy for one of our SPA projects and getting in trouble with the following configuration:

localhost
try_files {path} /index.html
file_server
tls /etc/ssl/certs/server.crt /etc/ssl/certs/server.key

@auth {
    not path /*
}

basicauth @auth {
    amzv JDJ5JDEyJFYvVXVyWXFIemNsUjlwMUlZdGJ4di5hTkxSUDZHd2JTekRVdUgvR0dKdkN0RGdDSXFqUmhlIA==
}

Rules:

  • Open file if exists, otherwise use the index.html file :white_check_mark:
  • Use basicauth for all routes including /js/app.js etc, but not for /{slug} :x:

Current state:

  • Basic auth is not working for any route

Shouldn’t be that hard, maybe someone can suggest a quick and easy answer

I’m not sure what you mean by {slug}.

Do you mean you want basicauth to apply for any request to a file that exists on disk, but not for any request to files that don’t exist?

Right now with not path /*, this means “not (every possible path)”, which is basically the same as saying “never”.

Maybe you wanted something like this:

@auth file
basicauth @auth {
	amzv JDJ5JDEyJFYvVXVyWXFIemNsUjlwMUlZdGJ4di5hTkxSUDZHd2JTekRVdUgvR0dKdkN0RGdDSXFqUmhlIA==
}

This uses the file matcher which has the default behaviour of checking if the current request path is a file that exists on disk (similar to try_files {path} except it doesn’t do a rewrite, it’s just the matcher part).

Also, I would organize your Caddyfile like this, for clarity (also added root because it seems you left it to be implicit, better to specify it for clarity):

localhost {
	tls /etc/ssl/certs/server.crt /etc/ssl/certs/server.key

	root * .

	try_files {path} /index.html
	
	@auth file
	basicauth @auth {
		amzv JDJ5JDEyJFYvVXVyWXFIemNsUjlwMUlZdGJ4di5hTkxSUDZHd2JTekRVdUgvR0dKdkN0RGdDSXFqUmhlIA==
	}

	file_server
}

This places each directive according in the order the Caddyfile adapter would sort them, according to the pre-defined order here:

Having said that, you’ll notice that try_files is ordered higher than basicauth. This will cause a problem, because try_files does a rewrite of the request path, but the basicauth matcher probably needs to work on the original request path to work correctly (if I’m understanding your goal, I mean). So to solve this, we would use route to force those to run in a particular order instead of their default order:

localhost {
	tls /etc/ssl/certs/server.crt /etc/ssl/certs/server.key

	root * .

	route {
		@auth file
		basicauth @auth {
			amzv JDJ5JDEyJFYvVXVyWXFIemNsUjlwMUlZdGJ4di5hTkxSUDZHd2JTekRVdUgvR0dKdkN0RGdDSXFqUmhlIA==
		}

		try_files {path} /index.html
	}

	file_server
}
1 Like