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,
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);
}
/*

View File

@ -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("");