Skip to content

Commit 5be77d0

Browse files
authored
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
1 parent 137711a commit 5be77d0

File tree

1 file changed

+8
-1
lines changed

1 file changed

+8
-1
lines changed

modules/caddyhttp/caddyauth/caddyauth.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,10 @@ func init() {
3737
// `{http.auth.user.*}` placeholders may be set for any authentication
3838
// modules that provide user metadata.
3939
//
40+
// In case of an error, the placeholder `{http.auth.<provider>.error}`
41+
// will be set to the error message returned by the authentication
42+
// provider.
43+
//
4044
// Its API is still experimental and may be subject to change.
4145
type Authentication struct {
4246
// A set of authentication providers. If none are specified,
@@ -71,6 +75,7 @@ func (a *Authentication) Provision(ctx caddy.Context) error {
7175
}
7276

7377
func (a Authentication) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
78+
repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
7479
var user User
7580
var authed bool
7681
var err error
@@ -80,6 +85,9 @@ func (a Authentication) ServeHTTP(w http.ResponseWriter, r *http.Request, next c
8085
if c := a.logger.Check(zapcore.ErrorLevel, "auth provider returned error"); c != nil {
8186
c.Write(zap.String("provider", provName), zap.Error(err))
8287
}
88+
// Set the error from the authentication provider in a placeholder,
89+
// so it can be used in the handle_errors directive.
90+
repl.Set("http.auth."+provName+".error", err.Error())
8391
continue
8492
}
8593
if authed {
@@ -90,7 +98,6 @@ func (a Authentication) ServeHTTP(w http.ResponseWriter, r *http.Request, next c
9098
return caddyhttp.Error(http.StatusUnauthorized, fmt.Errorf("not authenticated"))
9199
}
92100

93-
repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
94101
repl.Set("http.auth.user.id", user.ID)
95102
for k, v := range user.Metadata {
96103
repl.Set("http.auth.user."+k, v)

0 commit comments

Comments
 (0)