Skip to content

caddyauth: Set authentication provider error in placeholder #6932

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 15, 2025

Conversation

steffenbusch
Copy link
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
		}
	}
}

Copy link
Member

@mholt mholt left a comment

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
20 checks passed
@steffenbusch steffenbusch deleted the authenticate-provider-error branch April 16, 2025 18:21
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