Remove blank lines from all tests

Remove all blank lines from test code so that test methods are
visually grouped together. This generally helps to make the test
classes easer to scan, however, the "given" / "when" / "then"
blocks used by some tests are now not as easy to discern.

Issue gh-8945
This commit is contained in:
Phillip Webb
2020-08-01 19:33:21 -07:00
committed by Rob Winch
parent 5bdd757108
commit a5aa6b3d7f
787 changed files with 9 additions and 10241 deletions

View File

@@ -39,7 +39,6 @@ public class MockFilterConfig implements FilterConfig {
@Override
public String getInitParameter(String arg0) {
Object result = this.map.get(arg0);
if (result != null) {
return (String) result;
}

View File

@@ -36,9 +36,7 @@ public class DefaultRedirectStrategyTests {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContextPath("/context");
MockHttpServletResponse response = new MockHttpServletResponse();
rds.sendRedirect(request, response, "https://context.blah.com/context/remainder");
assertThat(response.getRedirectedUrl()).isEqualTo("remainder");
}
@@ -50,9 +48,7 @@ public class DefaultRedirectStrategyTests {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContextPath("/context");
MockHttpServletResponse response = new MockHttpServletResponse();
rds.sendRedirect(request, response, "https://https://context.blah.com/context/remainder");
assertThat(response.getRedirectedUrl()).isEqualTo("remainder");
}
@@ -63,7 +59,6 @@ public class DefaultRedirectStrategyTests {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContextPath("/context");
MockHttpServletResponse response = new MockHttpServletResponse();
rds.sendRedirect(request, response, "https://redirectme.somewhere.else");
}

View File

@@ -106,7 +106,6 @@ public class FilterChainProxyTests {
this.fcp.doFilter(this.request, this.response, this.chain);
assertThat(this.fcp.getFilterChains()).hasSize(1);
assertThat(this.fcp.getFilterChains().get(0).getFilters().get(0)).isSameAs(this.filter);
verifyZeroInteractions(this.filter);
// The actual filter chain should be invoked though
verify(this.chain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
@@ -116,7 +115,6 @@ public class FilterChainProxyTests {
public void originalChainIsInvokedAfterSecurityChainIfMatchSucceeds() throws Exception {
given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(true);
this.fcp.doFilter(this.request, this.response, this.chain);
verify(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(FilterChain.class));
verify(this.chain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
@@ -126,10 +124,8 @@ public class FilterChainProxyTests {
public void originalFilterChainIsInvokedIfMatchingSecurityChainIsEmpty() throws Exception {
List<Filter> noFilters = Collections.emptyList();
this.fcp = new FilterChainProxy(new DefaultSecurityFilterChain(this.matcher, noFilters));
given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(true);
this.fcp.doFilter(this.request, this.response, this.chain);
verify(this.chain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@@ -197,9 +193,7 @@ public class FilterChainProxyTests {
return null;
}).given(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(FilterChain.class));
this.fcp.doFilter(this.request, this.response, this.chain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -212,14 +206,12 @@ public class FilterChainProxyTests {
throw new ServletException("oops");
}).given(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(FilterChain.class));
try {
this.fcp.doFilter(this.request, this.response, this.chain);
fail("Expected Exception");
}
catch (ServletException success) {
}
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -236,15 +228,12 @@ public class FilterChainProxyTests {
return null;
}).given(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(FilterChain.class));
this.fcp.doFilter(this.request, this.response, innerChain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(expected);
return null;
}).given(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(FilterChain.class));
this.fcp.doFilter(this.request, this.response, this.chain);
verify(innerChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}

View File

@@ -48,7 +48,6 @@ public class FilterInvocationTests {
request.setServerPort(80);
request.setContextPath("/mycontext");
request.setRequestURI("/mycontext/HelloWorld/some/more/segments.html");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
FilterInvocation fi = new FilterInvocation(request, response, chain);
@@ -66,21 +65,18 @@ public class FilterInvocationTests {
public void testRejectsNullFilterChain() {
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
MockHttpServletResponse response = new MockHttpServletResponse();
new FilterInvocation(request, response, null);
}
@Test(expected = IllegalArgumentException.class)
public void testRejectsNullServletRequest() {
MockHttpServletResponse response = new MockHttpServletResponse();
new FilterInvocation(null, response, mock(FilterChain.class));
}
@Test(expected = IllegalArgumentException.class)
public void testRejectsNullServletResponse() {
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
new FilterInvocation(request, null, mock(FilterChain.class));
}
@@ -94,7 +90,6 @@ public class FilterInvocationTests {
request.setServerPort(80);
request.setContextPath("/mycontext");
request.setRequestURI("/mycontext/HelloWorld");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
assertThat(fi.getRequestUrl()).isEqualTo("/HelloWorld?foo=bar");
@@ -111,7 +106,6 @@ public class FilterInvocationTests {
request.setServerPort(80);
request.setContextPath("/mycontext");
request.setRequestURI("/mycontext/HelloWorld");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
assertThat(fi.getRequestUrl()).isEqualTo("/HelloWorld");

View File

@@ -43,26 +43,22 @@ public class PortMapperImplTests {
@Test
public void testDetectsEmptyMap() {
PortMapperImpl portMapper = new PortMapperImpl();
try {
portMapper.setPortMappings(new HashMap<>());
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
}
@Test
public void testDetectsNullMap() {
PortMapperImpl portMapper = new PortMapperImpl();
try {
portMapper.setPortMappings(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
}
@@ -77,13 +73,11 @@ public class PortMapperImplTests {
PortMapperImpl portMapper = new PortMapperImpl();
Map<String, String> map = new HashMap<>();
map.put("79", "80559");
try {
portMapper.setPortMappings(map);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
}
@@ -98,9 +92,7 @@ public class PortMapperImplTests {
PortMapperImpl portMapper = new PortMapperImpl();
Map<String, String> map = new HashMap<>();
map.put("79", "442");
portMapper.setPortMappings(map);
assertThat(portMapper.lookupHttpPort(442)).isEqualTo(Integer.valueOf(79));
assertThat(Integer.valueOf(442)).isEqualTo(portMapper.lookupHttpsPort(79));
}

View File

@@ -33,7 +33,6 @@ public class PortResolverImplTests {
@Test
public void testDetectsBuggyIeHttpRequest() {
PortResolverImpl pr = new PortResolverImpl();
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServerPort(8443);
request.setScheme("HTtP"); // proves case insensitive handling
@@ -43,7 +42,6 @@ public class PortResolverImplTests {
@Test
public void testDetectsBuggyIeHttpsRequest() {
PortResolverImpl pr = new PortResolverImpl();
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServerPort(8080);
request.setScheme("HTtPs"); // proves case insensitive handling
@@ -53,13 +51,11 @@ public class PortResolverImplTests {
@Test
public void testDetectsEmptyPortMapper() {
PortResolverImpl pr = new PortResolverImpl();
try {
pr.setPortMapper(null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
}
@@ -74,7 +70,6 @@ public class PortResolverImplTests {
@Test
public void testNormalOperation() {
PortResolverImpl pr = new PortResolverImpl();
MockHttpServletRequest request = new MockHttpServletRequest();
request.setScheme("http");
request.setServerPort(1021);

View File

@@ -101,10 +101,8 @@ public class DefaultWebInvocationPrivilegeEvaluatorTests {
public void deniesAccessIfAccessDecisionManagerDoes() {
Authentication token = new TestingAuthenticationToken("test", "Password", "MOCK_INDEX");
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(this.interceptor);
willThrow(new AccessDeniedException("")).given(this.adm).decide(any(Authentication.class), anyObject(),
anyList());
assertThat(wipe.isAllowed("/foo/index.jsp", token)).isFalse();
}

View File

@@ -67,10 +67,8 @@ public class DelegatingAccessDeniedHandlerTests {
public void moreSpecificDoesNotInvokeLessSpecific() throws Exception {
this.handlers.put(CsrfException.class, this.handler1);
this.handler = new DelegatingAccessDeniedHandler(this.handlers, this.handler3);
AccessDeniedException accessDeniedException = new AccessDeniedException("");
this.handler.handle(this.request, this.response, accessDeniedException);
verify(this.handler1, never()).handle(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(AccessDeniedException.class));
verify(this.handler3).handle(this.request, this.response, accessDeniedException);
@@ -81,10 +79,8 @@ public class DelegatingAccessDeniedHandlerTests {
this.handlers.put(InvalidCsrfTokenException.class, this.handler1);
this.handlers.put(MissingCsrfTokenException.class, this.handler2);
this.handler = new DelegatingAccessDeniedHandler(this.handlers, this.handler3);
AccessDeniedException accessDeniedException = new MissingCsrfTokenException("123");
this.handler.handle(this.request, this.response, accessDeniedException);
verify(this.handler1, never()).handle(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(AccessDeniedException.class));
verify(this.handler2).handle(this.request, this.response, accessDeniedException);

View File

@@ -69,14 +69,11 @@ public class ExceptionTranslationFilterTests {
private static String getSavedRequestUrl(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return null;
}
HttpSessionRequestCache rc = new HttpSessionRequestCache();
SavedRequest sr = rc.getRequest(request, new MockHttpServletResponse());
return sr.getRedirectUrl();
}
@@ -90,22 +87,18 @@ public class ExceptionTranslationFilterTests {
request.setServerName("localhost");
request.setContextPath("/mycontext");
request.setRequestURI("/mycontext/secure/page.html");
// Setup the FilterChain to thrown an access denied exception
FilterChain fc = mock(FilterChain.class);
willThrow(new AccessDeniedException("")).given(fc).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
// Setup SecurityContextHolder, as filter needs to check if user is
// anonymous
SecurityContextHolder.getContext().setAuthentication(
new AnonymousAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("IGNORED")));
// Test
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint);
filter.setAuthenticationTrustResolver(new AuthenticationTrustResolverImpl());
assertThat(filter.getAuthenticationTrustResolver()).isNotNull();
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, fc);
assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/login.jsp");
@@ -122,18 +115,15 @@ public class ExceptionTranslationFilterTests {
request.setServerName("localhost");
request.setContextPath("/mycontext");
request.setRequestURI("/mycontext/secure/page.html");
// Setup the FilterChain to thrown an access denied exception
FilterChain fc = mock(FilterChain.class);
willThrow(new AccessDeniedException("")).given(fc).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
// Setup SecurityContextHolder, as filter needs to check if user is remembered
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(
new RememberMeAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("IGNORED")));
SecurityContextHolder.setContext(securityContext);
// Test
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint);
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -147,24 +137,19 @@ public class ExceptionTranslationFilterTests {
// Setup our HTTP request
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServletPath("/secure/page.html");
// Setup the FilterChain to thrown an access denied exception
FilterChain fc = mock(FilterChain.class);
willThrow(new AccessDeniedException("")).given(fc).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
// Setup SecurityContextHolder, as filter needs to check if user is
// anonymous
SecurityContextHolder.clearContext();
// Setup a new AccessDeniedHandlerImpl that will do a "forward"
AccessDeniedHandlerImpl adh = new AccessDeniedHandlerImpl();
adh.setErrorPage("/error.jsp");
// Test
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint);
filter.setAccessDeniedHandler(adh);
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, fc);
assertThat(response.getStatus()).isEqualTo(403);
@@ -177,23 +162,19 @@ public class ExceptionTranslationFilterTests {
// Setup our HTTP request
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServletPath("/secure/page.html");
// Setup the FilterChain to thrown an access denied exception
FilterChain fc = mock(FilterChain.class);
willThrow(new AccessDeniedException("")).given(fc).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
// Setup SecurityContextHolder, as filter needs to check if user is
// anonymous
SecurityContextHolder.getContext().setAuthentication(
new AnonymousAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("IGNORED")));
// Test
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(
(req, res, ae) -> res.sendError(403, ae.getMessage()));
filter.setAuthenticationTrustResolver(new AuthenticationTrustResolverImpl());
assertThat(filter.getAuthenticationTrustResolver()).isNotNull();
LocaleContextHolder.setDefaultLocale(Locale.GERMAN);
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, fc);
@@ -211,12 +192,10 @@ public class ExceptionTranslationFilterTests {
request.setServerName("localhost");
request.setContextPath("/mycontext");
request.setRequestURI("/mycontext/secure/page.html");
// Setup the FilterChain to thrown an authentication failure exception
FilterChain fc = mock(FilterChain.class);
willThrow(new BadCredentialsException("")).given(fc).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
// Test
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint);
filter.afterPropertiesSet();
@@ -237,12 +216,10 @@ public class ExceptionTranslationFilterTests {
request.setServerName("localhost");
request.setContextPath("/mycontext");
request.setRequestURI("/mycontext/secure/page.html");
// Setup the FilterChain to thrown an authentication failure exception
FilterChain fc = mock(FilterChain.class);
willThrow(new BadCredentialsException("")).given(fc).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
// Test
HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint, requestCache);
@@ -269,11 +246,9 @@ public class ExceptionTranslationFilterTests {
// Setup our HTTP request
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServletPath("/secure/page.html");
// Test
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint);
assertThat(filter.getAuthenticationEntryPoint()).isSameAs(this.mockEntryPoint);
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, mock(FilterChain.class));
}
@@ -281,12 +256,10 @@ public class ExceptionTranslationFilterTests {
@Test
public void thrownIOExceptionServletExceptionAndRuntimeExceptionsAreRethrown() throws Exception {
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint);
filter.afterPropertiesSet();
Exception[] exceptions = { new IOException(), new ServletException(), new RuntimeException() };
for (Exception e : exceptions) {
FilterChain fc = mock(FilterChain.class);
willThrow(e).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
try {
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), fc);
@@ -309,10 +282,8 @@ public class ExceptionTranslationFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint);
assertThatThrownBy(() -> filter.doFilter(request, response, chain)).isInstanceOf(ServletException.class)
.hasCauseInstanceOf(AccessDeniedException.class);
verifyZeroInteractions(this.mockEntryPoint);
}

View File

@@ -58,9 +58,7 @@ public class RequestMatcherDelegatingAccessDeniedHandlerTests {
given(matcher.matches(this.request)).willReturn(false);
this.deniedHandlers.put(matcher, handler);
this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler);
this.delegator.handle(this.request, null, null);
verify(this.accessDeniedHandler).handle(this.request, null, null);
verify(handler, never()).handle(this.request, null, null);
}
@@ -75,9 +73,7 @@ public class RequestMatcherDelegatingAccessDeniedHandlerTests {
this.deniedHandlers.put(firstMatcher, firstHandler);
this.deniedHandlers.put(secondMatcher, secondHandler);
this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler);
this.delegator.handle(this.request, null, null);
verify(firstHandler).handle(this.request, null, null);
verify(secondHandler, never()).handle(this.request, null, null);
verify(this.accessDeniedHandler, never()).handle(this.request, null, null);
@@ -95,9 +91,7 @@ public class RequestMatcherDelegatingAccessDeniedHandlerTests {
this.deniedHandlers.put(firstMatcher, firstHandler);
this.deniedHandlers.put(secondMatcher, secondHandler);
this.delegator = new RequestMatcherDelegatingAccessDeniedHandler(this.deniedHandlers, this.accessDeniedHandler);
this.delegator.handle(this.request, null, null);
verify(secondHandler).handle(this.request, null, null);
verify(firstHandler, never()).handle(this.request, null, null);
verify(this.accessDeniedHandler, never()).handle(this.request, null, null);

View File

@@ -47,7 +47,6 @@ public class ChannelDecisionManagerImplTests {
@Test
public void testCannotSetEmptyChannelProcessorsList() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
try {
cdm.setChannelProcessors(new Vector());
cdm.afterPropertiesSet();
@@ -63,20 +62,17 @@ public class ChannelDecisionManagerImplTests {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
List list = new Vector();
list.add("THIS IS NOT A CHANNELPROCESSOR");
try {
cdm.setChannelProcessors(list);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
}
@Test
public void testCannotSetNullChannelProcessorsList() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
try {
cdm.setChannelProcessors(null);
cdm.afterPropertiesSet();
@@ -97,13 +93,10 @@ public class ChannelDecisionManagerImplTests {
list.add(cpAbc);
cdm.setChannelProcessors(list);
cdm.afterPropertiesSet();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
List<ConfigAttribute> cad = SecurityConfig.createList("xyz");
cdm.decide(fi, cad);
assertThat(fi.getResponse().isCommitted()).isTrue();
}
@@ -116,11 +109,9 @@ public class ChannelDecisionManagerImplTests {
list.add(cpAbc);
cdm.setChannelProcessors(list);
cdm.afterPropertiesSet();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
cdm.decide(fi, SecurityConfig.createList(new String[] { "abc", "ANY_CHANNEL" }));
assertThat(fi.getResponse().isCommitted()).isFalse();
}
@@ -135,11 +126,9 @@ public class ChannelDecisionManagerImplTests {
list.add(cpAbc);
cdm.setChannelProcessors(list);
cdm.afterPropertiesSet();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
cdm.decide(fi, SecurityConfig.createList("SOME_ATTRIBUTE_NO_PROCESSORS_SUPPORT"));
assertThat(fi.getResponse().isCommitted()).isFalse();
}
@@ -154,7 +143,6 @@ public class ChannelDecisionManagerImplTests {
list.add(cpAbc);
cdm.setChannelProcessors(list);
cdm.afterPropertiesSet();
assertThat(cdm.supports(new SecurityConfig("xyz"))).isTrue();
assertThat(cdm.supports(new SecurityConfig("abc"))).isTrue();
assertThat(cdm.supports(new SecurityConfig("UNSUPPORTED"))).isFalse();
@@ -164,21 +152,18 @@ public class ChannelDecisionManagerImplTests {
public void testGettersSetters() {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
assertThat(cdm.getChannelProcessors()).isNull();
MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false);
MockChannelProcessor cpAbc = new MockChannelProcessor("abc", false);
List list = new Vector();
list.add(cpXyz);
list.add(cpAbc);
cdm.setChannelProcessors(list);
assertThat(cdm.getChannelProcessors()).isEqualTo(list);
}
@Test
public void testStartupFailsWithEmptyChannelProcessorsList() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
try {
cdm.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
@@ -202,17 +187,13 @@ public class ChannelDecisionManagerImplTests {
@Override
public void decide(FilterInvocation invocation, Collection<ConfigAttribute> config) throws IOException {
Iterator iter = config.iterator();
if (this.failIfCalled) {
fail("Should not have called this channel processor: " + this.configAttribute);
}
while (iter.hasNext()) {
ConfigAttribute attr = (ConfigAttribute) iter.next();
if (attr.getAttribute().equals(this.configAttribute)) {
invocation.getHttpResponse().sendRedirect("/redirected");
return;
}
}

View File

@@ -43,10 +43,8 @@ public class ChannelProcessingFilterTests {
@Test(expected = IllegalArgumentException.class)
public void testDetectsMissingChannelDecisionManager() {
ChannelProcessingFilter filter = new ChannelProcessingFilter();
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap("/path", true, "MOCK");
filter.setSecurityMetadataSource(fids);
filter.afterPropertiesSet();
}
@@ -61,12 +59,9 @@ public class ChannelProcessingFilterTests {
public void testDetectsSupportedConfigAttribute() {
ChannelProcessingFilter filter = new ChannelProcessingFilter();
filter.setChannelDecisionManager(new MockChannelDecisionManager(false, "SUPPORTS_MOCK_ONLY"));
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap("/path", true,
"SUPPORTS_MOCK_ONLY");
filter.setSecurityMetadataSource(fids);
filter.afterPropertiesSet();
}
@@ -74,10 +69,8 @@ public class ChannelProcessingFilterTests {
public void testDetectsUnsupportedConfigAttribute() {
ChannelProcessingFilter filter = new ChannelProcessingFilter();
filter.setChannelDecisionManager(new MockChannelDecisionManager(false, "SUPPORTS_MOCK_ONLY"));
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap("/path", true,
"SUPPORTS_MOCK_ONLY", "INVALID_ATTRIBUTE");
filter.setSecurityMetadataSource(fids);
filter.afterPropertiesSet();
}
@@ -86,17 +79,12 @@ public class ChannelProcessingFilterTests {
public void testDoFilterWhenManagerDoesCommitResponse() throws Exception {
ChannelProcessingFilter filter = new ChannelProcessingFilter();
filter.setChannelDecisionManager(new MockChannelDecisionManager(true, "SOME_ATTRIBUTE"));
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap("/path", true, "SOME_ATTRIBUTE");
filter.setSecurityMetadataSource(fids);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setQueryString("info=now");
request.setServletPath("/path");
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, mock(FilterChain.class));
}
@@ -104,17 +92,12 @@ public class ChannelProcessingFilterTests {
public void testDoFilterWhenManagerDoesNotCommitResponse() throws Exception {
ChannelProcessingFilter filter = new ChannelProcessingFilter();
filter.setChannelDecisionManager(new MockChannelDecisionManager(false, "SOME_ATTRIBUTE"));
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap("/path", true, "SOME_ATTRIBUTE");
filter.setSecurityMetadataSource(fids);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setQueryString("info=now");
request.setServletPath("/path");
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, mock(FilterChain.class));
}
@@ -122,17 +105,12 @@ public class ChannelProcessingFilterTests {
public void testDoFilterWhenNullConfigAttributeReturned() throws Exception {
ChannelProcessingFilter filter = new ChannelProcessingFilter();
filter.setChannelDecisionManager(new MockChannelDecisionManager(false, "NOT_USED"));
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap("/path", true, "NOT_USED");
filter.setSecurityMetadataSource(fids);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setQueryString("info=now");
request.setServletPath("/PATH_NOT_MATCHING_CONFIG_ATTRIBUTE");
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, mock(FilterChain.class));
}
@@ -141,12 +119,9 @@ public class ChannelProcessingFilterTests {
ChannelProcessingFilter filter = new ChannelProcessingFilter();
filter.setChannelDecisionManager(new MockChannelDecisionManager(false, "MOCK"));
assertThat(filter.getChannelDecisionManager() != null).isTrue();
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap("/path", false, "MOCK");
filter.setSecurityMetadataSource(fids);
assertThat(filter.getSecurityMetadataSource()).isSameAs(fids);
filter.afterPropertiesSet();
}
@@ -192,7 +167,6 @@ public class ChannelProcessingFilterTests {
@Override
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
FilterInvocation fi = (FilterInvocation) object;
if (this.servletPath.equals(fi.getHttpRequest().getServletPath())) {
return this.toReturn;
}
@@ -206,7 +180,6 @@ public class ChannelProcessingFilterTests {
if (!this.provideIterator) {
return null;
}
return this.toReturn;
}

View File

@@ -45,13 +45,10 @@ public class InsecureChannelProcessorTests {
request.setServletPath("/servlet");
request.setScheme("http");
request.setServerPort(8080);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
InsecureChannelProcessor processor = new InsecureChannelProcessor();
processor.decide(fi, SecurityConfig.createList("SOME_IGNORED_ATTRIBUTE", "REQUIRES_INSECURE_CHANNEL"));
assertThat(fi.getResponse().isCommitted()).isFalse();
}
@@ -65,14 +62,11 @@ public class InsecureChannelProcessorTests {
request.setScheme("https");
request.setSecure(true);
request.setServerPort(8443);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
InsecureChannelProcessor processor = new InsecureChannelProcessor();
processor.decide(fi,
SecurityConfig.createList(new String[] { "SOME_IGNORED_ATTRIBUTE", "REQUIRES_INSECURE_CHANNEL" }));
assertThat(fi.getResponse().isCommitted()).isTrue();
}
@@ -80,13 +74,11 @@ public class InsecureChannelProcessorTests {
public void testDecideRejectsNulls() throws Exception {
InsecureChannelProcessor processor = new InsecureChannelProcessor();
processor.afterPropertiesSet();
try {
processor.decide(null, null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
}
@@ -96,7 +88,6 @@ public class InsecureChannelProcessorTests {
assertThat(processor.getInsecureKeyword()).isEqualTo("REQUIRES_INSECURE_CHANNEL");
processor.setInsecureKeyword("X");
assertThat(processor.getInsecureKeyword()).isEqualTo("X");
assertThat(processor.getEntryPoint() != null).isTrue();
processor.setEntryPoint(null);
assertThat(processor.getEntryPoint() == null).isTrue();
@@ -106,7 +97,6 @@ public class InsecureChannelProcessorTests {
public void testMissingEntryPoint() throws Exception {
InsecureChannelProcessor processor = new InsecureChannelProcessor();
processor.setEntryPoint(null);
try {
processor.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
@@ -120,7 +110,6 @@ public class InsecureChannelProcessorTests {
public void testMissingSecureChannelKeyword() throws Exception {
InsecureChannelProcessor processor = new InsecureChannelProcessor();
processor.setInsecureKeyword(null);
try {
processor.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
@@ -128,9 +117,7 @@ public class InsecureChannelProcessorTests {
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("insecureKeyword required");
}
processor.setInsecureKeyword("");
try {
processor.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");

View File

@@ -43,7 +43,6 @@ public class RetryWithHttpEntryPointTests {
@Test
public void testDetectsMissingPortMapper() {
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
try {
ep.setPortMapper(null);
fail("Should have thrown IllegalArgumentException");
@@ -55,7 +54,6 @@ public class RetryWithHttpEntryPointTests {
@Test
public void testDetectsMissingPortResolver() {
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
try {
ep.setPortResolver(null);
fail("Should have thrown IllegalArgumentException");
@@ -85,13 +83,10 @@ public class RetryWithHttpEntryPointTests {
request.setScheme("https");
request.setServerName("localhost");
request.setServerPort(443);
MockHttpServletResponse response = new MockHttpServletResponse();
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
ep.setPortMapper(new PortMapperImpl());
ep.setPortResolver(new MockPortResolver(80, 443));
ep.commence(request, response);
assertThat(response.getRedirectedUrl()).isEqualTo("http://localhost/bigWebApp/hello/pathInfo.html?open=true");
}
@@ -102,13 +97,10 @@ public class RetryWithHttpEntryPointTests {
request.setScheme("https");
request.setServerName("localhost");
request.setServerPort(443);
MockHttpServletResponse response = new MockHttpServletResponse();
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
ep.setPortMapper(new PortMapperImpl());
ep.setPortResolver(new MockPortResolver(80, 443));
ep.commence(request, response);
assertThat(response.getRedirectedUrl()).isEqualTo("http://localhost/bigWebApp/hello");
}
@@ -120,13 +112,10 @@ public class RetryWithHttpEntryPointTests {
request.setScheme("https");
request.setServerName("www.example.com");
request.setServerPort(8768);
MockHttpServletResponse response = new MockHttpServletResponse();
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
ep.setPortMapper(new PortMapperImpl());
ep.setPortResolver(new MockPortResolver(8768, 1234));
ep.commence(request, response);
assertThat(response.getRedirectedUrl()).isEqualTo("/bigWebApp?open=true");
}
@@ -138,18 +127,14 @@ public class RetryWithHttpEntryPointTests {
request.setScheme("https");
request.setServerName("localhost");
request.setServerPort(9999);
MockHttpServletResponse response = new MockHttpServletResponse();
PortMapperImpl portMapper = new PortMapperImpl();
Map<String, String> map = new HashMap<>();
map.put("8888", "9999");
portMapper.setPortMappings(map);
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
ep.setPortResolver(new MockPortResolver(8888, 9999));
ep.setPortMapper(portMapper);
ep.commence(request, response);
assertThat(response.getRedirectedUrl())
.isEqualTo("http://localhost:8888/bigWebApp/hello/pathInfo.html?open=true");

View File

@@ -39,7 +39,6 @@ public class RetryWithHttpsEntryPointTests {
@Test
public void testDetectsMissingPortMapper() {
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
try {
ep.setPortMapper(null);
fail("Should have thrown IllegalArgumentException");
@@ -51,7 +50,6 @@ public class RetryWithHttpsEntryPointTests {
@Test
public void testDetectsMissingPortResolver() {
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
try {
ep.setPortResolver(null);
fail("Should have thrown IllegalArgumentException");
@@ -76,13 +74,10 @@ public class RetryWithHttpsEntryPointTests {
request.setScheme("http");
request.setServerName("www.example.com");
request.setServerPort(80);
MockHttpServletResponse response = new MockHttpServletResponse();
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
ep.setPortMapper(new PortMapperImpl());
ep.setPortResolver(new MockPortResolver(80, 443));
ep.commence(request, response);
assertThat(response.getRedirectedUrl())
.isEqualTo("https://www.example.com/bigWebApp/hello/pathInfo.html?open=true");
@@ -94,13 +89,10 @@ public class RetryWithHttpsEntryPointTests {
request.setScheme("http");
request.setServerName("www.example.com");
request.setServerPort(80);
MockHttpServletResponse response = new MockHttpServletResponse();
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
ep.setPortMapper(new PortMapperImpl());
ep.setPortResolver(new MockPortResolver(80, 443));
ep.commence(request, response);
assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com/bigWebApp/hello");
}
@@ -112,13 +104,10 @@ public class RetryWithHttpsEntryPointTests {
request.setScheme("http");
request.setServerName("www.example.com");
request.setServerPort(8768);
MockHttpServletResponse response = new MockHttpServletResponse();
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
ep.setPortMapper(new PortMapperImpl());
ep.setPortResolver(new MockPortResolver(8768, 1234));
ep.commence(request, response);
assertThat(response.getRedirectedUrl()).isEqualTo("/bigWebApp?open=true");
}
@@ -130,18 +119,14 @@ public class RetryWithHttpsEntryPointTests {
request.setScheme("http");
request.setServerName("www.example.com");
request.setServerPort(8888);
MockHttpServletResponse response = new MockHttpServletResponse();
PortMapperImpl portMapper = new PortMapperImpl();
Map<String, String> map = new HashMap<>();
map.put("8888", "9999");
portMapper.setPortMappings(map);
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
ep.setPortResolver(new MockPortResolver(8888, 9999));
ep.setPortMapper(portMapper);
ep.commence(request, response);
assertThat(response.getRedirectedUrl())
.isEqualTo("https://www.example.com:9999/bigWebApp/hello/pathInfo.html?open=true");

View File

@@ -46,13 +46,10 @@ public class SecureChannelProcessorTests {
request.setScheme("https");
request.setSecure(true);
request.setServerPort(8443);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
SecureChannelProcessor processor = new SecureChannelProcessor();
processor.decide(fi, SecurityConfig.createList("SOME_IGNORED_ATTRIBUTE", "REQUIRES_SECURE_CHANNEL"));
assertThat(fi.getResponse().isCommitted()).isFalse();
}
@@ -65,14 +62,11 @@ public class SecureChannelProcessorTests {
request.setServletPath("/servlet");
request.setScheme("http");
request.setServerPort(8080);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
SecureChannelProcessor processor = new SecureChannelProcessor();
processor.decide(fi,
SecurityConfig.createList(new String[] { "SOME_IGNORED_ATTRIBUTE", "REQUIRES_SECURE_CHANNEL" }));
assertThat(fi.getResponse().isCommitted()).isTrue();
}
@@ -80,13 +74,11 @@ public class SecureChannelProcessorTests {
public void testDecideRejectsNulls() throws Exception {
SecureChannelProcessor processor = new SecureChannelProcessor();
processor.afterPropertiesSet();
try {
processor.decide(null, null);
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
}
@@ -96,7 +88,6 @@ public class SecureChannelProcessorTests {
assertThat(processor.getSecureKeyword()).isEqualTo("REQUIRES_SECURE_CHANNEL");
processor.setSecureKeyword("X");
assertThat(processor.getSecureKeyword()).isEqualTo("X");
assertThat(processor.getEntryPoint() != null).isTrue();
processor.setEntryPoint(null);
assertThat(processor.getEntryPoint() == null).isTrue();
@@ -106,7 +97,6 @@ public class SecureChannelProcessorTests {
public void testMissingEntryPoint() throws Exception {
SecureChannelProcessor processor = new SecureChannelProcessor();
processor.setEntryPoint(null);
try {
processor.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
@@ -120,7 +110,6 @@ public class SecureChannelProcessorTests {
public void testMissingSecureChannelKeyword() throws Exception {
SecureChannelProcessor processor = new SecureChannelProcessor();
processor.setSecureKeyword(null);
try {
processor.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
@@ -128,9 +117,7 @@ public class SecureChannelProcessorTests {
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo("secureKeyword required");
}
processor.setSecureKeyword("");
try {
processor.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");

View File

@@ -65,14 +65,12 @@ public class AbstractVariableEvaluationContextPostProcessorTests {
@Test
public void extractVariables() {
this.context = this.processor.postProcess(this.context, this.invocation);
assertThat(this.context.lookupVariable(KEY)).isEqualTo(VALUE);
}
@Test
public void extractVariablesOnlyUsedOnce() {
this.context = this.processor.postProcess(this.context, this.invocation);
assertThat(this.context.lookupVariable(KEY)).isEqualTo(VALUE);
this.processor.results = Collections.emptyMap();
assertThat(this.context.lookupVariable(KEY)).isEqualTo(VALUE);

View File

@@ -69,7 +69,6 @@ public class DefaultWebSecurityExpressionHandlerTests {
bean.getConstructorArgumentValues().addGenericArgumentValue("ROLE_A");
appContext.registerBeanDefinition("role", bean);
this.handler.setApplicationContext(appContext);
EvaluationContext ctx = this.handler.createEvaluationContext(mock(Authentication.class),
mock(FilterInvocation.class));
ExpressionParser parser = this.handler.getExpressionParser();
@@ -85,11 +84,9 @@ public class DefaultWebSecurityExpressionHandlerTests {
@Test
public void createEvaluationContextCustomTrustResolver() {
this.handler.setTrustResolver(this.trustResolver);
Expression expression = this.handler.getExpressionParser().parseExpression("anonymous");
EvaluationContext context = this.handler.createEvaluationContext(this.authentication, this.invocation);
assertThat(expression.getValue(context, Boolean.class)).isFalse();
verify(this.trustResolver).isAnonymous(this.authentication);
}

View File

@@ -56,7 +56,6 @@ public class DelegatingEvaluationContextTests {
public void getRootObject() {
TypedValue expected = mock(TypedValue.class);
given(this.delegate.getRootObject()).willReturn(expected);
assertThat(this.context.getRootObject()).isEqualTo(expected);
}
@@ -64,7 +63,6 @@ public class DelegatingEvaluationContextTests {
public void getConstructorResolvers() {
List<ConstructorResolver> expected = new ArrayList<>();
given(this.delegate.getConstructorResolvers()).willReturn(expected);
assertThat(this.context.getConstructorResolvers()).isEqualTo(expected);
}
@@ -72,7 +70,6 @@ public class DelegatingEvaluationContextTests {
public void getMethodResolvers() {
List<MethodResolver> expected = new ArrayList<>();
given(this.delegate.getMethodResolvers()).willReturn(expected);
assertThat(this.context.getMethodResolvers()).isEqualTo(expected);
}
@@ -80,16 +77,13 @@ public class DelegatingEvaluationContextTests {
public void getPropertyAccessors() {
List<PropertyAccessor> expected = new ArrayList<>();
given(this.delegate.getPropertyAccessors()).willReturn(expected);
assertThat(this.context.getPropertyAccessors()).isEqualTo(expected);
}
@Test
public void getTypeLocator() {
TypeLocator expected = mock(TypeLocator.class);
given(this.delegate.getTypeLocator()).willReturn(expected);
assertThat(this.context.getTypeLocator()).isEqualTo(expected);
}
@@ -97,7 +91,6 @@ public class DelegatingEvaluationContextTests {
public void getTypeConverter() {
TypeConverter expected = mock(TypeConverter.class);
given(this.delegate.getTypeConverter()).willReturn(expected);
assertThat(this.context.getTypeConverter()).isEqualTo(expected);
}
@@ -105,7 +98,6 @@ public class DelegatingEvaluationContextTests {
public void getTypeComparator() {
TypeComparator expected = mock(TypeComparator.class);
given(this.delegate.getTypeComparator()).willReturn(expected);
assertThat(this.context.getTypeComparator()).isEqualTo(expected);
}
@@ -113,7 +105,6 @@ public class DelegatingEvaluationContextTests {
public void getOperatorOverloader() {
OperatorOverloader expected = mock(OperatorOverloader.class);
given(this.delegate.getOperatorOverloader()).willReturn(expected);
assertThat(this.context.getOperatorOverloader()).isEqualTo(expected);
}
@@ -121,7 +112,6 @@ public class DelegatingEvaluationContextTests {
public void getBeanResolver() {
BeanResolver expected = mock(BeanResolver.class);
given(this.delegate.getBeanResolver()).willReturn(expected);
assertThat(this.context.getBeanResolver()).isEqualTo(expected);
}
@@ -129,9 +119,7 @@ public class DelegatingEvaluationContextTests {
public void setVariable() {
String name = "name";
String value = "value";
this.context.setVariable(name, value);
verify(this.delegate).setVariable(name, value);
}
@@ -140,7 +128,6 @@ public class DelegatingEvaluationContextTests {
String name = "name";
String expected = "expected";
given(this.delegate.lookupVariable(name)).willReturn(expected);
assertThat(this.context.lookupVariable(name)).isEqualTo(expected);
}

View File

@@ -55,7 +55,6 @@ public class WebExpressionVoterTests {
.isTrue();
assertThat(voter.supports(FilterInvocation.class)).isTrue();
assertThat(voter.supports(MethodInvocation.class)).isFalse();
}
@Test
@@ -83,9 +82,7 @@ public class WebExpressionVoterTests {
ArrayList attributes = new ArrayList();
attributes.addAll(SecurityConfig.createList("A", "B", "C"));
attributes.add(weca);
assertThat(voter.vote(this.user, fi, attributes)).isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
// Second time false
assertThat(voter.vote(this.user, fi, attributes)).isEqualTo(AccessDecisionVoter.ACCESS_DENIED);
}

View File

@@ -44,9 +44,7 @@ public class WebSecurityExpressionRootTests {
request.setRemoteAddr("192.168.1.1");
WebSecurityExpressionRoot root = new WebSecurityExpressionRoot(mock(Authentication.class),
new FilterInvocation(request, mock(HttpServletResponse.class), mock(FilterChain.class)));
assertThat(root.hasIpAddress("192.168.1.1")).isTrue();
// IPv6 Address
request.setRemoteAddr("fa:db8:85a3::8a2e:370:7334");
assertThat(root.hasIpAddress("fa:db8:85a3::8a2e:370:7334")).isTrue();
@@ -62,7 +60,6 @@ public class WebSecurityExpressionRootTests {
request.setRemoteAddr("192.168.1." + i);
assertThat(root.hasIpAddress("192.168.1.0/24")).isTrue();
}
request.setRemoteAddr("192.168.1.127");
// 25 = FF FF FF 80
assertThat(root.hasIpAddress("192.168.1.0/25")).isTrue();
@@ -75,7 +72,6 @@ public class WebSecurityExpressionRootTests {
assertThat(root.hasIpAddress("192.168.1.224/27")).isTrue();
assertThat(root.hasIpAddress("192.168.1.240/27")).isTrue();
assertThat(root.hasIpAddress("192.168.1.255/32")).isTrue();
request.setRemoteAddr("202.24.199.127");
assertThat(root.hasIpAddress("202.24.0.0/14")).isTrue();
request.setRemoteAddr("202.25.179.135");

View File

@@ -54,9 +54,7 @@ public class DefaultFilterInvocationSecurityMetadataSourceTests {
@Test
public void lookupNotRequiringExactMatchSucceedsIfNotMatching() {
createFids("/secure/super/**", null);
FilterInvocation fi = createFilterInvocation("/secure/super/somefile.html", null, null, null);
assertThat(this.fids.getAttributes(fi)).isEqualTo(this.def);
}
@@ -67,9 +65,7 @@ public class DefaultFilterInvocationSecurityMetadataSourceTests {
@Test
public void lookupNotRequiringExactMatchSucceedsIfSecureUrlPathContainsUpperCase() {
createFids("/secure/super/**", null);
FilterInvocation fi = createFilterInvocation("/secure", "/super/somefile.html", null, null);
Collection<ConfigAttribute> response = this.fids.getAttributes(fi);
assertThat(response).isEqualTo(this.def);
}
@@ -77,9 +73,7 @@ public class DefaultFilterInvocationSecurityMetadataSourceTests {
@Test
public void lookupRequiringExactMatchIsSuccessful() {
createFids("/SeCurE/super/**", null);
FilterInvocation fi = createFilterInvocation("/SeCurE/super/somefile.html", null, null, null);
Collection<ConfigAttribute> response = this.fids.getAttributes(fi);
assertThat(response).isEqualTo(this.def);
}
@@ -87,9 +81,7 @@ public class DefaultFilterInvocationSecurityMetadataSourceTests {
@Test
public void lookupRequiringExactMatchWithAdditionalSlashesIsSuccessful() {
createFids("/someAdminPage.html**", null);
FilterInvocation fi = createFilterInvocation("/someAdminPage.html", null, "a=/test", null);
Collection<ConfigAttribute> response = this.fids.getAttributes(fi);
assertThat(response); // see SEC-161 (it should truncate after ?
// sign).isEqualTo(def)
@@ -103,7 +95,6 @@ public class DefaultFilterInvocationSecurityMetadataSourceTests {
@Test
public void httpMethodLookupSucceeds() {
createFids("/somepage**", "GET");
FilterInvocation fi = createFilterInvocation("/somepage", null, null, "GET");
Collection<ConfigAttribute> attrs = this.fids.getAttributes(fi);
assertThat(attrs).isEqualTo(this.def);
@@ -112,7 +103,6 @@ public class DefaultFilterInvocationSecurityMetadataSourceTests {
@Test
public void generalMatchIsUsedIfNoMethodSpecificMatchExists() {
createFids("/somepage**", null);
FilterInvocation fi = createFilterInvocation("/somepage", null, null, "GET");
Collection<ConfigAttribute> attrs = this.fids.getAttributes(fi);
assertThat(attrs).isEqualTo(this.def);
@@ -121,7 +111,6 @@ public class DefaultFilterInvocationSecurityMetadataSourceTests {
@Test
public void requestWithDifferentHttpMethodDoesntMatch() {
createFids("/somepage**", "GET");
FilterInvocation fi = createFilterInvocation("/somepage", null, null, "POST");
Collection<ConfigAttribute> attrs = this.fids.getAttributes(fi);
assertThat(attrs).isNull();
@@ -132,11 +121,9 @@ public class DefaultFilterInvocationSecurityMetadataSourceTests {
public void mixingPatternsWithAndWithoutHttpMethodsIsSupported() {
LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<>();
Collection<ConfigAttribute> userAttrs = SecurityConfig.createList("A");
requestMap.put(new AntPathRequestMatcher("/user/**", null), userAttrs);
requestMap.put(new AntPathRequestMatcher("/teller/**", "GET"), SecurityConfig.createList("B"));
this.fids = new DefaultFilterInvocationSecurityMetadataSource(requestMap);
FilterInvocation fi = createFilterInvocation("/user", null, null, "GET");
Collection<ConfigAttribute> attrs = this.fids.getAttributes(fi);
assertThat(attrs).isEqualTo(userAttrs);
@@ -148,14 +135,10 @@ public class DefaultFilterInvocationSecurityMetadataSourceTests {
@Test
public void extraQuestionMarkStillMatches() {
createFids("/someAdminPage.html*", null);
FilterInvocation fi = createFilterInvocation("/someAdminPage.html", null, null, null);
Collection<ConfigAttribute> response = this.fids.getAttributes(fi);
assertThat(response).isEqualTo(this.def);
fi = createFilterInvocation("/someAdminPage.html", null, "?", null);
response = this.fids.getAttributes(fi);
assertThat(response).isEqualTo(this.def);
}
@@ -168,7 +151,6 @@ public class DefaultFilterInvocationSecurityMetadataSourceTests {
request.setServletPath(servletPath);
request.setPathInfo(pathInfo);
request.setQueryString(queryString);
return new FilterInvocation(request, new MockHttpServletResponse(), mock(FilterChain.class));
}

View File

@@ -117,13 +117,9 @@ public class FilterSecurityInterceptorTests {
// Setup a Context
Authentication token = new TestingAuthenticationToken("Test", "Password", "NOT_USED");
SecurityContextHolder.getContext().setAuthentication(token);
FilterInvocation fi = createinvocation();
given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK"));
this.interceptor.invoke(fi);
// SEC-1697
verify(this.publisher, never()).publishEvent(any(AuthorizedEvent.class));
}
@@ -132,24 +128,19 @@ public class FilterSecurityInterceptorTests {
public void afterInvocationIsNotInvokedIfExceptionThrown() throws Exception {
Authentication token = new TestingAuthenticationToken("Test", "Password", "NOT_USED");
SecurityContextHolder.getContext().setAuthentication(token);
FilterInvocation fi = createinvocation();
FilterChain chain = fi.getChain();
willThrow(new RuntimeException()).given(chain).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK"));
AfterInvocationManager aim = mock(AfterInvocationManager.class);
this.interceptor.setAfterInvocationManager(aim);
try {
this.interceptor.invoke(fi);
fail("Expected exception");
}
catch (RuntimeException expected) {
}
verifyZeroInteractions(aim);
}
@@ -161,29 +152,23 @@ public class FilterSecurityInterceptorTests {
Authentication token = new TestingAuthenticationToken("Test", "Password", "NOT_USED");
token.setAuthenticated(true);
ctx.setAuthentication(token);
RunAsManager runAsManager = mock(RunAsManager.class);
given(runAsManager.buildRunAs(eq(token), any(), anyCollection()))
.willReturn(new RunAsUserToken("key", "someone", "creds", token.getAuthorities(), token.getClass()));
this.interceptor.setRunAsManager(runAsManager);
FilterInvocation fi = createinvocation();
FilterChain chain = fi.getChain();
willThrow(new RuntimeException()).given(chain).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK"));
AfterInvocationManager aim = mock(AfterInvocationManager.class);
this.interceptor.setAfterInvocationManager(aim);
try {
this.interceptor.invoke(fi);
fail("Expected exception");
}
catch (RuntimeException expected) {
}
// Check we've changed back
assertThat(SecurityContextHolder.getContext()).isSameAs(ctx);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(token);
@@ -195,9 +180,7 @@ public class FilterSecurityInterceptorTests {
this.interceptor.setObserveOncePerRequest(false);
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest();
this.interceptor.doFilter(request, response, new MockFilterChain());
assertThat(request.getAttributeNames().hasMoreElements()).isFalse();
}
@@ -205,10 +188,8 @@ public class FilterSecurityInterceptorTests {
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServletPath("/secure/page.html");
FilterChain chain = mock(FilterChain.class);
FilterInvocation fi = new FilterInvocation(request, response, chain);
return fi;
}

View File

@@ -31,7 +31,6 @@ public class RequestKeyTests {
public void equalsWorksWithNullHttpMethod() {
RequestKey key1 = new RequestKey("/someurl");
RequestKey key2 = new RequestKey("/someurl");
assertThat(key2).isEqualTo(key1);
key1 = new RequestKey("/someurl", "GET");
assertThat(key1.equals(key2)).isFalse();
@@ -42,7 +41,6 @@ public class RequestKeyTests {
public void keysWithSameUrlAndHttpMethodAreEqual() {
RequestKey key1 = new RequestKey("/someurl", "GET");
RequestKey key2 = new RequestKey("/someurl", "GET");
assertThat(key2).isEqualTo(key1);
}
@@ -50,7 +48,6 @@ public class RequestKeyTests {
public void keysWithSameUrlAndDifferentHttpMethodAreNotEqual() {
RequestKey key1 = new RequestKey("/someurl", "GET");
RequestKey key2 = new RequestKey("/someurl", "POST");
assertThat(key1.equals(key2)).isFalse();
assertThat(key2.equals(key1)).isFalse();
}
@@ -59,7 +56,6 @@ public class RequestKeyTests {
public void keysWithDifferentUrlsAreNotEquals() {
RequestKey key1 = new RequestKey("/someurl", "GET");
RequestKey key2 = new RequestKey("/anotherurl", "GET");
assertThat(key1.equals(key2)).isFalse();
assertThat(key2.equals(key1)).isFalse();
}

View File

@@ -71,13 +71,11 @@ public class AbstractAuthenticationProcessingFilterTests {
private MockHttpServletRequest createMockAuthenticationRequest() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServletPath("/j_mock_post");
request.setScheme("http");
request.setServerName("www.example.com");
request.setRequestURI("/mycontext/j_mock_post");
request.setContextPath("/mycontext");
return request;
}
@@ -101,10 +99,8 @@ public class AbstractAuthenticationProcessingFilterTests {
MockHttpServletResponse response = new MockHttpServletResponse();
MockAuthenticationFilter filter = new MockAuthenticationFilter();
filter.setFilterProcessesUrl("/login");
DefaultHttpFirewall firewall = new DefaultHttpFirewall();
request.setServletPath("/login;jsessionid=I8MIONOSTHOR");
// the firewall ensures that path parameters are ignored
HttpServletRequest firewallRequest = firewall.getFirewalledRequest(request);
assertThat(filter.requiresAuthentication(firewallRequest, response)).isTrue();
@@ -116,20 +112,16 @@ public class AbstractAuthenticationProcessingFilterTests {
MockHttpServletRequest request = createMockAuthenticationRequest();
request.setServletPath("/j_OTHER_LOCATION");
request.setRequestURI("/mycontext/j_OTHER_LOCATION");
// Setup our filter configuration
MockFilterConfig config = new MockFilterConfig(null, null);
// Setup our expectation that the filter chain will not be invoked, as we redirect
// to defaultTargetUrl
MockFilterChain chain = new MockFilterChain(false);
MockHttpServletResponse response = new MockHttpServletResponse();
// Setup our test object, to grant access
MockAuthenticationFilter filter = new MockAuthenticationFilter(true);
filter.setFilterProcessesUrl("/j_OTHER_LOCATION");
filter.setAuthenticationSuccessHandler(this.successHandler);
// Test
filter.doFilter(request, response, chain);
assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/logged_in.jsp");
@@ -143,7 +135,6 @@ public class AbstractAuthenticationProcessingFilterTests {
filter.setAuthenticationManager(mock(AuthenticationManager.class));
filter.setFilterProcessesUrl("/p");
filter.afterPropertiesSet();
assertThat(filter.getRememberMeServices()).isNotNull();
filter.setRememberMeServices(
new TokenBasedRememberMeServices("key", new AbstractRememberMeServicesTests.MockUserDetailsService()));
@@ -157,18 +148,14 @@ public class AbstractAuthenticationProcessingFilterTests {
MockHttpServletRequest request = createMockAuthenticationRequest();
request.setServletPath("/some.file.html");
request.setRequestURI("/mycontext/some.file.html");
// Setup our filter configuration
MockFilterConfig config = new MockFilterConfig(null, null);
// Setup our expectation that the filter chain will be invoked, as our request is
// for a page the filter isn't monitoring
MockFilterChain chain = new MockFilterChain(true);
MockHttpServletResponse response = new MockHttpServletResponse();
// Setup our test object, to deny access
MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
// Test
filter.doFilter(request, response, chain);
}
@@ -178,25 +165,20 @@ public class AbstractAuthenticationProcessingFilterTests {
// Setup our HTTP request
MockHttpServletRequest request = createMockAuthenticationRequest();
HttpSession sessionPreAuth = request.getSession();
// Setup our filter configuration
MockFilterConfig config = new MockFilterConfig(null, null);
// Setup our expectation that the filter chain will not be invoked, as we redirect
// to defaultTargetUrl
MockFilterChain chain = new MockFilterChain(false);
MockHttpServletResponse response = new MockHttpServletResponse();
// Setup our test object, to grant access
MockAuthenticationFilter filter = new MockAuthenticationFilter(true);
filter.setFilterProcessesUrl("/j_mock_post");
filter.setSessionAuthenticationStrategy(mock(SessionAuthenticationStrategy.class));
filter.setAuthenticationSuccessHandler(this.successHandler);
filter.setAuthenticationFailureHandler(this.failureHandler);
filter.setAuthenticationManager(mock(AuthenticationManager.class));
filter.afterPropertiesSet();
// Test
filter.doFilter(request, response, chain);
assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/logged_in.jsp");
@@ -211,24 +193,19 @@ public class AbstractAuthenticationProcessingFilterTests {
// Setup our HTTP request
MockHttpServletRequest request = createMockAuthenticationRequest();
HttpSession sessionPreAuth = request.getSession();
// Setup our filter configuration
MockFilterConfig config = new MockFilterConfig(null, null);
// Setup our expectation that the filter chain will not be invoked, as we redirect
// to defaultTargetUrl
MockFilterChain chain = new MockFilterChain(false);
MockHttpServletResponse response = new MockHttpServletResponse();
// Setup our test object, to grant access
MockAuthenticationFilter filter = new MockAuthenticationFilter("/j_mock_post",
mock(AuthenticationManager.class));
filter.setSessionAuthenticationStrategy(mock(SessionAuthenticationStrategy.class));
filter.setAuthenticationSuccessHandler(this.successHandler);
filter.setAuthenticationFailureHandler(this.failureHandler);
filter.afterPropertiesSet();
// Test
filter.doFilter(request, response, chain);
assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/logged_in.jsp");
@@ -245,24 +222,19 @@ public class AbstractAuthenticationProcessingFilterTests {
request.setServletPath("/j_eradicate_corona_virus");
request.setRequestURI("/mycontext/j_eradicate_corona_virus");
HttpSession sessionPreAuth = request.getSession();
// Setup our filter configuration
MockFilterConfig config = new MockFilterConfig(null, null);
// Setup our expectation that the filter chain will not be invoked, as we redirect
// to defaultTargetUrl
MockFilterChain chain = new MockFilterChain(false);
MockHttpServletResponse response = new MockHttpServletResponse();
// Setup our test object, to grant access
MockAuthenticationFilter filter = new MockAuthenticationFilter(
new AntPathRequestMatcher("/j_eradicate_corona_virus"), mock(AuthenticationManager.class));
filter.setSessionAuthenticationStrategy(mock(SessionAuthenticationStrategy.class));
filter.setAuthenticationSuccessHandler(this.successHandler);
filter.setAuthenticationFailureHandler(this.failureHandler);
filter.afterPropertiesSet();
// Test
filter.doFilter(request, response, chain);
assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/logged_in.jsp");
@@ -279,7 +251,6 @@ public class AbstractAuthenticationProcessingFilterTests {
this.successHandler.setDefaultTargetUrl("/");
filter.setAuthenticationSuccessHandler(this.successHandler);
filter.setFilterProcessesUrl("/login");
try {
filter.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
@@ -295,7 +266,6 @@ public class AbstractAuthenticationProcessingFilterTests {
filter.setAuthenticationFailureHandler(this.failureHandler);
filter.setAuthenticationManager(mock(AuthenticationManager.class));
filter.setAuthenticationSuccessHandler(this.successHandler);
try {
filter.setFilterProcessesUrl(null);
fail("Should have thrown IllegalArgumentException");
@@ -309,38 +279,31 @@ public class AbstractAuthenticationProcessingFilterTests {
public void testSuccessLoginThenFailureLoginResultsInSessionLosingToken() throws Exception {
// Setup our HTTP request
MockHttpServletRequest request = createMockAuthenticationRequest();
// Setup our filter configuration
MockFilterConfig config = new MockFilterConfig(null, null);
// Setup our expectation that the filter chain will not be invoked, as we redirect
// to defaultTargetUrl
MockFilterChain chain = new MockFilterChain(false);
MockHttpServletResponse response = new MockHttpServletResponse();
// Setup our test object, to grant access
MockAuthenticationFilter filter = new MockAuthenticationFilter(true);
filter.setFilterProcessesUrl("/j_mock_post");
filter.setAuthenticationSuccessHandler(this.successHandler);
// Test
filter.doFilter(request, response, chain);
assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/logged_in.jsp");
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).isEqualTo("test");
// Now try again but this time have filter deny access
// Setup our HTTP request
// Setup our expectation that the filter chain will not be invoked, as we redirect
// to authenticationFailureUrl
chain = new MockFilterChain(false);
response = new MockHttpServletResponse();
// Setup our test object, to deny access
filter = new MockAuthenticationFilter(false);
filter.setFilterProcessesUrl("/j_mock_post");
filter.setAuthenticationFailureHandler(this.failureHandler);
// Test
filter.doFilter(request, response, chain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
@@ -350,27 +313,21 @@ public class AbstractAuthenticationProcessingFilterTests {
public void testSuccessfulAuthenticationInvokesSuccessHandlerAndSetsContext() throws Exception {
// Setup our HTTP request
MockHttpServletRequest request = createMockAuthenticationRequest();
// Setup our filter configuration
MockFilterConfig config = new MockFilterConfig(null, null);
// Setup our expectation that the filter chain will be invoked, as we want to go
// to the location requested in the session
MockFilterChain chain = new MockFilterChain(true);
MockHttpServletResponse response = new MockHttpServletResponse();
// Setup our test object, to grant access
MockAuthenticationFilter filter = new MockAuthenticationFilter(true);
filter.setFilterProcessesUrl("/j_mock_post");
AuthenticationSuccessHandler successHandler = mock(AuthenticationSuccessHandler.class);
filter.setAuthenticationSuccessHandler(successHandler);
// Test
filter.doFilter(request, response, chain);
verify(successHandler).onAuthenticationSuccess(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(Authentication.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
}
@@ -378,26 +335,20 @@ public class AbstractAuthenticationProcessingFilterTests {
public void testFailedAuthenticationInvokesFailureHandler() throws Exception {
// Setup our HTTP request
MockHttpServletRequest request = createMockAuthenticationRequest();
// Setup our filter configuration
MockFilterConfig config = new MockFilterConfig(null, null);
// Setup our expectation that the filter chain will not be invoked, as we redirect
// to authenticationFailureUrl
MockFilterChain chain = new MockFilterChain(false);
MockHttpServletResponse response = new MockHttpServletResponse();
// Setup our test object, to deny access
MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
AuthenticationFailureHandler failureHandler = mock(AuthenticationFailureHandler.class);
filter.setAuthenticationFailureHandler(failureHandler);
// Test
filter.doFilter(request, response, chain);
verify(failureHandler).onAuthenticationFailure(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(AuthenticationException.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -407,18 +358,14 @@ public class AbstractAuthenticationProcessingFilterTests {
@Test
public void testNoSessionIsCreatedIfAllowSessionCreationIsFalse() throws Exception {
MockHttpServletRequest request = createMockAuthenticationRequest();
MockFilterConfig config = new MockFilterConfig(null, null);
MockFilterChain chain = new MockFilterChain(true);
MockHttpServletResponse response = new MockHttpServletResponse();
// Reject authentication, so exception would normally be stored in session
MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
this.failureHandler.setAllowSessionCreation(false);
filter.setAuthenticationFailureHandler(this.failureHandler);
filter.doFilter(request, response, chain);
assertThat(request.getSession(false)).isNull();
}
@@ -428,17 +375,13 @@ public class AbstractAuthenticationProcessingFilterTests {
@Test
public void testLoginErrorWithNoFailureUrlSendsUnauthorizedStatus() throws Exception {
MockHttpServletRequest request = createMockAuthenticationRequest();
MockFilterConfig config = new MockFilterConfig(null, null);
MockFilterChain chain = new MockFilterChain(true);
MockHttpServletResponse response = new MockHttpServletResponse();
MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
this.successHandler.setDefaultTargetUrl("https://monkeymachine.co.uk/");
filter.setAuthenticationSuccessHandler(this.successHandler);
filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
}
@@ -448,19 +391,15 @@ public class AbstractAuthenticationProcessingFilterTests {
@Test
public void loginErrorWithInternAuthenticationServiceExceptionLogsError() throws Exception {
MockHttpServletRequest request = createMockAuthenticationRequest();
MockFilterChain chain = new MockFilterChain(true);
MockHttpServletResponse response = new MockHttpServletResponse();
Log logger = mock(Log.class);
MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
ReflectionTestUtils.setField(filter, "logger", logger);
filter.exceptionToThrow = new InternalAuthenticationServiceException("Mock requested to do so");
this.successHandler.setDefaultTargetUrl("https://monkeymachine.co.uk/");
filter.setAuthenticationSuccessHandler(this.successHandler);
filter.doFilter(request, response, chain);
verify(logger).error(anyString(), eq(filter.exceptionToThrow));
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
}

View File

@@ -74,16 +74,13 @@ public class AnonymousAuthenticationFilterTests {
// Put an Authentication object into the SecurityContextHolder
Authentication originalAuth = new TestingAuthenticationToken("user", "password", "ROLE_A");
SecurityContextHolder.getContext().setAuthentication(originalAuth);
AnonymousAuthenticationFilter filter = new AnonymousAuthenticationFilter("qwerty", "anonymousUsername",
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
// Test
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("x");
executeFilterInContainerSimulator(mock(FilterConfig.class), filter, request, new MockHttpServletResponse(),
new MockFilterChain(true));
// Ensure filter didn't change our original object
assertThat(SecurityContextHolder.getContext().getAuthentication()).isEqualTo(originalAuth);
}
@@ -93,12 +90,10 @@ public class AnonymousAuthenticationFilterTests {
AnonymousAuthenticationFilter filter = new AnonymousAuthenticationFilter("qwerty", "anonymousUsername",
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
filter.afterPropertiesSet();
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("x");
executeFilterInContainerSimulator(mock(FilterConfig.class), filter, request, new MockHttpServletResponse(),
new MockFilterChain(true));
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
assertThat(auth.getPrincipal()).isEqualTo("anonymousUsername");
assertThat(AuthorityUtils.authorityListToSet(auth.getAuthorities())).contains("ROLE_ANONYMOUS");

View File

@@ -89,12 +89,10 @@ public class AuthenticationFilterTests {
public void filterWhenDefaultsAndNoAuthenticationThenContinues() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager,
this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verifyZeroInteractions(this.authenticationManager);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
@@ -104,12 +102,10 @@ public class AuthenticationFilterTests {
public void filterWhenAuthenticationManagerResolverDefaultsAndNoAuthenticationThenContinues() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verifyZeroInteractions(this.authenticationManagerResolver);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
@@ -122,12 +118,10 @@ public class AuthenticationFilterTests {
given(this.authenticationManager.authenticate(any())).willReturn(authentication);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager,
this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verify(this.authenticationManager).authenticate(any(Authentication.class));
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
@@ -139,15 +133,12 @@ public class AuthenticationFilterTests {
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE");
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(authentication);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verify(this.authenticationManager).authenticate(any(Authentication.class));
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
@@ -158,15 +149,12 @@ public class AuthenticationFilterTests {
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE");
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willThrow(new BadCredentialsException("failed"));
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager,
this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -177,15 +165,12 @@ public class AuthenticationFilterTests {
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE");
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willThrow(new BadCredentialsException("failed"));
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -195,11 +180,9 @@ public class AuthenticationFilterTests {
given(this.authenticationConverter.convert(any())).willReturn(null);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, new MockHttpServletResponse(), chain);
verifyZeroInteractions(this.authenticationManagerResolver);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
@@ -210,16 +193,13 @@ public class AuthenticationFilterTests {
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER");
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(authentication);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
filter.setSuccessHandler(this.successHandler);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verify(this.successHandler).onAuthenticationSuccess(any(), any(), any(), eq(authentication));
verifyZeroInteractions(this.failureHandler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
@@ -230,11 +210,9 @@ public class AuthenticationFilterTests {
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER");
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(null);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
filter.setSuccessHandler(this.successHandler);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
@@ -244,7 +222,6 @@ public class AuthenticationFilterTests {
catch (ServletException ex) {
verifyZeroInteractions(this.successHandler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
throw ex;
}
}
@@ -252,16 +229,13 @@ public class AuthenticationFilterTests {
@Test
public void filterWhenNotMatchAndConvertAndAuthenticationSuccessThenContinues() throws Exception {
given(this.requestMatcher.matches(any())).willReturn(false);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
filter.setRequestMatcher(this.requestMatcher);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verifyZeroInteractions(this.authenticationConverter, this.authenticationManagerResolver, this.successHandler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -272,18 +246,15 @@ public class AuthenticationFilterTests {
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE_USER");
given(this.authenticationConverter.convert(any())).willReturn(authentication);
given(this.authenticationManager.authenticate(any())).willReturn(authentication);
MockHttpSession session = new MockHttpSession();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
request.setSession(session);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = new MockFilterChain();
String sessionId = session.getId();
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager,
this.authenticationConverter);
filter.doFilter(request, response, chain);
assertThat(session.getId()).isNotEqualTo(sessionId);
}

View File

@@ -60,9 +60,7 @@ public class DefaultLoginPageGeneratingFilterTests {
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(
new UsernamePasswordAuthenticationFilter());
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(new MockHttpServletRequest("GET", "/login"), response, this.chain);
assertThat(response.getContentAsString()).isNotEmpty();
}
@@ -71,10 +69,8 @@ public class DefaultLoginPageGeneratingFilterTests {
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(
new UsernamePasswordAuthenticationFilter());
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/login");
filter.doFilter(request, response, this.chain);
assertThat(response.getContentAsString()).isEmpty();
}
@@ -83,11 +79,9 @@ public class DefaultLoginPageGeneratingFilterTests {
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(
new UsernamePasswordAuthenticationFilter());
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/context/login");
request.setContextPath("/context");
filter.doFilter(request, response, this.chain);
assertThat(response.getContentAsString()).isNotEmpty();
}
@@ -96,9 +90,7 @@ public class DefaultLoginPageGeneratingFilterTests {
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(
new UsernamePasswordAuthenticationFilter());
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(new MockHttpServletRequest("GET", "/api/login"), response, this.chain);
assertThat(response.getContentAsString()).isEmpty();
}
@@ -107,12 +99,9 @@ public class DefaultLoginPageGeneratingFilterTests {
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(
new UsernamePasswordAuthenticationFilter());
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/login");
request.setQueryString("error");
filter.doFilter(request, response, this.chain);
assertThat(response.getContentAsString()).isNotEmpty();
}
@@ -136,12 +125,9 @@ public class DefaultLoginPageGeneratingFilterTests {
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(
new UsernamePasswordAuthenticationFilter());
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/login");
request.setQueryString("not");
filter.doFilter(request, response, this.chain);
assertThat(response.getContentAsString()).isEmpty();
}
@@ -162,7 +148,6 @@ public class DefaultLoginPageGeneratingFilterTests {
String message = messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials",
"Bad credentials", Locale.KOREA);
request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, new BadCredentialsException(message));
filter.doFilter(request, new MockHttpServletResponse(), this.chain);
}
@@ -172,14 +157,11 @@ public class DefaultLoginPageGeneratingFilterTests {
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter();
filter.setLoginPageUrl(DefaultLoginPageGeneratingFilter.DEFAULT_LOGIN_PAGE_URL);
filter.setOauth2LoginEnabled(true);
String clientName = "Google < > \" \' &";
filter.setOauth2AuthenticationUrlToClientName(
Collections.singletonMap("/oauth2/authorization/google", clientName));
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(new MockHttpServletRequest("GET", "/login"), response, this.chain);
assertThat(response.getContentAsString())
.contains("<a href=\"/oauth2/authorization/google\">Google &lt; &gt; &quot; &#39; &amp;</a>");
}
@@ -189,13 +171,10 @@ public class DefaultLoginPageGeneratingFilterTests {
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter();
filter.setLoginPageUrl(DefaultLoginPageGeneratingFilter.DEFAULT_LOGIN_PAGE_URL);
filter.setSaml2LoginEnabled(true);
String clientName = "Google < > \" \' &";
filter.setSaml2AuthenticationUrlToProviderName(Collections.singletonMap("/saml/sso/google", clientName));
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(new MockHttpServletRequest("GET", "/login"), response, this.chain);
assertThat(response.getContentAsString()).contains("Login with SAML 2.0");
assertThat(response.getContentAsString())
.contains("<a href=\"/saml/sso/google\">Google &lt; &gt; &quot; &#39; &amp;</a>");

View File

@@ -61,7 +61,6 @@ public class DelegatingAuthenticationEntryPointContextTests {
verify(this.firstAEP).commence(request, null, null);
verify(this.defaultAEP, never()).commence(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(AuthenticationException.class));
}
@Test
@@ -73,7 +72,6 @@ public class DelegatingAuthenticationEntryPointContextTests {
verify(this.defaultAEP).commence(request, null, null);
verify(this.firstAEP, never()).commence(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(AuthenticationException.class));
}
}

View File

@@ -63,9 +63,7 @@ public class DelegatingAuthenticationEntryPointTests {
RequestMatcher firstRM = mock(RequestMatcher.class);
given(firstRM.matches(this.request)).willReturn(false);
this.entryPoints.put(firstRM, firstAEP);
this.daep.commence(this.request, null, null);
verify(this.defaultEntryPoint).commence(this.request, null, null);
verify(firstAEP, never()).commence(this.request, null, null);
}
@@ -79,9 +77,7 @@ public class DelegatingAuthenticationEntryPointTests {
given(firstRM.matches(this.request)).willReturn(true);
this.entryPoints.put(firstRM, firstAEP);
this.entryPoints.put(secondRM, secondAEP);
this.daep.commence(this.request, null, null);
verify(firstAEP).commence(this.request, null, null);
verify(secondAEP, never()).commence(this.request, null, null);
verify(this.defaultEntryPoint, never()).commence(this.request, null, null);
@@ -98,9 +94,7 @@ public class DelegatingAuthenticationEntryPointTests {
given(secondRM.matches(this.request)).willReturn(true);
this.entryPoints.put(firstRM, firstAEP);
this.entryPoints.put(secondRM, secondAEP);
this.daep.commence(this.request, null, null);
verify(secondAEP).commence(this.request, null, null);
verify(firstAEP, never()).commence(this.request, null, null);
verify(this.defaultEntryPoint, never()).commence(this.request, null, null);

View File

@@ -79,10 +79,8 @@ public class DelegatingAuthenticationFailureHandlerTests {
public void handleByDefaultHandler() throws Exception {
this.handlers.put(BadCredentialsException.class, this.handler1);
this.handler = new DelegatingAuthenticationFailureHandler(this.handlers, this.defaultHandler);
AuthenticationException exception = new AccountExpiredException("");
this.handler.onAuthenticationFailure(this.request, this.response, exception);
verifyZeroInteractions(this.handler1, this.handler2);
verify(this.defaultHandler).onAuthenticationFailure(this.request, this.response, exception);
}
@@ -92,10 +90,8 @@ public class DelegatingAuthenticationFailureHandlerTests {
this.handlers.put(BadCredentialsException.class, this.handler1); // same type
this.handlers.put(AccountStatusException.class, this.handler2);
this.handler = new DelegatingAuthenticationFailureHandler(this.handlers, this.defaultHandler);
AuthenticationException exception = new BadCredentialsException("");
this.handler.onAuthenticationFailure(this.request, this.response, exception);
verifyZeroInteractions(this.handler2, this.defaultHandler);
verify(this.handler1).onAuthenticationFailure(this.request, this.response, exception);
}
@@ -106,43 +102,32 @@ public class DelegatingAuthenticationFailureHandlerTests {
this.handlers.put(AccountStatusException.class, this.handler2); // super type of
// CredentialsExpiredException
this.handler = new DelegatingAuthenticationFailureHandler(this.handlers, this.defaultHandler);
AuthenticationException exception = new CredentialsExpiredException("");
this.handler.onAuthenticationFailure(this.request, this.response, exception);
verifyZeroInteractions(this.handler1, this.defaultHandler);
verify(this.handler2).onAuthenticationFailure(this.request, this.response, exception);
}
@Test
public void handlersIsNull() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("handlers cannot be null or empty");
new DelegatingAuthenticationFailureHandler(null, this.defaultHandler);
}
@Test
public void handlersIsEmpty() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("handlers cannot be null or empty");
new DelegatingAuthenticationFailureHandler(this.handlers, this.defaultHandler);
}
@Test
public void defaultHandlerIsNull() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("defaultHandler cannot be null");
this.handlers.put(BadCredentialsException.class, this.handler1);
new DelegatingAuthenticationFailureHandler(this.handlers, null);
}
}

View File

@@ -37,7 +37,6 @@ public class ExceptionMappingAuthenticationFailureHandlerTests {
fh.setDefaultFailureUrl("/failed");
MockHttpServletResponse response = new MockHttpServletResponse();
fh.onAuthenticationFailure(new MockHttpServletRequest(), response, new BadCredentialsException(""));
assertThat(response.getRedirectedUrl()).isEqualTo("/failed");
}
@@ -50,7 +49,6 @@ public class ExceptionMappingAuthenticationFailureHandlerTests {
fh.setDefaultFailureUrl("/failed");
MockHttpServletResponse response = new MockHttpServletResponse();
fh.onAuthenticationFailure(new MockHttpServletRequest(), response, new BadCredentialsException(""));
assertThat(response.getRedirectedUrl()).isEqualTo("/badcreds");
}

View File

@@ -48,13 +48,10 @@ public class ForwardAuthenticaionSuccessHandlerTests {
@Test
public void responseIsForwarded() throws Exception {
ForwardAuthenticationSuccessHandler fash = new ForwardAuthenticationSuccessHandler("/forwardUrl");
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication authentication = mock(Authentication.class);
fash.onAuthenticationSuccess(request, response, authentication);
assertThat(response.getForwardedUrl()).isEqualTo("/forwardUrl");
}

View File

@@ -48,13 +48,10 @@ public class ForwardAuthenticationFailureHandlerTests {
@Test
public void responseIsForwarded() throws Exception {
ForwardAuthenticationFailureHandler fafh = new ForwardAuthenticationFailureHandler("/forwardUrl");
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
AuthenticationException e = mock(AuthenticationException.class);
fafh.onAuthenticationFailure(request, response, e);
assertThat(response.getForwardedUrl()).isEqualTo("/forwardUrl");
assertThat(request.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION)).isEqualTo(e);
}

View File

@@ -58,7 +58,6 @@ public class HttpStatusEntryPointTests {
@Test
public void unauthorized() throws Exception {
this.entryPoint.commence(this.request, this.response, this.authException);
assertThat(this.response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
}

View File

@@ -61,7 +61,6 @@ public class LoginUrlAuthenticationEntryPointTests {
assertThat(ep.getLoginFormUrl()).isEqualTo("/hello");
assertThat(ep.getPortMapper() != null).isTrue();
assertThat(ep.getPortResolver() != null).isTrue();
ep.setForceHttps(false);
assertThat(ep.isForceHttps()).isFalse();
ep.setForceHttps(true);
@@ -79,44 +78,36 @@ public class LoginUrlAuthenticationEntryPointTests {
request.setServerName("www.example.com");
request.setContextPath("/bigWebApp");
request.setServerPort(80);
MockHttpServletResponse response = new MockHttpServletResponse();
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
ep.setPortMapper(new PortMapperImpl());
ep.setForceHttps(true);
ep.setPortMapper(new PortMapperImpl());
ep.setPortResolver(new MockPortResolver(80, 443));
ep.afterPropertiesSet();
ep.commence(request, response, null);
assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com/bigWebApp/hello");
request.setServerPort(8080);
response = new MockHttpServletResponse();
ep.setPortResolver(new MockPortResolver(8080, 8443));
ep.commence(request, response, null);
assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com:8443/bigWebApp/hello");
// Now test an unusual custom HTTP:HTTPS is handled properly
request.setServerPort(8888);
response = new MockHttpServletResponse();
ep.commence(request, response, null);
assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com:8443/bigWebApp/hello");
PortMapperImpl portMapper = new PortMapperImpl();
Map<String, String> map = new HashMap<>();
map.put("8888", "9999");
portMapper.setPortMappings(map);
response = new MockHttpServletResponse();
ep = new LoginUrlAuthenticationEntryPoint("/hello");
ep.setPortMapper(new PortMapperImpl());
ep.setForceHttps(true);
ep.setPortMapper(portMapper);
ep.setPortResolver(new MockPortResolver(8888, 9999));
ep.afterPropertiesSet();
ep.commence(request, response, null);
assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com:9999/bigWebApp/hello");
}
@@ -129,19 +120,15 @@ public class LoginUrlAuthenticationEntryPointTests {
request.setServerName("www.example.com");
request.setContextPath("/bigWebApp");
request.setServerPort(443);
MockHttpServletResponse response = new MockHttpServletResponse();
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
ep.setPortMapper(new PortMapperImpl());
ep.setForceHttps(true);
ep.setPortMapper(new PortMapperImpl());
ep.setPortResolver(new MockPortResolver(80, 443));
ep.afterPropertiesSet();
ep.commence(request, response, null);
assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com/bigWebApp/hello");
request.setServerPort(8443);
response = new MockHttpServletResponse();
ep.setPortResolver(new MockPortResolver(8080, 8443));
@@ -155,7 +142,6 @@ public class LoginUrlAuthenticationEntryPointTests {
ep.setPortMapper(new PortMapperImpl());
ep.setPortResolver(new MockPortResolver(80, 443));
ep.afterPropertiesSet();
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/some_path");
request.setContextPath("/bigWebApp");
@@ -163,9 +149,7 @@ public class LoginUrlAuthenticationEntryPointTests {
request.setServerName("localhost");
request.setContextPath("/bigWebApp");
request.setServerPort(80);
MockHttpServletResponse response = new MockHttpServletResponse();
ep.commence(request, response, null);
assertThat(response.getRedirectedUrl()).isEqualTo("http://localhost/bigWebApp/hello");
}
@@ -176,7 +160,6 @@ public class LoginUrlAuthenticationEntryPointTests {
ep.setPortResolver(new MockPortResolver(8888, 1234));
ep.setForceHttps(true);
ep.afterPropertiesSet();
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/some_path");
request.setContextPath("/bigWebApp");
@@ -184,11 +167,8 @@ public class LoginUrlAuthenticationEntryPointTests {
request.setServerName("localhost");
request.setContextPath("/bigWebApp");
request.setServerPort(8888); // NB: Port we can't resolve
MockHttpServletResponse response = new MockHttpServletResponse();
ep.commence(request, response, null);
// Response doesn't switch to HTTPS, as we didn't know HTTP port 8888 to HTTP port
// mapping
assertThat(response.getRedirectedUrl()).isEqualTo("http://localhost:8888/bigWebApp/hello");
@@ -207,9 +187,7 @@ public class LoginUrlAuthenticationEntryPointTests {
request.setServerName("www.example.com");
request.setContextPath("/bigWebApp");
request.setServerPort(80);
MockHttpServletResponse response = new MockHttpServletResponse();
ep.commence(request, response, null);
assertThat(response.getForwardedUrl()).isEqualTo("/hello");
}
@@ -228,9 +206,7 @@ public class LoginUrlAuthenticationEntryPointTests {
request.setServerName("www.example.com");
request.setContextPath("/bigWebApp");
request.setServerPort(80);
MockHttpServletResponse response = new MockHttpServletResponse();
ep.commence(request, response, null);
assertThat(response.getRedirectedUrl()).isEqualTo("https://www.example.com/bigWebApp/some_path");
}

View File

@@ -35,11 +35,9 @@ public class SavedRequestAwareAuthenticationSuccessHandlerTests {
@Test
public void defaultUrlMuststartWithSlashOrHttpScheme() {
SavedRequestAwareAuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler();
handler.setDefaultTargetUrl("/acceptableRelativeUrl");
handler.setDefaultTargetUrl("https://some.site.org/index.html");
handler.setDefaultTargetUrl("https://some.site.org/index.html");
try {
handler.setDefaultTargetUrl("missingSlash");
fail("Shouldn't accept default target without leading slash");
@@ -58,12 +56,10 @@ public class SavedRequestAwareAuthenticationSuccessHandlerTests {
MockHttpServletResponse response = new MockHttpServletResponse();
given(savedRequest.getRedirectUrl()).willReturn(redirectUrl);
given(requestCache.getRequest(request, response)).willReturn(savedRequest);
SavedRequestAwareAuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler();
handler.setRequestCache(requestCache);
handler.setRedirectStrategy(redirectStrategy);
handler.onAuthenticationSuccess(request, response, mock(Authentication.class));
verify(redirectStrategy).sendRedirect(request, response, redirectUrl);
}

View File

@@ -40,7 +40,6 @@ public class SimpleUrlAuthenticationFailureHandlerTests {
assertThat(afh.getRedirectStrategy()).isSameAs(rs);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
afh.onAuthenticationFailure(request, response, mock(AuthenticationException.class));
assertThat(response.getStatus()).isEqualTo(401);
}
@@ -51,9 +50,7 @@ public class SimpleUrlAuthenticationFailureHandlerTests {
afh.setDefaultFailureUrl("/target");
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
AuthenticationException e = mock(AuthenticationException.class);
afh.onAuthenticationFailure(request, response, e);
assertThat(request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION)).isSameAs(e);
assertThat(response.getRedirectedUrl()).isEqualTo("/target");
@@ -66,7 +63,6 @@ public class SimpleUrlAuthenticationFailureHandlerTests {
assertThat(afh.isAllowSessionCreation()).isFalse();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
afh.onAuthenticationFailure(request, response, mock(AuthenticationException.class));
assertThat(request.getSession(false)).isNull();
}
@@ -77,11 +73,9 @@ public class SimpleUrlAuthenticationFailureHandlerTests {
SimpleUrlAuthenticationFailureHandler afh = new SimpleUrlAuthenticationFailureHandler("/target");
afh.setUseForward(true);
assertThat(afh.isUseForward()).isTrue();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
AuthenticationException e = mock(AuthenticationException.class);
afh.onAuthenticationFailure(request, response, e);
assertThat(request.getSession(false)).isNull();
assertThat(response.getRedirectedUrl()).isNull();

View File

@@ -34,12 +34,9 @@ public class SimpleUrlAuthenticationSuccessHandlerTests {
@Test
public void defaultTargetUrlIsUsedIfNoOtherInformationSet() throws Exception {
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
ash.onAuthenticationSuccess(request, response, mock(Authentication.class));
assertThat(response.getRedirectedUrl()).isEqualTo("/");
}
@@ -50,7 +47,6 @@ public class SimpleUrlAuthenticationSuccessHandlerTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
response.setCommitted(true);
ash.onAuthenticationSuccess(request, response, mock(Authentication.class));
assertThat(response.getRedirectedUrl()).isNull();
}
@@ -64,10 +60,8 @@ public class SimpleUrlAuthenticationSuccessHandlerTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setParameter("targetUrl", "/target");
ash.onAuthenticationSuccess(request, response, mock(Authentication.class));
assertThat(response.getRedirectedUrl()).isEqualTo("/defaultTarget");
// Try with parameter set
ash.setTargetUrlParameter("targetUrl");
response = new MockHttpServletResponse();
@@ -82,7 +76,6 @@ public class SimpleUrlAuthenticationSuccessHandlerTests {
MockHttpServletResponse response = new MockHttpServletResponse();
ash.setUseReferer(true);
request.addHeader("Referer", "https://www.springsource.com/");
ash.onAuthenticationSuccess(request, response, mock(Authentication.class));
assertThat(response.getRedirectedUrl()).isEqualTo("https://www.springsource.com/");
}
@@ -96,9 +89,7 @@ public class SimpleUrlAuthenticationSuccessHandlerTests {
ash.setDefaultTargetUrl("https://monkeymachine.co.uk/");
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
ash.onAuthenticationSuccess(request, response, mock(Authentication.class));
assertThat(response.getRedirectedUrl()).isEqualTo("https://monkeymachine.co.uk/");
}
@@ -113,14 +104,12 @@ public class SimpleUrlAuthenticationSuccessHandlerTests {
@Test
public void setTargetUrlParameterEmptyTargetUrlParameter() {
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler();
try {
ash.setTargetUrlParameter("");
fail("Expected Exception");
}
catch (IllegalArgumentException success) {
}
try {
ash.setTargetUrlParameter(" ");
fail("Expected Exception");

View File

@@ -44,11 +44,9 @@ public class UsernamePasswordAuthenticationFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod");
request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "koala");
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
filter.setAuthenticationManager(createAuthenticationManager());
// filter.init(null);
Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse());
assertThat(result != null).isTrue();
assertThat(((WebAuthenticationDetails) result.getDetails()).getRemoteAddress()).isEqualTo("127.0.0.1");
@@ -59,10 +57,8 @@ public class UsernamePasswordAuthenticationFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod");
request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "dokdo");
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(
createAuthenticationManager());
Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse());
assertThat(result).isNotNull();
}
@@ -71,7 +67,6 @@ public class UsernamePasswordAuthenticationFilterTests {
public void testNullPasswordHandledGracefully() {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod");
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
filter.setAuthenticationManager(createAuthenticationManager());
assertThat(filter.attemptAuthentication(request, new MockHttpServletResponse())).isNotNull();
@@ -81,7 +76,6 @@ public class UsernamePasswordAuthenticationFilterTests {
public void testNullUsernameHandledGracefully() {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "koala");
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
filter.setAuthenticationManager(createAuthenticationManager());
assertThat(filter.attemptAuthentication(request, new MockHttpServletResponse())).isNotNull();
@@ -93,11 +87,9 @@ public class UsernamePasswordAuthenticationFilterTests {
filter.setAuthenticationManager(createAuthenticationManager());
filter.setUsernameParameter("x");
filter.setPasswordParameter("y");
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
request.addParameter("x", "rod");
request.addParameter("y", "koala");
Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse());
assertThat(result).isNotNull();
assertThat(((WebAuthenticationDetails) result.getDetails()).getRemoteAddress()).isEqualTo("127.0.0.1");
@@ -108,10 +100,8 @@ public class UsernamePasswordAuthenticationFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, " rod ");
request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "koala");
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
filter.setAuthenticationManager(createAuthenticationManager());
Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse());
assertThat(result.getName()).isEqualTo("rod");
}
@@ -124,7 +114,6 @@ public class UsernamePasswordAuthenticationFilterTests {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
filter.setAuthenticationManager(am);
try {
filter.attemptAuthentication(request, new MockHttpServletResponse());
fail("Expected AuthenticationException");
@@ -140,13 +129,10 @@ public class UsernamePasswordAuthenticationFilterTests {
public void noSessionIsCreatedIfAllowSessionCreationIsFalse() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("POST");
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
filter.setAllowSessionCreation(false);
filter.setAuthenticationManager(createAuthenticationManager());
filter.attemptAuthentication(request, new MockHttpServletResponse());
assertThat(request.getSession(false)).isNull();
}
@@ -154,7 +140,6 @@ public class UsernamePasswordAuthenticationFilterTests {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(Authentication.class)))
.willAnswer((Answer<Authentication>) (invocation) -> (Authentication) invocation.getArguments()[0]);
return am;
}

View File

@@ -59,11 +59,8 @@ public class CompositeLogoutHandlerTests {
public void callLogoutHandlersSuccessfullyWithArray() {
LogoutHandler securityContextLogoutHandler = mock(SecurityContextLogoutHandler.class);
LogoutHandler csrfLogoutHandler = mock(SecurityContextLogoutHandler.class);
LogoutHandler handler = new CompositeLogoutHandler(securityContextLogoutHandler, csrfLogoutHandler);
handler.logout(mock(HttpServletRequest.class), mock(HttpServletResponse.class), mock(Authentication.class));
verify(securityContextLogoutHandler, times(1)).logout(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(Authentication.class));
verify(csrfLogoutHandler, times(1)).logout(any(HttpServletRequest.class), any(HttpServletResponse.class),
@@ -74,12 +71,9 @@ public class CompositeLogoutHandlerTests {
public void callLogoutHandlersSuccessfully() {
LogoutHandler securityContextLogoutHandler = mock(SecurityContextLogoutHandler.class);
LogoutHandler csrfLogoutHandler = mock(SecurityContextLogoutHandler.class);
List<LogoutHandler> logoutHandlers = Arrays.asList(securityContextLogoutHandler, csrfLogoutHandler);
LogoutHandler handler = new CompositeLogoutHandler(logoutHandlers);
handler.logout(mock(HttpServletRequest.class), mock(HttpServletResponse.class), mock(Authentication.class));
verify(securityContextLogoutHandler, times(1)).logout(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(Authentication.class));
verify(csrfLogoutHandler, times(1)).logout(any(HttpServletRequest.class), any(HttpServletResponse.class),
@@ -90,22 +84,17 @@ public class CompositeLogoutHandlerTests {
public void callLogoutHandlersThrowException() {
LogoutHandler firstLogoutHandler = mock(LogoutHandler.class);
LogoutHandler secondLogoutHandler = mock(LogoutHandler.class);
willThrow(new IllegalArgumentException()).given(firstLogoutHandler).logout(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(Authentication.class));
List<LogoutHandler> logoutHandlers = Arrays.asList(firstLogoutHandler, secondLogoutHandler);
LogoutHandler handler = new CompositeLogoutHandler(logoutHandlers);
try {
handler.logout(mock(HttpServletRequest.class), mock(HttpServletResponse.class), mock(Authentication.class));
fail("Expected Exception");
}
catch (IllegalArgumentException success) {
}
InOrder logoutHandlersInOrder = inOrder(firstLogoutHandler, secondLogoutHandler);
logoutHandlersInOrder.verify(firstLogoutHandler, times(1)).logout(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(Authentication.class));
logoutHandlersInOrder.verify(secondLogoutHandler, never()).logout(any(HttpServletRequest.class),

View File

@@ -81,9 +81,7 @@ public class DelegatingLogoutSuccessHandlerTests {
public void onLogoutSuccessFirstMatches() throws Exception {
this.delegatingHandler.setDefaultLogoutSuccessHandler(this.defaultHandler);
given(this.matcher.matches(this.request)).willReturn(true);
this.delegatingHandler.onLogoutSuccess(this.request, this.response, this.authentication);
verify(this.handler).onLogoutSuccess(this.request, this.response, this.authentication);
verifyZeroInteractions(this.matcher2, this.handler2, this.defaultHandler);
}
@@ -92,9 +90,7 @@ public class DelegatingLogoutSuccessHandlerTests {
public void onLogoutSuccessSecondMatches() throws Exception {
this.delegatingHandler.setDefaultLogoutSuccessHandler(this.defaultHandler);
given(this.matcher2.matches(this.request)).willReturn(true);
this.delegatingHandler.onLogoutSuccess(this.request, this.response, this.authentication);
verify(this.handler2).onLogoutSuccess(this.request, this.response, this.authentication);
verifyZeroInteractions(this.handler, this.defaultHandler);
}
@@ -102,18 +98,14 @@ public class DelegatingLogoutSuccessHandlerTests {
@Test
public void onLogoutSuccessDefault() throws Exception {
this.delegatingHandler.setDefaultLogoutSuccessHandler(this.defaultHandler);
this.delegatingHandler.onLogoutSuccess(this.request, this.response, this.authentication);
verify(this.defaultHandler).onLogoutSuccess(this.request, this.response, this.authentication);
verifyZeroInteractions(this.handler, this.handler2);
}
@Test
public void onLogoutSuccessNoMatchDefaultNull() throws Exception {
this.delegatingHandler.onLogoutSuccess(this.request, this.response, this.authentication);
verifyZeroInteractions(this.handler, this.handler2, this.defaultHandler);
}

View File

@@ -40,20 +40,16 @@ public class ForwardLogoutSuccessHandlerTests {
@Test
public void invalidTargetUrl() {
String targetUrl = "not.valid";
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("'" + targetUrl + "' is not a valid target URL");
new ForwardLogoutSuccessHandler(targetUrl);
}
@Test
public void emptyTargetUrl() {
String targetUrl = " ";
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("'" + targetUrl + "' is not a valid target URL");
new ForwardLogoutSuccessHandler(targetUrl);
}
@@ -61,13 +57,10 @@ public class ForwardLogoutSuccessHandlerTests {
public void logoutSuccessIsHandled() throws Exception {
String targetUrl = "/login?logout";
ForwardLogoutSuccessHandler handler = new ForwardLogoutSuccessHandler(targetUrl);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication authentication = mock(Authentication.class);
handler.onLogoutSuccess(request, response, authentication);
assertThat(response.getForwardedUrl()).isEqualTo(targetUrl);
}

View File

@@ -53,7 +53,6 @@ public class HeaderWriterLogoutHandlerTests {
public void constructorWhenHeaderWriterIsNullThenThrowsException() {
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("headerWriter cannot be null");
new HeaderWriterLogoutHandler(null);
}
@@ -62,7 +61,6 @@ public class HeaderWriterLogoutHandlerTests {
HeaderWriter headerWriter = mock(HeaderWriter.class);
HeaderWriterLogoutHandler handler = new HeaderWriterLogoutHandler(headerWriter);
handler.logout(this.request, this.response, mock(Authentication.class));
verify(headerWriter).writeHeaders(this.request, this.response);
}

View File

@@ -35,12 +35,9 @@ public class HttpStatusReturningLogoutSuccessHandlerTests {
@Test
public void testDefaultHttpStatusBeingReturned() throws Exception {
final HttpStatusReturningLogoutSuccessHandler lsh = new HttpStatusReturningLogoutSuccessHandler();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
lsh.onLogoutSuccess(request, response, mock(Authentication.class));
assertThat(request.getSession(false)).isNull();
assertThat(response.getRedirectedUrl()).isNull();
assertThat(response.getForwardedUrl()).isNull();
@@ -51,12 +48,9 @@ public class HttpStatusReturningLogoutSuccessHandlerTests {
public void testCustomHttpStatusBeingReturned() throws Exception {
final HttpStatusReturningLogoutSuccessHandler lsh = new HttpStatusReturningLogoutSuccessHandler(
HttpStatus.NO_CONTENT);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
lsh.onLogoutSuccess(request, response, mock(Authentication.class));
assertThat(request.getSession(false)).isNull();
assertThat(response.getRedirectedUrl()).isNull();
assertThat(response.getForwardedUrl()).isNull();
@@ -65,7 +59,6 @@ public class HttpStatusReturningLogoutSuccessHandlerTests {
@Test
public void testThatSettNullHttpStatusThrowsException() {
try {
new HttpStatusReturningLogoutSuccessHandler(null);
}
@@ -73,7 +66,6 @@ public class HttpStatusReturningLogoutSuccessHandlerTests {
assertThat(ex).hasMessage("The provided HttpStatus must not be null.");
return;
}
fail("Expected an IllegalArgumentException to be thrown.");
}

View File

@@ -41,11 +41,9 @@ public class LogoutHandlerTests {
public void testRequiresLogoutUrlWorksWithPathParams() {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setRequestURI("/context/logout;someparam=blah?param=blah");
request.setServletPath("/logout;someparam=blah");
request.setQueryString("otherparam=blah");
DefaultHttpFirewall fw = new DefaultHttpFirewall();
assertThat(this.filter.requiresLogout(fw.getFirewalledRequest(request), response)).isTrue();
}
@@ -55,11 +53,9 @@ public class LogoutHandlerTests {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContextPath("/context");
MockHttpServletResponse response = new MockHttpServletResponse();
request.setServletPath("/logout");
request.setRequestURI("/context/logout?param=blah");
request.setQueryString("otherparam=blah");
assertThat(this.filter.requiresLogout(request, response)).isTrue();
}

View File

@@ -37,9 +37,7 @@ public class LogoutSuccessEventPublishingLogoutHandlerTests {
LogoutSuccessEventPublishingLogoutHandler handler = new LogoutSuccessEventPublishingLogoutHandler();
LogoutAwareEventPublisher eventPublisher = new LogoutAwareEventPublisher();
handler.setApplicationEventPublisher(eventPublisher);
handler.logout(new MockHttpServletRequest(), new MockHttpServletResponse(), mock(Authentication.class));
assertThat(eventPublisher.flag).isTrue();
}
@@ -48,9 +46,7 @@ public class LogoutSuccessEventPublishingLogoutHandlerTests {
LogoutSuccessEventPublishingLogoutHandler handler = new LogoutSuccessEventPublishingLogoutHandler();
LogoutAwareEventPublisher eventPublisher = new LogoutAwareEventPublisher();
handler.setApplicationEventPublisher(eventPublisher);
handler.logout(new MockHttpServletRequest(), new MockHttpServletResponse(), null);
assertThat(eventPublisher.flag).isFalse();
}

View File

@@ -46,9 +46,7 @@ public class SecurityContextLogoutHandlerTests {
public void setUp() {
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.handler = new SecurityContextLogoutHandler();
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(
new TestingAuthenticationToken("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER")));
@@ -74,7 +72,6 @@ public class SecurityContextLogoutHandlerTests {
SecurityContext beforeContext = SecurityContextHolder.getContext();
Authentication beforeAuthentication = beforeContext.getAuthentication();
this.handler.logout(this.request, this.response, SecurityContextHolder.getContext().getAuthentication());
assertThat(beforeContext.getAuthentication()).isNotNull();
assertThat(beforeContext.getAuthentication()).isSameAs(beforeAuthentication);
}

View File

@@ -144,9 +144,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
filter.principal = null;
filter.setCheckForPrincipalChanges(true);
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -156,9 +154,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
SecurityContextHolder.getContext().setAuthentication(authentication);
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
filter.principal = null;
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isEqualTo(authentication);
}
@@ -170,16 +166,13 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
filter.setCheckForPrincipalChanges(true);
filter.principal = principal;
AuthenticationManager am = mock(AuthenticationManager.class);
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verifyZeroInteractions(am);
}
@@ -192,16 +185,13 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
filter.setCheckForPrincipalChanges(true);
filter.principal = "newUser";
AuthenticationManager am = mock(AuthenticationManager.class);
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class));
}
@@ -214,7 +204,6 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
filter.setAuthenticationSuccessHandler(new ForwardAuthenticationSuccessHandler("/forwardUrl"));
filter.setCheckForPrincipalChanges(true);
@@ -222,9 +211,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
AuthenticationManager am = mock(AuthenticationManager.class);
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class));
assertThat(response.getForwardedUrl()).isEqualTo("/forwardUrl");
}
@@ -234,7 +221,6 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
filter.setAuthenticationFailureHandler(new ForwardAuthenticationFailureHandler("/forwardUrl"));
filter.setCheckForPrincipalChanges(true);
@@ -243,9 +229,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
.willThrow(new PreAuthenticatedCredentialsNotFoundException("invalid"));
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class));
assertThat(response.getForwardedUrl()).isEqualTo("/forwardUrl");
assertThat(request.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION)).isNotNull();
@@ -260,16 +244,13 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
filter.setCheckForPrincipalChanges(true);
filter.principal = principal;
AuthenticationManager am = mock(AuthenticationManager.class);
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verifyZeroInteractions(am);
}
@@ -282,7 +263,6 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
filter.setCheckForPrincipalChanges(true);
filter.principal = new User(currentPrincipal.getUsername(), currentPrincipal.getPassword(),
@@ -290,9 +270,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
AuthenticationManager am = mock(AuthenticationManager.class);
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verifyZeroInteractions(am);
}
@@ -305,16 +283,13 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
filter.setCheckForPrincipalChanges(true);
filter.principal = new Object();
AuthenticationManager am = mock(AuthenticationManager.class);
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class));
}
@@ -326,7 +301,6 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter() {
@Override
protected boolean principalChanged(HttpServletRequest request, Authentication currentAuthentication) {
@@ -338,9 +312,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
AuthenticationManager am = mock(AuthenticationManager.class);
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class));
}
@@ -352,7 +324,6 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter() {
@Override
protected boolean principalChanged(HttpServletRequest request, Authentication currentAuthentication) {
@@ -364,9 +335,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
AuthenticationManager am = mock(AuthenticationManager.class);
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verifyZeroInteractions(am);
}
@@ -375,16 +344,12 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
filter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/no-matching"));
AuthenticationManager am = mock(AuthenticationManager.class);
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verifyZeroInteractions(am);
}
@@ -393,18 +358,13 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
filter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/**"));
AuthenticationManager am = mock(AuthenticationManager.class);
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class));
}
private void testDoFilter(boolean grantAccess) throws Exception {
@@ -417,7 +377,6 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
private static ConcretePreAuthenticatedProcessingFilter getFilter(boolean grantAccess) {
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
AuthenticationManager am = mock(AuthenticationManager.class);
if (!grantAccess) {
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
}
@@ -425,7 +384,6 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
given(am.authenticate(any(Authentication.class)))
.willAnswer((Answer<Authentication>) (invocation) -> (Authentication) invocation.getArguments()[0]);
}
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
return filter;

View File

@@ -37,7 +37,6 @@ public class PreAuthenticatedAuthenticationProviderTests {
@Test(expected = IllegalArgumentException.class)
public final void afterPropertiesSet() {
PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
provider.afterPropertiesSet();
}
@@ -120,7 +119,6 @@ public class PreAuthenticatedAuthenticationProviderTests {
if (aUserDetails != null && aUserDetails.getUsername().equals(token.getName())) {
return aUserDetails;
}
throw new UsernameNotFoundException("notfound");
};
}

View File

@@ -68,12 +68,10 @@ public class PreAuthenticatedAuthenticationTokenTests {
assertThat(token.getDetails()).isNull();
assertThat(token.getAuthorities()).isNotNull();
Collection<GrantedAuthority> resultColl = token.getAuthorities();
assertThat(
gas.containsAll(resultColl) && resultColl.containsAll(gas)).withFailMessage(
assertThat(gas.containsAll(resultColl) && resultColl.containsAll(gas))
.withFailMessage(
"GrantedAuthority collections do not match; result: " + resultColl + ", expected: " + gas)
.isTrue();
.isTrue();
}
}

View File

@@ -71,11 +71,9 @@ public class PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests {
assertThat(ud.isCredentialsNonExpired()).isTrue();
assertThat(ud.isEnabled()).isTrue();
assertThat(userName).isEqualTo(ud.getUsername());
// Password is not saved by
// PreAuthenticatedGrantedAuthoritiesUserDetailsService
// assertThat(password).isEqualTo(ud.getPassword());
assertThat(gas.containsAll(ud.getAuthorities()) && ud.getAuthorities().containsAll(gas)).withFailMessage(
"GrantedAuthority collections do not match; result: " + ud.getAuthorities() + ", expected: " + gas)
.isTrue();

View File

@@ -50,7 +50,6 @@ public class RequestAttributeAuthenticationFilterTests {
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
RequestAttributeAuthenticationFilter filter = new RequestAttributeAuthenticationFilter();
filter.doFilter(request, response, chain);
}
@@ -62,7 +61,6 @@ public class RequestAttributeAuthenticationFilterTests {
MockFilterChain chain = new MockFilterChain();
RequestAttributeAuthenticationFilter filter = new RequestAttributeAuthenticationFilter();
filter.setAuthenticationManager(createAuthenticationManager());
filter.doFilter(request, response, chain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("cat");
@@ -78,7 +76,6 @@ public class RequestAttributeAuthenticationFilterTests {
RequestAttributeAuthenticationFilter filter = new RequestAttributeAuthenticationFilter();
filter.setAuthenticationManager(createAuthenticationManager());
filter.setPrincipalEnvironmentVariable("myUsernameVariable");
filter.doFilter(request, response, chain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("wolfman");
@@ -94,7 +91,6 @@ public class RequestAttributeAuthenticationFilterTests {
filter.setCredentialsEnvironmentVariable("myCredentialsVariable");
request.setAttribute("REMOTE_USER", "cat");
request.setAttribute("myCredentialsVariable", "catspassword");
filter.doFilter(request, response, chain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("catspassword");
@@ -130,7 +126,6 @@ public class RequestAttributeAuthenticationFilterTests {
MockFilterChain chain = new MockFilterChain();
RequestAttributeAuthenticationFilter filter = new RequestAttributeAuthenticationFilter();
filter.setAuthenticationManager(createAuthenticationManager());
filter.doFilter(request, response, chain);
}
@@ -152,7 +147,6 @@ public class RequestAttributeAuthenticationFilterTests {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(Authentication.class)))
.willAnswer((Answer<Authentication>) (invocation) -> (Authentication) invocation.getArguments()[0]);
return am;
}

View File

@@ -52,7 +52,6 @@ public class RequestHeaderAuthenticationFilterTests {
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
filter.doFilter(request, response, chain);
}
@@ -64,7 +63,6 @@ public class RequestHeaderAuthenticationFilterTests {
MockFilterChain chain = new MockFilterChain();
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
filter.setAuthenticationManager(createAuthenticationManager());
filter.doFilter(request, response, chain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("cat");
@@ -80,7 +78,6 @@ public class RequestHeaderAuthenticationFilterTests {
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
filter.setAuthenticationManager(createAuthenticationManager());
filter.setPrincipalRequestHeader("myUsernameHeader");
filter.doFilter(request, response, chain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("wolfman");
@@ -96,7 +93,6 @@ public class RequestHeaderAuthenticationFilterTests {
filter.setCredentialsRequestHeader("myCredentialsHeader");
request.addHeader("SM_USER", "cat");
request.addHeader("myCredentialsHeader", "catspassword");
filter.doFilter(request, response, chain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("catspassword");
@@ -131,7 +127,6 @@ public class RequestHeaderAuthenticationFilterTests {
MockFilterChain chain = new MockFilterChain();
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
filter.setAuthenticationManager(createAuthenticationManager());
filter.doFilter(request, response, chain);
}
@@ -153,7 +148,6 @@ public class RequestHeaderAuthenticationFilterTests {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(Authentication.class)))
.willAnswer((Answer<Authentication>) (invocation) -> (Authentication) invocation.getArguments()[0]);
return am;
}

View File

@@ -125,7 +125,6 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests {
List<GrantedAuthority> gas = details.getGrantedAuthorities();
assertThat(gas).as("Granted authorities should not be null").isNotNull();
assertThat(gas).hasSize(expectedRoles.length);
Collection<String> expectedRolesColl = Arrays.asList(expectedRoles);
Collection<String> gasRolesSet = new HashSet<>();
for (GrantedAuthority grantedAuthority : gas) {
@@ -140,7 +139,6 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests {
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource result = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource();
result.setMappableRolesRetriever(getMappableRolesRetriever(mappedRoles));
result.setUserRoles2GrantedAuthoritiesMapper(getJ2eeUserRoles2GrantedAuthoritiesMapper());
try {
result.afterPropertiesSet();
}
@@ -167,7 +165,6 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests {
private HttpServletRequest getRequest(final String userName, final String[] aRoles) {
MockHttpServletRequest req = new MockHttpServletRequest() {
private Set<String> roles = new HashSet<>(Arrays.asList(aRoles));
@Override

View File

@@ -49,7 +49,6 @@ public class J2eePreAuthenticatedProcessingFilterTests {
private HttpServletRequest getRequest(final String aUserName, final String[] aRoles) {
MockHttpServletRequest req = new MockHttpServletRequest() {
private Set<String> roles = new HashSet<>(Arrays.asList(aRoles));
@Override

View File

@@ -35,7 +35,6 @@ public class WebXmlJ2eeDefinedRolesRetrieverTests {
List<String> ROLE1TO4_EXPECTED_ROLES = Arrays.asList("Role1", "Role2", "Role3", "Role4");
final Resource webXml = new ClassPathResource("webxml/Role1-4.web.xml");
WebXmlMappableAttributesRetriever rolesRetriever = new WebXmlMappableAttributesRetriever();
rolesRetriever.setResourceLoader(new ResourceLoader() {
@Override
public ClassLoader getClassLoader() {
@@ -47,7 +46,6 @@ public class WebXmlJ2eeDefinedRolesRetrieverTests {
return webXml;
}
});
rolesRetriever.afterPropertiesSet();
Set<String> j2eeRoles = rolesRetriever.getMappableAttributes();
assertThat(j2eeRoles).containsAll(ROLE1TO4_EXPECTED_ROLES);

View File

@@ -52,17 +52,14 @@ public class WebSpherePreAuthenticatedProcessingFilterTests {
WebSpherePreAuthenticatedProcessingFilter filter = new WebSpherePreAuthenticatedProcessingFilter(helper);
assertThat(filter.getPreAuthenticatedPrincipal(new MockHttpServletRequest())).isEqualTo("jerry");
assertThat(filter.getPreAuthenticatedCredentials(new MockHttpServletRequest())).isEqualTo("N/A");
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(Authentication.class)))
.willAnswer((Answer<Authentication>) (invocation) -> (Authentication) invocation.getArguments()[0]);
filter.setAuthenticationManager(am);
WebSpherePreAuthenticatedWebAuthenticationDetailsSource ads = new WebSpherePreAuthenticatedWebAuthenticationDetailsSource(
helper);
ads.setWebSphereGroups2GrantedAuthoritiesMapper(new SimpleAttributes2GrantedAuthoritiesMapper());
filter.setAuthenticationDetailsSource(ads);
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), mock(FilterChain.class));
}

View File

@@ -94,10 +94,8 @@ public final class X509TestUtils {
+ "lcKwXuDRBWciODK/xWhvQbaegGJ1BtXcEHtvNjrUJLwSMDSr+U5oUYdMohG0h1iJ\n"
+ "R+JQc49I33o2cTc77wfEWLtVdXAyYY4GSJR6VfgvV40x85ItaNS3HHfT/aXU1x4m\n"
+ "W9YQkWlA6t0blGlC+ghTOY1JbgWnEfXMmVgg9a9cWaYQ+NQwqA==\n" + "-----END CERTIFICATE-----";
ByteArrayInputStream in = new ByteArrayInputStream(cert.getBytes());
CertificateFactory cf = CertificateFactory.getInstance("X.509");
return (X509Certificate) cf.generateCertificate(in);
}
@@ -134,7 +132,6 @@ public final class X509TestUtils {
+ "-----END CERTIFICATE-----\n";
ByteArrayInputStream in = new ByteArrayInputStream(cert.getBytes());
CertificateFactory cf = CertificateFactory.getInstance("X.509");
return (X509Certificate) cf.generateCertificate(in);
}

View File

@@ -90,12 +90,10 @@ public class AbstractRememberMeServicesTests {
public void cookieShouldBeCorrectlyEncodedAndDecoded() {
String[] cookie = new String[] { "name:with:colon", "cookie", "tokens", "blah" };
MockRememberMeServices services = new MockRememberMeServices(this.uds);
String encoded = services.encodeCookie(cookie);
// '=' aren't allowed in version 0 cookies.
assertThat(encoded).doesNotEndWith("=");
String[] decoded = services.decodeCookie(encoded);
assertThat(decoded).containsExactly("name:with:colon", "cookie", "tokens", "blah");
}
@@ -103,11 +101,9 @@ public class AbstractRememberMeServicesTests {
public void cookieWithOpenIDidentifierAsNameIsEncodedAndDecoded() {
String[] cookie = new String[] { "https://id.openid.zz", "cookie", "tokens", "blah" };
MockRememberMeServices services = new MockRememberMeServices(this.uds);
String[] decoded = services.decodeCookie(services.encodeCookie(cookie));
assertThat(decoded).hasSize(4);
assertThat(decoded[0]).isEqualTo("https://id.openid.zz");
// Check https (SEC-1410)
cookie[0] = "https://id.openid.zz";
decoded = services.decodeCookie(services.encodeCookie(cookie));
@@ -120,12 +116,9 @@ public class AbstractRememberMeServicesTests {
MockRememberMeServices services = new MockRememberMeServices(this.uds);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(services.autoLogin(request, response)).isNull();
// shouldn't try to invalidate our cookie
assertThat(response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull();
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
// set non-login cookie
@@ -139,14 +132,10 @@ public class AbstractRememberMeServicesTests {
MockRememberMeServices services = new MockRememberMeServices(this.uds);
services.afterPropertiesSet();
assertThat(services.getUserDetailsService()).isNotNull();
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(createLoginCookie("cookie:1:2"));
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication result = services.autoLogin(request, response);
assertThat(result).isNotNull();
}
@@ -155,7 +144,6 @@ public class AbstractRememberMeServicesTests {
MockRememberMeServices services = new MockRememberMeServices(this.uds);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setCookies(new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, "ZZZ"));
Authentication result = services.autoLogin(request, response);
assertThat(result).isNull();
@@ -167,7 +155,6 @@ public class AbstractRememberMeServicesTests {
MockRememberMeServices services = new MockRememberMeServices(this.uds);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setCookies(new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, ""));
Authentication result = services.autoLogin(request, response);
assertThat(result).isNull();
@@ -177,16 +164,12 @@ public class AbstractRememberMeServicesTests {
@Test
public void autoLoginShouldFailIfInvalidCookieExceptionIsRaised() {
MockRememberMeServices services = new MockRememberMeServices(new MockUserDetailsService(joe, true));
MockHttpServletRequest request = new MockHttpServletRequest();
// Wrong number of tokens
request.setCookies(createLoginCookie("cookie:1"));
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication result = services.autoLogin(request, response);
assertThat(result).isNull();
assertCookieCancelled(response);
}
@@ -194,15 +177,11 @@ public class AbstractRememberMeServicesTests {
public void autoLoginShouldFailIfUserNotFound() {
this.uds.setThrowException(true);
MockRememberMeServices services = new MockRememberMeServices(this.uds);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(createLoginCookie("cookie:1:2"));
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication result = services.autoLogin(request, response);
assertThat(result).isNull();
assertCookieCancelled(response);
}
@@ -211,15 +190,11 @@ public class AbstractRememberMeServicesTests {
MockRememberMeServices services = new MockRememberMeServices(this.uds);
services.setUserDetailsChecker(new AccountStatusUserDetailsChecker());
this.uds.toReturn = new User("joe", "password", false, true, true, true, joe.getAuthorities());
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(createLoginCookie("cookie:1:2"));
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication result = services.autoLogin(request, response);
assertThat(result).isNull();
assertCookieCancelled(response);
}
@@ -227,14 +202,11 @@ public class AbstractRememberMeServicesTests {
public void loginFailShouldCancelCookie() {
this.uds.setThrowException(true);
MockRememberMeServices services = new MockRememberMeServices(this.uds);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContextPath("contextpath");
request.setCookies(createLoginCookie("cookie:1:2"));
MockHttpServletResponse response = new MockHttpServletResponse();
services.loginFail(request, response);
assertCookieCancelled(response);
}
@@ -242,20 +214,15 @@ public class AbstractRememberMeServicesTests {
public void logoutShouldCancelCookie() {
MockRememberMeServices services = new MockRememberMeServices(this.uds);
services.setCookieDomain("spring.io");
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContextPath("contextpath");
request.setCookies(createLoginCookie("cookie:1:2"));
MockHttpServletResponse response = new MockHttpServletResponse();
services.logout(request, response, Mockito.mock(Authentication.class));
// Try again with null Authentication
response = new MockHttpServletResponse();
services.logout(request, response, null);
assertCookieCancelled(response);
Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie.getDomain()).isEqualTo("spring.io");
}
@@ -265,20 +232,15 @@ public class AbstractRememberMeServicesTests {
MockRememberMeServices services = new MockRememberMeServices(this.uds);
services.setCookieDomain("spring.io");
services.setUseSecureCookie(true);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContextPath("contextpath");
request.setCookies(createLoginCookie("cookie:1:2"));
MockHttpServletResponse response = new MockHttpServletResponse();
services.logout(request, response, Mockito.mock(Authentication.class));
// Try again with null Authentication
response = new MockHttpServletResponse();
services.logout(request, response, null);
assertCookieCancelled(response);
Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie.getDomain()).isEqualTo("spring.io");
assertThat(returnedCookie.getSecure()).isEqualTo(true);
@@ -288,21 +250,16 @@ public class AbstractRememberMeServicesTests {
public void cancelledCookieShouldUseRequestIsSecure() {
MockRememberMeServices services = new MockRememberMeServices(this.uds);
services.setCookieDomain("spring.io");
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContextPath("contextpath");
request.setCookies(createLoginCookie("cookie:1:2"));
request.setSecure(true);
MockHttpServletResponse response = new MockHttpServletResponse();
services.logout(request, response, Mockito.mock(Authentication.class));
// Try again with null Authentication
response = new MockHttpServletResponse();
services.logout(request, response, null);
assertCookieCancelled(response);
Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie.getDomain()).isEqualTo("spring.io");
assertThat(returnedCookie.getSecure()).isEqualTo(true);
@@ -311,53 +268,43 @@ public class AbstractRememberMeServicesTests {
@Test(expected = CookieTheftException.class)
public void cookieTheftExceptionShouldBeRethrown() {
MockRememberMeServices services = new MockRememberMeServices(this.uds) {
@Override
protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request,
HttpServletResponse response) {
throw new CookieTheftException("Pretending cookie was stolen");
}
};
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(createLoginCookie("cookie:1:2"));
MockHttpServletResponse response = new MockHttpServletResponse();
services.autoLogin(request, response);
}
@Test
public void loginSuccessCallsOnLoginSuccessCorrectly() {
MockRememberMeServices services = new MockRememberMeServices(this.uds);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication auth = new UsernamePasswordAuthenticationToken("joe", "password");
// No parameter set
services.loginSuccess(request, response, auth);
assertThat(services.loginSuccessCalled).isFalse();
// Parameter set to true
services = new MockRememberMeServices(this.uds);
request.setParameter(AbstractRememberMeServices.DEFAULT_PARAMETER, "true");
services.loginSuccess(request, response, auth);
assertThat(services.loginSuccessCalled).isTrue();
// Different parameter name, set to true
services = new MockRememberMeServices(this.uds);
services.setParameter("my_parameter");
request.setParameter("my_parameter", "true");
services.loginSuccess(request, response, auth);
assertThat(services.loginSuccessCalled).isTrue();
// Parameter set to false
services = new MockRememberMeServices(this.uds);
request.setParameter(AbstractRememberMeServices.DEFAULT_PARAMETER, "false");
services.loginSuccess(request, response, auth);
assertThat(services.loginSuccessCalled).isFalse();
// alwaysRemember set to true
services = new MockRememberMeServices(this.uds);
services.setAlwaysRemember(true);
@@ -371,7 +318,6 @@ public class AbstractRememberMeServicesTests {
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContextPath("contextpath");
MockRememberMeServices services = new MockRememberMeServices(this.uds) {
@Override
protected String encodeCookie(String[] cookieTokens) {
return cookieTokens[0];
@@ -380,7 +326,6 @@ public class AbstractRememberMeServicesTests {
services.setCookieName("mycookiename");
services.setCookie(new String[] { "mycookie" }, 1000, request, response);
Cookie cookie = response.getCookie("mycookiename");
assertThat(cookie).isNotNull();
assertThat(cookie.getValue()).isEqualTo("mycookie");
assertThat(cookie.getName()).isEqualTo("mycookiename");
@@ -393,9 +338,7 @@ public class AbstractRememberMeServicesTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContextPath("contextpath");
MockRememberMeServices services = new MockRememberMeServices(this.uds) {
@Override
protected String encodeCookie(String[] cookieTokens) {
return cookieTokens[0];
@@ -412,7 +355,6 @@ public class AbstractRememberMeServicesTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContextPath("contextpath");
MockRememberMeServices services = new MockRememberMeServices(this.uds);
services.setCookie(new String[] { "mycookie" }, 1000, request, response);
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
@@ -425,9 +367,7 @@ public class AbstractRememberMeServicesTests {
MockRememberMeServices services = new MockRememberMeServices();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
services.setCookie(new String[] { "value" }, 0, request, response);
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(cookie.getVersion()).isEqualTo(1);
}
@@ -438,9 +378,7 @@ public class AbstractRememberMeServicesTests {
MockRememberMeServices services = new MockRememberMeServices();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
services.setCookie(new String[] { "value" }, -1, request, response);
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(cookie.getVersion()).isEqualTo(1);
}
@@ -451,9 +389,7 @@ public class AbstractRememberMeServicesTests {
MockRememberMeServices services = new MockRememberMeServices();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
services.setCookie(new String[] { "value" }, 1, request, response);
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(cookie.getVersion()).isZero();
}
@@ -463,12 +399,10 @@ public class AbstractRememberMeServicesTests {
MockRememberMeServices services = new MockRememberMeServices();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
services.setCookieName("mycookiename");
services.setCookieDomain("spring.io");
services.setCookie(new String[] { "mycookie" }, 1000, request, response);
Cookie cookie = response.getCookie("mycookiename");
assertThat(cookie).isNotNull();
assertThat(cookie.getDomain()).isEqualTo("spring.io");
}
@@ -477,7 +411,6 @@ public class AbstractRememberMeServicesTests {
MockRememberMeServices services = new MockRememberMeServices(this.uds);
Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
services.encodeCookie(StringUtils.delimitedListToStringArray(cookieToken, ":")));
return new Cookie[] { cookie };
}
@@ -515,9 +448,7 @@ public class AbstractRememberMeServicesTests {
if (cookieTokens.length != 3) {
throw new InvalidCookieException("deliberate exception");
}
UserDetails user = getUserDetailsService().loadUserByUsername("joe");
return user;
}
@@ -543,7 +474,6 @@ public class AbstractRememberMeServicesTests {
if (this.throwException) {
throw new UsernameNotFoundException("as requested by mock");
}
return this.toReturn;
}

View File

@@ -94,9 +94,7 @@ public class JdbcTokenRepositoryImplTests {
Timestamp currentDate = new Timestamp(Calendar.getInstance().getTimeInMillis());
PersistentRememberMeToken token = new PersistentRememberMeToken("joeuser", "joesseries", "atoken", currentDate);
this.repo.createNewToken(token);
Map<String, Object> results = this.template.queryForMap("select * from persistent_logins");
assertThat(results.get("last_used")).isEqualTo(currentDate);
assertThat(results.get("username")).isEqualTo("joeuser");
assertThat(results.get("series")).isEqualTo("joesseries");
@@ -105,11 +103,9 @@ public class JdbcTokenRepositoryImplTests {
@Test
public void retrievingTokenReturnsCorrectData() {
this.template.execute("insert into persistent_logins (series, username, token, last_used) values "
+ "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')");
PersistentRememberMeToken token = this.repo.getTokenForSeries("joesseries");
assertThat(token.getUsername()).isEqualTo("joeuser");
assertThat(token.getSeries()).isEqualTo("joesseries");
assertThat(token.getTokenValue()).isEqualTo("atoken");
@@ -122,11 +118,9 @@ public class JdbcTokenRepositoryImplTests {
+ "('joesseries', 'joeuser', 'atoken2', '2007-10-19 18:19:25.000000000')");
this.template.execute("insert into persistent_logins (series, username, token, last_used) values "
+ "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')");
// List results =
// template.queryForList("select * from persistent_logins where series =
// 'joesseries'");
assertThat(this.repo.getTokenForSeries("joesseries")).isNull();
}
@@ -146,16 +140,12 @@ public class JdbcTokenRepositoryImplTests {
+ "('joesseries2', 'joeuser', 'atoken2', '2007-10-19 18:19:25.000000000')");
this.template.execute("insert into persistent_logins (series, username, token, last_used) values "
+ "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')");
// List results =
// template.queryForList("select * from persistent_logins where series =
// 'joesseries'");
this.repo.removeUserTokens("joeuser");
List<Map<String, Object>> results = this.template
.queryForList("select * from persistent_logins where username = 'joeuser'");
assertThat(results).isEmpty();
}
@@ -165,10 +155,8 @@ public class JdbcTokenRepositoryImplTests {
this.template.execute("insert into persistent_logins (series, username, token, last_used) values "
+ "('joesseries', 'joeuser', 'atoken', '" + ts.toString() + "')");
this.repo.updateToken("joesseries", "newtoken", new Date());
Map<String, Object> results = this.template
.queryForMap("select * from persistent_logins where series = 'joesseries'");
assertThat(results.get("username")).isEqualTo("joeuser");
assertThat(results.get("series")).isEqualTo("joesseries");
assertThat(results.get("token")).isEqualTo("newtoken");
@@ -183,7 +171,6 @@ public class JdbcTokenRepositoryImplTests {
this.repo.setDataSource(dataSource);
this.repo.setCreateTableOnStartup(true);
this.repo.initDao();
this.template.queryForList("select username,series,token,last_used from persistent_logins");
}
@@ -194,9 +181,7 @@ public class JdbcTokenRepositoryImplTests {
Date lastUsed = new Date(1424841314059L);
JdbcTokenRepositoryImpl repository = new JdbcTokenRepositoryImpl();
repository.setJdbcTemplate(template);
repository.updateToken("series", "token", lastUsed);
verify(template).update(anyString(), anyString(), eq(lastUsed), anyString());
}

View File

@@ -35,7 +35,6 @@ public class NullRememberMeServicesTests {
assertThat(services.autoLogin(null, null)).isNull();
services.loginFail(null, null);
services.loginSuccess(null, null, null);
}
}

View File

@@ -69,7 +69,6 @@ public class PersistentTokenBasedRememberMeServicesTests {
this.services = create(new PersistentRememberMeToken("joe", "series", "token",
new Date(System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(1) - 100)));
this.services.setTokenValiditySeconds(1);
this.services.processAutoLoginCookie(new String[] { "series", "token" }, new MockHttpServletRequest(),
new MockHttpServletResponse());
}
@@ -107,9 +106,7 @@ public class PersistentTokenBasedRememberMeServicesTests {
new UsernamePasswordAuthenticationToken("joe", "password"));
assertThat(this.repo.getStoredToken().getSeries().length()).isEqualTo(16);
assertThat(this.repo.getStoredToken().getTokenValue().length()).isEqualTo(16);
String[] cookie = this.services.decodeCookie(response.getCookie("mycookiename").getValue());
assertThat(cookie[0]).isEqualTo(this.repo.getStoredToken().getSeries());
assertThat(cookie[1]).isEqualTo(this.repo.getStoredToken().getTokenValue());
}
@@ -125,7 +122,6 @@ public class PersistentTokenBasedRememberMeServicesTests {
Cookie returnedCookie = response.getCookie("mycookiename");
assertThat(returnedCookie).isNotNull();
assertThat(returnedCookie.getMaxAge()).isZero();
// SEC-1280
this.services.logout(request, response, null);
}
@@ -135,7 +131,6 @@ public class PersistentTokenBasedRememberMeServicesTests {
PersistentTokenBasedRememberMeServices services = new PersistentTokenBasedRememberMeServices("key",
new AbstractRememberMeServicesTests.MockUserDetailsService(AbstractRememberMeServicesTests.joe, false),
this.repo);
services.setCookieName("mycookiename");
return services;
}

View File

@@ -78,18 +78,15 @@ public class RememberMeAuthenticationFilterTests {
// Put an Authentication object into the SecurityContextHolder
Authentication originalAuth = new TestingAuthenticationToken("user", "password", "ROLE_A");
SecurityContextHolder.getContext().setAuthentication(originalAuth);
// Setup our filter correctly
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(mock(AuthenticationManager.class),
new MockRememberMeServices(this.remembered));
filter.afterPropertiesSet();
// Test
MockHttpServletRequest request = new MockHttpServletRequest();
FilterChain fc = mock(FilterChain.class);
request.setRequestURI("x");
filter.doFilter(request, new MockHttpServletResponse(), fc);
// Ensure filter didn't change our original object
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(originalAuth);
verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
@@ -99,16 +96,13 @@ public class RememberMeAuthenticationFilterTests {
public void testOperationWhenNoAuthenticationInContextHolder() throws Exception {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(this.remembered)).willReturn(this.remembered);
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am,
new MockRememberMeServices(this.remembered));
filter.afterPropertiesSet();
MockHttpServletRequest request = new MockHttpServletRequest();
FilterChain fc = mock(FilterChain.class);
request.setRequestURI("x");
filter.doFilter(request, new MockHttpServletResponse(), fc);
// Ensure filter setup with our remembered authentication object
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.remembered);
verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
@@ -119,7 +113,6 @@ public class RememberMeAuthenticationFilterTests {
final Authentication failedAuth = new TestingAuthenticationToken("failed", "");
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am,
new MockRememberMeServices(this.remembered)) {
@Override
@@ -131,12 +124,10 @@ public class RememberMeAuthenticationFilterTests {
};
filter.setApplicationEventPublisher(mock(ApplicationEventPublisher.class));
filter.afterPropertiesSet();
MockHttpServletRequest request = new MockHttpServletRequest();
FilterChain fc = mock(FilterChain.class);
request.setRequestURI("x");
filter.doFilter(request, new MockHttpServletResponse(), fc);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(failedAuth);
verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@@ -153,9 +144,7 @@ public class RememberMeAuthenticationFilterTests {
FilterChain fc = mock(FilterChain.class);
request.setRequestURI("x");
filter.doFilter(request, response, fc);
assertThat(response.getRedirectedUrl()).isEqualTo("/target");
// Should return after success handler is invoked, so chain should not proceed
verifyZeroInteractions(fc);
}

View File

@@ -78,7 +78,6 @@ public class TokenBasedRememberMeServicesTests {
private long determineExpiryTimeFromBased64EncodedToken(String validToken) {
String cookieAsPlainText = new String(Base64.decodeBase64(validToken.getBytes()));
String[] cookieTokens = StringUtils.delimitedListToStringArray(cookieAsPlainText, ":");
if (cookieTokens.length == 3) {
try {
return Long.parseLong(cookieTokens[1]);
@@ -86,7 +85,6 @@ public class TokenBasedRememberMeServicesTests {
catch (NumberFormatException ignored) {
}
}
return -1;
}
@@ -96,14 +94,12 @@ public class TokenBasedRememberMeServicesTests {
// password + ":" + key)
String signatureValue = DigestUtils.md5Hex(username + ":" + expiryTime + ":" + password + ":" + key);
String tokenValue = username + ":" + expiryTime + ":" + signatureValue;
return new String(Base64.encodeBase64(tokenValue.getBytes()));
}
@Test
public void autoLoginReturnsNullIfNoCookiePresented() {
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication result = this.services.autoLogin(new MockHttpServletRequest(), response);
assertThat(result).isNull();
// No cookie set
@@ -116,9 +112,7 @@ public class TokenBasedRememberMeServicesTests {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication result = this.services.autoLogin(request, response);
assertThat(result).isNull();
assertThat(response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull();
}
@@ -130,9 +124,7 @@ public class TokenBasedRememberMeServicesTests {
"key"));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(this.services.autoLogin(request, response)).isNull();
Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
@@ -145,10 +137,8 @@ public class TokenBasedRememberMeServicesTests {
new String(Base64.encodeBase64("x".getBytes())));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(this.services.autoLogin(request, response)).isNull();
Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
assertThat(returnedCookie.getMaxAge()).isZero();
@@ -160,10 +150,8 @@ public class TokenBasedRememberMeServicesTests {
"NOT_BASE_64_ENCODED");
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(this.services.autoLogin(request, response)).isNull();
Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
assertThat(returnedCookie.getMaxAge()).isZero();
@@ -177,11 +165,8 @@ public class TokenBasedRememberMeServicesTests {
"WRONG_KEY"));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(this.services.autoLogin(request, response)).isNull();
Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
assertThat(returnedCookie.getMaxAge()).isZero();
@@ -193,10 +178,8 @@ public class TokenBasedRememberMeServicesTests {
new String(Base64.encodeBase64("username:NOT_A_NUMBER:signature".getBytes())));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(this.services.autoLogin(request, response)).isNull();
Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
assertThat(returnedCookie.getMaxAge()).isZero();
@@ -210,11 +193,8 @@ public class TokenBasedRememberMeServicesTests {
"key"));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(this.services.autoLogin(request, response)).isNull();
Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
assertThat(returnedCookie.getMaxAge()).isZero();
@@ -228,9 +208,7 @@ public class TokenBasedRememberMeServicesTests {
"key"));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
MockHttpServletResponse response = new MockHttpServletResponse();
this.services.autoLogin(request, response);
}
@@ -242,11 +220,8 @@ public class TokenBasedRememberMeServicesTests {
"key"));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication result = this.services.autoLogin(request, response);
assertThat(result).isNotNull();
assertThat(result.getPrincipal()).isEqualTo(this.user);
}
@@ -254,13 +229,10 @@ public class TokenBasedRememberMeServicesTests {
@Test
public void testGettersSetters() {
assertThat(this.services.getUserDetailsService()).isEqualTo(this.uds);
assertThat(this.services.getKey()).isEqualTo("key");
assertThat(this.services.getParameter()).isEqualTo(AbstractRememberMeServices.DEFAULT_PARAMETER);
this.services.setParameter("some_param");
assertThat(this.services.getParameter()).isEqualTo("some_param");
this.services.setTokenValiditySeconds(12);
assertThat(this.services.getTokenValiditySeconds()).isEqualTo(12);
}
@@ -270,7 +242,6 @@ public class TokenBasedRememberMeServicesTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
this.services.loginFail(request, response);
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(cookie).isNotNull();
assertThat(cookie.getMaxAge()).isZero();
@@ -282,10 +253,8 @@ public class TokenBasedRememberMeServicesTests {
new AbstractRememberMeServicesTests.MockUserDetailsService(null, false));
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter(AbstractRememberMeServices.DEFAULT_PARAMETER, "false");
MockHttpServletResponse response = new MockHttpServletResponse();
services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password", "ROLE_ABC"));
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(cookie).isNull();
}
@@ -296,11 +265,9 @@ public class TokenBasedRememberMeServicesTests {
this.services.setTokenValiditySeconds(500000000);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter(AbstractRememberMeServices.DEFAULT_PARAMETER, "true");
MockHttpServletResponse response = new MockHttpServletResponse();
this.services.loginSuccess(request, response,
new TestingAuthenticationToken("someone", "password", "ROLE_ABC"));
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
String expiryTime = this.services.decodeCookie(cookie.getValue())[1];
long expectedExpiryTime = 1000L * 500000000;
@@ -316,11 +283,9 @@ public class TokenBasedRememberMeServicesTests {
public void loginSuccessNormalWithUserDetailsBasedPrincipalSetsExpectedCookie() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter(AbstractRememberMeServices.DEFAULT_PARAMETER, "true");
MockHttpServletResponse response = new MockHttpServletResponse();
this.services.loginSuccess(request, response,
new TestingAuthenticationToken("someone", "password", "ROLE_ABC"));
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(cookie).isNotNull();
assertThat(cookie.getMaxAge()).isEqualTo(this.services.getTokenValiditySeconds());
@@ -340,12 +305,10 @@ public class TokenBasedRememberMeServicesTests {
public void negativeValidityPeriodIsSetOnCookieButExpiryTimeRemainsAtTwoWeeks() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter(AbstractRememberMeServices.DEFAULT_PARAMETER, "true");
MockHttpServletResponse response = new MockHttpServletResponse();
this.services.setTokenValiditySeconds(-1);
this.services.loginSuccess(request, response,
new TestingAuthenticationToken("someone", "password", "ROLE_ABC"));
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(cookie).isNotNull();
// Check the expiry time is within 50ms of two weeks from current time

View File

@@ -76,7 +76,6 @@ public class CompositeSessionAuthenticationStrategyTests {
CompositeSessionAuthenticationStrategy strategy = new CompositeSessionAuthenticationStrategy(
Arrays.asList(this.strategy1, this.strategy2));
strategy.onAuthentication(this.authentication, this.request, this.response);
verify(this.strategy1).onAuthentication(this.authentication, this.request, this.response);
verify(this.strategy2).onAuthentication(this.authentication, this.request, this.response);
}
@@ -85,17 +84,14 @@ public class CompositeSessionAuthenticationStrategyTests {
public void delegateShortCircuits() {
willThrow(new SessionAuthenticationException("oops")).given(this.strategy1)
.onAuthentication(this.authentication, this.request, this.response);
CompositeSessionAuthenticationStrategy strategy = new CompositeSessionAuthenticationStrategy(
Arrays.asList(this.strategy1, this.strategy2));
try {
strategy.onAuthentication(this.authentication, this.request, this.response);
fail("Expected Exception");
}
catch (SessionAuthenticationException success) {
}
verify(this.strategy1).onAuthentication(this.authentication, this.request, this.response);
verify(this.strategy2, times(0)).onAuthentication(this.authentication, this.request, this.response);
}

View File

@@ -67,7 +67,6 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
this.response = new MockHttpServletResponse();
this.sessionInformation = new SessionInformation(this.authentication.getPrincipal(), "unique",
new Date(1374766134216L));
this.strategy = new ConcurrentSessionControlAuthenticationStrategy(this.sessionRegistry);
}
@@ -82,9 +81,7 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
.willReturn(Collections.<SessionInformation>emptyList());
this.strategy.setMaximumSessions(1);
this.strategy.setExceptionIfMaximumExceeded(true);
this.strategy.onAuthentication(this.authentication, this.request, this.response);
// no exception
}
@@ -96,9 +93,7 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
.willReturn(Collections.<SessionInformation>singletonList(this.sessionInformation));
this.strategy.setMaximumSessions(1);
this.strategy.setExceptionIfMaximumExceeded(true);
this.strategy.onAuthentication(this.authentication, this.request, this.response);
// no exception
}
@@ -108,7 +103,6 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
.willReturn(Collections.<SessionInformation>singletonList(this.sessionInformation));
this.strategy.setMaximumSessions(1);
this.strategy.setExceptionIfMaximumExceeded(true);
this.strategy.onAuthentication(this.authentication, this.request, this.response);
}
@@ -117,9 +111,7 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
given(this.sessionRegistry.getAllSessions(any(), anyBoolean()))
.willReturn(Collections.<SessionInformation>singletonList(this.sessionInformation));
this.strategy.setMaximumSessions(1);
this.strategy.onAuthentication(this.authentication, this.request, this.response);
assertThat(this.sessionInformation.isExpired()).isTrue();
}
@@ -130,9 +122,7 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
given(this.sessionRegistry.getAllSessions(any(), anyBoolean()))
.willReturn(Arrays.<SessionInformation>asList(moreRecentSessionInfo, this.sessionInformation));
this.strategy.setMaximumSessions(2);
this.strategy.onAuthentication(this.authentication, this.request, this.response);
assertThat(this.sessionInformation.isExpired()).isTrue();
}
@@ -145,9 +135,7 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
given(this.sessionRegistry.getAllSessions(any(), anyBoolean())).willReturn(
Arrays.<SessionInformation>asList(oldestSessionInfo, secondOldestSessionInfo, this.sessionInformation));
this.strategy.setMaximumSessions(2);
this.strategy.onAuthentication(this.authentication, this.request, this.response);
assertThat(oldestSessionInfo.isExpired()).isTrue();
assertThat(secondOldestSessionInfo.isExpired()).isTrue();
assertThat(this.sessionInformation.isExpired()).isFalse();

View File

@@ -64,7 +64,6 @@ public class RegisterSessionAuthenticationStrategyTests {
@Test
public void onAuthenticationRegistersSession() {
this.authenticationStrategy.onAuthentication(this.authentication, this.request, this.response);
verify(this.registry).registerNewSession(this.request.getSession().getId(), this.authentication.getPrincipal());
}

View File

@@ -84,30 +84,24 @@ public class SwitchUserFilterTests {
request.setServerName("localhost");
request.setRequestURI("/login/impersonate");
request.setMethod("POST");
return request;
}
private Authentication switchToUser(String name) {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("myUsernameParameter", name);
SwitchUserFilter filter = new SwitchUserFilter();
filter.setUsernameParameter("myUsernameParameter");
filter.setUserDetailsService(new MockUserDetailsService());
return filter.attemptSwitchUser(request);
}
private Authentication switchToUserWithAuthorityRole(String name, String switchAuthorityRole) {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, name);
SwitchUserFilter filter = new SwitchUserFilter();
filter.setUserDetailsService(new MockUserDetailsService());
filter.setSwitchAuthorityRole(switchAuthorityRole);
return filter.attemptSwitchUser(request);
}
@@ -115,10 +109,8 @@ public class SwitchUserFilterTests {
public void requiresExitUserMatchesCorrectly() {
SwitchUserFilter filter = new SwitchUserFilter();
filter.setExitUserUrl("/j_spring_security_my_exit_user");
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/j_spring_security_my_exit_user");
assertThat(filter.requiresExitUser(request)).isTrue();
}
@@ -127,10 +119,8 @@ public class SwitchUserFilterTests {
public void requiresExitUserWhenEndsWithThenDoesNotMatch() {
SwitchUserFilter filter = new SwitchUserFilter();
filter.setExitUserUrl("/j_spring_security_my_exit_user");
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/foo/bar/j_spring_security_my_exit_user");
assertThat(filter.requiresExitUser(request)).isFalse();
}
@@ -138,13 +128,11 @@ public class SwitchUserFilterTests {
// gh-4183
public void requiresExitUserWhenGetThenDoesNotMatch() {
SwitchUserFilter filter = new SwitchUserFilter();
MockHttpServletRequest request = new MockHttpServletRequest();
request.setScheme("http");
request.setServerName("localhost");
request.setRequestURI("/login/impersonate");
request.setMethod("GET");
assertThat(filter.requiresExitUser(request)).isFalse();
}
@@ -152,10 +140,8 @@ public class SwitchUserFilterTests {
public void requiresExitUserWhenMatcherThenWorks() {
SwitchUserFilter filter = new SwitchUserFilter();
filter.setExitUserMatcher(AnyRequestMatcher.INSTANCE);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/foo/bar/j_spring_security_my_exit_user");
assertThat(filter.requiresExitUser(request)).isTrue();
}
@@ -163,10 +149,8 @@ public class SwitchUserFilterTests {
public void requiresSwitchMatchesCorrectly() {
SwitchUserFilter filter = new SwitchUserFilter();
filter.setSwitchUserUrl("/j_spring_security_my_switch_user");
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/j_spring_security_my_switch_user");
assertThat(filter.requiresSwitchUser(request)).isTrue();
}
@@ -175,10 +159,8 @@ public class SwitchUserFilterTests {
public void requiresSwitchUserWhenEndsWithThenDoesNotMatch() {
SwitchUserFilter filter = new SwitchUserFilter();
filter.setSwitchUserUrl("/j_spring_security_my_exit_user");
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/foo/bar/j_spring_security_my_exit_user");
assertThat(filter.requiresSwitchUser(request)).isFalse();
}
@@ -186,13 +168,11 @@ public class SwitchUserFilterTests {
// gh-4183
public void requiresSwitchUserWhenGetThenDoesNotMatch() {
SwitchUserFilter filter = new SwitchUserFilter();
MockHttpServletRequest request = new MockHttpServletRequest();
request.setScheme("http");
request.setServerName("localhost");
request.setRequestURI("/login/impersonate");
request.setMethod("GET");
assertThat(filter.requiresSwitchUser(request)).isFalse();
}
@@ -200,19 +180,15 @@ public class SwitchUserFilterTests {
public void requiresSwitchUserWhenMatcherThenWorks() {
SwitchUserFilter filter = new SwitchUserFilter();
filter.setSwitchUserMatcher(AnyRequestMatcher.INSTANCE);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/foo/bar/j_spring_security_my_exit_user");
assertThat(filter.requiresSwitchUser(request)).isTrue();
}
@Test(expected = UsernameNotFoundException.class)
public void attemptSwitchToUnknownUserFails() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "user-that-doesnt-exist");
SwitchUserFilter filter = new SwitchUserFilter();
filter.setUserDetailsService(new MockUserDetailsService());
filter.attemptSwitchUser(request);
@@ -253,14 +229,11 @@ public class SwitchUserFilterTests {
filter.setTargetUrl("/target");
filter.setUserDetailsService(new MockUserDetailsService());
filter.afterPropertiesSet();
// Check it with no url set (should get a text response)
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(request, response);
assertThat(response.getErrorMessage()).isNotNull();
// Now check for the redirect
request.setContextPath("/mywebapp");
request.setRequestURI("/mywebapp/login/impersonate");
@@ -270,11 +243,9 @@ public class SwitchUserFilterTests {
filter.setSwitchFailureUrl("/switchfailed");
filter.afterPropertiesSet();
response = new MockHttpServletResponse();
chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(request, response);
assertThat(response.getRedirectedUrl()).isEqualTo("/mywebapp/switchfailed");
assertThat(FieldUtils.getFieldValue(filter, "switchFailureUrl")).isEqualTo("/switchfailed");
}
@@ -303,7 +274,6 @@ public class SwitchUserFilterTests {
request.setContextPath("/webapp");
SwitchUserFilter filter = new SwitchUserFilter();
filter.setSwitchUserUrl("/login/impersonate");
request.setRequestURI("/webapp/login/impersonate;jsessionid=8JHDUD723J8");
assertThat(filter.requiresSwitchUser(request)).isTrue();
}
@@ -313,32 +283,25 @@ public class SwitchUserFilterTests {
// original user
UsernamePasswordAuthenticationToken source = new UsernamePasswordAuthenticationToken("dano", "hawaii50",
ROLES_12);
// set current user (Admin)
List<GrantedAuthority> adminAuths = new ArrayList<>();
adminAuths.addAll(ROLES_12);
adminAuths.add(new SwitchUserGrantedAuthority("PREVIOUS_ADMINISTRATOR", source));
UsernamePasswordAuthenticationToken admin = new UsernamePasswordAuthenticationToken("jacklord", "hawaii50",
adminAuths);
SecurityContextHolder.getContext().setAuthentication(admin);
MockHttpServletRequest request = createMockSwitchRequest();
request.setRequestURI("/logout/impersonate");
// setup filter
SwitchUserFilter filter = new SwitchUserFilter();
filter.setUserDetailsService(new MockUserDetailsService());
filter.setExitUserUrl("/logout/impersonate");
filter.setSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/webapp/someOtherUrl"));
// run 'exit'
FilterChain chain = mock(FilterChain.class);
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(request, response);
// check current user, should be back to original user (dano)
Authentication targetAuth = SecurityContextHolder.getContext().getAuthentication();
assertThat(targetAuth).isNotNull();
@@ -349,20 +312,16 @@ public class SwitchUserFilterTests {
public void exitUserWithNoCurrentUserFails() throws Exception {
// no current user in secure context
SecurityContextHolder.clearContext();
MockHttpServletRequest request = createMockSwitchRequest();
request.setRequestURI("/logout/impersonate");
// setup filter
SwitchUserFilter filter = new SwitchUserFilter();
filter.setUserDetailsService(new MockUserDetailsService());
filter.setExitUserUrl("/logout/impersonate");
// run 'exit', expect fail due to no current user
FilterChain chain = mock(FilterChain.class);
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(request, response);
}
@@ -372,18 +331,14 @@ public class SwitchUserFilterTests {
request.setContextPath("/webapp");
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "jacklord");
request.setRequestURI("/webapp/login/impersonate");
SwitchUserFilter filter = new SwitchUserFilter();
filter.setSwitchUserUrl("/login/impersonate");
filter.setSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/someOtherUrl"));
filter.setUserDetailsService(new MockUserDetailsService());
FilterChain chain = mock(FilterChain.class);
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(request, response);
assertThat(response.getRedirectedUrl()).isEqualTo("/webapp/someOtherUrl");
}
@@ -392,12 +347,10 @@ public class SwitchUserFilterTests {
// set current user
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("dano", "hawaii50");
SecurityContextHolder.getContext().setAuthentication(auth);
MockHttpServletRequest request = createMockSwitchRequest();
request.setContextPath("/webapp");
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "jacklord");
request.setRequestURI("/webapp/login/impersonate");
SwitchUserFilter filter = new SwitchUserFilter();
filter.setSwitchUserUrl("/login/impersonate");
SimpleUrlAuthenticationSuccessHandler switchSuccessHandler = new SimpleUrlAuthenticationSuccessHandler(
@@ -407,14 +360,10 @@ public class SwitchUserFilterTests {
switchSuccessHandler.setRedirectStrategy(contextRelativeRedirector);
filter.setSuccessHandler(switchSuccessHandler);
filter.setUserDetailsService(new MockUserDetailsService());
FilterChain chain = mock(FilterChain.class);
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(request, response);
assertThat(response.getRedirectedUrl()).isEqualTo("/someOtherUrl");
}
@@ -423,28 +372,22 @@ public class SwitchUserFilterTests {
// set current user
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("dano", "hawaii50");
SecurityContextHolder.getContext().setAuthentication(auth);
// http request
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/webapp/login/impersonate");
request.setContextPath("/webapp");
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "jacklord");
// http response
MockHttpServletResponse response = new MockHttpServletResponse();
// setup filter
SwitchUserFilter filter = new SwitchUserFilter();
filter.setUserDetailsService(new MockUserDetailsService());
filter.setSwitchUserUrl("/login/impersonate");
filter.setSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/webapp/someOtherUrl"));
FilterChain chain = mock(FilterChain.class);
// test updates user token and context
filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(request, response);
// check current user
Authentication targetAuth = SecurityContextHolder.getContext().getAuthentication();
assertThat(targetAuth).isNotNull();
@@ -456,10 +399,8 @@ public class SwitchUserFilterTests {
public void modificationOfAuthoritiesWorks() {
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("dano", "hawaii50");
SecurityContextHolder.getContext().setAuthentication(auth);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "jacklord");
SwitchUserFilter filter = new SwitchUserFilter();
filter.setUserDetailsService(new MockUserDetailsService());
filter.setSwitchUserAuthorityChanger((targetUser, currentAuthentication, authoritiesToBeGranted) -> {
@@ -467,7 +408,6 @@ public class SwitchUserFilterTests {
auths.add(new SimpleGrantedAuthority("ROLE_NEW"));
return auths;
});
Authentication result = filter.attemptSwitchUser(request);
assertThat(result != null).isTrue();
assertThat(result.getAuthorities()).hasSize(2);
@@ -483,16 +423,13 @@ public class SwitchUserFilterTests {
SecurityContextHolder.getContext().setAuthentication(source);
SecurityContextHolder.getContext().setAuthentication(switchToUser("jacklord"));
Authentication switched = switchToUser("dano");
SwitchUserGrantedAuthority switchedFrom = null;
for (GrantedAuthority ga : switched.getAuthorities()) {
if (ga instanceof SwitchUserGrantedAuthority) {
switchedFrom = (SwitchUserGrantedAuthority) ga;
break;
}
}
assertThat(switchedFrom).isNotNull();
assertThat(source).isSameAs(switchedFrom.getSource());
}
@@ -509,23 +446,19 @@ public class SwitchUserFilterTests {
@Test
public void switchAuthorityRoleCanBeChanged() {
String switchAuthorityRole = "PREVIOUS_ADMINISTRATOR";
// original user
UsernamePasswordAuthenticationToken source = new UsernamePasswordAuthenticationToken("orig", "hawaii50",
ROLES_12);
SecurityContextHolder.getContext().setAuthentication(source);
SecurityContextHolder.getContext().setAuthentication(switchToUser("jacklord"));
Authentication switched = switchToUserWithAuthorityRole("dano", switchAuthorityRole);
SwitchUserGrantedAuthority switchedFrom = null;
for (GrantedAuthority ga : switched.getAuthorities()) {
if (ga instanceof SwitchUserGrantedAuthority) {
switchedFrom = (SwitchUserGrantedAuthority) ga;
break;
}
}
assertThat(switchedFrom).isNotNull();
assertThat(switchedFrom.getSource()).isSameAs(source);
assertThat(switchAuthorityRole).isEqualTo(switchedFrom.getAuthority());

View File

@@ -38,7 +38,6 @@ public class DefaultLogoutPageGeneratingFilterTests {
@Test
public void doFilterWhenNoHiddenInputsThenPageRendered() throws Exception {
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new Object()).addFilter(this.filter).build();
mockMvc.perform(get("/logout")).andExpect(content().string("<!DOCTYPE html>\n" + "<html lang=\"en\">\n"
+ " <head>\n" + " <meta charset=\"utf-8\">\n"
+ " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n"
@@ -58,7 +57,6 @@ public class DefaultLogoutPageGeneratingFilterTests {
public void doFilterWhenHiddenInputsSetThenHiddenInputsRendered() throws Exception {
this.filter.setResolveHiddenInputs((r) -> Collections.singletonMap("_csrf", "csrf-token-1"));
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new Object()).addFilters(this.filter).build();
mockMvc.perform(get("/logout")).andExpect(
content().string(containsString("<input name=\"_csrf\" type=\"hidden\" value=\"csrf-token-1\" />")));
}
@@ -66,7 +64,6 @@ public class DefaultLogoutPageGeneratingFilterTests {
@Test
public void doFilterWhenRequestContextThenActionContainsRequestContext() throws Exception {
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new Object()).addFilters(this.filter).build();
mockMvc.perform(get("/context/logout").contextPath("/context"))
.andExpect(content().string(containsString("action=\"/context/logout\"")));
}

View File

@@ -58,7 +58,6 @@ public class BasicAuthenticationConverterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
UsernamePasswordAuthenticationToken authentication = this.converter.convert(request);
verify(this.authenticationDetailsSource).buildDetails(any());
assertThat(authentication).isNotNull();
assertThat(authentication.getName()).isEqualTo("rod");
@@ -70,7 +69,6 @@ public class BasicAuthenticationConverterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "BaSiC " + new String(Base64.encodeBase64(token.getBytes())));
UsernamePasswordAuthenticationToken authentication = this.converter.convert(request);
verify(this.authenticationDetailsSource).buildDetails(any());
assertThat(authentication).isNotNull();
assertThat(authentication.getName()).isEqualTo("rod");
@@ -81,7 +79,6 @@ public class BasicAuthenticationConverterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Bearer someOtherToken");
UsernamePasswordAuthenticationToken authentication = this.converter.convert(request);
verifyZeroInteractions(this.authenticationDetailsSource);
assertThat(authentication).isNull();
}
@@ -98,7 +95,6 @@ public class BasicAuthenticationConverterTests {
public void testWhenInvalidBase64ThenError() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic NOT_VALID_BASE64");
this.converter.convert(request);
}
@@ -108,7 +104,6 @@ public class BasicAuthenticationConverterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
UsernamePasswordAuthenticationToken authentication = this.converter.convert(request);
verify(this.authenticationDetailsSource).buildDetails(any());
assertThat(authentication).isNotNull();
assertThat(authentication.getName()).isEqualTo("rod");

View File

@@ -36,7 +36,6 @@ public class BasicAuthenticationEntryPointTests {
@Test
public void testDetectsMissingRealmName() {
BasicAuthenticationEntryPoint ep = new BasicAuthenticationEntryPoint();
try {
ep.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
@@ -56,21 +55,14 @@ public class BasicAuthenticationEntryPointTests {
@Test
public void testNormalOperation() throws Exception {
BasicAuthenticationEntryPoint ep = new BasicAuthenticationEntryPoint();
ep.setRealmName("hello");
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/some_path");
MockHttpServletResponse response = new MockHttpServletResponse();
// ep.afterPropertiesSet();
ep.commence(request, response, new DisabledException("These are the jokes kid"));
assertThat(response.getStatus()).isEqualTo(401);
assertThat(response.getErrorMessage()).isEqualTo(HttpStatus.UNAUTHORIZED.getReasonPhrase());
assertThat(response.getHeader("WWW-Authenticate")).isEqualTo("Basic realm=\"hello\"");
}

View File

@@ -67,11 +67,9 @@ public class BasicAuthenticationFilterTests {
rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
Authentication rod = new UsernamePasswordAuthenticationToken("rod", "koala",
AuthorityUtils.createAuthorityList("ROLE_1"));
this.manager = mock(AuthenticationManager.class);
given(this.manager.authenticate(rodRequest)).willReturn(rod);
given(this.manager.authenticate(not(eq(rodRequest)))).willThrow(new BadCredentialsException(""));
this.filter = new BasicAuthenticationFilter(this.manager, new BasicAuthenticationEntryPoint());
}
@@ -82,16 +80,12 @@ public class BasicAuthenticationFilterTests {
@Test
public void testFilterIgnoresRequestsContainingNoAuthorizationHeader() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServletPath("/some_file.html");
final MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, response, chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
// Test
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -110,10 +104,8 @@ public class BasicAuthenticationFilterTests {
request.setServletPath("/some_file.html");
request.setSession(new MockHttpSession());
final MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
@@ -126,7 +118,6 @@ public class BasicAuthenticationFilterTests {
request.setServletPath("/some_file.html");
request.setSession(new MockHttpSession());
final MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, response, chain);
// The filter chain shouldn't proceed
@@ -141,12 +132,10 @@ public class BasicAuthenticationFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
request.setServletPath("/some_file.html");
// Test
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, new MockHttpServletResponse(), chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
@@ -159,12 +148,10 @@ public class BasicAuthenticationFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "basic " + new String(Base64.encodeBase64(token.getBytes())));
request.setServletPath("/some_file.html");
// Test
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, new MockHttpServletResponse(), chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
@@ -176,11 +163,9 @@ public class BasicAuthenticationFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "BaSiC " + new String(Base64.encodeBase64(token.getBytes())));
request.setServletPath("/some_file.html");
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, new MockHttpServletResponse(), chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
@@ -188,13 +173,11 @@ public class BasicAuthenticationFilterTests {
@Test
public void testOtherAuthorizationSchemeIsIgnored() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "SOME_OTHER_AUTHENTICATION_SCHEME");
request.setServletPath("/some_file.html");
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, new MockHttpServletResponse(), chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -216,32 +199,23 @@ public class BasicAuthenticationFilterTests {
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
request.setServletPath("/some_file.html");
final MockHttpServletResponse response1 = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, response1, chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
// Test
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
// NOW PERFORM FAILED AUTHENTICATION
token = "otherUser:WRONG_PASSWORD";
request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
final MockHttpServletResponse response2 = new MockHttpServletResponse();
chain = mock(FilterChain.class);
this.filter.doFilter(request, response2, chain);
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
request.setServletPath("/some_file.html");
// Test - the filter chain will not be invoked, as we get a 401 forbidden response
MockHttpServletResponse response = response2;
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
}
@@ -253,14 +227,11 @@ public class BasicAuthenticationFilterTests {
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
request.setServletPath("/some_file.html");
request.setSession(new MockHttpSession());
this.filter = new BasicAuthenticationFilter(this.manager);
assertThat(this.filter.isIgnoreFailure()).isTrue();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, new MockHttpServletResponse(), chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
// Test - the filter chain will be invoked, as we've set ignoreFailure = true
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -274,10 +245,8 @@ public class BasicAuthenticationFilterTests {
request.setSession(new MockHttpSession());
assertThat(this.filter.isIgnoreFailure()).isFalse();
final MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, response, chain);
// Test - the filter chain will not be invoked, as we get a 401 forbidden response
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
@@ -287,50 +256,38 @@ public class BasicAuthenticationFilterTests {
// SEC-2054
@Test
public void skippedOnErrorDispatch() throws Exception {
String token = "bad:credentials";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
request.setServletPath("/some_file.html");
request.setAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE, "/error");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(200);
}
@Test
public void doFilterWhenTokenAndFilterCharsetMatchDefaultThenAuthenticated() throws Exception {
SecurityContextHolder.clearContext();
UsernamePasswordAuthenticationToken rodRequest = new UsernamePasswordAuthenticationToken("rod", "äöü");
rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
Authentication rod = new UsernamePasswordAuthenticationToken("rod", "äöü",
AuthorityUtils.createAuthorityList("ROLE_1"));
this.manager = mock(AuthenticationManager.class);
given(this.manager.authenticate(rodRequest)).willReturn(rod);
given(this.manager.authenticate(not(eq(rodRequest)))).willThrow(new BadCredentialsException(""));
this.filter = new BasicAuthenticationFilter(this.manager, new BasicAuthenticationEntryPoint());
String token = "rod:äöü";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization",
"Basic " + new String(Base64.encodeBase64(token.getBytes(StandardCharsets.UTF_8))));
request.setServletPath("/some_file.html");
MockHttpServletResponse response = new MockHttpServletResponse();
// Test
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
@@ -340,33 +297,25 @@ public class BasicAuthenticationFilterTests {
@Test
public void doFilterWhenTokenAndFilterCharsetMatchNonDefaultThenAuthenticated() throws Exception {
SecurityContextHolder.clearContext();
UsernamePasswordAuthenticationToken rodRequest = new UsernamePasswordAuthenticationToken("rod", "äöü");
rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
Authentication rod = new UsernamePasswordAuthenticationToken("rod", "äöü",
AuthorityUtils.createAuthorityList("ROLE_1"));
this.manager = mock(AuthenticationManager.class);
given(this.manager.authenticate(rodRequest)).willReturn(rod);
given(this.manager.authenticate(not(eq(rodRequest)))).willThrow(new BadCredentialsException(""));
this.filter = new BasicAuthenticationFilter(this.manager, new BasicAuthenticationEntryPoint());
this.filter.setCredentialsCharset("ISO-8859-1");
String token = "rod:äöü";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization",
"Basic " + new String(Base64.encodeBase64(token.getBytes(StandardCharsets.ISO_8859_1))));
request.setServletPath("/some_file.html");
MockHttpServletResponse response = new MockHttpServletResponse();
// Test
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
@@ -376,33 +325,25 @@ public class BasicAuthenticationFilterTests {
@Test
public void doFilterWhenTokenAndFilterCharsetDoNotMatchThenUnauthorized() throws Exception {
SecurityContextHolder.clearContext();
UsernamePasswordAuthenticationToken rodRequest = new UsernamePasswordAuthenticationToken("rod", "äöü");
rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
Authentication rod = new UsernamePasswordAuthenticationToken("rod", "äöü",
AuthorityUtils.createAuthorityList("ROLE_1"));
this.manager = mock(AuthenticationManager.class);
given(this.manager.authenticate(rodRequest)).willReturn(rod);
given(this.manager.authenticate(not(eq(rodRequest)))).willThrow(new BadCredentialsException(""));
this.filter = new BasicAuthenticationFilter(this.manager, new BasicAuthenticationEntryPoint());
this.filter.setCredentialsCharset("ISO-8859-1");
String token = "rod:äöü";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization",
"Basic " + new String(Base64.encodeBase64(token.getBytes(StandardCharsets.UTF_8))));
request.setServletPath("/some_file.html");
MockHttpServletResponse response = new MockHttpServletResponse();
// Test
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
@@ -415,7 +356,6 @@ public class BasicAuthenticationFilterTests {
request.setServletPath("/some_file.html");
request.setSession(new MockHttpSession());
final MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
this.filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));

View File

@@ -38,7 +38,6 @@ public class DigestAuthUtilsTests {
String unsplit = "username=\"rod\", invalidEntryThatHasNoEqualsSign, realm=\"Contacts Realm\", nonce=\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\", uri=\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\", response=\"38644211cf9ac3da63ab639807e2baff\", qop=auth, nc=00000004, cnonce=\"2b8d329a8571b99a\"";
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(unsplit);
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
assertThat(headerMap.get("username")).isEqualTo("rod");
assertThat(headerMap.get("realm")).isEqualTo("Contacts Realm");
assertThat(headerMap.get("nonce"))
@@ -57,7 +56,6 @@ public class DigestAuthUtilsTests {
String unsplit = "username=\"rod\", realm=\"Contacts Realm\", nonce=\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\", uri=\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\", response=\"38644211cf9ac3da63ab639807e2baff\", qop=auth, nc=00000004, cnonce=\"2b8d329a8571b99a\"";
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(unsplit);
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", null);
assertThat(headerMap.get("username")).isEqualTo("\"rod\"");
assertThat(headerMap.get("realm")).isEqualTo("\"Contacts Realm\"");
assertThat(headerMap.get("nonce"))
@@ -97,39 +95,30 @@ public class DigestAuthUtilsTests {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
DigestAuthUtils.split("", "="); // empty string
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
DigestAuthUtils.split("sdch=dfgf", null); // null
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
DigestAuthUtils.split("fvfv=dcdc", ""); // empty string
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
try {
DigestAuthUtils.split("dfdc=dcdc", "BIGGER_THAN_ONE_CHARACTER");
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
}
}
@@ -137,7 +126,6 @@ public class DigestAuthUtilsTests {
public void testSplitWorksWithDifferentDelimiters() {
assertThat(DigestAuthUtils.split("18/rod", "/")).hasSize(2);
assertThat(DigestAuthUtils.split("18/rod", "!")).isNull();
// only guarantees to split at FIRST delimiter, not EACH delimiter
assertThat(DigestAuthUtils.split("18|rod|foo|bar", "|")).hasSize(2);
}
@@ -145,9 +133,7 @@ public class DigestAuthUtilsTests {
public void testAuthorizationHeaderWithCommasIsSplitCorrectly() {
String header = "Digest username=\"hamilton,bob\", realm=\"bobs,ok,realm\", nonce=\"the,nonce\", "
+ "uri=\"the,Uri\", response=\"the,response,Digest\", qop=theqop, nc=thenc, cnonce=\"the,cnonce\"";
String[] parts = DigestAuthUtils.splitIgnoringQuotes(header, ',');
assertThat(parts).hasSize(8);
}

View File

@@ -42,11 +42,9 @@ public class DigestAuthenticationEntryPointTests {
// format of nonce is:
// base64(expirationTime + ":" + md5Hex(expirationTime + ":" + key))
assertThat(Base64.isArrayByteBase64(nonce.getBytes())).isTrue();
String decodedNonce = new String(Base64.decodeBase64(nonce.getBytes()));
String[] nonceTokens = StringUtils.delimitedListToStringArray(decodedNonce, ":");
assertThat(nonceTokens).hasSize(2);
String expectedNonceSignature = DigestUtils.md5Hex(nonceTokens[0] + ":" + "key");
assertThat(nonceTokens[1]).isEqualTo(expectedNonceSignature);
}
@@ -55,7 +53,6 @@ public class DigestAuthenticationEntryPointTests {
public void testDetectsMissingKey() throws Exception {
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
ep.setRealmName("realm");
try {
ep.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
@@ -70,7 +67,6 @@ public class DigestAuthenticationEntryPointTests {
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
ep.setKey("dcdc");
ep.setNonceValiditySeconds(12);
try {
ep.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
@@ -97,29 +93,21 @@ public class DigestAuthenticationEntryPointTests {
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
ep.setRealmName("hello");
ep.setKey("key");
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/some_path");
MockHttpServletResponse response = new MockHttpServletResponse();
ep.afterPropertiesSet();
ep.commence(request, response, new DisabledException("foobar"));
// Check response is properly formed
assertThat(response.getStatus()).isEqualTo(401);
assertThat(response.getHeader("WWW-Authenticate").toString()).startsWith("Digest ");
// Break up response header
String header = response.getHeader("WWW-Authenticate").toString().substring(7);
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header);
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
assertThat(headerMap.get("realm")).isEqualTo("hello");
assertThat(headerMap.get("qop")).isEqualTo("auth");
assertThat(headerMap.get("stale")).isNull();
checkNonceValid(headerMap.get("nonce"));
}
@@ -128,29 +116,21 @@ public class DigestAuthenticationEntryPointTests {
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
ep.setRealmName("hello");
ep.setKey("key");
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/some_path");
MockHttpServletResponse response = new MockHttpServletResponse();
ep.afterPropertiesSet();
ep.commence(request, response, new NonceExpiredException("expired nonce"));
// Check response is properly formed
assertThat(response.getStatus()).isEqualTo(401);
assertThat(response.getHeader("WWW-Authenticate").toString()).startsWith("Digest ");
// Break up response header
String header = response.getHeader("WWW-Authenticate").toString().substring(7);
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header);
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
assertThat(headerMap.get("realm")).isEqualTo("hello");
assertThat(headerMap.get("qop")).isEqualTo("auth");
assertThat(headerMap.get("stale")).isEqualTo("true");
checkNonceValid(headerMap.get("nonce"));
}

View File

@@ -90,11 +90,8 @@ public class DigestAuthenticationFilterTests {
private MockHttpServletResponse executeFilterInContainerSimulator(Filter filter, final ServletRequest request,
final boolean expectChainToProceed) throws ServletException, IOException {
final MockHttpServletResponse response = new MockHttpServletResponse();
final FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verify(chain, times(expectChainToProceed ? 1 : 0)).doFilter(request, response);
return response;
}
@@ -107,7 +104,6 @@ public class DigestAuthenticationFilterTests {
long expiryTime = System.currentTimeMillis() + (validitySeconds * 1000);
String signatureValue = DigestUtils.md5Hex(expiryTime + ":" + key);
String nonceValue = expiryTime + ":" + signatureValue;
return new String(Base64.encodeBase64(nonceValue.getBytes()));
}
@@ -119,19 +115,15 @@ public class DigestAuthenticationFilterTests {
@Before
public void setUp() {
SecurityContextHolder.clearContext();
// Create User Details Service
UserDetailsService uds = (username) -> new User("rod,ok", "koala",
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
ep.setRealmName(REALM);
ep.setKey(KEY);
this.filter = new DigestAuthenticationFilter();
this.filter.setUserDetailsService(uds);
this.filter.setAuthenticationEntryPoint(ep);
this.request = new MockHttpServletRequest("GET", REQUEST_URI);
this.request.setServletPath(REQUEST_URI);
}
@@ -141,17 +133,12 @@ public class DigestAuthenticationFilterTests {
String nonce = generateNonce(0);
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, nonce, NC, CNONCE);
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
Thread.sleep(1000); // ensures token expired
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
String header = response.getHeader("WWW-Authenticate").toString().substring(7);
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header);
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
@@ -163,12 +150,9 @@ public class DigestAuthenticationFilterTests {
String badNonce = generateNonce(60, "badkey");
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, badNonce, NC, CNONCE);
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, badNonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
assertThat(response.getStatus()).isEqualTo(401);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -176,7 +160,6 @@ public class DigestAuthenticationFilterTests {
@Test
public void testFilterIgnoresRequestsContainingNoAuthorizationHeader() throws Exception {
executeFilterInContainerSimulator(this.filter, this.request, true);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -185,10 +168,8 @@ public class DigestAuthenticationFilterTests {
DigestAuthenticationFilter filter = new DigestAuthenticationFilter();
filter.setUserDetailsService(mock(UserDetailsService.class));
assertThat(filter.getUserDetailsService() != null).isTrue();
filter.setAuthenticationEntryPoint(new DigestAuthenticationEntryPoint());
assertThat(filter.getAuthenticationEntryPoint() != null).isTrue();
filter.setUserCache(null);
assertThat(filter.getUserCache()).isNull();
filter.setUserCache(new NullUserCache());
@@ -198,11 +179,8 @@ public class DigestAuthenticationFilterTests {
@Test
public void testInvalidDigestAuthorizationTokenGeneratesError() throws Exception {
String token = "NOT_A_VALID_TOKEN_AS_MISSING_COLON";
this.request.addHeader("Authorization", "Digest " + new String(Base64.encodeBase64(token.getBytes())));
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
assertThat(response.getStatus()).isEqualTo(401);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -210,9 +188,7 @@ public class DigestAuthenticationFilterTests {
@Test
public void testMalformedHeaderReturnsForbidden() throws Exception {
this.request.addHeader("Authorization", "Digest scsdcsdc");
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
}
@@ -220,15 +196,11 @@ public class DigestAuthenticationFilterTests {
@Test
public void testNonBase64EncodedNonceReturnsForbidden() throws Exception {
String nonce = "NOT_BASE_64_ENCODED";
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, nonce, NC, CNONCE);
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
}
@@ -238,12 +210,9 @@ public class DigestAuthenticationFilterTests {
String nonce = new String(Base64.encodeBase64("123456:incorrectStringPassword".getBytes()));
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, nonce, NC, CNONCE);
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
}
@@ -253,12 +222,9 @@ public class DigestAuthenticationFilterTests {
String nonce = new String(Base64.encodeBase64("hello:ignoredSecondElement".getBytes()));
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, nonce, NC, CNONCE);
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
}
@@ -268,12 +234,9 @@ public class DigestAuthenticationFilterTests {
String nonce = new String(Base64.encodeBase64("a base 64 string without a colon".getBytes()));
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, nonce, NC, CNONCE);
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
}
@@ -283,12 +246,9 @@ public class DigestAuthenticationFilterTests {
String encodedPassword = DigestAuthUtils.encodePasswordInA1Format(USERNAME, REALM, PASSWORD);
String responseDigest = DigestAuthUtils.generateDigest(true, USERNAME, REALM, encodedPassword, "GET",
REQUEST_URI, QOP, NONCE, NC, CNONCE);
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
executeFilterInContainerSimulator(this.filter, this.request, true);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername())
.isEqualTo(USERNAME);
@@ -298,12 +258,9 @@ public class DigestAuthenticationFilterTests {
public void testNormalOperationWhenPasswordNotAlreadyEncoded() throws Exception {
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, NONCE, NC, CNONCE);
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
executeFilterInContainerSimulator(this.filter, this.request, true);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername())
.isEqualTo(USERNAME);
@@ -314,13 +271,10 @@ public class DigestAuthenticationFilterTests {
public void testNormalOperationWhenPasswordNotAlreadyEncodedAndWithoutReAuthentication() throws Exception {
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, NONCE, NC, CNONCE);
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
this.filter.setCreateAuthenticatedToken(true);
executeFilterInContainerSimulator(this.filter, this.request, true);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername())
.isEqualTo(USERNAME);
@@ -332,9 +286,7 @@ public class DigestAuthenticationFilterTests {
@Test
public void otherAuthorizationSchemeIsIgnored() throws Exception {
this.request.addHeader("Authorization", "SOME_OTHER_AUTHENTICATION_SCHEME");
executeFilterInContainerSimulator(this.filter, this.request, true);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -356,24 +308,17 @@ public class DigestAuthenticationFilterTests {
public void successfulLoginThenFailedLoginResultsInSessionLosingToken() throws Exception {
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, NONCE, NC, CNONCE);
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
executeFilterInContainerSimulator(this.filter, this.request, true);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
// Now retry, giving an invalid nonce
responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, "WRONG_PASSWORD", "GET", REQUEST_URI,
QOP, NONCE, NC, CNONCE);
this.request = new MockHttpServletRequest();
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
// Check we lost our previous authentication
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
@@ -382,15 +327,11 @@ public class DigestAuthenticationFilterTests {
@Test
public void wrongCnonceBasedOnDigestReturnsForbidden() throws Exception {
String cnonce = "NOT_SAME_AS_USED_FOR_DIGEST_COMPUTATION";
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, NONCE, NC, "DIFFERENT_CNONCE");
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, cnonce));
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
}
@@ -400,12 +341,9 @@ public class DigestAuthenticationFilterTests {
String password = "WRONG_PASSWORD";
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, password, "GET", REQUEST_URI,
QOP, NONCE, NC, CNONCE);
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
}
@@ -415,12 +353,9 @@ public class DigestAuthenticationFilterTests {
String realm = "WRONG_REALM";
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, realm, PASSWORD, "GET", REQUEST_URI,
QOP, NONCE, NC, CNONCE);
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, realm, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
}
@@ -429,12 +364,9 @@ public class DigestAuthenticationFilterTests {
public void wrongUsernameReturnsForbidden() throws Exception {
String responseDigest = DigestAuthUtils.generateDigest(false, "NOT_A_KNOWN_USER", REALM, PASSWORD, "GET",
REQUEST_URI, QOP, NONCE, NC, CNONCE);
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
}
@@ -446,18 +378,13 @@ public class DigestAuthenticationFilterTests {
TestingAuthenticationToken existingAuthentication = new TestingAuthenticationToken("existingauthenitcated",
"pass", "ROLE_USER");
existingContext.setAuthentication(existingAuthentication);
SecurityContextHolder.setContext(existingContext);
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, NONCE, NC, CNONCE);
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
this.filter.setCreateAuthenticatedToken(true);
executeFilterInContainerSimulator(this.filter, this.request, true);
assertThat(existingAuthentication).isSameAs(existingContext.getAuthentication());
}

View File

@@ -91,26 +91,20 @@ public class ConcurrentSessionFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpSession session = new MockHttpSession();
request.setSession(session);
MockHttpServletResponse response = new MockHttpServletResponse();
SessionRegistry registry = new SessionRegistryImpl();
registry.registerNewSession(session.getId(), "principal");
registry.getSessionInformation(session.getId()).expireNow();
// Setup our test fixture and registry to want this session to be expired
SimpleRedirectSessionInformationExpiredStrategy expiredSessionStrategy = new SimpleRedirectSessionInformationExpiredStrategy(
"/expired.jsp");
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, expiredSessionStrategy);
filter.setLogoutHandlers(new LogoutHandler[] { new SecurityContextLogoutHandler() });
filter.afterPropertiesSet();
FilterChain fc = mock(FilterChain.class);
filter.doFilter(request, response, fc);
// Expect that the filter chain will not be invoked, as we redirect to expiredUrl
verifyZeroInteractions(fc);
assertThat(response.getRedirectedUrl()).isEqualTo("/expired.jsp");
}
@@ -120,18 +114,14 @@ public class ConcurrentSessionFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpSession session = new MockHttpSession();
request.setSession(session);
MockHttpServletResponse response = new MockHttpServletResponse();
SessionRegistry registry = new SessionRegistryImpl();
registry.registerNewSession(session.getId(), "principal");
registry.getSessionInformation(session.getId()).expireNow();
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry);
FilterChain fc = mock(FilterChain.class);
filter.doFilter(request, response, fc);
verifyZeroInteractions(fc);
assertThat(response.getContentAsString())
.isEqualTo("This session has been expired (possibly due to multiple concurrent logins being "
+ "attempted as the same user).");
@@ -148,23 +138,17 @@ public class ConcurrentSessionFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpSession session = new MockHttpSession();
request.setSession(session);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain fc = mock(FilterChain.class);
// Setup our test fixture
SessionRegistry registry = new SessionRegistryImpl();
registry.registerNewSession(session.getId(), "principal");
SimpleRedirectSessionInformationExpiredStrategy expiredSessionStrategy = new SimpleRedirectSessionInformationExpiredStrategy(
"/expired.jsp");
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, expiredSessionStrategy);
Date lastRequest = registry.getSessionInformation(session.getId()).getLastRequest();
Thread.sleep(1000);
filter.doFilter(request, response, fc);
verify(fc).doFilter(request, response);
assertThat(registry.getSessionInformation(session.getId()).getLastRequest().after(lastRequest)).isTrue();
}
@@ -173,22 +157,17 @@ public class ConcurrentSessionFilterTests {
public void doFilterWhenNoSessionThenChainIsContinued() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
RedirectStrategy redirect = mock(RedirectStrategy.class);
SessionRegistry registry = mock(SessionRegistry.class);
SessionInformation information = new SessionInformation("user", "sessionId",
new Date(System.currentTimeMillis() - 1000));
information.expireNow();
given(registry.getSessionInformation(anyString())).willReturn(information);
String expiredUrl = "/expired";
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, expiredUrl);
filter.setRedirectStrategy(redirect);
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, response, chain);
assertThat(chain.getRequest()).isNotNull();
}
@@ -197,18 +176,13 @@ public class ConcurrentSessionFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(new MockHttpSession());
MockHttpServletResponse response = new MockHttpServletResponse();
RedirectStrategy redirect = mock(RedirectStrategy.class);
SessionRegistry registry = mock(SessionRegistry.class);
String expiredUrl = "/expired";
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, expiredUrl);
filter.setRedirectStrategy(redirect);
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, response, chain);
assertThat(chain.getRequest()).isNotNull();
}
@@ -218,20 +192,16 @@ public class ConcurrentSessionFilterTests {
MockHttpSession session = new MockHttpSession();
request.setSession(session);
MockHttpServletResponse response = new MockHttpServletResponse();
RedirectStrategy redirect = mock(RedirectStrategy.class);
SessionRegistry registry = mock(SessionRegistry.class);
SessionInformation information = new SessionInformation("user", "sessionId",
new Date(System.currentTimeMillis() - 1000));
information.expireNow();
given(registry.getSessionInformation(anyString())).willReturn(information);
String expiredUrl = "/expired";
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, expiredUrl);
filter.setRedirectStrategy(redirect);
filter.doFilter(request, response, new MockFilterChain());
verify(redirect).sendRedirect(request, response, expiredUrl);
}
@@ -241,27 +211,21 @@ public class ConcurrentSessionFilterTests {
MockHttpSession session = new MockHttpSession();
request.setSession(session);
MockHttpServletResponse response = new MockHttpServletResponse();
RedirectStrategy redirect = mock(RedirectStrategy.class);
SessionRegistry registry = mock(SessionRegistry.class);
SessionInformation information = new SessionInformation("user", "sessionId",
new Date(System.currentTimeMillis() - 1000));
information.expireNow();
given(registry.getSessionInformation(anyString())).willReturn(information);
final String expiredUrl = "/expired";
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, expiredUrl + "will-be-overrridden") {
@Override
protected String determineExpiredUrl(HttpServletRequest request, SessionInformation info) {
return expiredUrl;
}
};
filter.setRedirectStrategy(redirect);
filter.doFilter(request, response, new MockFilterChain());
verify(redirect).sendRedirect(request, response, expiredUrl);
}
@@ -271,17 +235,13 @@ public class ConcurrentSessionFilterTests {
MockHttpSession session = new MockHttpSession();
request.setSession(session);
MockHttpServletResponse response = new MockHttpServletResponse();
SessionRegistry registry = mock(SessionRegistry.class);
SessionInformation information = new SessionInformation("user", "sessionId",
new Date(System.currentTimeMillis() - 1000));
information.expireNow();
given(registry.getSessionInformation(anyString())).willReturn(information);
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry);
filter.doFilter(request, response, new MockFilterChain());
assertThat(response.getContentAsString()).contains(
"This session has been expired (possibly due to multiple concurrent logins being attempted as the same user).");
}
@@ -293,32 +253,26 @@ public class ConcurrentSessionFilterTests {
MockHttpSession session = new MockHttpSession();
request.setSession(session);
MockHttpServletResponse response = new MockHttpServletResponse();
SessionRegistry registry = mock(SessionRegistry.class);
SessionInformation information = new SessionInformation("user", "sessionId",
new Date(System.currentTimeMillis() - 1000));
information.expireNow();
given(registry.getSessionInformation(anyString())).willReturn(information);
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry);
filter.setLogoutHandlers(new LogoutHandler[] { handler });
filter.doFilter(request, response, new MockFilterChain());
verify(handler).logout(eq(request), eq(response), any());
}
@Test(expected = IllegalArgumentException.class)
public void setLogoutHandlersWhenNullThenThrowsException() {
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(new SessionRegistryImpl());
filter.setLogoutHandlers((List<LogoutHandler>) null);
}
@Test(expected = IllegalArgumentException.class)
public void setLogoutHandlersWhenEmptyThenThrowsException() {
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(new SessionRegistryImpl());
filter.setLogoutHandlers(new LogoutHandler[0]);
}

View File

@@ -60,15 +60,11 @@ public class AbstractSecurityWebApplicationInitializerTests {
public void onStartupWhenDefaultContextThenRegistersSpringSecurityFilterChain() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration).setAsyncSupported(true);
verifyNoAddListener(context);
@@ -78,16 +74,11 @@ public class AbstractSecurityWebApplicationInitializerTests {
public void onStartupWhenConfigurationClassThenAddsContextLoaderListener() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer(MyRootConfiguration.class) {
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration).setAsyncSupported(true);
verify(context).addListener(any(ContextLoaderListener.class));
@@ -97,20 +88,15 @@ public class AbstractSecurityWebApplicationInitializerTests {
public void onStartupWhenEnableHttpSessionEventPublisherIsTrueThenAddsHttpSessionEventPublisher() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected boolean enableHttpSessionEventPublisher() {
return true;
}
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration).setAsyncSupported(true);
verify(context).addListener(HttpSessionEventPublisher.class.getName());
@@ -120,20 +106,15 @@ public class AbstractSecurityWebApplicationInitializerTests {
public void onStartupWhenCustomSecurityDispatcherTypesThenUses() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected EnumSet<DispatcherType> getSecurityDispatcherTypes() {
return EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.FORWARD);
}
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(
EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.FORWARD), false, "/*");
verify(registration).setAsyncSupported(true);
@@ -144,23 +125,18 @@ public class AbstractSecurityWebApplicationInitializerTests {
public void onStartupWhenCustomDispatcherWebApplicationContextSuffixThenUses() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected String getDispatcherWebApplicationContextSuffix() {
return "dispatcher";
}
}.onStartup(context);
DelegatingFilterProxy proxy = proxyCaptor.getValue();
assertThat(proxy.getContextAttribute())
.isEqualTo("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher");
assertThat(proxy).hasFieldOrPropertyWithValue("targetBeanName", "springSecurityFilterChain");
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration).setAsyncSupported(true);
verifyNoAddListener(context);
@@ -169,7 +145,6 @@ public class AbstractSecurityWebApplicationInitializerTests {
@Test
public void onStartupWhenSpringSecurityFilterChainAlreadyRegisteredThenException() {
ServletContext context = mock(ServletContext.class);
assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() {
}.onStartup(context)).isInstanceOf(IllegalStateException.class)
.hasMessage("Duplicate Filter registration for 'springSecurityFilterChain'. "
@@ -182,22 +157,17 @@ public class AbstractSecurityWebApplicationInitializerTests {
Filter filter2 = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter1))).willReturn(registration);
given(context.addFilter(anyString(), eq(filter2))).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context, filter1, filter2);
}
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
verify(registration, times(3)).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration, times(3)).setAsyncSupported(true);
verifyNoAddListener(context);
@@ -210,11 +180,8 @@ public class AbstractSecurityWebApplicationInitializerTests {
Filter filter1 = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
@@ -222,9 +189,7 @@ public class AbstractSecurityWebApplicationInitializerTests {
}
}.onStartup(context)).isInstanceOf(IllegalStateException.class).hasMessage(
"Duplicate Filter registration for 'object'. " + "Check to ensure the Filter is only configured once.");
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(context).addFilter(anyString(), eq(filter1));
}
@@ -233,11 +198,8 @@ public class AbstractSecurityWebApplicationInitializerTests {
public void onStartupWhenInsertFiltersEmptyThenException() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
@@ -245,7 +207,6 @@ public class AbstractSecurityWebApplicationInitializerTests {
}
}.onStartup(context)).isInstanceOf(IllegalArgumentException.class)
.hasMessage("filters cannot be null or empty");
assertProxyDefaults(proxyCaptor.getValue());
}
@@ -254,12 +215,9 @@ public class AbstractSecurityWebApplicationInitializerTests {
Filter filter = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter))).willReturn(registration);
assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
@@ -267,7 +225,6 @@ public class AbstractSecurityWebApplicationInitializerTests {
}
}.onStartup(context)).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("filters cannot contain null values");
verify(context, times(2)).addFilter(anyString(), any(Filter.class));
}
@@ -277,20 +234,16 @@ public class AbstractSecurityWebApplicationInitializerTests {
Filter filter2 = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter1))).willReturn(registration);
given(context.addFilter(anyString(), eq(filter2))).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context, filter1, filter2);
}
}.onStartup(context);
verify(registration, times(1)).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration, times(2)).addMappingForUrlPatterns(DEFAULT_DISPATCH, true, "/*");
verify(registration, times(3)).setAsyncSupported(true);
@@ -303,11 +256,8 @@ public class AbstractSecurityWebApplicationInitializerTests {
Filter filter1 = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
@@ -315,9 +265,7 @@ public class AbstractSecurityWebApplicationInitializerTests {
}
}.onStartup(context)).isInstanceOf(IllegalStateException.class).hasMessage(
"Duplicate Filter registration for 'object'. " + "Check to ensure the Filter is only configured once.");
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(context).addFilter(anyString(), eq(filter1));
}
@@ -326,11 +274,8 @@ public class AbstractSecurityWebApplicationInitializerTests {
public void onStartupWhenAppendFiltersEmptyThenException() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
@@ -338,7 +283,6 @@ public class AbstractSecurityWebApplicationInitializerTests {
}
}.onStartup(context)).isInstanceOf(IllegalArgumentException.class)
.hasMessage("filters cannot be null or empty");
assertProxyDefaults(proxyCaptor.getValue());
}
@@ -347,12 +291,9 @@ public class AbstractSecurityWebApplicationInitializerTests {
Filter filter = mock(Filter.class);
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter))).willReturn(registration);
assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
@@ -360,7 +301,6 @@ public class AbstractSecurityWebApplicationInitializerTests {
}
}.onStartup(context)).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("filters cannot contain null values");
verify(context, times(2)).addFilter(anyString(), any(Filter.class));
}
@@ -368,20 +308,15 @@ public class AbstractSecurityWebApplicationInitializerTests {
public void onStartupWhenDefaultsThenSessionTrackingModes() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
ArgumentCaptor<Set<SessionTrackingMode>> modesCaptor = ArgumentCaptor
.forClass(new HashSet<SessionTrackingMode>() {
}.getClass());
willDoNothing().given(context).setSessionTrackingModes(modesCaptor.capture());
new AbstractSecurityWebApplicationInitializer() {
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
Set<SessionTrackingMode> modes = modesCaptor.getValue();
assertThat(modes).hasSize(1);
assertThat(modes).containsExactly(SessionTrackingMode.COOKIE);
@@ -391,24 +326,19 @@ public class AbstractSecurityWebApplicationInitializerTests {
public void onStartupWhenSessionTrackingModesConfiguredThenUsed() {
ServletContext context = mock(ServletContext.class);
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
ArgumentCaptor<Set<SessionTrackingMode>> modesCaptor = ArgumentCaptor
.forClass(new HashSet<SessionTrackingMode>() {
}.getClass());
willDoNothing().given(context).setSessionTrackingModes(modesCaptor.capture());
new AbstractSecurityWebApplicationInitializer() {
@Override
public Set<SessionTrackingMode> getSessionTrackingModes() {
return Collections.singleton(SessionTrackingMode.SSL);
}
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
Set<SessionTrackingMode> modes = modesCaptor.getValue();
assertThat(modes).hasSize(1);
assertThat(modes).containsExactly(SessionTrackingMode.SSL);

View File

@@ -71,11 +71,9 @@ public class HttpSessionSecurityContextRepositoryTests {
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
repo.loadContext(holder);
reset(request);
holder.getRequest().startAsync();
holder.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST);
// ensure that sendError did cause interaction with the HttpSession
verify(request, never()).getSession(anyBoolean());
verify(request, never()).getSession();
@@ -88,11 +86,9 @@ public class HttpSessionSecurityContextRepositoryTests {
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
repo.loadContext(holder);
reset(request);
holder.getRequest().startAsync(request, response);
holder.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST);
// ensure that sendError did cause interaction with the HttpSession
verify(request, never()).getSession(anyBoolean());
verify(request, never()).getSession();
@@ -156,12 +152,10 @@ public class HttpSessionSecurityContextRepositoryTests {
request.setSession(session);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse());
assertThat(repo.loadContext(holder)).isSameAs(ctx);
// Modify context contents. Same user, different role
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("someone", "passwd", "ROLE_B"));
repo.saveContext(ctx, holder.getRequest(), holder.getResponse());
// Must be called even though the value in the local VM is already the same
verify(session).setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, ctx);
}
@@ -224,7 +218,6 @@ public class HttpSessionSecurityContextRepositoryTests {
SecurityContextHolder.getContext().setAuthentication(this.testToken);
holder.getResponse().sendError(404);
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext());
assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue();
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
// Check it's still the same
@@ -441,13 +434,10 @@ public class HttpSessionSecurityContextRepositoryTests {
ctxInSession.setAuthentication(this.testToken);
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
ctxInSession);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse());
repo.loadContext(holder);
ctxInSession.setAuthentication(null);
repo.saveContext(ctxInSession, holder.getRequest(), holder.getResponse());
assertThat(request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY))
.isNull();
}
@@ -459,7 +449,6 @@ public class HttpSessionSecurityContextRepositoryTests {
MockHttpServletRequest request = new MockHttpServletRequest();
final String sessionId = ";jsessionid=id";
MockHttpServletResponse response = new MockHttpServletResponse() {
@Override
public String encodeRedirectUrl(String url) {
return url + sessionId;
@@ -506,9 +495,7 @@ public class HttpSessionSecurityContextRepositoryTests {
repo.loadContext(holder);
AuthenticationTrustResolver trustResolver = mock(AuthenticationTrustResolver.class);
repo.setTrustResolver(trustResolver);
repo.saveContext(contextToSave, holder.getRequest(), holder.getResponse());
verify(trustResolver).isAnonymous(contextToSave.getAuthentication());
}
@@ -529,10 +516,8 @@ public class HttpSessionSecurityContextRepositoryTests {
assertThat(request.getSession(false)).isNull();
// Simulate authentication during the request
context.setAuthentication(this.testToken);
repo.saveContext(context, new HttpServletRequestWrapper(holder.getRequest()),
new HttpServletResponseWrapper(holder.getResponse()));
assertThat(request.getSession(false)).isNotNull();
assertThat(request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY))
.isEqualTo(context);
@@ -545,7 +530,6 @@ public class HttpSessionSecurityContextRepositoryTests {
MockHttpServletResponse response = new MockHttpServletResponse();
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(this.testToken);
repo.saveContext(context, request, response);
}
@@ -556,12 +540,9 @@ public class HttpSessionSecurityContextRepositoryTests {
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContext context = repo.loadContext(holder);
SomeTransientAuthentication authentication = new SomeTransientAuthentication();
context.setAuthentication(authentication);
repo.saveContext(context, holder.getRequest(), holder.getResponse());
MockHttpSession session = (MockHttpSession) request.getSession(false);
assertThat(session).isNull();
}
@@ -573,12 +554,9 @@ public class HttpSessionSecurityContextRepositoryTests {
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContext context = repo.loadContext(holder);
SomeTransientAuthenticationSubclass authentication = new SomeTransientAuthenticationSubclass();
context.setAuthentication(authentication);
repo.saveContext(context, holder.getRequest(), holder.getResponse());
MockHttpSession session = (MockHttpSession) request.getSession(false);
assertThat(session).isNull();
}
@@ -590,12 +568,9 @@ public class HttpSessionSecurityContextRepositoryTests {
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContext context = repo.loadContext(holder);
SomeOtherTransientAuthentication authentication = new SomeOtherTransientAuthentication();
context.setAuthentication(authentication);
repo.saveContext(context, holder.getRequest(), holder.getResponse());
MockHttpSession session = (MockHttpSession) request.getSession(false);
assertThat(session).isNull();
}

View File

@@ -35,7 +35,6 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Rob Winch
*
*/
@RunWith(MockitoJUnitRunner.class)
public class SaveContextOnUpdateOrErrorResponseWrapperTests {

View File

@@ -56,7 +56,6 @@ public class SecurityContextPersistenceFilterTests {
final MockHttpServletResponse response = new MockHttpServletResponse();
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
SecurityContextHolder.getContext().setAuthentication(this.testToken);
filter.doFilter(request, response, chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
@@ -76,7 +75,6 @@ public class SecurityContextPersistenceFilterTests {
}
catch (IOException expected) {
}
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -91,17 +89,13 @@ public class SecurityContextPersistenceFilterTests {
scBefore.setAuthentication(beforeAuth);
final SecurityContextRepository repo = mock(SecurityContextRepository.class);
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(repo);
given(repo.loadContext(any(HttpRequestResponseHolder.class))).willReturn(scBefore);
final FilterChain chain = (request1, response1) -> {
assertThat(SecurityContextHolder.getContext().getAuthentication()).isEqualTo(beforeAuth);
// Change the context here
SecurityContextHolder.setContext(scExpectedAfter);
};
filter.doFilter(request, response, chain);
verify(repo).saveContext(scExpectedAfter, request, response);
}
@@ -112,7 +106,6 @@ public class SecurityContextPersistenceFilterTests {
final MockHttpServletResponse response = new MockHttpServletResponse();
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(
mock(SecurityContextRepository.class));
request.setAttribute(SecurityContextPersistenceFilter.FILTER_APPLIED, Boolean.TRUE);
filter.doFilter(request, response, chain);
verify(chain).doFilter(request, response);

View File

@@ -62,10 +62,8 @@ public class SecurityContextCallableProcessingInterceptorTests {
SecurityContextHolder.setContext(this.securityContext);
interceptor.beforeConcurrentHandling(this.webRequest, this.callable);
SecurityContextHolder.clearContext();
interceptor.preProcess(this.webRequest, this.callable);
assertThat(SecurityContextHolder.getContext()).isSameAs(this.securityContext);
interceptor.postProcess(this.webRequest, this.callable, null);
assertThat(SecurityContextHolder.getContext()).isNotSameAs(this.securityContext);
}
@@ -74,10 +72,8 @@ public class SecurityContextCallableProcessingInterceptorTests {
public void specificSecurityContext() throws Exception {
SecurityContextCallableProcessingInterceptor interceptor = new SecurityContextCallableProcessingInterceptor(
this.securityContext);
interceptor.preProcess(this.webRequest, this.callable);
assertThat(SecurityContextHolder.getContext()).isSameAs(this.securityContext);
interceptor.postProcess(this.webRequest, this.callable, null);
assertThat(SecurityContextHolder.getContext()).isNotSameAs(this.securityContext);
}

View File

@@ -72,16 +72,13 @@ public class WebAsyncManagerIntegrationFilterTests {
@Before
public void setUp() {
this.filterChain = new MockFilterChain();
this.threadFactory = new JoinableThreadFactory();
SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor();
executor.setThreadFactory(this.threadFactory);
this.asyncManager = WebAsyncUtils.getAsyncManager(this.request);
this.asyncManager.setAsyncWebRequest(this.asyncWebRequest);
this.asyncManager.setTaskExecutor(executor);
given(this.request.getAttribute(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE)).willReturn(this.asyncManager);
this.filter = new WebAsyncManagerIntegrationFilter();
}
@@ -101,7 +98,6 @@ public class WebAsyncManagerIntegrationFilterTests {
}
});
this.filter.doFilterInternal(this.request, this.response, this.filterChain);
VerifyingCallable verifyingCallable = new VerifyingCallable();
this.asyncManager.startCallableProcessing(verifyingCallable);
this.threadFactory.join();
@@ -120,7 +116,6 @@ public class WebAsyncManagerIntegrationFilterTests {
});
this.filter.doFilterInternal(this.request, this.response, this.filterChain);
SecurityContextHolder.setContext(this.securityContext);
VerifyingCallable verifyingCallable = new VerifyingCallable();
this.asyncManager.startCallableProcessing(verifyingCallable);
this.threadFactory.join();

View File

@@ -49,7 +49,6 @@ public class CookieCsrfTokenRepositoryTests {
@Test
public void generateToken() {
CsrfToken generateToken = this.repository.generateToken(this.request);
assertThat(generateToken).isNotNull();
assertThat(generateToken.getHeaderName()).isEqualTo(CookieCsrfTokenRepository.DEFAULT_CSRF_HEADER_NAME);
assertThat(generateToken.getParameterName()).isEqualTo(CookieCsrfTokenRepository.DEFAULT_CSRF_PARAMETER_NAME);
@@ -62,9 +61,7 @@ public class CookieCsrfTokenRepositoryTests {
String parameterName = "paramName";
this.repository.setHeaderName(headerName);
this.repository.setParameterName(parameterName);
CsrfToken generateToken = this.repository.generateToken(this.request);
assertThat(generateToken).isNotNull();
assertThat(generateToken.getHeaderName()).isEqualTo(headerName);
assertThat(generateToken.getParameterName()).isEqualTo(parameterName);
@@ -75,9 +72,7 @@ public class CookieCsrfTokenRepositoryTests {
public void saveToken() {
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getMaxAge()).isEqualTo(-1);
assertThat(tokenCookie.getName()).isEqualTo(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getPath()).isEqualTo(this.request.getContextPath());
@@ -91,9 +86,7 @@ public class CookieCsrfTokenRepositoryTests {
this.request.setSecure(true);
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getSecure()).isTrue();
}
@@ -103,9 +96,7 @@ public class CookieCsrfTokenRepositoryTests {
this.repository.setSecure(Boolean.TRUE);
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getSecure()).isTrue();
}
@@ -115,9 +106,7 @@ public class CookieCsrfTokenRepositoryTests {
this.repository.setSecure(Boolean.FALSE);
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getSecure()).isFalse();
}
@@ -125,9 +114,7 @@ public class CookieCsrfTokenRepositoryTests {
public void saveTokenNull() {
this.request.setSecure(true);
this.repository.saveToken(null, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getMaxAge()).isZero();
assertThat(tokenCookie.getName()).isEqualTo(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getPath()).isEqualTo(this.request.getContextPath());
@@ -140,9 +127,7 @@ public class CookieCsrfTokenRepositoryTests {
this.repository.setCookieHttpOnly(true);
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.isHttpOnly()).isTrue();
}
@@ -151,9 +136,7 @@ public class CookieCsrfTokenRepositoryTests {
this.repository.setCookieHttpOnly(false);
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.isHttpOnly()).isFalse();
}
@@ -162,9 +145,7 @@ public class CookieCsrfTokenRepositoryTests {
this.repository = CookieCsrfTokenRepository.withHttpOnlyFalse();
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.isHttpOnly()).isFalse();
}
@@ -174,9 +155,7 @@ public class CookieCsrfTokenRepositoryTests {
this.repository.setCookiePath(customPath);
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getPath()).isEqualTo(this.repository.getCookiePath());
}
@@ -186,9 +165,7 @@ public class CookieCsrfTokenRepositoryTests {
this.repository.setCookiePath(customPath);
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getPath()).isEqualTo(this.request.getContextPath());
}
@@ -198,9 +175,7 @@ public class CookieCsrfTokenRepositoryTests {
this.repository.setCookiePath(customPath);
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getPath()).isEqualTo(this.request.getContextPath());
}
@@ -208,12 +183,9 @@ public class CookieCsrfTokenRepositoryTests {
public void saveTokenWithCookieDomain() {
String domainName = "example.com";
this.repository.setCookieDomain(domainName);
CsrfToken token = this.repository.generateToken(this.request);
this.repository.saveToken(token, this.request, this.response);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getDomain()).isEqualTo(domainName);
}
@@ -225,26 +197,21 @@ public class CookieCsrfTokenRepositoryTests {
@Test
public void loadTokenCookieIncorrectNameNull() {
this.request.setCookies(new Cookie("other", "name"));
assertThat(this.repository.loadToken(this.request)).isNull();
}
@Test
public void loadTokenCookieValueEmptyString() {
this.request.setCookies(new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, ""));
assertThat(this.repository.loadToken(this.request)).isNull();
}
@Test
public void loadToken() {
CsrfToken generateToken = this.repository.generateToken(this.request);
this.request
.setCookies(new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, generateToken.getToken()));
CsrfToken loadToken = this.repository.loadToken(this.request);
assertThat(loadToken).isNotNull();
assertThat(loadToken.getHeaderName()).isEqualTo(generateToken.getHeaderName());
assertThat(loadToken.getParameterName()).isEqualTo(generateToken.getParameterName());
@@ -260,11 +227,8 @@ public class CookieCsrfTokenRepositoryTests {
this.repository.setHeaderName(headerName);
this.repository.setParameterName(parameterName);
this.repository.setCookieName(cookieName);
this.request.setCookies(new Cookie(cookieName, value));
CsrfToken loadToken = this.repository.loadToken(this.request);
assertThat(loadToken).isNotNull();
assertThat(loadToken.getHeaderName()).isEqualTo(headerName);
assertThat(loadToken.getParameterName()).isEqualTo(parameterName);

View File

@@ -77,7 +77,6 @@ public class CsrfAuthenticationStrategyTests {
given(this.csrfTokenRepository.generateToken(this.request)).willReturn(this.generatedToken);
this.strategy.onAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"), this.request,
this.response);
verify(this.csrfTokenRepository).saveToken(null, this.request, this.response);
verify(this.csrfTokenRepository).saveToken(eq(this.generatedToken), any(HttpServletRequest.class),
any(HttpServletResponse.class));
@@ -93,16 +92,13 @@ public class CsrfAuthenticationStrategyTests {
@Test
public void delaySavingCsrf() {
this.strategy = new CsrfAuthenticationStrategy(new LazyCsrfTokenRepository(this.csrfTokenRepository));
given(this.csrfTokenRepository.loadToken(this.request)).willReturn(this.existingToken);
given(this.csrfTokenRepository.generateToken(this.request)).willReturn(this.generatedToken);
this.strategy.onAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"), this.request,
this.response);
verify(this.csrfTokenRepository).saveToken(null, this.request, this.response);
verify(this.csrfTokenRepository, never()).saveToken(eq(this.generatedToken), any(HttpServletRequest.class),
any(HttpServletResponse.class));
CsrfToken tokenInRequest = (CsrfToken) this.request.getAttribute(CsrfToken.class.getName());
tokenInRequest.getToken();
verify(this.csrfTokenRepository).saveToken(eq(this.generatedToken), any(HttpServletRequest.class),
@@ -113,7 +109,6 @@ public class CsrfAuthenticationStrategyTests {
public void logoutRemovesNoActionIfNullToken() {
this.strategy.onAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"), this.request,
this.response);
verify(this.csrfTokenRepository, never()).saveToken(any(CsrfToken.class), any(HttpServletRequest.class),
any(HttpServletResponse.class));
}

View File

@@ -106,18 +106,14 @@ public class CsrfFilterTests {
this.filter = createCsrfFilter(new LazyCsrfTokenRepository(this.tokenRepository));
given(this.requestMatcher.matches(this.request)).willReturn(false);
given(this.tokenRepository.generateToken(this.request)).willReturn(this.token);
this.filter.doFilter(this.request, this.response, this.filterChain);
CsrfToken attrToken = (CsrfToken) this.request.getAttribute(this.token.getParameterName());
// no CsrfToken should have been saved yet
verify(this.tokenRepository, times(0)).saveToken(any(CsrfToken.class), any(HttpServletRequest.class),
any(HttpServletResponse.class));
verify(this.filterChain).doFilter(this.request, this.response);
// access the token
attrToken.getToken();
// now the CsrfToken should have been saved
verify(this.tokenRepository).saveToken(eq(this.token), any(HttpServletRequest.class),
any(HttpServletResponse.class));
@@ -127,12 +123,9 @@ public class CsrfFilterTests {
public void doFilterAccessDeniedNoTokenPresent() throws ServletException, IOException {
given(this.requestMatcher.matches(this.request)).willReturn(true);
given(this.tokenRepository.loadToken(this.request)).willReturn(this.token);
this.filter.doFilter(this.request, this.response, this.filterChain);
assertThat(this.request.getAttribute(this.token.getParameterName())).isEqualTo(this.token);
assertThat(this.request.getAttribute(CsrfToken.class.getName())).isEqualTo(this.token);
verify(this.deniedHandler).handle(eq(this.request), eq(this.response), any(InvalidCsrfTokenException.class));
verifyZeroInteractions(this.filterChain);
}
@@ -142,12 +135,9 @@ public class CsrfFilterTests {
given(this.requestMatcher.matches(this.request)).willReturn(true);
given(this.tokenRepository.loadToken(this.request)).willReturn(this.token);
this.request.setParameter(this.token.getParameterName(), this.token.getToken() + " INVALID");
this.filter.doFilter(this.request, this.response, this.filterChain);
assertThat(this.request.getAttribute(this.token.getParameterName())).isEqualTo(this.token);
assertThat(this.request.getAttribute(CsrfToken.class.getName())).isEqualTo(this.token);
verify(this.deniedHandler).handle(eq(this.request), eq(this.response), any(InvalidCsrfTokenException.class));
verifyZeroInteractions(this.filterChain);
}
@@ -157,12 +147,9 @@ public class CsrfFilterTests {
given(this.requestMatcher.matches(this.request)).willReturn(true);
given(this.tokenRepository.loadToken(this.request)).willReturn(this.token);
this.request.addHeader(this.token.getHeaderName(), this.token.getToken() + " INVALID");
this.filter.doFilter(this.request, this.response, this.filterChain);
assertThat(this.request.getAttribute(this.token.getParameterName())).isEqualTo(this.token);
assertThat(this.request.getAttribute(CsrfToken.class.getName())).isEqualTo(this.token);
verify(this.deniedHandler).handle(eq(this.request), eq(this.response), any(InvalidCsrfTokenException.class));
verifyZeroInteractions(this.filterChain);
}
@@ -174,12 +161,9 @@ public class CsrfFilterTests {
given(this.tokenRepository.loadToken(this.request)).willReturn(this.token);
this.request.setParameter(this.token.getParameterName(), this.token.getToken());
this.request.addHeader(this.token.getHeaderName(), this.token.getToken() + " INVALID");
this.filter.doFilter(this.request, this.response, this.filterChain);
assertThat(this.request.getAttribute(this.token.getParameterName())).isEqualTo(this.token);
assertThat(this.request.getAttribute(CsrfToken.class.getName())).isEqualTo(this.token);
verify(this.deniedHandler).handle(eq(this.request), eq(this.response), any(InvalidCsrfTokenException.class));
verifyZeroInteractions(this.filterChain);
}
@@ -188,12 +172,9 @@ public class CsrfFilterTests {
public void doFilterNotCsrfRequestExistingToken() throws ServletException, IOException {
given(this.requestMatcher.matches(this.request)).willReturn(false);
given(this.tokenRepository.loadToken(this.request)).willReturn(this.token);
this.filter.doFilter(this.request, this.response, this.filterChain);
assertThat(this.request.getAttribute(this.token.getParameterName())).isEqualTo(this.token);
assertThat(this.request.getAttribute(CsrfToken.class.getName())).isEqualTo(this.token);
verify(this.filterChain).doFilter(this.request, this.response);
verifyZeroInteractions(this.deniedHandler);
}
@@ -202,12 +183,9 @@ public class CsrfFilterTests {
public void doFilterNotCsrfRequestGenerateToken() throws ServletException, IOException {
given(this.requestMatcher.matches(this.request)).willReturn(false);
given(this.tokenRepository.generateToken(this.request)).willReturn(this.token);
this.filter.doFilter(this.request, this.response, this.filterChain);
assertToken(this.request.getAttribute(this.token.getParameterName())).isEqualTo(this.token);
assertToken(this.request.getAttribute(CsrfToken.class.getName())).isEqualTo(this.token);
verify(this.filterChain).doFilter(this.request, this.response);
verifyZeroInteractions(this.deniedHandler);
}
@@ -217,12 +195,9 @@ public class CsrfFilterTests {
given(this.requestMatcher.matches(this.request)).willReturn(true);
given(this.tokenRepository.loadToken(this.request)).willReturn(this.token);
this.request.addHeader(this.token.getHeaderName(), this.token.getToken());
this.filter.doFilter(this.request, this.response, this.filterChain);
assertThat(this.request.getAttribute(this.token.getParameterName())).isEqualTo(this.token);
assertThat(this.request.getAttribute(CsrfToken.class.getName())).isEqualTo(this.token);
verify(this.filterChain).doFilter(this.request, this.response);
verifyZeroInteractions(this.deniedHandler);
}
@@ -234,12 +209,9 @@ public class CsrfFilterTests {
given(this.tokenRepository.loadToken(this.request)).willReturn(this.token);
this.request.setParameter(this.token.getParameterName(), this.token.getToken() + " INVALID");
this.request.addHeader(this.token.getHeaderName(), this.token.getToken());
this.filter.doFilter(this.request, this.response, this.filterChain);
assertThat(this.request.getAttribute(this.token.getParameterName())).isEqualTo(this.token);
assertThat(this.request.getAttribute(CsrfToken.class.getName())).isEqualTo(this.token);
verify(this.filterChain).doFilter(this.request, this.response);
verifyZeroInteractions(this.deniedHandler);
}
@@ -249,12 +221,9 @@ public class CsrfFilterTests {
given(this.requestMatcher.matches(this.request)).willReturn(true);
given(this.tokenRepository.loadToken(this.request)).willReturn(this.token);
this.request.setParameter(this.token.getParameterName(), this.token.getToken());
this.filter.doFilter(this.request, this.response, this.filterChain);
assertThat(this.request.getAttribute(this.token.getParameterName())).isEqualTo(this.token);
assertThat(this.request.getAttribute(CsrfToken.class.getName())).isEqualTo(this.token);
verify(this.filterChain).doFilter(this.request, this.response);
verifyZeroInteractions(this.deniedHandler);
verify(this.tokenRepository, never()).saveToken(any(CsrfToken.class), any(HttpServletRequest.class),
@@ -266,15 +235,11 @@ public class CsrfFilterTests {
given(this.requestMatcher.matches(this.request)).willReturn(true);
given(this.tokenRepository.generateToken(this.request)).willReturn(this.token);
this.request.setParameter(this.token.getParameterName(), this.token.getToken());
this.filter.doFilter(this.request, this.response, this.filterChain);
assertToken(this.request.getAttribute(this.token.getParameterName())).isEqualTo(this.token);
assertToken(this.request.getAttribute(CsrfToken.class.getName())).isEqualTo(this.token);
// LazyCsrfTokenRepository requires the response as an attribute
assertThat(this.request.getAttribute(HttpServletResponse.class.getName())).isEqualTo(this.response);
verify(this.filterChain).doFilter(this.request, this.response);
verify(this.tokenRepository).saveToken(this.token, this.request, this.response);
verifyZeroInteractions(this.deniedHandler);
@@ -284,14 +249,11 @@ public class CsrfFilterTests {
public void doFilterDefaultRequireCsrfProtectionMatcherAllowedMethods() throws ServletException, IOException {
this.filter = new CsrfFilter(this.tokenRepository);
this.filter.setAccessDeniedHandler(this.deniedHandler);
for (String method : Arrays.asList("GET", "TRACE", "OPTIONS", "HEAD")) {
resetRequestResponse();
given(this.tokenRepository.loadToken(this.request)).willReturn(this.token);
this.request.setMethod(method);
this.filter.doFilter(this.request, this.response, this.filterChain);
verify(this.filterChain).doFilter(this.request, this.response);
verifyZeroInteractions(this.deniedHandler);
}
@@ -307,14 +269,11 @@ public class CsrfFilterTests {
public void doFilterDefaultRequireCsrfProtectionMatcherAllowedMethodsCaseSensitive() throws Exception {
this.filter = new CsrfFilter(this.tokenRepository);
this.filter.setAccessDeniedHandler(this.deniedHandler);
for (String method : Arrays.asList("get", "TrAcE", "oPTIOnS", "hEaD")) {
resetRequestResponse();
given(this.tokenRepository.loadToken(this.request)).willReturn(this.token);
this.request.setMethod(method);
this.filter.doFilter(this.request, this.response, this.filterChain);
verify(this.deniedHandler).handle(eq(this.request), eq(this.response),
any(InvalidCsrfTokenException.class));
verifyZeroInteractions(this.filterChain);
@@ -325,14 +284,11 @@ public class CsrfFilterTests {
public void doFilterDefaultRequireCsrfProtectionMatcherDeniedMethods() throws ServletException, IOException {
this.filter = new CsrfFilter(this.tokenRepository);
this.filter.setAccessDeniedHandler(this.deniedHandler);
for (String method : Arrays.asList("POST", "PUT", "PATCH", "DELETE", "INVALID")) {
resetRequestResponse();
given(this.tokenRepository.loadToken(this.request)).willReturn(this.token);
this.request.setMethod(method);
this.filter.doFilter(this.request, this.response, this.filterChain);
verify(this.deniedHandler).handle(eq(this.request), eq(this.response),
any(InvalidCsrfTokenException.class));
verifyZeroInteractions(this.filterChain);
@@ -345,28 +301,21 @@ public class CsrfFilterTests {
this.filter.setRequireCsrfProtectionMatcher(this.requestMatcher);
given(this.requestMatcher.matches(this.request)).willReturn(true);
given(this.tokenRepository.loadToken(this.request)).willReturn(this.token);
this.filter.doFilter(this.request, this.response, this.filterChain);
assertThat(this.request.getAttribute(this.token.getParameterName())).isEqualTo(this.token);
assertThat(this.request.getAttribute(CsrfToken.class.getName())).isEqualTo(this.token);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
verifyZeroInteractions(this.filterChain);
}
@Test
public void doFilterWhenSkipRequestInvokedThenSkips() throws Exception {
CsrfTokenRepository repository = mock(CsrfTokenRepository.class);
CsrfFilter filter = new CsrfFilter(repository);
lenient().when(repository.loadToken(any(HttpServletRequest.class))).thenReturn(this.token);
MockHttpServletRequest request = new MockHttpServletRequest();
CsrfFilter.skipRequest(request);
filter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());
verifyZeroInteractions(repository);
}

View File

@@ -60,7 +60,6 @@ public class CsrfLogoutHandlerTests {
public void logoutRemovesCsrfToken() {
this.handler.logout(this.request, this.response,
new TestingAuthenticationToken("user", "password", "ROLE_USER"));
verify(this.csrfTokenRepository).saveToken(null, this.request, this.response);
}

View File

@@ -48,12 +48,9 @@ public class HttpSessionCsrfTokenRepositoryTests {
@Test
public void generateToken() {
this.token = this.repo.generateToken(this.request);
assertThat(this.token.getParameterName()).isEqualTo("_csrf");
assertThat(this.token.getToken()).isNotEmpty();
CsrfToken loadedToken = this.repo.loadToken(this.request);
assertThat(loadedToken).isNull();
}
@@ -61,9 +58,7 @@ public class HttpSessionCsrfTokenRepositoryTests {
public void generateCustomParameter() {
String paramName = "_csrf";
this.repo.setParameterName(paramName);
this.token = this.repo.generateToken(this.request);
assertThat(this.token.getParameterName()).isEqualTo(paramName);
assertThat(this.token.getToken()).isNotEmpty();
}
@@ -72,9 +67,7 @@ public class HttpSessionCsrfTokenRepositoryTests {
public void generateCustomHeader() {
String headerName = "CSRF";
this.repo.setHeaderName(headerName);
this.token = this.repo.generateToken(this.request);
assertThat(this.token.getHeaderName()).isEqualTo(headerName);
assertThat(this.token.getToken()).isNotEmpty();
}
@@ -95,10 +88,8 @@ public class HttpSessionCsrfTokenRepositoryTests {
public void saveToken() {
CsrfToken tokenToSave = new DefaultCsrfToken("123", "abc", "def");
this.repo.saveToken(tokenToSave, this.request, this.response);
String attrName = this.request.getSession().getAttributeNames().nextElement();
CsrfToken loadedToken = (CsrfToken) this.request.getSession().getAttribute(attrName);
assertThat(loadedToken).isEqualTo(tokenToSave);
}
@@ -108,26 +99,20 @@ public class HttpSessionCsrfTokenRepositoryTests {
String sessionAttributeName = "custom";
this.repo.setSessionAttributeName(sessionAttributeName);
this.repo.saveToken(tokenToSave, this.request, this.response);
CsrfToken loadedToken = (CsrfToken) this.request.getSession().getAttribute(sessionAttributeName);
assertThat(loadedToken).isEqualTo(tokenToSave);
}
@Test
public void saveTokenNullToken() {
saveToken();
this.repo.saveToken(null, this.request, this.response);
assertThat(this.request.getSession().getAttributeNames().hasMoreElements()).isFalse();
}
@Test
public void saveTokenNullTokenWhenSessionNotExists() {
this.repo.saveToken(null, this.request, this.response);
assertThat(this.request.getSession(false)).isNull();
}

View File

@@ -72,33 +72,27 @@ public class LazyCsrfTokenRepositoryTests {
@Test
public void generateTokenGetTokenSavesToken() {
CsrfToken newToken = this.repository.generateToken(this.request);
newToken.getToken();
verify(this.delegate).saveToken(this.token, this.request, this.response);
}
@Test
public void saveNonNullDoesNothing() {
this.repository.saveToken(this.token, this.request, this.response);
verifyZeroInteractions(this.delegate);
}
@Test
public void saveNullDelegates() {
this.repository.saveToken(null, this.request, this.response);
verify(this.delegate).saveToken(null, this.request, this.response);
}
@Test
public void loadTokenDelegates() {
given(this.delegate.loadToken(this.request)).willReturn(this.token);
CsrfToken loadToken = this.repository.loadToken(this.request);
assertThat(loadToken).isSameAs(this.token);
verify(this.delegate).loadToken(this.request);
}

View File

@@ -89,7 +89,6 @@ public class DebugFilterTests {
@Test
public void doFilterProcessesRequests() throws Exception {
this.filter.doFilter(this.request, this.response, this.filterChain);
verify(this.logger).info(anyString());
verify(this.request).setAttribute(this.requestAttr, Boolean.TRUE);
verify(this.fcp).doFilter(this.requestCaptor.capture(), eq(this.response), eq(this.filterChain));
@@ -102,9 +101,7 @@ public class DebugFilterTests {
public void doFilterProcessesForwardedRequests() throws Exception {
given(this.request.getAttribute(this.requestAttr)).willReturn(Boolean.TRUE);
HttpServletRequest request = new DebugRequestWrapper(this.request);
this.filter.doFilter(request, this.response, this.filterChain);
verify(this.logger).info(anyString());
verify(this.fcp).doFilter(request, this.response, this.filterChain);
verify(this.request, never()).removeAttribute(this.requestAttr);
@@ -114,9 +111,7 @@ public class DebugFilterTests {
public void doFilterDoesNotWrapWithDebugRequestWrapperAgain() throws Exception {
given(this.request.getAttribute(this.requestAttr)).willReturn(Boolean.TRUE);
HttpServletRequest fireWalledRequest = new HttpServletRequestWrapper(new DebugRequestWrapper(this.request));
this.filter.doFilter(fireWalledRequest, this.response, this.filterChain);
verify(this.fcp).doFilter(fireWalledRequest, this.response, this.filterChain);
}
@@ -129,11 +124,8 @@ public class DebugFilterTests {
request.addHeader("A", "A Value");
request.addHeader("A", "Another Value");
request.addHeader("B", "B Value");
this.filter.doFilter(request, this.response, this.filterChain);
verify(this.logger).info(this.logCaptor.capture());
assertThat(this.logCaptor.getValue()).isEqualTo("Request received for GET '/path/':\n" + "\n" + request + "\n"
+ "\n" + "servletPath:/path\n" + "pathInfo:/\n" + "headers: \n" + "A: A Value, Another Value\n"
+ "B: B Value\n" + "\n" + "\n" + "Security filter chain: no match");

View File

@@ -33,7 +33,6 @@ public class DefaultHttpFirewallTests {
@Test
public void unnormalizedPathsAreRejected() {
DefaultHttpFirewall fw = new DefaultHttpFirewall();
MockHttpServletRequest request;
for (String path : this.unnormalizedPaths) {
request = new MockHttpServletRequest();
@@ -78,7 +77,6 @@ public class DefaultHttpFirewallTests {
request.setContextPath("/context-root");
request.setServletPath("");
request.setPathInfo("/a/b;/1/c"); // URL decoded requestURI
fw.getFirewalledRequest(request);
}
@@ -91,7 +89,6 @@ public class DefaultHttpFirewallTests {
request.setContextPath("/context-root");
request.setServletPath("");
request.setPathInfo("/a/b;/1/c"); // URL decoded requestURI
fw.getFirewalledRequest(request);
}
@@ -104,7 +101,6 @@ public class DefaultHttpFirewallTests {
request.setContextPath("/context-root");
request.setServletPath("");
request.setPathInfo("/a/b;/1/c"); // URL decoded requestURI
fw.getFirewalledRequest(request);
}

View File

@@ -51,49 +51,42 @@ public class FirewalledResponseTests {
@Test
public void sendRedirectWhenValidThenNoException() throws Exception {
this.fwResponse.sendRedirect("/theURL");
verify(this.response).sendRedirect("/theURL");
}
@Test
public void sendRedirectWhenNullThenDelegateInvoked() throws Exception {
this.fwResponse.sendRedirect(null);
verify(this.response).sendRedirect(null);
}
@Test
public void sendRedirectWhenHasCrlfThenThrowsException() throws Exception {
expectCrlfValidationException();
this.fwResponse.sendRedirect("/theURL\r\nsomething");
}
@Test
public void addHeaderWhenValidThenDelegateInvoked() {
this.fwResponse.addHeader("foo", "bar");
verify(this.response).addHeader("foo", "bar");
}
@Test
public void addHeaderWhenNullValueThenDelegateInvoked() {
this.fwResponse.addHeader("foo", null);
verify(this.response).addHeader("foo", null);
}
@Test
public void addHeaderWhenHeaderValueHasCrlfThenException() {
expectCrlfValidationException();
this.fwResponse.addHeader("foo", "abc\r\nContent-Length:100");
}
@Test
public void addHeaderWhenHeaderNameHasCrlfThenException() {
expectCrlfValidationException();
this.fwResponse.addHeader("abc\r\nContent-Length:100", "bar");
}
@@ -103,16 +96,13 @@ public class FirewalledResponseTests {
cookie.setPath("/foobar");
cookie.setDomain("foobar");
cookie.setComment("foobar");
this.fwResponse.addCookie(cookie);
verify(this.response).addCookie(cookie);
}
@Test
public void addCookieWhenNullThenDelegateInvoked() {
this.fwResponse.addCookie(null);
verify(this.response).addCookie(null);
}
@@ -124,10 +114,8 @@ public class FirewalledResponseTests {
public String getName() {
return "foo\r\nbar";
}
};
expectCrlfValidationException();
this.fwResponse.addCookie(cookie);
}
@@ -135,7 +123,6 @@ public class FirewalledResponseTests {
public void addCookieWhenCookieValueContainsCrlfThenException() {
Cookie cookie = new Cookie("foo", "foo\r\nbar");
expectCrlfValidationException();
this.fwResponse.addCookie(cookie);
}
@@ -144,7 +131,6 @@ public class FirewalledResponseTests {
Cookie cookie = new Cookie("foo", "bar");
cookie.setPath("/foo\r\nbar");
expectCrlfValidationException();
this.fwResponse.addCookie(cookie);
}
@@ -153,7 +139,6 @@ public class FirewalledResponseTests {
Cookie cookie = new Cookie("foo", "bar");
cookie.setDomain("foo\r\nbar");
expectCrlfValidationException();
this.fwResponse.addCookie(cookie);
}
@@ -162,7 +147,6 @@ public class FirewalledResponseTests {
Cookie cookie = new Cookie("foo", "bar");
cookie.setComment("foo\r\nbar");
expectCrlfValidationException();
this.fwResponse.addCookie(cookie);
}
@@ -171,7 +155,6 @@ public class FirewalledResponseTests {
validateLineEnding("foo", "foo\rbar");
validateLineEnding("foo", "foo\r\nbar");
validateLineEnding("foo", "foo\nbar");
validateLineEnding("foo\rbar", "bar");
validateLineEnding("foo\r\nbar", "bar");
validateLineEnding("foo\nbar", "bar");

View File

@@ -56,7 +56,6 @@ public class RequestWrapperTests {
@Test
public void pathParametersAreRemovedFromServletPath() {
MockHttpServletRequest request = new MockHttpServletRequest();
for (Map.Entry<String, String> entry : testPaths.entrySet()) {
String path = entry.getKey();
String expectedResult = entry.getValue();
@@ -71,7 +70,6 @@ public class RequestWrapperTests {
@Test
public void pathParametersAreRemovedFromPathInfo() {
MockHttpServletRequest request = new MockHttpServletRequest();
for (Map.Entry<String, String> entry : testPaths.entrySet()) {
String path = entry.getKey();
String expectedResult = entry.getValue();
@@ -97,11 +95,9 @@ public class RequestWrapperTests {
given(mockRequest.getServletPath()).willReturn("");
given(mockRequest.getPathInfo()).willReturn(denormalizedPath);
given(mockRequest.getRequestDispatcher(forwardPath)).willReturn(mockDispatcher);
RequestWrapper wrapper = new RequestWrapper(mockRequest);
RequestDispatcher dispatcher = wrapper.getRequestDispatcher(forwardPath);
dispatcher.forward(mockRequest, mockResponse);
verify(mockRequest).getRequestDispatcher(forwardPath);
verify(mockDispatcher).forward(mockRequest, mockResponse);
assertThat(wrapper.getPathInfo()).isEqualTo(denormalizedPath);

View File

@@ -149,84 +149,72 @@ public class StrictHttpFirewallTests {
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestWhenSemicolonInContextPathThenThrowsRequestRejectedException() {
this.request.setContextPath(";/context");
this.firewall.getFirewalledRequest(this.request);
}
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestWhenSemicolonInServletPathThenThrowsRequestRejectedException() {
this.request.setServletPath("/spring;/");
this.firewall.getFirewalledRequest(this.request);
}
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestWhenSemicolonInPathInfoThenThrowsRequestRejectedException() {
this.request.setPathInfo("/path;/");
this.firewall.getFirewalledRequest(this.request);
}
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestWhenSemicolonInRequestUriThenThrowsRequestRejectedException() {
this.request.setRequestURI("/path;/");
this.firewall.getFirewalledRequest(this.request);
}
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestWhenEncodedSemicolonInContextPathThenThrowsRequestRejectedException() {
this.request.setContextPath("%3B/context");
this.firewall.getFirewalledRequest(this.request);
}
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestWhenEncodedSemicolonInServletPathThenThrowsRequestRejectedException() {
this.request.setServletPath("/spring%3B/");
this.firewall.getFirewalledRequest(this.request);
}
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestWhenEncodedSemicolonInPathInfoThenThrowsRequestRejectedException() {
this.request.setPathInfo("/path%3B/");
this.firewall.getFirewalledRequest(this.request);
}
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestWhenEncodedSemicolonInRequestUriThenThrowsRequestRejectedException() {
this.request.setRequestURI("/path%3B/");
this.firewall.getFirewalledRequest(this.request);
}
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestWhenLowercaseEncodedSemicolonInContextPathThenThrowsRequestRejectedException() {
this.request.setContextPath("%3b/context");
this.firewall.getFirewalledRequest(this.request);
}
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestWhenLowercaseEncodedSemicolonInServletPathThenThrowsRequestRejectedException() {
this.request.setServletPath("/spring%3b/");
this.firewall.getFirewalledRequest(this.request);
}
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestWhenLowercaseEncodedSemicolonInPathInfoThenThrowsRequestRejectedException() {
this.request.setPathInfo("/path%3b/");
this.firewall.getFirewalledRequest(this.request);
}
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestWhenLowercaseEncodedSemicolonInRequestUriThenThrowsRequestRejectedException() {
this.request.setRequestURI("/path%3b/");
this.firewall.getFirewalledRequest(this.request);
}
@@ -234,7 +222,6 @@ public class StrictHttpFirewallTests {
public void getFirewalledRequestWhenSemicolonInContextPathAndAllowSemicolonThenNoException() {
this.firewall.setAllowSemicolon(true);
this.request.setContextPath(";/context");
this.firewall.getFirewalledRequest(this.request);
}
@@ -242,7 +229,6 @@ public class StrictHttpFirewallTests {
public void getFirewalledRequestWhenSemicolonInServletPathAndAllowSemicolonThenNoException() {
this.firewall.setAllowSemicolon(true);
this.request.setServletPath("/spring;/");
this.firewall.getFirewalledRequest(this.request);
}
@@ -250,7 +236,6 @@ public class StrictHttpFirewallTests {
public void getFirewalledRequestWhenSemicolonInPathInfoAndAllowSemicolonThenNoException() {
this.firewall.setAllowSemicolon(true);
this.request.setPathInfo("/path;/");
this.firewall.getFirewalledRequest(this.request);
}
@@ -258,7 +243,6 @@ public class StrictHttpFirewallTests {
public void getFirewalledRequestWhenSemicolonInRequestUriAndAllowSemicolonThenNoException() {
this.firewall.setAllowSemicolon(true);
this.request.setRequestURI("/path;/");
this.firewall.getFirewalledRequest(this.request);
}
@@ -267,7 +251,6 @@ public class StrictHttpFirewallTests {
this.firewall.setAllowUrlEncodedPercent(true);
this.firewall.setAllowSemicolon(true);
this.request.setContextPath("%3B/context");
this.firewall.getFirewalledRequest(this.request);
}
@@ -276,7 +259,6 @@ public class StrictHttpFirewallTests {
this.firewall.setAllowUrlEncodedPercent(true);
this.firewall.setAllowSemicolon(true);
this.request.setServletPath("/spring%3B/");
this.firewall.getFirewalledRequest(this.request);
}
@@ -285,7 +267,6 @@ public class StrictHttpFirewallTests {
this.firewall.setAllowUrlEncodedPercent(true);
this.firewall.setAllowSemicolon(true);
this.request.setPathInfo("/path%3B/");
this.firewall.getFirewalledRequest(this.request);
}
@@ -293,7 +274,6 @@ public class StrictHttpFirewallTests {
public void getFirewalledRequestWhenEncodedSemicolonInRequestUriAndAllowSemicolonThenNoException() {
this.firewall.setAllowSemicolon(true);
this.request.setRequestURI("/path%3B/");
this.firewall.getFirewalledRequest(this.request);
}
@@ -302,7 +282,6 @@ public class StrictHttpFirewallTests {
this.firewall.setAllowUrlEncodedPercent(true);
this.firewall.setAllowSemicolon(true);
this.request.setContextPath("%3b/context");
this.firewall.getFirewalledRequest(this.request);
}
@@ -311,7 +290,6 @@ public class StrictHttpFirewallTests {
this.firewall.setAllowUrlEncodedPercent(true);
this.firewall.setAllowSemicolon(true);
this.request.setServletPath("/spring%3b/");
this.firewall.getFirewalledRequest(this.request);
}
@@ -320,7 +298,6 @@ public class StrictHttpFirewallTests {
this.firewall.setAllowUrlEncodedPercent(true);
this.firewall.setAllowSemicolon(true);
this.request.setPathInfo("/path%3b/");
this.firewall.getFirewalledRequest(this.request);
}
@@ -328,21 +305,18 @@ public class StrictHttpFirewallTests {
public void getFirewalledRequestWhenLowercaseEncodedSemicolonInRequestUriAndAllowSemicolonThenNoException() {
this.firewall.setAllowSemicolon(true);
this.request.setRequestURI("/path%3b/");
this.firewall.getFirewalledRequest(this.request);
}
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestWhenEncodedPeriodInThenThrowsRequestRejectedException() {
this.request.setRequestURI("/%2E/");
this.firewall.getFirewalledRequest(this.request);
}
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestWhenLowercaseEncodedPeriodInThenThrowsRequestRejectedException() {
this.request.setRequestURI("/%2e/");
this.firewall.getFirewalledRequest(this.request);
}
@@ -350,7 +324,6 @@ public class StrictHttpFirewallTests {
public void getFirewalledRequestWhenAllowEncodedPeriodAndEncodedPeriodInThenNoException() {
this.firewall.setAllowUrlEncodedPeriod(true);
this.request.setRequestURI("/%2E/");
this.firewall.getFirewalledRequest(this.request);
}
@@ -410,7 +383,6 @@ public class StrictHttpFirewallTests {
this.request.setContextPath("/context-root");
this.request.setServletPath("");
this.request.setPathInfo("/a/b;/1/c"); // URL decoded requestURI
this.firewall.getFirewalledRequest(this.request);
}
@@ -423,7 +395,6 @@ public class StrictHttpFirewallTests {
request.setContextPath("/context-root");
request.setServletPath("");
request.setPathInfo("/a/b;/1/c"); // URL decoded requestURI
this.firewall.getFirewalledRequest(request);
}
@@ -436,7 +407,6 @@ public class StrictHttpFirewallTests {
request.setContextPath("/context-root");
request.setServletPath("");
request.setPathInfo("/a/b;/1/c"); // URL decoded requestURI
this.firewall.getFirewalledRequest(request);
}
@@ -533,7 +503,6 @@ public class StrictHttpFirewallTests {
}
// blocklist
@Test
public void getFirewalledRequestWhenRemoveFromUpperCaseEncodedUrlBlocklistThenNoException() {
this.firewall.setAllowUrlEncodedSlash(true);
@@ -582,7 +551,6 @@ public class StrictHttpFirewallTests {
public void getFirewalledRequestWhenTrustedDomainThenNoException() {
this.request.addHeader("Host", "example.org");
this.firewall.setAllowedHostnames((hostname) -> hostname.equals("example.org"));
assertThatCode(() -> this.firewall.getFirewalledRequest(this.request)).doesNotThrowAnyException();
}
@@ -590,14 +558,12 @@ public class StrictHttpFirewallTests {
public void getFirewalledRequestWhenUntrustedDomainThenException() {
this.request.addHeader("Host", "example.org");
this.firewall.setAllowedHostnames((hostname) -> hostname.equals("myexample.org"));
this.firewall.getFirewalledRequest(this.request);
}
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestGetHeaderWhenNotAllowedHeaderNameThenException() {
this.firewall.setAllowedHeaderNames((name) -> !name.equals("bad name"));
HttpServletRequest request = this.firewall.getFirewalledRequest(this.request);
request.getHeader("bad name");
}
@@ -606,7 +572,6 @@ public class StrictHttpFirewallTests {
public void getFirewalledRequestGetHeaderWhenNotAllowedHeaderValueThenException() {
this.request.addHeader("good name", "bad value");
this.firewall.setAllowedHeaderValues((value) -> !value.equals("bad value"));
HttpServletRequest request = this.firewall.getFirewalledRequest(this.request);
request.getHeader("good name");
}
@@ -614,7 +579,6 @@ public class StrictHttpFirewallTests {
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestGetDateHeaderWhenControlCharacterInHeaderNameThenException() {
this.request.addHeader("Bad\0Name", "some value");
HttpServletRequest request = this.firewall.getFirewalledRequest(this.request);
request.getDateHeader("Bad\0Name");
}
@@ -622,7 +586,6 @@ public class StrictHttpFirewallTests {
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestGetIntHeaderWhenControlCharacterInHeaderNameThenException() {
this.request.addHeader("Bad\0Name", "some value");
HttpServletRequest request = this.firewall.getFirewalledRequest(this.request);
request.getIntHeader("Bad\0Name");
}
@@ -630,7 +593,6 @@ public class StrictHttpFirewallTests {
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestGetHeaderWhenControlCharacterInHeaderNameThenException() {
this.request.addHeader("Bad\0Name", "some value");
HttpServletRequest request = this.firewall.getFirewalledRequest(this.request);
request.getHeader("Bad\0Name");
}
@@ -638,7 +600,6 @@ public class StrictHttpFirewallTests {
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestGetHeaderWhenUndefinedCharacterInHeaderNameThenException() {
this.request.addHeader("Bad\uFFFEName", "some value");
HttpServletRequest request = this.firewall.getFirewalledRequest(this.request);
request.getHeader("Bad\uFFFEName");
}
@@ -646,7 +607,6 @@ public class StrictHttpFirewallTests {
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestGetHeadersWhenControlCharacterInHeaderNameThenException() {
this.request.addHeader("Bad\0Name", "some value");
HttpServletRequest request = this.firewall.getFirewalledRequest(this.request);
request.getHeaders("Bad\0Name");
}
@@ -654,7 +614,6 @@ public class StrictHttpFirewallTests {
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestGetHeaderNamesWhenControlCharacterInHeaderNameThenException() {
this.request.addHeader("Bad\0Name", "some value");
HttpServletRequest request = this.firewall.getFirewalledRequest(this.request);
request.getHeaderNames().nextElement();
}
@@ -662,7 +621,6 @@ public class StrictHttpFirewallTests {
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestGetHeaderWhenControlCharacterInHeaderValueThenException() {
this.request.addHeader("Something", "bad\0value");
HttpServletRequest request = this.firewall.getFirewalledRequest(this.request);
request.getHeader("Something");
}
@@ -670,7 +628,6 @@ public class StrictHttpFirewallTests {
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestGetHeaderWhenUndefinedCharacterInHeaderValueThenException() {
this.request.addHeader("Something", "bad\uFFFEvalue");
HttpServletRequest request = this.firewall.getFirewalledRequest(this.request);
request.getHeader("Something");
}
@@ -678,7 +635,6 @@ public class StrictHttpFirewallTests {
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestGetHeadersWhenControlCharacterInHeaderValueThenException() {
this.request.addHeader("Something", "bad\0value");
HttpServletRequest request = this.firewall.getFirewalledRequest(this.request);
request.getHeaders("Something").nextElement();
}
@@ -686,7 +642,6 @@ public class StrictHttpFirewallTests {
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestGetParameterWhenControlCharacterInParameterNameThenException() {
this.request.addParameter("Bad\0Name", "some value");
HttpServletRequest request = this.firewall.getFirewalledRequest(this.request);
request.getParameter("Bad\0Name");
}
@@ -694,7 +649,6 @@ public class StrictHttpFirewallTests {
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestGetParameterMapWhenControlCharacterInParameterNameThenException() {
this.request.addParameter("Bad\0Name", "some value");
HttpServletRequest request = this.firewall.getFirewalledRequest(this.request);
request.getParameterMap();
}
@@ -702,7 +656,6 @@ public class StrictHttpFirewallTests {
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestGetParameterNamesWhenControlCharacterInParameterNameThenException() {
this.request.addParameter("Bad\0Name", "some value");
HttpServletRequest request = this.firewall.getFirewalledRequest(this.request);
request.getParameterNames().nextElement();
}
@@ -710,7 +663,6 @@ public class StrictHttpFirewallTests {
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestGetParameterNamesWhenUndefinedCharacterInParameterNameThenException() {
this.request.addParameter("Bad\uFFFEName", "some value");
HttpServletRequest request = this.firewall.getFirewalledRequest(this.request);
request.getParameterNames().nextElement();
}
@@ -718,9 +670,7 @@ public class StrictHttpFirewallTests {
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestGetParameterValuesWhenNotAllowedInParameterValueThenException() {
this.firewall.setAllowedParameterValues((value) -> !value.equals("bad value"));
this.request.addParameter("Something", "bad value");
HttpServletRequest request = this.firewall.getFirewalledRequest(this.request);
request.getParameterValues("Something");
}
@@ -728,9 +678,7 @@ public class StrictHttpFirewallTests {
@Test(expected = RequestRejectedException.class)
public void getFirewalledRequestGetParameterValuesWhenNotAllowedInParameterNameThenException() {
this.firewall.setAllowedParameterNames((value) -> !value.equals("bad name"));
this.request.addParameter("bad name", "good value");
HttpServletRequest request = this.firewall.getFirewalledRequest(this.request);
request.getParameterValues("bad name");
}

View File

@@ -71,15 +71,11 @@ public class HeaderWriterFilterTests {
List<HeaderWriter> headerWriters = new ArrayList<>();
headerWriters.add(this.writer1);
headerWriters.add(this.writer2);
HeaderWriterFilter filter = new HeaderWriterFilter(headerWriters);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain filterChain = new MockFilterChain();
filter.doFilter(request, response, filterChain);
verify(this.writer1).writeHeaders(request, response);
verify(this.writer2).writeHeaders(request, response);
HeaderWriterFilter.HeaderWriterRequest wrappedRequest = (HeaderWriterFilter.HeaderWriterRequest) filterChain
@@ -93,19 +89,14 @@ public class HeaderWriterFilterTests {
@Test
public void headersDelayed() throws Exception {
HeaderWriterFilter filter = new HeaderWriterFilter(Arrays.<HeaderWriter>asList(this.writer1));
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, (request1, response1) -> {
verifyZeroInteractions(HeaderWriterFilterTests.this.writer1);
response1.flushBuffer();
verify(HeaderWriterFilterTests.this.writer1).writeHeaders(any(HttpServletRequest.class),
any(HttpServletResponse.class));
});
verifyNoMoreInteractions(this.writer1);
}
@@ -113,19 +104,14 @@ public class HeaderWriterFilterTests {
@Test
public void doFilterWhenRequestContainsIncludeThenHeadersStillWritten() throws Exception {
HeaderWriterFilter filter = new HeaderWriterFilter(Collections.singletonList(this.writer1));
MockHttpServletRequest mockRequest = new MockHttpServletRequest();
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
filter.doFilter(mockRequest, mockResponse, (request, response) -> {
verifyZeroInteractions(HeaderWriterFilterTests.this.writer1);
request.getRequestDispatcher("/").include(request, response);
verify(HeaderWriterFilterTests.this.writer1).writeHeaders(any(HttpServletRequest.class),
any(HttpServletResponse.class));
});
verifyNoMoreInteractions(this.writer1);
}
@@ -133,13 +119,10 @@ public class HeaderWriterFilterTests {
public void headersWrittenAtBeginningOfRequest() throws Exception {
HeaderWriterFilter filter = new HeaderWriterFilter(Collections.singletonList(this.writer1));
filter.setShouldWriteHeadersEagerly(true);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, (request1, response1) -> verify(HeaderWriterFilterTests.this.writer1)
.writeHeaders(any(HttpServletRequest.class), any(HttpServletResponse.class)));
verifyNoMoreInteractions(this.writer1);
}

View File

@@ -53,7 +53,6 @@ public class CacheControlHeadersWriterTests {
@Test
public void writeHeaders() {
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames().size()).isEqualTo(3);
assertThat(this.response.getHeaderValues("Cache-Control"))
.containsOnly("no-cache, no-store, max-age=0, must-revalidate");
@@ -65,9 +64,7 @@ public class CacheControlHeadersWriterTests {
@Test
public void writeHeadersDisabledIfCacheControl() {
this.response.setHeader("Cache-Control", "max-age: 123");
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeaderValues("Cache-Control")).containsOnly("max-age: 123");
assertThat(this.response.getHeaderValue("Pragma")).isNull();
@@ -77,9 +74,7 @@ public class CacheControlHeadersWriterTests {
@Test
public void writeHeadersDisabledIfPragma() {
this.response.setHeader("Pragma", "mock");
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeaderValues("Pragma")).containsOnly("mock");
assertThat(this.response.getHeaderValue("Expires")).isNull();
@@ -89,9 +84,7 @@ public class CacheControlHeadersWriterTests {
@Test
public void writeHeadersDisabledIfExpires() {
this.response.setHeader("Expires", "mock");
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeaderValues("Expires")).containsOnly("mock");
assertThat(this.response.getHeaderValue("Cache-Control")).isNull();
@@ -102,9 +95,7 @@ public class CacheControlHeadersWriterTests {
// gh-5534
public void writeHeadersDisabledIfNotModified() {
this.response.setStatus(HttpStatus.NOT_MODIFIED.value());
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).isEmpty();
}

View File

@@ -54,7 +54,6 @@ public class ClearSiteDataHeaderWriterTests {
public void createInstanceWhenMissingSourceThenThrowsException() {
this.thrown.expect(Exception.class);
this.thrown.expectMessage("directives cannot be empty or null");
new ClearSiteDataHeaderWriter();
}
@@ -63,7 +62,6 @@ public class ClearSiteDataHeaderWriterTests {
this.request.setSecure(false);
ClearSiteDataHeaderWriter headerWriter = new ClearSiteDataHeaderWriter(Directive.CACHE);
headerWriter.writeHeaders(this.request, this.response);
assertThat(this.response.getHeader(HEADER_NAME)).isNull();
}
@@ -71,7 +69,6 @@ public class ClearSiteDataHeaderWriterTests {
public void writeHeaderWhenRequestIsSecureThenHeaderValueMatchesPassedSource() {
ClearSiteDataHeaderWriter headerWriter = new ClearSiteDataHeaderWriter(Directive.STORAGE);
headerWriter.writeHeaders(this.request, this.response);
assertThat(this.response.getHeader(HEADER_NAME)).isEqualTo("\"storage\"");
}
@@ -80,7 +77,6 @@ public class ClearSiteDataHeaderWriterTests {
ClearSiteDataHeaderWriter headerWriter = new ClearSiteDataHeaderWriter(Directive.CACHE, Directive.COOKIES,
Directive.STORAGE, Directive.EXECUTION_CONTEXTS);
headerWriter.writeHeaders(this.request, this.response);
assertThat(this.response.getHeader(HEADER_NAME))
.isEqualTo("\"cache\", \"cookies\", \"storage\", \"executionContexts\"");
}

View File

@@ -44,9 +44,7 @@ public class CompositeHeaderWriterTests {
HttpServletResponse response = mock(HttpServletResponse.class);
HeaderWriter one = mock(HeaderWriter.class);
HeaderWriter two = mock(HeaderWriter.class);
CompositeHeaderWriter headerWriter = new CompositeHeaderWriter(Arrays.asList(one, two));
headerWriter.writeHeaders(request, response);
verify(one).writeHeaders(request, response);
verify(two).writeHeaders(request, response);

View File

@@ -54,7 +54,6 @@ public class ContentSecurityPolicyHeaderWriterTests {
public void writeHeadersWhenNoPolicyDirectivesThenUsesDefault() {
ContentSecurityPolicyHeaderWriter noPolicyWriter = new ContentSecurityPolicyHeaderWriter();
noPolicyWriter.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Content-Security-Policy")).isEqualTo(DEFAULT_POLICY_DIRECTIVES);
}
@@ -62,7 +61,6 @@ public class ContentSecurityPolicyHeaderWriterTests {
@Test
public void writeHeadersContentSecurityPolicyDefault() {
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Content-Security-Policy")).isEqualTo(DEFAULT_POLICY_DIRECTIVES);
}
@@ -71,10 +69,8 @@ public class ContentSecurityPolicyHeaderWriterTests {
public void writeHeadersContentSecurityPolicyCustom() {
String policyDirectives = "default-src 'self'; " + "object-src plugins1.example.com plugins2.example.com; "
+ "script-src trustedscripts.example.com";
this.writer = new ContentSecurityPolicyHeaderWriter(policyDirectives);
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Content-Security-Policy")).isEqualTo(policyDirectives);
}
@@ -84,7 +80,6 @@ public class ContentSecurityPolicyHeaderWriterTests {
ContentSecurityPolicyHeaderWriter noPolicyWriter = new ContentSecurityPolicyHeaderWriter();
this.writer.setReportOnly(true);
noPolicyWriter.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Content-Security-Policy")).isEqualTo(DEFAULT_POLICY_DIRECTIVES);
}
@@ -93,7 +88,6 @@ public class ContentSecurityPolicyHeaderWriterTests {
public void writeHeadersContentSecurityPolicyReportOnlyDefault() {
this.writer.setReportOnly(true);
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Content-Security-Policy-Report-Only")).isEqualTo(DEFAULT_POLICY_DIRECTIVES);
}
@@ -101,11 +95,9 @@ public class ContentSecurityPolicyHeaderWriterTests {
@Test
public void writeHeadersContentSecurityPolicyReportOnlyCustom() {
String policyDirectives = "default-src https:; report-uri https://example.com/";
this.writer = new ContentSecurityPolicyHeaderWriter(policyDirectives);
this.writer.setReportOnly(true);
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Content-Security-Policy-Report-Only")).isEqualTo(policyDirectives);
}

View File

@@ -70,18 +70,14 @@ public class DelegatingRequestMatcherHeaderWriterTests {
@Test
public void writeHeadersOnMatch() {
given(this.matcher.matches(this.request)).willReturn(true);
this.headerWriter.writeHeaders(this.request, this.response);
verify(this.delegate).writeHeaders(this.request, this.response);
}
@Test
public void writeHeadersOnNoMatch() {
given(this.matcher.matches(this.request)).willReturn(false);
this.headerWriter.writeHeaders(this.request, this.response);
verify(this.delegate, times(0)).writeHeaders(this.request, this.response);
}

Some files were not shown because too many files have changed in this diff Show More