From c9d47d762e34a0fa066161fc1dd682a03c892745 Mon Sep 17 00:00:00 2001 From: Kristof De Langhe Date: Fri, 19 May 2023 14:27:35 +0200 Subject: [PATCH] 101573: No default csrf set-cookie on statistics endpoints --- .../security/DSpaceCsrfTokenRepository.java | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/dspace-server-webapp/src/main/java/org/dspace/app/rest/security/DSpaceCsrfTokenRepository.java b/dspace-server-webapp/src/main/java/org/dspace/app/rest/security/DSpaceCsrfTokenRepository.java index 9f4380d2bb7d..0a28131632d5 100644 --- a/dspace-server-webapp/src/main/java/org/dspace/app/rest/security/DSpaceCsrfTokenRepository.java +++ b/dspace-server-webapp/src/main/java/org/dspace/app/rest/security/DSpaceCsrfTokenRepository.java @@ -96,9 +96,19 @@ public CsrfToken generateToken(HttpServletRequest request) { @Override public void saveToken(CsrfToken token, HttpServletRequest request, HttpServletResponse response) { - if (request.getMethod().equals("GET")) { + // Custom conditions on which to avoid certain default CSRF strategies to add csrf cookies to the response + if (request.getMethod().equals("GET") || request.getRequestURI().contains("/api/statistics/")) { return; } + saveTokenWithoutConditions(token, request, response); + } + + /** + * Save the csrf token to the response (see saveToken method), assuming custom conditional checks have already been + * applied + */ + public void saveTokenWithoutConditions(CsrfToken token, HttpServletRequest request, + HttpServletResponse response) { String tokenValue = token == null ? "" : token.getToken(); Cookie cookie = new Cookie(this.cookieName, tokenValue); cookie.setSecure(request.isSecure()); @@ -126,9 +136,9 @@ public void saveToken(CsrfToken token, HttpServletRequest request, sameSite = "Lax"; } ResponseCookie responseCookie = ResponseCookie.from(cookie.getName(), cookie.getValue()) - .path(cookie.getPath()).maxAge(cookie.getMaxAge()) - .domain(cookie.getDomain()).httpOnly(cookie.isHttpOnly()) - .secure(cookie.getSecure()).sameSite(sameSite).build(); + .path(cookie.getPath()).maxAge(cookie.getMaxAge()) + .domain(cookie.getDomain()).httpOnly(cookie.isHttpOnly()) + .secure(cookie.getSecure()).sameSite(sameSite).build(); // Write the ResponseCookie to the Set-Cookie header // This cookie is only used by the backend & not needed by client @@ -151,7 +161,7 @@ public void saveNewTokenWhenCookieAndHeaderDontMatch(HttpServletRequest request, CsrfToken headerToken = loadTokenFromHeader(request); if (token == null || headerToken == null || !token.getToken().equals(headerToken.getToken())) { CsrfToken newToken = generateToken(request); - saveToken(newToken, request, response); + saveTokenWithoutConditions(newToken, request, response); } }