From 5be77d07ab730e6035ec7a47fb0fe161785af35c Mon Sep 17 00:00:00 2001 From: Steffen Busch <37350514+steffenbusch@users.noreply.github.com> Date: Wed, 16 Apr 2025 00:32:08 +0200 Subject: [PATCH] caddyauth: Set authentication provider error in placeholder (#6932) * caddyauth: Set authentication provider error in placeholder for handle_errors directive * caddyauth: Simplify error placeholder setting for authentication provider --- modules/caddyhttp/caddyauth/caddyauth.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/modules/caddyhttp/caddyauth/caddyauth.go b/modules/caddyhttp/caddyauth/caddyauth.go index f799d7a0c..69db62a5c 100644 --- a/modules/caddyhttp/caddyauth/caddyauth.go +++ b/modules/caddyhttp/caddyauth/caddyauth.go @@ -37,6 +37,10 @@ func init() { // `{http.auth.user.*}` placeholders may be set for any authentication // modules that provide user metadata. // +// In case of an error, the placeholder `{http.auth..error}` +// will be set to the error message returned by the authentication +// provider. +// // Its API is still experimental and may be subject to change. type Authentication struct { // A set of authentication providers. If none are specified, @@ -71,6 +75,7 @@ func (a *Authentication) Provision(ctx caddy.Context) error { } func (a Authentication) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { + repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) var user User var authed bool var err error @@ -80,6 +85,9 @@ func (a Authentication) ServeHTTP(w http.ResponseWriter, r *http.Request, next c if c := a.logger.Check(zapcore.ErrorLevel, "auth provider returned error"); c != nil { c.Write(zap.String("provider", provName), zap.Error(err)) } + // Set the error from the authentication provider in a placeholder, + // so it can be used in the handle_errors directive. + repl.Set("http.auth."+provName+".error", err.Error()) continue } if authed { @@ -90,7 +98,6 @@ func (a Authentication) ServeHTTP(w http.ResponseWriter, r *http.Request, next c return caddyhttp.Error(http.StatusUnauthorized, fmt.Errorf("not authenticated")) } - repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer) repl.Set("http.auth.user.id", user.ID) for k, v := range user.Metadata { repl.Set("http.auth.user."+k, v)