Caddy basicauth using query


(James Jones) #1

Hi,

I am trying to allow authentication to a proxied service either using basicauth (when a user wants to visit the service website) or if the incoming request contains a specific api key value (for api request!). I cannot figure out how to do this.

In my previous APACHE config I used two REQUIRE commands within the virtual domain to enable this (REQUIRE expr … and REQUIRE valid-user). In caddy, I always get a authentication prompt even when the “apikey=” string is in the uri. Is this possible within caddy?
Note that the services performing api requests cannot pass login credentials as part of the api request.

My caddy file looks like:

<web address> {
	tls <email>
	basicauth / <user> <pass>

  rewrite {
		if {uri} has "apikey=<apikey>"
		to /<service>/{uri}
	}
  
	proxy /<service> http://<service>:<port> {
  	websocket
  	transparent
 	}
}

(Matthew Fay) #2

Hi @titchjones, welcome to the Caddy community!

This is going to be a bit tricky because there’s no method to exclude subpaths from a basicauth directive; it affects everything below it, regardless of the other directives you use (like proxy and rewrite in your case).

We need to be a bit creative here; instead of applying a blanket basic auth, and then trying to exclude clients supplying the API key, you can instead apply basic auth to one subfolder, and rewrite clients there if they don’t supply an API key.

example.com {
  tls [email]
  basicauth /no-api-key [user] [pass]

  rewrite {
    if {uri} not_has "apikey=[apikey]"
    to /no-api-key
  }

  proxy / http://[service]:[port]/service {
    websocket
    transparent
  }
}

Note:

  1. I added /service to the end of the proxy upstream, because we’re no longer rewriting to add it;
  2. Requests without the API key will fall through to Caddy’s static file server, like it would in the example config you gave above - if you want to serve files to these clients, you’ll want to put them in a ./no-api-key subfolder of the web root (or otherwise appropriately named folder)

(system) closed #3

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