http servers: add --user-from-header to use for authentication

Retrieve the username from a specified HTTP header if no
other authentication methods are configured
(ideal for proxied setups)
This commit is contained in:
Moises Lima
2025-01-17 12:53:23 -03:00
committed by GitHub
parent bf5a4774c6
commit 347be176af
4 changed files with 115 additions and 30 deletions

View File

@@ -5,6 +5,7 @@ import (
"encoding/base64"
"fmt"
"net/http"
"regexp"
"strings"
"sync"
@@ -153,6 +154,26 @@ func MiddlewareAuthCustom(fn CustomAuthFn, realm string, userFromContext bool) M
}
}
var validUsernameRegexp = regexp.MustCompile(`^[\p{L}\d@._-]+$`)
// MiddlewareAuthGetUserFromHeader middleware that bypasses authentication and extracts the user via a specified HTTP header(ideal for proxied setups).
func MiddlewareAuthGetUserFromHeader(header string) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
username := strings.TrimSpace(r.Header.Get(header))
if username != "" && validUsernameRegexp.MatchString(username) {
r = r.WithContext(context.WithValue(r.Context(), ctxKeyUser, username))
next.ServeHTTP(w, r)
return
}
code := http.StatusUnauthorized
w.Header().Set("Content-Type", "text/plain")
http.Error(w, http.StatusText(code), code)
})
}
}
var onlyOnceWarningAllowOrigin sync.Once
// MiddlewareCORS instantiates middleware that handles basic CORS protections for rcd