Compare commits
2 Commits
ab17ff8b79
...
12db6409ce
| Author | SHA1 | Date | |
|---|---|---|---|
| 12db6409ce | |||
| 5fc208c9da |
@@ -71,7 +71,7 @@ func CSRFMiddleware() func(http.Handler) http.Handler {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if strings.HasPrefix(r.URL.Path, "/api/") {
|
if strings.HasPrefix(r.URL.Path, "/api/") && hasBearerToken(r) {
|
||||||
next.ServeHTTP(w, r)
|
next.ServeHTTP(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -86,6 +86,11 @@ func CSRFMiddleware() func(http.Handler) http.Handler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func hasBearerToken(r *http.Request) bool {
|
||||||
|
auth := strings.TrimSpace(r.Header.Get("Authorization"))
|
||||||
|
return strings.HasPrefix(auth, "Bearer ")
|
||||||
|
}
|
||||||
|
|
||||||
func IsHTTPS(r *http.Request) bool {
|
func IsHTTPS(r *http.Request) bool {
|
||||||
if r.TLS != nil {
|
if r.TLS != nil {
|
||||||
return true
|
return true
|
||||||
|
|||||||
@@ -186,8 +186,9 @@ func TestCSRFMiddlewareAllowsValidToken(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCSRFMiddlewareSkipsAPI(t *testing.T) {
|
func TestCSRFMiddlewareSkipsAPIWithBearerToken(t *testing.T) {
|
||||||
request := httptest.NewRequest("POST", "/api/test", nil)
|
request := httptest.NewRequest("POST", "/api/test", nil)
|
||||||
|
request.Header.Set("Authorization", "Bearer valid-token")
|
||||||
recorder := httptest.NewRecorder()
|
recorder := httptest.NewRecorder()
|
||||||
|
|
||||||
handler := CSRFMiddleware()(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
handler := CSRFMiddleware()(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -197,7 +198,22 @@ func TestCSRFMiddlewareSkipsAPI(t *testing.T) {
|
|||||||
handler.ServeHTTP(recorder, request)
|
handler.ServeHTTP(recorder, request)
|
||||||
|
|
||||||
if recorder.Code != http.StatusOK {
|
if recorder.Code != http.StatusOK {
|
||||||
t.Errorf("API requests should skip CSRF validation, got status %d", recorder.Code)
|
t.Errorf("API requests with Bearer token should skip CSRF validation, got status %d", recorder.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCSRFMiddlewareBlocksAPIWithoutBearerToken(t *testing.T) {
|
||||||
|
request := httptest.NewRequest("POST", "/api/test", nil)
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
|
||||||
|
handler := CSRFMiddleware()(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
}))
|
||||||
|
|
||||||
|
handler.ServeHTTP(recorder, request)
|
||||||
|
|
||||||
|
if recorder.Code != http.StatusForbidden {
|
||||||
|
t.Errorf("API requests without Bearer token should require CSRF validation, got status %d", recorder.Code)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user