Skip to content

caddyauth: Set authentication provider error in placeholder - #6932

Merged
mholt merged 3 commits into
caddyserver:masterfrom
steffenbusch:authenticate-provider-error
Apr 15, 2025
Merged

mholt merged 3 commits into
caddyserver:masterfrom
steffenbusch:authenticate-provider-error

Conversation

@steffenbusch

Copy link
Copy Markdown
Contributor

This PR introduces a new placeholder, {http.auth.<provider>.error}, which is set when an authentication provider returns an error from the authentication process.

This allows errors during Authenticate from specific authentication providers to be exposed and handled more effectively in the handle_errors directive. Since a non-succesful authentication results in just a 401 Unauhtorized, this new placeholder enables much more fine-grained error handling.

The following example demonstrates the flexibility of handling 401 Unauthorized errors from the caddy-jwt plugin (= provider jwt) using the new placeholder ({http.auth.jwt.error}) in a handle_errors 401 block:

:8080 {
	handle /jwt/* {
		jwtauth {
			sign_key {file.jwt-secret.txt}
			sign_alg HS256
			issuer_whitelist https://jwt.example.com
			audience_whitelist https://api.example.com
			user_claims sub
		}
		respond "behind jwt auth"
	}

	handle_errors 401 {
		@jwt_invalid_audience {
			vars {http.auth.jwt.error} "invalid audience"
		}

		@jwt_expired {
			vars {http.auth.jwt.error} `"exp" not satisfied`
		}

		route {
			# Transform the 401 error into a 403 Forbidden response.
			respond @jwt_invalid_audience "Access denied: The audience claim in the provided JWT is invalid or does not match the required audience." 403

			# Redirect to a login endpoint with an explanation that the JWT has expired.
			redir @jwt_expired https://auth.example.com/login?reason=expired

			# In all other cases, redirect to general login endpoint
			redir https://auth.example.com/login
		}
	}
}

@mholt mholt left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Thanks for the contribution.

@mholt
mholt enabled auto-merge (squash) April 15, 2025 22:27
@mholt
mholt merged commit 5be77d0 into caddyserver:master Apr 15, 2025
@steffenbusch
steffenbusch deleted the authenticate-provider-error branch April 16, 2025 18:21
mohammed90 pushed a commit to cedricziel/caddy that referenced this pull request Aug 29, 2025
…ver#6932)

* caddyauth: Set authentication provider error in placeholder for handle_errors directive

* caddyauth: Simplify error placeholder setting for authentication provider
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants