BearerAuthMiddleware returns an http.Handler that enforces bearer token authentication when cfg.AuthEnabled() is true. When auth is disabled it passes all requests through unchanged. On failure it responds 401 with a WWW-Authenticate header.
(cfg *Config, next http.Handler)
| 24 | // passes all requests through unchanged. On failure it responds 401 with a |
| 25 | // WWW-Authenticate header. |
| 26 | func BearerAuthMiddleware(cfg *Config, next http.Handler) http.Handler { |
| 27 | if !cfg.AuthEnabled() { |
| 28 | return next |
| 29 | } |
| 30 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 31 | if extractBearerToken(r) != cfg.AuthToken { |
| 32 | w.Header().Set("WWW-Authenticate", `Bearer realm="gosqlx-mcp"`) |
| 33 | http.Error(w, "Unauthorized", http.StatusUnauthorized) |
| 34 | return |
| 35 | } |
| 36 | next.ServeHTTP(w, r) |
| 37 | }) |
| 38 | } |
| 39 | |
| 40 | // extractBearerToken parses the "Authorization: Bearer <token>" header. |
| 41 | // Returns an empty string if the header is absent or malformed. |