Add CsrfFilter.csrfRequestAttributeName
Previously the CsrfToken was set on the request attribute with the name equal to CsrfToken.getParameterName(). This didn't really make a lot of sense because the CsrfToken.getParameterName() is intended to be used as the HTTP parameter that the CSRF token was provided. What's more is it meant that the CsrfToken needed to be read for every request to place it as an HttpServletRequestAttribute. This causes unnecessary HttpSession access which can decrease performance for applications. This commit allows setting CsrfFilter.csrfReqeustAttributeName to remove the dual purposing of CsrfToken.parameterName and to allow deferal of reading the CsrfToken to prevent unnecessary HttpSession access. Issue gh-11699
This commit is contained in:
@@ -48,6 +48,7 @@ import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.verifyZeroInteractions;
|
||||
|
||||
/**
|
||||
@@ -344,6 +345,23 @@ public class CsrfFilterTests {
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setAccessDeniedHandler(null));
|
||||
}
|
||||
|
||||
// This ensures that the HttpSession on get requests unless the CsrfToken is used
|
||||
@Test
|
||||
public void doFilterWhenCsrfRequestAttributeNameThenNoCsrfTokenMethodInvokedOnGet()
|
||||
throws ServletException, IOException {
|
||||
CsrfFilter filter = createCsrfFilter(this.tokenRepository);
|
||||
String csrfAttrName = "_csrf";
|
||||
filter.setCsrfRequestAttributeName(csrfAttrName);
|
||||
CsrfToken expectedCsrfToken = mock(CsrfToken.class);
|
||||
given(this.tokenRepository.loadToken(this.request)).willReturn(expectedCsrfToken);
|
||||
|
||||
filter.doFilter(this.request, this.response, this.filterChain);
|
||||
|
||||
verifyNoInteractions(expectedCsrfToken);
|
||||
CsrfToken tokenFromRequest = (CsrfToken) this.request.getAttribute(csrfAttrName);
|
||||
assertThat(tokenFromRequest).isEqualTo(expectedCsrfToken);
|
||||
}
|
||||
|
||||
private static CsrfTokenAssert assertToken(Object token) {
|
||||
return new CsrfTokenAssert((CsrfToken) token);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user