Skip to content

Commit c447bf8

Browse files
authored
fix(auth): move 401 response handling to a common helper func (#353)
Signed-off-by: Matthias Wessendorf <[email protected]>
1 parent 07b1ebc commit c447bf8

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

pkg/http/authorization.go

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,12 @@ type KubernetesApiTokenVerifier interface {
2323
KubernetesApiVerifyToken(ctx context.Context, token, audience string) (*authenticationapiv1.UserInfo, []string, error)
2424
}
2525

26+
// write401 sends a 401/Unauthorized response with WWW-Authenticate header.
27+
func write401(w http.ResponseWriter, wwwAuthenticateHeader, errorType, message string) {
28+
w.Header().Set("WWW-Authenticate", wwwAuthenticateHeader+fmt.Sprintf(`, error="%s"`, errorType))
29+
http.Error(w, message, http.StatusUnauthorized)
30+
}
31+
2632
// AuthorizationMiddleware validates the OAuth flow for protected resources.
2733
//
2834
// The flow is skipped for unprotected resources, such as health checks and well-known endpoints.
@@ -82,9 +88,7 @@ func AuthorizationMiddleware(staticConfig *config.StaticConfig, oidcProvider *oi
8288
authHeader := r.Header.Get("Authorization")
8389
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
8490
klog.V(1).Infof("Authentication failed - missing or invalid bearer token: %s %s from %s", r.Method, r.URL.Path, r.RemoteAddr)
85-
86-
w.Header().Set("WWW-Authenticate", wwwAuthenticateHeader+", error=\"missing_token\"")
87-
http.Error(w, "Unauthorized: Bearer token required", http.StatusUnauthorized)
91+
write401(w, wwwAuthenticateHeader, "missing_token", "Unauthorized: Bearer token required")
8892
return
8993
}
9094

@@ -132,9 +136,7 @@ func AuthorizationMiddleware(staticConfig *config.StaticConfig, oidcProvider *oi
132136
}
133137
if err != nil {
134138
klog.V(1).Infof("Authentication failed - JWT validation error: %s %s from %s, error: %v", r.Method, r.URL.Path, r.RemoteAddr, err)
135-
136-
w.Header().Set("WWW-Authenticate", wwwAuthenticateHeader+", error=\"invalid_token\"")
137-
http.Error(w, "Unauthorized: Invalid token", http.StatusUnauthorized)
139+
write401(w, wwwAuthenticateHeader, "invalid_token", "Unauthorized: Invalid token")
138140
return
139141
}
140142

0 commit comments

Comments
 (0)