SEC-2352: HttpSessionCsrfTokenRepository lazy session creation

This commit is contained in:
kazuki43zoo 2013-10-06 00:12:50 +09:00 committed by Rob Winch
parent 5f10d84bf5
commit 611a97023d
2 changed files with 26 additions and 4 deletions

View File

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

View File

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