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 <jiangd@vmware.com>
This commit is contained in:
Daniel Jiang 2020-08-20 02:18:29 +08:00 committed by AllForNothing
parent 446ae4c173
commit 05afb94b9b
2 changed files with 2 additions and 9 deletions

View File

@ -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")
}

View File

@ -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) != "")
}
}