From 05afb94b9bd4ccd5254014ae5e2e9b2ac7a6c3f8 Mon Sep 17 00:00:00 2001 From: Daniel Jiang Date: Thu, 20 Aug 2020 02:18:29 +0800 Subject: [PATCH] Store csrf token in the header of response instead of cookie The current approach will prevent the effectiveness of `Cache-Control` header and gorilla's library add `Vary:Cookie` header in all responses. We will set the token in a header of response so the response can be cached when needed. Signed-off-by: Daniel Jiang --- src/server/middleware/csrf/csrf.go | 9 +-------- src/server/middleware/csrf/csrf_test.go | 2 +- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/src/server/middleware/csrf/csrf.go b/src/server/middleware/csrf/csrf.go index eda3da928..fcfb505f3 100644 --- a/src/server/middleware/csrf/csrf.go +++ b/src/server/middleware/csrf/csrf.go @@ -19,7 +19,6 @@ import ( const ( csrfKeyEnv = "CSRF_KEY" tokenHeader = "X-Harbor-CSRF-Token" - tokenCookie = "__csrf" ) var ( @@ -31,13 +30,7 @@ var ( // attachToken makes sure if csrf generate a new token it will be included in the response header func attachToken(w http.ResponseWriter, r *http.Request) { if t := csrf.Token(r); len(t) > 0 { - http.SetCookie(w, &http.Cookie{ - Name: tokenCookie, - Secure: secureFlag, - Value: t, - Path: "/", - SameSite: http.SameSiteStrictMode, - }) + w.Header().Set(tokenHeader, t) } else { log.Warningf("token not found in context, skip attaching") } diff --git a/src/server/middleware/csrf/csrf_test.go b/src/server/middleware/csrf/csrf_test.go index 14eaf86e6..6225990cb 100644 --- a/src/server/middleware/csrf/csrf_test.go +++ b/src/server/middleware/csrf/csrf_test.go @@ -58,7 +58,7 @@ func TestMiddleware(t *testing.T) { rec := httptest.NewRecorder() srv.ServeHTTP(rec, c.req) assert.Equal(t, c.statusCode, rec.Result().StatusCode) - assert.Equal(t, c.returnToken, hasCookie(rec.Result(), tokenCookie)) + assert.Equal(t, c.returnToken, rec.Result().Header.Get(tokenHeader) != "") } }