Check for token in request or a cookie and react accordingly

I have a web-service that I am using Caddy as a reverse proxy for and that part works just fine, but I want Caddy to only allow access, if the request parameters include a certain token or if a certain cookie has been set with a specific value. If the token has been given and it’s correct, I’d like Caddy to set the cookie in the browser.

I think I got the check for the token more-or-less right, but I just cannot understand how to do the cookies. I’m new to Caddy, so no, I have no idea what I’m doing and I’m just basically flailing about like a headless chicken.

As pseudo-code what I want:

my.webservice {
	if(not "mycookie" in cookies or cookies["mycookie"] != "goodvalue"){
		if(not "mytoken" in request_parameters or request_parameters["mytoken"] != "goodvalue"){
			respond 403
		}
	}

	reverse_proxy my.webservice:80
}

What I currently have:

(KEYFILTER) {
	@keyfilter {
		not query mytoken=goodvalue
	}
	respond @keyfilter 403
}

my.webservice {
        tls /etc/letsencrypt/my.webservice.fullchain /etc/letsencrypt/my.webservice.key

        import KEYFILTER
        reverse_proxy my.webservice:80
}

Would anyone be so kind as to explain how to achieve this? I am assuming it is possible, given how capable Caddy is, but I’m not 100% certain.

Well, I managed to eventually get it working. No idea, if this is a correct or a good approach to it, but it at least works. I’m leaving what I did here in case any other newbie happens to come across it and finds it useful:

my.webservice {
        tls /etc/letsencrypt/my.webservice.fullchain /etc/letsencrypt/my.webservice.key

        @headerfilter {
                not header Cookie *mytoken=somevalue*
                not query mytoken=somevalue
        }

        respond @headerfilter 403

        reverse_proxy my.webservice:8080 {
                header_down +Set-Cookie "mytoken=somevalue; Path=/"
        }
}
2 Likes

This topic was automatically closed after 30 days. New replies are no longer allowed.