Explorar o código

SEC-2352: HttpSessionCsrfTokenRepository lazy session creation

kazuki43zoo %!s(int64=12) %!d(string=hai) anos
pai
achega
611a97023d

+ 11 - 4
web/src/main/java/org/springframework/security/web/csrf/HttpSessionCsrfTokenRepository.java

@@ -48,10 +48,13 @@ public final class HttpSessionCsrfTokenRepository implements CsrfTokenRepository
      */
     public void saveToken(CsrfToken token, HttpServletRequest request,
             HttpServletResponse response) {
-        HttpSession session = request.getSession();
-        if(token == null) {
-            session.removeAttribute(sessionAttributeName);
+        if (token == null) {
+            HttpSession session = request.getSession(false);
+            if (session != null) {
+                session.removeAttribute(sessionAttributeName);
+            }
         } else {
+            HttpSession session = request.getSession();
             session.setAttribute(sessionAttributeName, token);
         }
     }
@@ -60,7 +63,11 @@ public final class HttpSessionCsrfTokenRepository implements CsrfTokenRepository
      * @see org.springframework.security.web.csrf.CsrfTokenRepository#loadToken(javax.servlet.http.HttpServletRequest)
      */
     public CsrfToken loadToken(HttpServletRequest request) {
-        return (CsrfToken) request.getSession().getAttribute(sessionAttributeName);
+        HttpSession session = request.getSession(false);
+        if (session == null) {
+            return null;
+        }
+        return (CsrfToken) session.getAttribute(sessionAttributeName);
     }
 
     /*

+ 15 - 0
web/src/test/java/org/springframework/security/web/csrf/HttpSessionCsrfTokenRepositoryTests.java

@@ -67,6 +67,13 @@ public class HttpSessionCsrfTokenRepositoryTests {
     @Test
     public void loadTokenNull() {
         assertThat(repo.loadToken(request)).isNull();
+        assertThat(request.getSession(false)).isNull();
+    }
+
+    @Test
+    public void loadTokenNullWhenSessionExists() {
+        request.getSession();
+        assertThat(repo.loadToken(request)).isNull();
     }
 
     @Test
@@ -105,6 +112,14 @@ public class HttpSessionCsrfTokenRepositoryTests {
                 .isFalse();
     }
 
+    @Test
+    public void saveTokenNullTokenWhenSessionNotExists() {
+
+        repo.saveToken(null, request, response);
+        
+        assertThat(request.getSession(false)).isNull();
+    }
+
     @Test(expected = IllegalArgumentException.class)
     public void setSessionAttributeNameEmpty() {
         repo.setSessionAttributeName("");