Reformat code using spring-javaformat

Run `./gradlew format` to reformat all java files.

Issue gh-8945
This commit is contained in:
Phillip Webb
2020-08-10 16:39:17 -05:00
committed by Rob Winch
parent 81d9c6cac5
commit b7fc18262d
2487 changed files with 41506 additions and 46548 deletions

View File

@@ -24,11 +24,11 @@ import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
/**
*
* @author Ben Alex
*/
@SuppressWarnings("unchecked")
public class MockFilterConfig implements FilterConfig {
// ~ Instance fields
// ================================================================================================
private Map map = new HashMap();
@@ -62,4 +62,5 @@ public class MockFilterConfig implements FilterConfig {
public void setInitParmeter(String parameter, String value) {
map.put(parameter, value);
}
}

View File

@@ -26,10 +26,12 @@ import javax.servlet.ServletRequest;
* @author Ben Alex
*/
public class MockPortResolver implements PortResolver {
// ~ Instance fields
// ================================================================================================
private int http = 80;
private int https = 443;
// ~ Constructors
@@ -51,4 +53,5 @@ public class MockPortResolver implements PortResolver {
return http;
}
}
}

View File

@@ -47,17 +47,20 @@ public class WebTestClientBuilder {
return WebTestClient.bindToController(controller).webFilter(webFilters).configureClient();
}
public static Builder bindToControllerAndWebFilters(Class<?> controller, SecurityWebFilterChain securityWebFilterChain) {
public static Builder bindToControllerAndWebFilters(Class<?> controller,
SecurityWebFilterChain securityWebFilterChain) {
return bindToControllerAndWebFilters(controller, new WebFilterChainProxy(securityWebFilterChain));
}
@RestController
public static class Http200RestController {
@RequestMapping("/**")
@ResponseStatus(HttpStatus.OK)
public String ok() {
return "ok";
}
}
}

View File

@@ -27,12 +27,13 @@ import reactor.core.publisher.Mono;
import java.util.Arrays;
/**
*
* @author Rob Winch
* @since 5.0
*/
public class WebTestHandler {
private final MockWebHandler webHandler = new MockWebHandler();
private final WebHandler handler;
private WebTestHandler(WebFilter... filters) {
@@ -50,6 +51,7 @@ public class WebTestHandler {
}
public static class WebHandlerResult {
private final ServerWebExchange exchange;
private WebHandlerResult(ServerWebExchange exchange) {
@@ -59,6 +61,7 @@ public class WebTestHandler {
public ServerWebExchange getExchange() {
return exchange;
}
}
public static WebTestHandler bindToWebFilters(WebFilter... filters) {
@@ -66,6 +69,7 @@ public class WebTestHandler {
}
static class MockWebHandler implements WebHandler {
private ServerWebExchange exchange;
@Override
@@ -73,5 +77,7 @@ public class WebTestHandler {
this.exchange = exchange;
return Mono.empty();
}
}
}

View File

@@ -22,14 +22,13 @@ import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
/**
*
* @author Luke Taylor
* @since 3.0
*/
public class DefaultRedirectStrategyTests {
@Test
public void contextRelativeUrlWithContextNameInHostnameIsHandledCorrectly()
throws Exception {
public void contextRelativeUrlWithContextNameInHostnameIsHandledCorrectly() throws Exception {
DefaultRedirectStrategy rds = new DefaultRedirectStrategy();
rds.setContextRelative(true);
MockHttpServletRequest request = new MockHttpServletRequest();
@@ -43,30 +42,27 @@ public class DefaultRedirectStrategyTests {
// SEC-2177
@Test
public void contextRelativeUrlWithMultipleSchemesInHostnameIsHandledCorrectly()
throws Exception {
public void contextRelativeUrlWithMultipleSchemesInHostnameIsHandledCorrectly() throws Exception {
DefaultRedirectStrategy rds = new DefaultRedirectStrategy();
rds.setContextRelative(true);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContextPath("/context");
MockHttpServletResponse response = new MockHttpServletResponse();
rds.sendRedirect(request, response,
"https://https://context.blah.com/context/remainder");
rds.sendRedirect(request, response, "https://https://context.blah.com/context/remainder");
assertThat(response.getRedirectedUrl()).isEqualTo("remainder");
}
@Test(expected = IllegalArgumentException.class)
public void contextRelativeShouldThrowExceptionIfURLDoesNotContainContextPath()
throws Exception {
public void contextRelativeShouldThrowExceptionIfURLDoesNotContainContextPath() throws Exception {
DefaultRedirectStrategy rds = new DefaultRedirectStrategy();
rds.setContextRelative(true);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContextPath("/context");
MockHttpServletResponse response = new MockHttpServletResponse();
rds.sendRedirect(request, response,
"https://redirectme.somewhere.else");
rds.sendRedirect(request, response, "https://redirectme.somewhere.else");
}
}

View File

@@ -45,11 +45,17 @@ import java.util.*;
* @author Rob Winch
*/
public class FilterChainProxyTests {
private FilterChainProxy fcp;
private RequestMatcher matcher;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private FilterChain chain;
private Filter filter;
@Before
@@ -59,14 +65,11 @@ public class FilterChainProxyTests {
doAnswer((Answer<Object>) inv -> {
Object[] args = inv.getArguments();
FilterChain fc = (FilterChain) args[2];
HttpServletRequestWrapper extraWrapper = new HttpServletRequestWrapper(
(HttpServletRequest) args[0]);
HttpServletRequestWrapper extraWrapper = new HttpServletRequestWrapper((HttpServletRequest) args[0]);
fc.doFilter(extraWrapper, (HttpServletResponse) args[1]);
return null;
}).when(filter).doFilter(any(),
any(), any());
fcp = new FilterChainProxy(new DefaultSecurityFilterChain(matcher,
Arrays.asList(filter)));
}).when(filter).doFilter(any(), any(), any());
fcp = new FilterChainProxy(new DefaultSecurityFilterChain(matcher, Arrays.asList(filter)));
fcp.setFilterChainValidator(mock(FilterChainProxy.FilterChainValidator.class));
request = new MockHttpServletRequest("GET", "");
request.setServletPath("/path");
@@ -94,56 +97,45 @@ public class FilterChainProxyTests {
verifyZeroInteractions(filter);
// The actual filter chain should be invoked though
verify(chain).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
verify(chain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@Test
public void originalChainIsInvokedAfterSecurityChainIfMatchSucceeds()
throws Exception {
public void originalChainIsInvokedAfterSecurityChainIfMatchSucceeds() throws Exception {
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
fcp.doFilter(request, response, chain);
verify(filter).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(FilterChain.class));
verify(chain).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
verify(filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), any(FilterChain.class));
verify(chain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@Test
public void originalFilterChainIsInvokedIfMatchingSecurityChainIsEmpty()
throws Exception {
public void originalFilterChainIsInvokedIfMatchingSecurityChainIsEmpty() throws Exception {
List<Filter> noFilters = Collections.emptyList();
fcp = new FilterChainProxy(new DefaultSecurityFilterChain(matcher, noFilters));
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
fcp.doFilter(request, response, chain);
verify(chain).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
verify(chain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@Test
public void requestIsWrappedForMatchingAndFilteringWhenMatchIsFound()
throws Exception {
public void requestIsWrappedForMatchingAndFilteringWhenMatchIsFound() throws Exception {
when(matcher.matches(any())).thenReturn(true);
fcp.doFilter(request, response, chain);
verify(matcher).matches(any(FirewalledRequest.class));
verify(filter).doFilter(any(FirewalledRequest.class),
any(HttpServletResponse.class), any(FilterChain.class));
verify(chain).doFilter(any(),
any(HttpServletResponse.class));
verify(filter).doFilter(any(FirewalledRequest.class), any(HttpServletResponse.class), any(FilterChain.class));
verify(chain).doFilter(any(), any(HttpServletResponse.class));
}
@Test
public void requestIsWrappedForMatchingAndFilteringWhenMatchIsNotFound()
throws Exception {
public void requestIsWrappedForMatchingAndFilteringWhenMatchIsNotFound() throws Exception {
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(false);
fcp.doFilter(request, response, chain);
verify(matcher).matches(any(FirewalledRequest.class));
verifyZeroInteractions(filter);
verify(chain).doFilter(any(FirewalledRequest.class),
any(HttpServletResponse.class));
verify(chain).doFilter(any(FirewalledRequest.class), any(HttpServletResponse.class));
}
@Test
@@ -163,8 +155,7 @@ public class FilterChainProxyTests {
@Test
public void bothWrappersAreResetWithNestedFcps() throws Exception {
HttpFirewall fw = mock(HttpFirewall.class);
FilterChainProxy firstFcp = new FilterChainProxy(new DefaultSecurityFilterChain(
matcher, fcp));
FilterChainProxy firstFcp = new FilterChainProxy(new DefaultSecurityFilterChain(matcher, fcp));
firstFcp.setFirewall(fw);
fcp.setFirewall(fw);
FirewalledRequest firstFwr = mock(FirewalledRequest.class, "firstFwr");
@@ -187,11 +178,10 @@ public class FilterChainProxyTests {
public void doFilterClearsSecurityContextHolder() throws Exception {
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
doAnswer((Answer<Object>) inv -> {
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken("username", "password"));
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("username", "password"));
return null;
}).when(filter).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(FilterChain.class));
}).when(filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), any(FilterChain.class));
fcp.doFilter(request, response, chain);
@@ -202,11 +192,10 @@ public class FilterChainProxyTests {
public void doFilterClearsSecurityContextHolderWithException() throws Exception {
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
doAnswer((Answer<Object>) inv -> {
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken("username", "password"));
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("username", "password"));
throw new ServletException("oops");
}).when(filter).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(FilterChain.class));
}).when(filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), any(FilterChain.class));
try {
fcp.doFilter(request, response, chain);
@@ -224,25 +213,22 @@ public class FilterChainProxyTests {
final FilterChain innerChain = mock(FilterChain.class);
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
doAnswer((Answer<Object>) inv -> {
TestingAuthenticationToken expected = new TestingAuthenticationToken(
"username", "password");
TestingAuthenticationToken expected = new TestingAuthenticationToken("username", "password");
SecurityContextHolder.getContext().setAuthentication(expected);
doAnswer((Answer<Object>) inv1 -> {
innerChain.doFilter(request, response);
return null;
}).when(filter).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(FilterChain.class));
}).when(filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(FilterChain.class));
fcp.doFilter(request, response, innerChain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(expected);
return null;
}).when(filter).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(FilterChain.class));
}).when(filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), any(FilterChain.class));
fcp.doFilter(request, response, chain);
verify(innerChain).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
verify(innerChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -262,4 +248,5 @@ public class FilterChainProxyTests {
fcp.doFilter(request, response, chain);
verify(rjh).handle(eq(request), eq(response), eq((requestRejectedException)));
}
}

View File

@@ -98,8 +98,7 @@ public class FilterInvocationTests {
request.setRequestURI("/mycontext/HelloWorld");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterInvocation fi = new FilterInvocation(request, response,
mock(FilterChain.class));
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
assertThat(fi.getRequestUrl()).isEqualTo("/HelloWorld?foo=bar");
assertThat(fi.toString()).isEqualTo("FilterInvocation: URL: /HelloWorld?foo=bar");
assertThat(fi.getFullRequestUrl()).isEqualTo("http://localhost/mycontext/HelloWorld?foo=bar");
@@ -116,8 +115,7 @@ public class FilterInvocationTests {
request.setRequestURI("/mycontext/HelloWorld");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterInvocation fi = new FilterInvocation(request, response,
mock(FilterChain.class));
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
assertThat(fi.getRequestUrl()).isEqualTo("/HelloWorld");
assertThat(fi.toString()).isEqualTo("FilterInvocation: URL: /HelloWorld");
assertThat(fi.getFullRequestUrl()).isEqualTo("http://localhost/mycontext/HelloWorld");
@@ -125,8 +123,7 @@ public class FilterInvocationTests {
@Test(expected = UnsupportedOperationException.class)
public void dummyChainRejectsInvocation() throws Exception {
FilterInvocation.DUMMY_CHAIN.doFilter(mock(HttpServletRequest.class),
mock(HttpServletResponse.class));
FilterInvocation.DUMMY_CHAIN.doFilter(mock(HttpServletRequest.class), mock(HttpServletResponse.class));
}
@Test

View File

@@ -36,14 +36,10 @@ public class PortMapperImplTests {
@Test
public void testDefaultMappingsAreKnown() {
PortMapperImpl portMapper = new PortMapperImpl();
assertThat(portMapper.lookupHttpPort(443)).isEqualTo(
Integer.valueOf(80));
assertThat(Integer.valueOf(8080)).isEqualTo(
portMapper.lookupHttpPort(8443));
assertThat(Integer.valueOf(443)).isEqualTo(
portMapper.lookupHttpsPort(80));
assertThat(Integer.valueOf(8443)).isEqualTo(
portMapper.lookupHttpsPort(8080));
assertThat(portMapper.lookupHttpPort(443)).isEqualTo(Integer.valueOf(80));
assertThat(Integer.valueOf(8080)).isEqualTo(portMapper.lookupHttpPort(8443));
assertThat(Integer.valueOf(443)).isEqualTo(portMapper.lookupHttpsPort(80));
assertThat(Integer.valueOf(8443)).isEqualTo(portMapper.lookupHttpsPort(8080));
}
@Test
@@ -107,9 +103,8 @@ public class PortMapperImplTests {
portMapper.setPortMappings(map);
assertThat(portMapper.lookupHttpPort(442)).isEqualTo(
Integer.valueOf(79));
assertThat(Integer.valueOf(442)).isEqualTo(
portMapper.lookupHttpsPort(79));
assertThat(portMapper.lookupHttpPort(442)).isEqualTo(Integer.valueOf(79));
assertThat(Integer.valueOf(442)).isEqualTo(portMapper.lookupHttpsPort(79));
}
}

View File

@@ -81,4 +81,5 @@ public class PortResolverImplTests {
request.setServerPort(1021);
assertThat(pr.getServerPort(request)).isEqualTo(1021);
}
}

View File

@@ -39,9 +39,13 @@ import org.springframework.security.web.access.intercept.FilterSecurityIntercept
* @author Ben Alex
*/
public class DefaultWebInvocationPrivilegeEvaluatorTests {
private AccessDecisionManager adm;
private FilterInvocationSecurityMetadataSource ods;
private RunAsManager ram;
private FilterSecurityInterceptor interceptor;
// ~ Methods
@@ -63,50 +67,41 @@ public class DefaultWebInvocationPrivilegeEvaluatorTests {
@Test
public void permitsAccessIfNoMatchingAttributesAndPublicInvocationsAllowed() {
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(
interceptor);
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(interceptor);
when(ods.getAttributes(anyObject())).thenReturn(null);
assertThat(wipe.isAllowed("/context", "/foo/index.jsp", "GET",
mock(Authentication.class))).isTrue();
assertThat(wipe.isAllowed("/context", "/foo/index.jsp", "GET", mock(Authentication.class))).isTrue();
}
@Test
public void deniesAccessIfNoMatchingAttributesAndPublicInvocationsNotAllowed() {
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(
interceptor);
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(interceptor);
when(ods.getAttributes(anyObject())).thenReturn(null);
interceptor.setRejectPublicInvocations(true);
assertThat(wipe.isAllowed("/context", "/foo/index.jsp", "GET",
mock(Authentication.class))).isFalse();
assertThat(wipe.isAllowed("/context", "/foo/index.jsp", "GET", mock(Authentication.class))).isFalse();
}
@Test
public void deniesAccessIfAuthenticationIsNull() {
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(
interceptor);
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(interceptor);
assertThat(wipe.isAllowed("/foo/index.jsp", null)).isFalse();
}
@Test
public void allowsAccessIfAccessDecisionManagerDoes() {
Authentication token = new TestingAuthenticationToken("test", "Password",
"MOCK_INDEX");
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(
interceptor);
Authentication token = new TestingAuthenticationToken("test", "Password", "MOCK_INDEX");
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(interceptor);
assertThat(wipe.isAllowed("/foo/index.jsp", token)).isTrue();
}
@SuppressWarnings("unchecked")
@Test
public void deniesAccessIfAccessDecisionManagerDoes() {
Authentication token = new TestingAuthenticationToken("test", "Password",
"MOCK_INDEX");
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(
interceptor);
Authentication token = new TestingAuthenticationToken("test", "Password", "MOCK_INDEX");
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(interceptor);
doThrow(new AccessDeniedException("")).when(adm).decide(
any(Authentication.class), anyObject(), anyList());
doThrow(new AccessDeniedException("")).when(adm).decide(any(Authentication.class), anyObject(), anyList());
assertThat(wipe.isAllowed("/foo/index.jsp", token)).isFalse();
}
}

View File

@@ -36,14 +36,19 @@ import org.springframework.security.web.csrf.MissingCsrfTokenException;
@RunWith(MockitoJUnitRunner.class)
public class DelegatingAccessDeniedHandlerTests {
@Mock
private AccessDeniedHandler handler1;
@Mock
private AccessDeniedHandler handler2;
@Mock
private AccessDeniedHandler handler3;
@Mock
private HttpServletRequest request;
@Mock
private HttpServletResponse response;
@@ -64,8 +69,8 @@ public class DelegatingAccessDeniedHandlerTests {
AccessDeniedException accessDeniedException = new AccessDeniedException("");
handler.handle(request, response, accessDeniedException);
verify(handler1, never()).handle(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(AccessDeniedException.class));
verify(handler1, never()).handle(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(AccessDeniedException.class));
verify(handler3).handle(request, response, accessDeniedException);
}
@@ -78,10 +83,11 @@ public class DelegatingAccessDeniedHandlerTests {
AccessDeniedException accessDeniedException = new MissingCsrfTokenException("123");
handler.handle(request, response, accessDeniedException);
verify(handler1, never()).handle(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(AccessDeniedException.class));
verify(handler1, never()).handle(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(AccessDeniedException.class));
verify(handler2).handle(request, response, accessDeniedException);
verify(handler3, never()).handle(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(AccessDeniedException.class));
verify(handler3, never()).handle(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(AccessDeniedException.class));
}
}

View File

@@ -91,14 +91,13 @@ public class ExceptionTranslationFilterTests {
// Setup the FilterChain to thrown an access denied exception
FilterChain fc = mock(FilterChain.class);
doThrow(new AccessDeniedException("")).when(fc).doFilter(
any(HttpServletRequest.class), any(HttpServletResponse.class));
doThrow(new AccessDeniedException("")).when(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")));
new AnonymousAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("IGNORED")));
// Test
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
@@ -124,13 +123,13 @@ public class ExceptionTranslationFilterTests {
// Setup the FilterChain to thrown an access denied exception
FilterChain fc = mock(FilterChain.class);
doThrow(new AccessDeniedException("")).when(fc).doFilter(
any(HttpServletRequest.class), any(HttpServletResponse.class));
doThrow(new AccessDeniedException("")).when(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")));
securityContext.setAuthentication(
new RememberMeAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("IGNORED")));
SecurityContextHolder.setContext(securityContext);
// Test
@@ -141,7 +140,6 @@ public class ExceptionTranslationFilterTests {
assertThat(getSavedRequestUrl(request)).isEqualTo("http://localhost/mycontext/secure/page.html");
}
@Test
public void testAccessDeniedWhenNonAnonymous() throws Exception {
// Setup our HTTP request
@@ -150,8 +148,8 @@ public class ExceptionTranslationFilterTests {
// Setup the FilterChain to thrown an access denied exception
FilterChain fc = mock(FilterChain.class);
doThrow(new AccessDeniedException("")).when(fc).doFilter(
any(HttpServletRequest.class), any(HttpServletResponse.class));
doThrow(new AccessDeniedException("")).when(fc).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
// Setup SecurityContextHolder, as filter needs to check if user is
// anonymous
@@ -168,7 +166,8 @@ public class ExceptionTranslationFilterTests {
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, fc);
assertThat(response.getStatus()).isEqualTo(403);
assertThat(request.getAttribute(WebAttributes.ACCESS_DENIED_403)).isExactlyInstanceOf(AccessDeniedException.class);
assertThat(request.getAttribute(WebAttributes.ACCESS_DENIED_403))
.isExactlyInstanceOf(AccessDeniedException.class);
}
@Test
@@ -179,18 +178,17 @@ public class ExceptionTranslationFilterTests {
// Setup the FilterChain to thrown an access denied exception
FilterChain fc = mock(FilterChain.class);
doThrow(new AccessDeniedException("")).when(fc).doFilter(
any(HttpServletRequest.class), any(HttpServletResponse.class));
doThrow(new AccessDeniedException("")).when(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")));
new AnonymousAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("IGNORED")));
// Test
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(
(req, res, ae) -> res.sendError(403, ae.getMessage()));
(req, res, ae) -> res.sendError(403, ae.getMessage()));
filter.setAuthenticationTrustResolver(new AuthenticationTrustResolverImpl());
assertThat(filter.getAuthenticationTrustResolver()).isNotNull();
@@ -198,12 +196,11 @@ public class ExceptionTranslationFilterTests {
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, fc);
assertThat(response.getErrorMessage())
.isEqualTo("Vollst\u00e4ndige Authentifikation wird ben\u00f6tigt um auf diese Resource zuzugreifen");
.isEqualTo("Vollst\u00e4ndige Authentifikation wird ben\u00f6tigt um auf diese Resource zuzugreifen");
}
@Test
public void redirectedToLoginFormAndSessionShowsOriginalTargetWhenAuthenticationException()
throws Exception {
public void redirectedToLoginFormAndSessionShowsOriginalTargetWhenAuthenticationException() throws Exception {
// Setup our HTTP request
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServletPath("/secure/page.html");
@@ -215,8 +212,8 @@ public class ExceptionTranslationFilterTests {
// Setup the FilterChain to thrown an authentication failure exception
FilterChain fc = mock(FilterChain.class);
doThrow(new BadCredentialsException("")).when(fc).doFilter(
any(HttpServletRequest.class), any(HttpServletResponse.class));
doThrow(new BadCredentialsException("")).when(fc).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
// Test
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
@@ -241,13 +238,12 @@ public class ExceptionTranslationFilterTests {
// Setup the FilterChain to thrown an authentication failure exception
FilterChain fc = mock(FilterChain.class);
doThrow(new BadCredentialsException("")).when(fc).doFilter(
any(HttpServletRequest.class), any(HttpServletResponse.class));
doThrow(new BadCredentialsException("")).when(fc).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
// Test
HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(
mockEntryPoint, requestCache);
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint, requestCache);
requestCache.setPortResolver(new MockPortResolver(8080, 8443));
filter.afterPropertiesSet();
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -281,21 +277,17 @@ public class ExceptionTranslationFilterTests {
}
@Test
public void thrownIOExceptionServletExceptionAndRuntimeExceptionsAreRethrown()
throws Exception {
public void thrownIOExceptionServletExceptionAndRuntimeExceptionsAreRethrown() throws Exception {
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
filter.afterPropertiesSet();
Exception[] exceptions = { new IOException(), new ServletException(),
new RuntimeException() };
Exception[] exceptions = { new IOException(), new ServletException(), new RuntimeException() };
for (Exception e : exceptions) {
FilterChain fc = mock(FilterChain.class);
doThrow(e).when(fc).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
doThrow(e).when(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
try {
filter.doFilter(new MockHttpServletRequest(),
new MockHttpServletResponse(), fc);
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), fc);
fail("Should have thrown Exception");
}
catch (Exception expected) {
@@ -316,12 +308,13 @@ public class ExceptionTranslationFilterTests {
MockHttpServletResponse response = new MockHttpServletResponse();
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
assertThatThrownBy(() -> filter.doFilter(request, response, chain))
.isInstanceOf(ServletException.class)
.hasCauseInstanceOf(AccessDeniedException.class);
assertThatThrownBy(() -> filter.doFilter(request, response, chain)).isInstanceOf(ServletException.class)
.hasCauseInstanceOf(AccessDeniedException.class);
verifyZeroInteractions(mockEntryPoint);
}
private AuthenticationEntryPoint mockEntryPoint = (request, response, authException) -> response.sendRedirect(request.getContextPath() + "/login.jsp");
private AuthenticationEntryPoint mockEntryPoint = (request, response, authException) -> response
.sendRedirect(request.getContextPath() + "/login.jsp");
}

View File

@@ -34,9 +34,13 @@ import static org.mockito.Mockito.when;
* @author Josh Cummings
*/
public class RequestMatcherDelegatingAccessDeniedHandlerTests {
private RequestMatcherDelegatingAccessDeniedHandler delegator;
private LinkedHashMap<RequestMatcher, AccessDeniedHandler> deniedHandlers;
private AccessDeniedHandler accessDeniedHandler;
private HttpServletRequest request;
@Before
@@ -97,4 +101,5 @@ public class RequestMatcherDelegatingAccessDeniedHandlerTests {
verify(firstHandler, never()).handle(this.request, null, null);
verify(this.accessDeniedHandler, never()).handle(this.request, null, null);
}
}

View File

@@ -43,6 +43,7 @@ import static org.mockito.Mockito.mock;
*/
@SuppressWarnings("unchecked")
public class ChannelDecisionManagerImplTests {
// ~ Methods
// ========================================================================================================
@Test
@@ -55,8 +56,7 @@ public class ChannelDecisionManagerImplTests {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage())
.isEqualTo("A list of ChannelProcessors is required");
assertThat(expected.getMessage()).isEqualTo("A list of ChannelProcessors is required");
}
}
@@ -85,8 +85,7 @@ public class ChannelDecisionManagerImplTests {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage())
.isEqualTo("A list of ChannelProcessors is required");
assertThat(expected.getMessage()).isEqualTo("A list of ChannelProcessors is required");
}
}
@@ -103,8 +102,7 @@ public class ChannelDecisionManagerImplTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterInvocation fi = new FilterInvocation(request, response,
mock(FilterChain.class));
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
List<ConfigAttribute> cad = SecurityConfig.createList("xyz");
@@ -123,8 +121,7 @@ public class ChannelDecisionManagerImplTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterInvocation fi = new FilterInvocation(request, response,
mock(FilterChain.class));
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
cdm.decide(fi, SecurityConfig.createList(new String[] { "abc", "ANY_CHANNEL" }));
assertThat(fi.getResponse().isCommitted()).isFalse();
@@ -143,8 +140,7 @@ public class ChannelDecisionManagerImplTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterInvocation fi = new FilterInvocation(request, response,
mock(FilterChain.class));
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
cdm.decide(fi, SecurityConfig.createList("SOME_ATTRIBUTE_NO_PROCESSORS_SUPPORT"));
assertThat(fi.getResponse().isCommitted()).isFalse();
@@ -190,8 +186,7 @@ public class ChannelDecisionManagerImplTests {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage())
.isEqualTo("A list of ChannelProcessors is required");
assertThat(expected.getMessage()).isEqualTo("A list of ChannelProcessors is required");
}
}
@@ -199,7 +194,9 @@ public class ChannelDecisionManagerImplTests {
// ==================================================================================================
private class MockChannelProcessor implements ChannelProcessor {
private String configAttribute;
private boolean failIfCalled;
MockChannelProcessor(String configAttribute, boolean failIfCalled) {
@@ -207,13 +204,11 @@ public class ChannelDecisionManagerImplTests {
this.failIfCalled = failIfCalled;
}
public void decide(FilterInvocation invocation,
Collection<ConfigAttribute> config) throws IOException {
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);
fail("Should not have called this channel processor: " + this.configAttribute);
}
while (iter.hasNext()) {
@@ -235,5 +230,7 @@ public class ChannelDecisionManagerImplTests {
return false;
}
}
}
}

View File

@@ -38,6 +38,7 @@ import org.springframework.security.web.access.intercept.FilterInvocationSecurit
* @author Ben Alex
*/
public class ChannelProcessingFilterTests {
// ~ Methods
// ========================================================================================================
@@ -45,8 +46,7 @@ public class ChannelProcessingFilterTests {
public void testDetectsMissingChannelDecisionManager() {
ChannelProcessingFilter filter = new ChannelProcessingFilter();
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap(
"/path", true, "MOCK");
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap("/path", true, "MOCK");
filter.setSecurityMetadataSource(fids);
filter.afterPropertiesSet();
@@ -62,11 +62,10 @@ public class ChannelProcessingFilterTests {
@Test
public void testDetectsSupportedConfigAttribute() {
ChannelProcessingFilter filter = new ChannelProcessingFilter();
filter.setChannelDecisionManager(new MockChannelDecisionManager(false,
"SUPPORTS_MOCK_ONLY"));
filter.setChannelDecisionManager(new MockChannelDecisionManager(false, "SUPPORTS_MOCK_ONLY"));
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap(
"/path", true, "SUPPORTS_MOCK_ONLY");
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap("/path", true,
"SUPPORTS_MOCK_ONLY");
filter.setSecurityMetadataSource(fids);
@@ -76,11 +75,10 @@ public class ChannelProcessingFilterTests {
@Test(expected = IllegalArgumentException.class)
public void testDetectsUnsupportedConfigAttribute() {
ChannelProcessingFilter filter = new ChannelProcessingFilter();
filter.setChannelDecisionManager(new MockChannelDecisionManager(false,
"SUPPORTS_MOCK_ONLY"));
filter.setChannelDecisionManager(new MockChannelDecisionManager(false, "SUPPORTS_MOCK_ONLY"));
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap(
"/path", true, "SUPPORTS_MOCK_ONLY", "INVALID_ATTRIBUTE");
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap("/path", true,
"SUPPORTS_MOCK_ONLY", "INVALID_ATTRIBUTE");
filter.setSecurityMetadataSource(fids);
filter.afterPropertiesSet();
@@ -89,11 +87,9 @@ public class ChannelProcessingFilterTests {
@Test
public void testDoFilterWhenManagerDoesCommitResponse() throws Exception {
ChannelProcessingFilter filter = new ChannelProcessingFilter();
filter.setChannelDecisionManager(new MockChannelDecisionManager(true,
"SOME_ATTRIBUTE"));
filter.setChannelDecisionManager(new MockChannelDecisionManager(true, "SOME_ATTRIBUTE"));
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap(
"/path", true, "SOME_ATTRIBUTE");
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap("/path", true, "SOME_ATTRIBUTE");
filter.setSecurityMetadataSource(fids);
@@ -109,11 +105,9 @@ public class ChannelProcessingFilterTests {
@Test
public void testDoFilterWhenManagerDoesNotCommitResponse() throws Exception {
ChannelProcessingFilter filter = new ChannelProcessingFilter();
filter.setChannelDecisionManager(new MockChannelDecisionManager(false,
"SOME_ATTRIBUTE"));
filter.setChannelDecisionManager(new MockChannelDecisionManager(false, "SOME_ATTRIBUTE"));
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap(
"/path", true, "SOME_ATTRIBUTE");
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap("/path", true, "SOME_ATTRIBUTE");
filter.setSecurityMetadataSource(fids);
@@ -131,8 +125,7 @@ public class ChannelProcessingFilterTests {
ChannelProcessingFilter filter = new ChannelProcessingFilter();
filter.setChannelDecisionManager(new MockChannelDecisionManager(false, "NOT_USED"));
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap(
"/path", true, "NOT_USED");
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap("/path", true, "NOT_USED");
filter.setSecurityMetadataSource(fids);
@@ -151,8 +144,7 @@ public class ChannelProcessingFilterTests {
filter.setChannelDecisionManager(new MockChannelDecisionManager(false, "MOCK"));
assertThat(filter.getChannelDecisionManager() != null).isTrue();
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap(
"/path", false, "MOCK");
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap("/path", false, "MOCK");
filter.setSecurityMetadataSource(fids);
assertThat(filter.getSecurityMetadataSource()).isSameAs(fids);
@@ -164,7 +156,9 @@ public class ChannelProcessingFilterTests {
// ==================================================================================================
private class MockChannelDecisionManager implements ChannelDecisionManager {
private String supportAttribute;
private boolean commitAResponse;
MockChannelDecisionManager(boolean commitAResponse, String supportAttribute) {
@@ -172,8 +166,7 @@ public class ChannelProcessingFilterTests {
this.supportAttribute = supportAttribute;
}
public void decide(FilterInvocation invocation, Collection<ConfigAttribute> config)
throws IOException {
public void decide(FilterInvocation invocation, Collection<ConfigAttribute> config) throws IOException {
if (commitAResponse) {
invocation.getHttpResponse().sendRedirect("/redirected");
}
@@ -187,23 +180,24 @@ public class ChannelProcessingFilterTests {
return false;
}
}
}
private class MockFilterInvocationDefinitionMap implements
FilterInvocationSecurityMetadataSource {
private class MockFilterInvocationDefinitionMap implements FilterInvocationSecurityMetadataSource {
private Collection<ConfigAttribute> toReturn;
private String servletPath;
private boolean provideIterator;
MockFilterInvocationDefinitionMap(String servletPath,
boolean provideIterator, String... toReturn) {
MockFilterInvocationDefinitionMap(String servletPath, boolean provideIterator, String... toReturn) {
this.servletPath = servletPath;
this.toReturn = SecurityConfig.createList(toReturn);
this.provideIterator = provideIterator;
}
public Collection<ConfigAttribute> getAttributes(Object object)
throws IllegalArgumentException {
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
FilterInvocation fi = (FilterInvocation) object;
if (servletPath.equals(fi.getHttpRequest().getServletPath())) {
@@ -225,5 +219,7 @@ public class ChannelProcessingFilterTests {
public boolean supports(Class<?> clazz) {
return true;
}
}
}

View File

@@ -47,12 +47,10 @@ public class InsecureChannelProcessorTests {
request.setServerPort(8080);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterInvocation fi = new FilterInvocation(request, response,
mock(FilterChain.class));
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
InsecureChannelProcessor processor = new InsecureChannelProcessor();
processor.decide(fi, SecurityConfig.createList("SOME_IGNORED_ATTRIBUTE",
"REQUIRES_INSECURE_CHANNEL"));
processor.decide(fi, SecurityConfig.createList("SOME_IGNORED_ATTRIBUTE", "REQUIRES_INSECURE_CHANNEL"));
assertThat(fi.getResponse().isCommitted()).isFalse();
}
@@ -69,12 +67,11 @@ public class InsecureChannelProcessorTests {
request.setServerPort(8443);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterInvocation fi = new FilterInvocation(request, response,
mock(FilterChain.class));
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" }));
processor.decide(fi,
SecurityConfig.createList(new String[] { "SOME_IGNORED_ATTRIBUTE", "REQUIRES_INSECURE_CHANNEL" }));
assertThat(fi.getResponse().isCommitted()).isTrue();
}
@@ -146,9 +143,9 @@ public class InsecureChannelProcessorTests {
@Test
public void testSupports() {
InsecureChannelProcessor processor = new InsecureChannelProcessor();
assertThat(processor.supports(new SecurityConfig("REQUIRES_INSECURE_CHANNEL")))
.isTrue();
assertThat(processor.supports(new SecurityConfig("REQUIRES_INSECURE_CHANNEL"))).isTrue();
assertThat(processor.supports(null)).isFalse();
assertThat(processor.supports(new SecurityConfig("NOT_SUPPORTED"))).isFalse();
}
}

View File

@@ -39,6 +39,7 @@ import static org.mockito.Mockito.mock;
* @author Ben Alex
*/
public class RetryWithHttpEntryPointTests {
// ~ Methods
// ========================================================================================================
@Test
@@ -81,8 +82,7 @@ public class RetryWithHttpEntryPointTests {
@Test
public void testNormalOperation() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET",
"/bigWebApp/hello/pathInfo.html");
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello/pathInfo.html");
request.setQueryString("open=true");
request.setScheme("https");
request.setServerName("localhost");
@@ -95,14 +95,12 @@ public class RetryWithHttpEntryPointTests {
ep.setPortResolver(new MockPortResolver(80, 443));
ep.commence(request, response);
assertThat(response.getRedirectedUrl()).isEqualTo(
"http://localhost/bigWebApp/hello/pathInfo.html?open=true");
assertThat(response.getRedirectedUrl()).isEqualTo("http://localhost/bigWebApp/hello/pathInfo.html?open=true");
}
@Test
public void testNormalOperationWithNullQueryString() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET",
"/bigWebApp/hello");
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello");
request.setScheme("https");
request.setServerName("localhost");
request.setServerPort(443);
@@ -114,8 +112,7 @@ public class RetryWithHttpEntryPointTests {
ep.setPortResolver(new MockPortResolver(80, 443));
ep.commence(request, response);
assertThat(response.getRedirectedUrl())
.isEqualTo("http://localhost/bigWebApp/hello");
assertThat(response.getRedirectedUrl()).isEqualTo("http://localhost/bigWebApp/hello");
}
@Test
@@ -138,8 +135,7 @@ public class RetryWithHttpEntryPointTests {
@Test
public void testOperationWithNonStandardPort() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET",
"/bigWebApp/hello/pathInfo.html");
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello/pathInfo.html");
request.setQueryString("open=true");
request.setScheme("https");
request.setServerName("localhost");
@@ -157,7 +153,8 @@ public class RetryWithHttpEntryPointTests {
ep.setPortMapper(portMapper);
ep.commence(request, response);
assertThat(response.getRedirectedUrl()).isEqualTo(
"http://localhost:8888/bigWebApp/hello/pathInfo.html?open=true");
assertThat(response.getRedirectedUrl())
.isEqualTo("http://localhost:8888/bigWebApp/hello/pathInfo.html?open=true");
}
}

View File

@@ -35,6 +35,7 @@ import java.util.Map;
* @author Ben Alex
*/
public class RetryWithHttpsEntryPointTests {
// ~ Methods
// ========================================================================================================
@Test
@@ -72,8 +73,7 @@ public class RetryWithHttpsEntryPointTests {
@Test
public void testNormalOperation() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET",
"/bigWebApp/hello/pathInfo.html");
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello/pathInfo.html");
request.setQueryString("open=true");
request.setScheme("http");
request.setServerName("www.example.com");
@@ -86,14 +86,13 @@ public class RetryWithHttpsEntryPointTests {
ep.setPortResolver(new MockPortResolver(80, 443));
ep.commence(request, response);
assertThat(response.getRedirectedUrl()).isEqualTo(
"https://www.example.com/bigWebApp/hello/pathInfo.html?open=true");
assertThat(response.getRedirectedUrl())
.isEqualTo("https://www.example.com/bigWebApp/hello/pathInfo.html?open=true");
}
@Test
public void testNormalOperationWithNullQueryString() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET",
"/bigWebApp/hello");
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello");
request.setScheme("http");
request.setServerName("www.example.com");
request.setServerPort(80);
@@ -128,8 +127,7 @@ public class RetryWithHttpsEntryPointTests {
@Test
public void testOperationWithNonStandardPort() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET",
"/bigWebApp/hello/pathInfo.html");
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello/pathInfo.html");
request.setQueryString("open=true");
request.setScheme("http");
request.setServerName("www.example.com");
@@ -147,7 +145,8 @@ public class RetryWithHttpsEntryPointTests {
ep.setPortMapper(portMapper);
ep.commence(request, response);
assertThat(response.getRedirectedUrl()).isEqualTo(
"https://www.example.com:9999/bigWebApp/hello/pathInfo.html?open=true");
assertThat(response.getRedirectedUrl())
.isEqualTo("https://www.example.com:9999/bigWebApp/hello/pathInfo.html?open=true");
}
}

View File

@@ -34,6 +34,7 @@ import org.springframework.security.web.access.channel.SecureChannelProcessor;
* @author Ben Alex
*/
public class SecureChannelProcessorTests {
// ~ Methods
// ========================================================================================================
@Test
@@ -48,12 +49,10 @@ public class SecureChannelProcessorTests {
request.setServerPort(8443);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterInvocation fi = new FilterInvocation(request, response,
mock(FilterChain.class));
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
SecureChannelProcessor processor = new SecureChannelProcessor();
processor.decide(fi, SecurityConfig.createList("SOME_IGNORED_ATTRIBUTE",
"REQUIRES_SECURE_CHANNEL"));
processor.decide(fi, SecurityConfig.createList("SOME_IGNORED_ATTRIBUTE", "REQUIRES_SECURE_CHANNEL"));
assertThat(fi.getResponse().isCommitted()).isFalse();
}
@@ -69,14 +68,11 @@ public class SecureChannelProcessorTests {
request.setServerPort(8080);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterInvocation fi = new FilterInvocation(request, response,
mock(FilterChain.class));
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" }));
processor.decide(fi,
SecurityConfig.createList(new String[] { "SOME_IGNORED_ATTRIBUTE", "REQUIRES_SECURE_CHANNEL" }));
assertThat(fi.getResponse().isCommitted()).isTrue();
}
@@ -152,4 +148,5 @@ public class SecureChannelProcessorTests {
assertThat(processor.supports(null)).isFalse();
assertThat(processor.supports(new SecurityConfig("NOT_SUPPORTED"))).isFalse();
}
}

View File

@@ -37,14 +37,18 @@ import static org.assertj.core.api.Assertions.assertThat;
*
*/
public class AbstractVariableEvaluationContextPostProcessorTests {
static final String KEY = "a";
static final String VALUE = "b";
VariableEvaluationContextPostProcessor processor;
FilterInvocation invocation;
MockHttpServletRequest request;
MockHttpServletResponse response;
EvaluationContext context;
@Before
@@ -53,8 +57,7 @@ public class AbstractVariableEvaluationContextPostProcessorTests {
this.request = new MockHttpServletRequest();
this.request.setServletPath("/");
this.response = new MockHttpServletResponse();
this.invocation = new FilterInvocation(this.request, this.response,
new MockFilterChain());
this.invocation = new FilterInvocation(this.request, this.response, new MockFilterChain());
this.context = new StandardEvaluationContext();
}
@@ -74,13 +77,15 @@ public class AbstractVariableEvaluationContextPostProcessorTests {
assertThat(this.context.lookupVariable(KEY)).isEqualTo(VALUE);
}
static class VariableEvaluationContextPostProcessor
extends AbstractVariableEvaluationContextPostProcessor {
static class VariableEvaluationContextPostProcessor extends AbstractVariableEvaluationContextPostProcessor {
Map<String, String> results = Collections.singletonMap(KEY, VALUE);
@Override
protected Map<String, String> extractVariables(HttpServletRequest request) {
return this.results;
}
}
}

View File

@@ -70,13 +70,11 @@ public class DefaultWebSecurityExpressionHandlerTests {
appContext.registerBeanDefinition("role", bean);
handler.setApplicationContext(appContext);
EvaluationContext ctx = handler.createEvaluationContext(
mock(Authentication.class), mock(FilterInvocation.class));
EvaluationContext ctx = handler.createEvaluationContext(mock(Authentication.class),
mock(FilterInvocation.class));
ExpressionParser parser = handler.getExpressionParser();
assertThat(parser.parseExpression("@role.getAttribute() == 'ROLE_A'").getValue(
ctx, Boolean.class)).isTrue();
assertThat(parser.parseExpression("@role.attribute == 'ROLE_A'").getValue(ctx,
Boolean.class)).isTrue();
assertThat(parser.parseExpression("@role.getAttribute() == 'ROLE_A'").getValue(ctx, Boolean.class)).isTrue();
assertThat(parser.parseExpression("@role.attribute == 'ROLE_A'").getValue(ctx, Boolean.class)).isTrue();
}
@Test(expected = IllegalArgumentException.class)
@@ -88,10 +86,8 @@ public class DefaultWebSecurityExpressionHandlerTests {
public void createEvaluationContextCustomTrustResolver() {
handler.setTrustResolver(trustResolver);
Expression expression = handler.getExpressionParser().parseExpression(
"anonymous");
EvaluationContext context = handler.createEvaluationContext(authentication,
invocation);
Expression expression = handler.getExpressionParser().parseExpression("anonymous");
EvaluationContext context = handler.createEvaluationContext(authentication, invocation);
assertThat(expression.getValue(context, Boolean.class)).isFalse();
verify(trustResolver).isAnonymous(authentication);

View File

@@ -45,8 +45,10 @@ import static org.mockito.Mockito.when;
*/
@RunWith(MockitoJUnitRunner.class)
public class DelegatingEvaluationContextTests {
@Mock
DelegatingEvaluationContext delegate;
@InjectMocks
DelegatingEvaluationContext context;
@@ -141,4 +143,5 @@ public class DelegatingEvaluationContextTests {
assertThat(this.context.lookupVariable(name)).isEqualTo(expected);
}
}

View File

@@ -40,11 +40,9 @@ public class ExpressionBasedFilterInvocationSecurityMetadataSourceTests {
ExpressionBasedFilterInvocationSecurityMetadataSource mds = new ExpressionBasedFilterInvocationSecurityMetadataSource(
requestMap, new DefaultWebSecurityExpressionHandler());
assertThat(mds.getAllConfigAttributes()).hasSize(1);
Collection<ConfigAttribute> attrs = mds.getAttributes(new FilterInvocation(
"/path", "GET"));
Collection<ConfigAttribute> attrs = mds.getAttributes(new FilterInvocation("/path", "GET"));
assertThat(attrs).hasSize(1);
WebExpressionConfigAttribute attribute = (WebExpressionConfigAttribute) attrs
.toArray()[0];
WebExpressionConfigAttribute attribute = (WebExpressionConfigAttribute) attrs.toArray()[0];
assertThat(attribute.getAttribute()).isNull();
assertThat(attribute.getAuthorizeExpression().getExpressionString()).isEqualTo(expression);
assertThat(attribute.toString()).isEqualTo(expression);
@@ -53,9 +51,9 @@ public class ExpressionBasedFilterInvocationSecurityMetadataSourceTests {
@Test(expected = IllegalArgumentException.class)
public void invalidExpressionIsRejected() {
LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<>();
requestMap.put(AnyRequestMatcher.INSTANCE,
SecurityConfig.createList("hasRole('X'"));
requestMap.put(AnyRequestMatcher.INSTANCE, SecurityConfig.createList("hasRole('X'"));
ExpressionBasedFilterInvocationSecurityMetadataSource mds = new ExpressionBasedFilterInvocationSecurityMetadataSource(
requestMap, new DefaultWebSecurityExpressionHandler());
}
}

View File

@@ -48,8 +48,9 @@ public class WebExpressionVoterTests {
@Test
public void supportsWebConfigAttributeAndFilterInvocation() {
WebExpressionVoter voter = new WebExpressionVoter();
assertThat(voter.supports(new WebExpressionConfigAttribute(mock(Expression.class),
mock(EvaluationContextPostProcessor.class)))).isTrue();
assertThat(voter.supports(
new WebExpressionConfigAttribute(mock(Expression.class), mock(EvaluationContextPostProcessor.class))))
.isTrue();
assertThat(voter.supports(FilterInvocation.class)).isTrue();
assertThat(voter.supports(MethodInvocation.class)).isFalse();
@@ -58,38 +59,32 @@ public class WebExpressionVoterTests {
@Test
public void abstainsIfNoAttributeFound() {
WebExpressionVoter voter = new WebExpressionVoter();
assertThat(voter.vote(user, new FilterInvocation("/path", "GET"),
SecurityConfig.createList("A", "B", "C"))).isEqualTo(
AccessDecisionVoter.ACCESS_ABSTAIN);
assertThat(voter.vote(user, new FilterInvocation("/path", "GET"), SecurityConfig.createList("A", "B", "C")))
.isEqualTo(AccessDecisionVoter.ACCESS_ABSTAIN);
}
@Test
public void grantsAccessIfExpressionIsTrueDeniesIfFalse() {
WebExpressionVoter voter = new WebExpressionVoter();
Expression ex = mock(Expression.class);
EvaluationContextPostProcessor postProcessor = mock(
EvaluationContextPostProcessor.class);
when(postProcessor.postProcess(any(EvaluationContext.class),
any(FilterInvocation.class))).thenAnswer( invocation -> invocation.getArgument(0));
WebExpressionConfigAttribute weca = new WebExpressionConfigAttribute(ex,
postProcessor);
EvaluationContextPostProcessor postProcessor = mock(EvaluationContextPostProcessor.class);
when(postProcessor.postProcess(any(EvaluationContext.class), any(FilterInvocation.class)))
.thenAnswer(invocation -> invocation.getArgument(0));
WebExpressionConfigAttribute weca = new WebExpressionConfigAttribute(ex, postProcessor);
EvaluationContext ctx = mock(EvaluationContext.class);
SecurityExpressionHandler eh = mock(SecurityExpressionHandler.class);
FilterInvocation fi = new FilterInvocation("/path", "GET");
voter.setExpressionHandler(eh);
when(eh.createEvaluationContext(user, fi)).thenReturn(ctx);
when(ex.getValue(ctx, Boolean.class)).thenReturn(Boolean.TRUE).thenReturn(
Boolean.FALSE);
when(ex.getValue(ctx, Boolean.class)).thenReturn(Boolean.TRUE).thenReturn(Boolean.FALSE);
ArrayList attributes = new ArrayList();
attributes.addAll(SecurityConfig.createList("A", "B", "C"));
attributes.add(weca);
assertThat(voter.vote(user, fi, attributes)).isEqualTo(
AccessDecisionVoter.ACCESS_GRANTED);
assertThat(voter.vote(user, fi, attributes)).isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
// Second time false
assertThat(voter.vote(user, fi, attributes)).isEqualTo(
AccessDecisionVoter.ACCESS_DENIED);
assertThat(voter.vote(user, fi, attributes)).isEqualTo(AccessDecisionVoter.ACCESS_DENIED);
}
// SEC-2507
@@ -101,10 +96,10 @@ public class WebExpressionVoterTests {
private static class FilterInvocationChild extends FilterInvocation {
FilterInvocationChild(ServletRequest request, ServletResponse response,
FilterChain chain) {
FilterInvocationChild(ServletRequest request, ServletResponse response, FilterChain chain) {
super(request, response, chain);
}
}
@Test
@@ -118,4 +113,5 @@ public class WebExpressionVoterTests {
WebExpressionVoter voter = new WebExpressionVoter();
assertThat(voter.supports(Object.class)).isFalse();
}
}

View File

@@ -41,9 +41,8 @@ public class WebSecurityExpressionRootTests {
request.setRequestURI("/test");
// IPv4
request.setRemoteAddr("192.168.1.1");
WebSecurityExpressionRoot root = new WebSecurityExpressionRoot(
mock(Authentication.class), new FilterInvocation(request,
mock(HttpServletResponse.class), mock(FilterChain.class)));
WebSecurityExpressionRoot root = new WebSecurityExpressionRoot(mock(Authentication.class),
new FilterInvocation(request, mock(HttpServletResponse.class), mock(FilterChain.class)));
assertThat(root.hasIpAddress("192.168.1.1")).isTrue();
@@ -56,9 +55,8 @@ public class WebSecurityExpressionRootTests {
public void addressesInIpRangeMatch() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/test");
WebSecurityExpressionRoot root = new WebSecurityExpressionRoot(
mock(Authentication.class), new FilterInvocation(request,
mock(HttpServletResponse.class), mock(FilterChain.class)));
WebSecurityExpressionRoot root = new WebSecurityExpressionRoot(mock(Authentication.class),
new FilterInvocation(request, mock(HttpServletResponse.class), mock(FilterChain.class)));
for (int i = 0; i < 255; i++) {
request.setRemoteAddr("192.168.1." + i);
assertThat(root.hasIpAddress("192.168.1.0/24")).isTrue();

View File

@@ -40,7 +40,9 @@ import static org.mockito.Mockito.mock;
* @author Ben Alex
*/
public class DefaultFilterInvocationSecurityMetadataSourceTests {
private DefaultFilterInvocationSecurityMetadataSource fids;
private Collection<ConfigAttribute> def = SecurityConfig.createList("ROLE_ONE");
// ~ Methods
@@ -55,8 +57,7 @@ public class DefaultFilterInvocationSecurityMetadataSourceTests {
public void lookupNotRequiringExactMatchSucceedsIfNotMatching() {
createFids("/secure/super/**", null);
FilterInvocation fi = createFilterInvocation("/secure/super/somefile.html", null,
null, null);
FilterInvocation fi = createFilterInvocation("/secure/super/somefile.html", null, null, null);
assertThat(this.fids.getAttributes(fi)).isEqualTo(this.def);
}
@@ -69,8 +70,7 @@ public class DefaultFilterInvocationSecurityMetadataSourceTests {
public void lookupNotRequiringExactMatchSucceedsIfSecureUrlPathContainsUpperCase() {
createFids("/secure/super/**", null);
FilterInvocation fi = createFilterInvocation("/secure", "/super/somefile.html",
null, null);
FilterInvocation fi = createFilterInvocation("/secure", "/super/somefile.html", null, null);
Collection<ConfigAttribute> response = this.fids.getAttributes(fi);
assertThat(response).isEqualTo(this.def);
@@ -80,8 +80,7 @@ public class DefaultFilterInvocationSecurityMetadataSourceTests {
public void lookupRequiringExactMatchIsSuccessful() {
createFids("/SeCurE/super/**", null);
FilterInvocation fi = createFilterInvocation("/SeCurE/super/somefile.html", null,
null, null);
FilterInvocation fi = createFilterInvocation("/SeCurE/super/somefile.html", null, null, null);
Collection<ConfigAttribute> response = this.fids.getAttributes(fi);
assertThat(response).isEqualTo(this.def);
@@ -91,8 +90,7 @@ public class DefaultFilterInvocationSecurityMetadataSourceTests {
public void lookupRequiringExactMatchWithAdditionalSlashesIsSuccessful() {
createFids("/someAdminPage.html**", null);
FilterInvocation fi = createFilterInvocation("/someAdminPage.html", null,
"a=/test", 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 ?
@@ -138,8 +136,7 @@ public class DefaultFilterInvocationSecurityMetadataSourceTests {
Collection<ConfigAttribute> userAttrs = SecurityConfig.createList("A");
requestMap.put(new AntPathRequestMatcher("/user/**", null), userAttrs);
requestMap.put(new AntPathRequestMatcher("/teller/**", "GET"),
SecurityConfig.createList("B"));
requestMap.put(new AntPathRequestMatcher("/teller/**", "GET"), SecurityConfig.createList("B"));
this.fids = new DefaultFilterInvocationSecurityMetadataSource(requestMap);
FilterInvocation fi = createFilterInvocation("/user", null, null, "GET");
@@ -154,8 +151,7 @@ public class DefaultFilterInvocationSecurityMetadataSourceTests {
public void extraQuestionMarkStillMatches() {
createFids("/someAdminPage.html*", null);
FilterInvocation fi = createFilterInvocation("/someAdminPage.html", null, null,
null);
FilterInvocation fi = createFilterInvocation("/someAdminPage.html", null, null, null);
Collection<ConfigAttribute> response = this.fids.getAttributes(fi);
assertThat(response).isEqualTo(this.def);
@@ -166,8 +162,8 @@ public class DefaultFilterInvocationSecurityMetadataSourceTests {
assertThat(response).isEqualTo(this.def);
}
private FilterInvocation createFilterInvocation(String servletPath, String pathInfo,
String queryString, String method) {
private FilterInvocation createFilterInvocation(String servletPath, String pathInfo, String queryString,
String method) {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI(null);
request.setMethod(method);
@@ -175,7 +171,7 @@ public class DefaultFilterInvocationSecurityMetadataSourceTests {
request.setPathInfo(pathInfo);
request.setQueryString(queryString);
return new FilterInvocation(request, new MockHttpServletResponse(),
mock(FilterChain.class));
return new FilterInvocation(request, new MockHttpServletResponse(), mock(FilterChain.class));
}
}

View File

@@ -49,11 +49,17 @@ import javax.servlet.http.HttpServletResponse;
* @author Rob Winch
*/
public class FilterSecurityInterceptorTests {
private AuthenticationManager am;
private AccessDecisionManager adm;
private FilterInvocationSecurityMetadataSource ods;
private RunAsManager ram;
private FilterSecurityInterceptor interceptor;
private ApplicationEventPublisher publisher;
// ~ Methods
@@ -81,8 +87,7 @@ public class FilterSecurityInterceptorTests {
}
@Test(expected = IllegalArgumentException.class)
public void testEnsuresAccessDecisionManagerSupportsFilterInvocationClass()
throws Exception {
public void testEnsuresAccessDecisionManagerSupportsFilterInvocationClass() throws Exception {
when(adm.supports(FilterInvocation.class)).thenReturn(true);
interceptor.afterPropertiesSet();
}
@@ -101,8 +106,7 @@ public class FilterSecurityInterceptorTests {
@Test
public void testSuccessfulInvocation() throws Throwable {
// Setup a Context
Authentication token = new TestingAuthenticationToken("Test", "Password",
"NOT_USED");
Authentication token = new TestingAuthenticationToken("Test", "Password", "NOT_USED");
SecurityContextHolder.getContext().setAuthentication(token);
FilterInvocation fi = createinvocation();
@@ -117,15 +121,14 @@ public class FilterSecurityInterceptorTests {
@Test
public void afterInvocationIsNotInvokedIfExceptionThrown() throws Exception {
Authentication token = new TestingAuthenticationToken("Test", "Password",
"NOT_USED");
Authentication token = new TestingAuthenticationToken("Test", "Password", "NOT_USED");
SecurityContextHolder.getContext().setAuthentication(token);
FilterInvocation fi = createinvocation();
FilterChain chain = fi.getChain();
doThrow(new RuntimeException()).when(chain).doFilter(
any(HttpServletRequest.class), any(HttpServletResponse.class));
doThrow(new RuntimeException()).when(chain).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
when(ods.getAttributes(fi)).thenReturn(SecurityConfig.createList("MOCK_OK"));
AfterInvocationManager aim = mock(AfterInvocationManager.class);
@@ -146,22 +149,20 @@ public class FilterSecurityInterceptorTests {
@SuppressWarnings("unchecked")
public void finallyInvocationIsInvokedIfExceptionThrown() throws Exception {
SecurityContext ctx = SecurityContextHolder.getContext();
Authentication token = new TestingAuthenticationToken("Test", "Password",
"NOT_USED");
Authentication token = new TestingAuthenticationToken("Test", "Password", "NOT_USED");
token.setAuthenticated(true);
ctx.setAuthentication(token);
RunAsManager runAsManager = mock(RunAsManager.class);
when(runAsManager.buildRunAs(eq(token), any(), anyCollection())).thenReturn(
new RunAsUserToken("key", "someone", "creds", token.getAuthorities(),
token.getClass()));
when(runAsManager.buildRunAs(eq(token), any(), anyCollection()))
.thenReturn(new RunAsUserToken("key", "someone", "creds", token.getAuthorities(), token.getClass()));
interceptor.setRunAsManager(runAsManager);
FilterInvocation fi = createinvocation();
FilterChain chain = fi.getChain();
doThrow(new RuntimeException()).when(chain).doFilter(
any(HttpServletRequest.class), any(HttpServletResponse.class));
doThrow(new RuntimeException()).when(chain).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
when(ods.getAttributes(fi)).thenReturn(SecurityConfig.createList("MOCK_OK"));
AfterInvocationManager aim = mock(AfterInvocationManager.class);

View File

@@ -22,7 +22,6 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.springframework.security.web.access.intercept.RequestKey;
/**
*
* @author Luke Taylor
*
*/
@@ -69,8 +68,8 @@ public class RequestKeyTests {
*/
@Test
public void keysWithNullUrlFailsAssertion() {
assertThatThrownBy(() -> new RequestKey(null, null))
.isInstanceOf(IllegalArgumentException.class)
assertThatThrownBy(() -> new RequestKey(null, null)).isInstanceOf(IllegalArgumentException.class)
.hasMessage("url cannot be null");
}
}

View File

@@ -136,9 +136,7 @@ public class AbstractAuthenticationProcessingFilterTests {
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");
assertThat(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).isEqualTo("test");
}
@Test
@@ -149,10 +147,9 @@ public class AbstractAuthenticationProcessingFilterTests {
filter.afterPropertiesSet();
assertThat(filter.getRememberMeServices()).isNotNull();
filter.setRememberMeServices(new TokenBasedRememberMeServices("key",
new AbstractRememberMeServicesTests.MockUserDetailsService()));
assertThat(filter.getRememberMeServices().getClass()).isEqualTo(
TokenBasedRememberMeServices.class);
filter.setRememberMeServices(
new TokenBasedRememberMeServices("key", new AbstractRememberMeServicesTests.MockUserDetailsService()));
assertThat(filter.getRememberMeServices().getClass()).isEqualTo(TokenBasedRememberMeServices.class);
assertThat(filter.getAuthenticationManager() != null).isTrue();
}
@@ -196,8 +193,7 @@ public class AbstractAuthenticationProcessingFilterTests {
MockAuthenticationFilter filter = new MockAuthenticationFilter(true);
filter.setFilterProcessesUrl("/j_mock_post");
filter.setSessionAuthenticationStrategy(
mock(SessionAuthenticationStrategy.class));
filter.setSessionAuthenticationStrategy(mock(SessionAuthenticationStrategy.class));
filter.setAuthenticationSuccessHandler(successHandler);
filter.setAuthenticationFailureHandler(failureHandler);
filter.setAuthenticationManager(mock(AuthenticationManager.class));
@@ -207,9 +203,7 @@ public class AbstractAuthenticationProcessingFilterTests {
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");
assertThat(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).isEqualTo("test");
// Should still have the same session
assertThat(request.getSession()).isEqualTo(sessionPreAuth);
}
@@ -229,11 +223,10 @@ public class AbstractAuthenticationProcessingFilterTests {
MockHttpServletResponse response = new MockHttpServletResponse();
// Setup our test object, to grant access
MockAuthenticationFilter filter = new MockAuthenticationFilter(
"/j_mock_post", mock(AuthenticationManager.class));
MockAuthenticationFilter filter = new MockAuthenticationFilter("/j_mock_post",
mock(AuthenticationManager.class));
filter.setSessionAuthenticationStrategy(
mock(SessionAuthenticationStrategy.class));
filter.setSessionAuthenticationStrategy(mock(SessionAuthenticationStrategy.class));
filter.setAuthenticationSuccessHandler(successHandler);
filter.setAuthenticationFailureHandler(failureHandler);
filter.afterPropertiesSet();
@@ -242,9 +235,7 @@ public class AbstractAuthenticationProcessingFilterTests {
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");
assertThat(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).isEqualTo("test");
// Should still have the same session
assertThat(request.getSession()).isEqualTo(sessionPreAuth);
}
@@ -269,8 +260,7 @@ public class AbstractAuthenticationProcessingFilterTests {
MockAuthenticationFilter filter = new MockAuthenticationFilter(
new AntPathRequestMatcher("/j_eradicate_corona_virus"), mock(AuthenticationManager.class));
filter.setSessionAuthenticationStrategy(
mock(SessionAuthenticationStrategy.class));
filter.setSessionAuthenticationStrategy(mock(SessionAuthenticationStrategy.class));
filter.setAuthenticationSuccessHandler(successHandler);
filter.setAuthenticationFailureHandler(failureHandler);
filter.afterPropertiesSet();
@@ -279,9 +269,7 @@ public class AbstractAuthenticationProcessingFilterTests {
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");
assertThat(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).isEqualTo("test");
// Should still have the same session
assertThat(request.getSession()).isEqualTo(sessionPreAuth);
}
@@ -299,8 +287,7 @@ public class AbstractAuthenticationProcessingFilterTests {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo(
"authenticationManager must be specified");
assertThat(expected.getMessage()).isEqualTo("authenticationManager must be specified");
}
}
@@ -316,14 +303,12 @@ public class AbstractAuthenticationProcessingFilterTests {
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException expected) {
assertThat(expected.getMessage()).isEqualTo(
"Pattern cannot be null or empty");
assertThat(expected.getMessage()).isEqualTo("Pattern cannot be null or empty");
}
}
@Test
public void testSuccessLoginThenFailureLoginResultsInSessionLosingToken()
throws Exception {
public void testSuccessLoginThenFailureLoginResultsInSessionLosingToken() throws Exception {
// Setup our HTTP request
MockHttpServletRequest request = createMockAuthenticationRequest();
@@ -344,9 +329,7 @@ public class AbstractAuthenticationProcessingFilterTests {
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");
assertThat(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).isEqualTo("test");
// Now try again but this time have filter deny access
// Setup our HTTP request
@@ -366,8 +349,7 @@ public class AbstractAuthenticationProcessingFilterTests {
}
@Test
public void testSuccessfulAuthenticationInvokesSuccessHandlerAndSetsContext()
throws Exception {
public void testSuccessfulAuthenticationInvokesSuccessHandlerAndSetsContext() throws Exception {
// Setup our HTTP request
MockHttpServletRequest request = createMockAuthenticationRequest();
@@ -382,15 +364,14 @@ public class AbstractAuthenticationProcessingFilterTests {
// Setup our test object, to grant access
MockAuthenticationFilter filter = new MockAuthenticationFilter(true);
filter.setFilterProcessesUrl("/j_mock_post");
AuthenticationSuccessHandler successHandler = mock(
AuthenticationSuccessHandler.class);
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));
verify(successHandler).onAuthenticationSuccess(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(Authentication.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
}
@@ -410,15 +391,14 @@ public class AbstractAuthenticationProcessingFilterTests {
// Setup our test object, to deny access
MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
AuthenticationFailureHandler failureHandler = mock(
AuthenticationFailureHandler.class);
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));
verify(failureHandler).onAuthenticationFailure(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(AuthenticationException.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -468,8 +448,7 @@ public class AbstractAuthenticationProcessingFilterTests {
* SEC-1919
*/
@Test
public void loginErrorWithInternAuthenticationServiceExceptionLogsError()
throws Exception {
public void loginErrorWithInternAuthenticationServiceExceptionLogsError() throws Exception {
MockHttpServletRequest request = createMockAuthenticationRequest();
MockFilterChain chain = new MockFilterChain(true);
@@ -478,8 +457,7 @@ public class AbstractAuthenticationProcessingFilterTests {
Log logger = mock(Log.class);
MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
ReflectionTestUtils.setField(filter, "logger", logger);
filter.exceptionToThrow = new InternalAuthenticationServiceException(
"Mock requested to do so");
filter.exceptionToThrow = new InternalAuthenticationServiceException("Mock requested to do so");
successHandler.setDefaultTargetUrl("https://monkeymachine.co.uk/");
filter.setAuthenticationSuccessHandler(successHandler);
@@ -501,8 +479,7 @@ public class AbstractAuthenticationProcessingFilterTests {
// ~ Inner Classes
// ==================================================================================================
private class MockAuthenticationFilter
extends AbstractAuthenticationProcessingFilter {
private class MockAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
private static final String DEFAULT_FILTER_PROCESSING_URL = "/j_mock_post";
@@ -520,7 +497,8 @@ public class AbstractAuthenticationProcessingFilterTests {
super(DEFAULT_FILTER_PROCESSING_URL);
}
private MockAuthenticationFilter(String defaultFilterProcessingUrl, AuthenticationManager authenticationManager) {
private MockAuthenticationFilter(String defaultFilterProcessingUrl,
AuthenticationManager authenticationManager) {
super(defaultFilterProcessingUrl, authenticationManager);
setupRememberMeServicesAndAuthenticationException();
this.grantAccess = true;
@@ -533,8 +511,8 @@ public class AbstractAuthenticationProcessingFilterTests {
this.grantAccess = true;
}
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
if (grantAccess) {
return new UsernamePasswordAuthenticationToken("test", "test",
AuthorityUtils.createAuthorityList("TEST"));
@@ -546,8 +524,7 @@ public class AbstractAuthenticationProcessingFilterTests {
private void setupRememberMeServicesAndAuthenticationException() {
setRememberMeServices(new NullRememberMeServices());
this.exceptionToThrow = new BadCredentialsException(
"Mock requested to do so");
this.exceptionToThrow = new BadCredentialsException("Mock requested to do so");
}
}
@@ -568,5 +545,7 @@ public class AbstractAuthenticationProcessingFilterTests {
fail("Did not expect filter chain to proceed");
}
}
}
}

View File

@@ -51,9 +51,8 @@ public class AnonymousAuthenticationFilterTests {
// ~ Methods
// ========================================================================================================
private void executeFilterInContainerSimulator(FilterConfig filterConfig,
Filter filter, ServletRequest request, ServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
private void executeFilterInContainerSimulator(FilterConfig filterConfig, Filter filter, ServletRequest request,
ServletResponse response, FilterChain filterChain) throws ServletException, IOException {
filter.doFilter(request, response, filterChain);
}
@@ -76,36 +75,32 @@ public class AnonymousAuthenticationFilterTests {
@Test
public void testOperationWhenAuthenticationExistsInContextHolder() throws Exception {
// Put an Authentication object into the SecurityContextHolder
Authentication originalAuth = new TestingAuthenticationToken("user", "password",
"ROLE_A");
Authentication originalAuth = new TestingAuthenticationToken("user", "password", "ROLE_A");
SecurityContextHolder.getContext().setAuthentication(originalAuth);
AnonymousAuthenticationFilter filter = new AnonymousAuthenticationFilter(
"qwerty", "anonymousUsername",
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));
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);
}
@Test
public void testOperationWhenNoAuthenticationInSecurityContextHolder()
throws Exception {
AnonymousAuthenticationFilter filter = new AnonymousAuthenticationFilter(
"qwerty", "anonymousUsername",
public void testOperationWhenNoAuthenticationInSecurityContextHolder() throws Exception {
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));
executeFilterInContainerSimulator(mock(FilterConfig.class), filter, request, new MockHttpServletResponse(),
new MockFilterChain(true));
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
assertThat(auth.getPrincipal()).isEqualTo("anonymousUsername");
@@ -118,6 +113,7 @@ public class AnonymousAuthenticationFilterTests {
// ==================================================================================================
private class MockFilterChain implements FilterChain {
private boolean expectToProceed;
MockFilterChain(boolean expectToProceed) {
@@ -129,5 +125,7 @@ public class AnonymousAuthenticationFilterTests {
fail("Did not expect filter chain to proceed");
}
}
}
}

View File

@@ -58,14 +58,19 @@ public class AuthenticationFilterTests {
@Mock
private AuthenticationSuccessHandler successHandler;
@Mock
private AuthenticationConverter authenticationConverter;
@Mock
private AuthenticationManager authenticationManager;
@Mock
private AuthenticationFailureHandler failureHandler;
@Mock
private AuthenticationManagerResolver<HttpServletRequest> authenticationManagerResolver;
@Mock
private RequestMatcher requestMatcher;
@@ -81,7 +86,8 @@ public class AuthenticationFilterTests {
@Test
public void filterWhenDefaultsAndNoAuthenticationThenContinues() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager, this.authenticationConverter);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager,
this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -95,7 +101,8 @@ public class AuthenticationFilterTests {
@Test
public void filterWhenAuthenticationManagerResolverDefaultsAndNoAuthenticationThenContinues() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -112,7 +119,8 @@ public class AuthenticationFilterTests {
Authentication authentication = new TestingAuthenticationToken("test", "this", "ROLE");
when(this.authenticationConverter.convert(any())).thenReturn(authentication);
when(this.authenticationManager.authenticate(any())).thenReturn(authentication);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager, this.authenticationConverter);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager,
this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -131,7 +139,8 @@ public class AuthenticationFilterTests {
when(this.authenticationConverter.convert(any())).thenReturn(authentication);
when(this.authenticationManager.authenticate(any())).thenReturn(authentication);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -149,7 +158,8 @@ public class AuthenticationFilterTests {
when(this.authenticationConverter.convert(any())).thenReturn(authentication);
when(this.authenticationManager.authenticate(any())).thenThrow(new BadCredentialsException("failed"));
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager, this.authenticationConverter);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager,
this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -167,7 +177,8 @@ public class AuthenticationFilterTests {
when(this.authenticationConverter.convert(any())).thenReturn(authentication);
when(this.authenticationManager.authenticate(any())).thenThrow(new BadCredentialsException("failed"));
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -181,7 +192,8 @@ public class AuthenticationFilterTests {
@Test
public void filterWhenConvertEmptyThenOk() throws Exception {
when(this.authenticationConverter.convert(any())).thenReturn(null);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
FilterChain chain = mock(FilterChain.class);
@@ -198,7 +210,8 @@ public class AuthenticationFilterTests {
when(this.authenticationConverter.convert(any())).thenReturn(authentication);
when(this.authenticationManager.authenticate(any())).thenReturn(authentication);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
filter.setSuccessHandler(successHandler);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
@@ -217,7 +230,8 @@ public class AuthenticationFilterTests {
when(this.authenticationConverter.convert(any())).thenReturn(authentication);
when(this.authenticationManager.authenticate(any())).thenReturn(null);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
filter.setSuccessHandler(successHandler);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
@@ -225,7 +239,8 @@ public class AuthenticationFilterTests {
FilterChain chain = mock(FilterChain.class);
try {
filter.doFilter(request, response, chain);
} catch (ServletException e) {
}
catch (ServletException e) {
verifyZeroInteractions(this.successHandler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
@@ -237,7 +252,8 @@ public class AuthenticationFilterTests {
public void filterWhenNotMatchAndConvertAndAuthenticationSuccessThenContinues() throws Exception {
when(this.requestMatcher.matches(any())).thenReturn(false);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver, this.authenticationConverter);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
filter.setRequestMatcher(this.requestMatcher);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
@@ -263,7 +279,8 @@ public class AuthenticationFilterTests {
FilterChain chain = new MockFilterChain();
String sessionId = session.getId();
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager, this.authenticationConverter);
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManager,
this.authenticationConverter);
filter.doFilter(request, response, chain);
assertThat(session.getId()).isNotEqualTo(sessionId);

View File

@@ -37,22 +37,20 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
*
* @author Luke Taylor
* @since 3.0
*/
public class DefaultLoginPageGeneratingFilterTests {
private FilterChain chain = mock(FilterChain.class);
@Test
public void generatingPageWithAuthenticationProcessingFilterOnlyIsSuccessFul()
throws Exception {
public void generatingPageWithAuthenticationProcessingFilterOnlyIsSuccessFul() throws Exception {
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(
new UsernamePasswordAuthenticationFilter());
filter.doFilter(new MockHttpServletRequest("GET", "/login"),
new MockHttpServletResponse(), chain);
filter.doFilter(new MockHttpServletRequest("GET", "/login;pathparam=unused"),
new MockHttpServletResponse(), chain);
filter.doFilter(new MockHttpServletRequest("GET", "/login"), new MockHttpServletResponse(), chain);
filter.doFilter(new MockHttpServletRequest("GET", "/login;pathparam=unused"), new MockHttpServletResponse(),
chain);
}
@Test
@@ -84,8 +82,7 @@ public class DefaultLoginPageGeneratingFilterTests {
new UsernamePasswordAuthenticationFilter());
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest("GET",
"/context/login");
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/context/login");
request.setContextPath("/context");
filter.doFilter(request, response, chain);
@@ -122,13 +119,14 @@ public class DefaultLoginPageGeneratingFilterTests {
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(
new UsernamePasswordAuthenticationFilter());
filter.setOauth2LoginEnabled(true);
filter.setOauth2AuthenticationUrlToClientName(Collections.singletonMap("XYUU",
"\u8109\u640F\u7F51\u5E10\u6237\u767B\u5F55"));
filter.setOauth2AuthenticationUrlToClientName(
Collections.singletonMap("XYUU", "\u8109\u640F\u7F51\u5E10\u6237\u767B\u5F55"));
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/login");
filter.doFilter(request, response, chain);
assertThat(response.getContentLength() == response.getContentAsString().getBytes(
response.getCharacterEncoding()).length).isTrue();
assertThat(response
.getContentLength() == response.getContentAsString().getBytes(response.getCharacterEncoding()).length)
.isTrue();
}
@Test
@@ -147,29 +145,28 @@ public class DefaultLoginPageGeneratingFilterTests {
@Test
public void generatingPageWithOpenIdFilterOnlyIsSuccessFul() throws Exception {
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(
new MockProcessingFilter());
filter.doFilter(new MockHttpServletRequest("GET", "/login"),
new MockHttpServletResponse(), chain);
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(new MockProcessingFilter());
filter.doFilter(new MockHttpServletRequest("GET", "/login"), new MockHttpServletResponse(), chain);
}
// Fake OpenID filter (since it's not in this module
@SuppressWarnings("unused")
private static class MockProcessingFilter extends
AbstractAuthenticationProcessingFilter {
private static class MockProcessingFilter extends AbstractAuthenticationProcessingFilter {
MockProcessingFilter() {
super("/someurl");
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
return null;
}
public String getClaimedIdentityFieldName() {
return "unused";
}
}
/* SEC-1111 */
@@ -180,11 +177,9 @@ public class DefaultLoginPageGeneratingFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/login");
request.addParameter("login_error", "true");
MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
String message = messages.getMessage(
"AbstractUserDetailsAuthenticationProvider.badCredentials",
String message = messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials",
"Bad credentials", Locale.KOREA);
request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION,
new BadCredentialsException(message));
request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, new BadCredentialsException(message));
filter.doFilter(request, new MockHttpServletResponse(), chain);
}
@@ -198,12 +193,13 @@ public class DefaultLoginPageGeneratingFilterTests {
String clientName = "Google < > \" \' &";
filter.setOauth2AuthenticationUrlToClientName(
Collections.singletonMap("/oauth2/authorization/google", clientName));
Collections.singletonMap("/oauth2/authorization/google", clientName));
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(new MockHttpServletRequest("GET", "/login"), response, chain);
assertThat(response.getContentAsString()).contains("<a href=\"/oauth2/authorization/google\">Google &lt; &gt; &quot; &#39; &amp;</a>");
assertThat(response.getContentAsString())
.contains("<a href=\"/oauth2/authorization/google\">Google &lt; &gt; &quot; &#39; &amp;</a>");
}
@Test
@@ -213,13 +209,14 @@ public class DefaultLoginPageGeneratingFilterTests {
filter.setSaml2LoginEnabled(true);
String clientName = "Google < > \" \' &";
filter.setSaml2AuthenticationUrlToProviderName(
Collections.singletonMap("/saml/sso/google", clientName));
filter.setSaml2AuthenticationUrlToProviderName(Collections.singletonMap("/saml/sso/google", clientName));
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(new MockHttpServletRequest("GET", "/login"), response, 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>");
assertThat(response.getContentAsString())
.contains("<a href=\"/saml/sso/google\">Google &lt; &gt; &quot; &#39; &amp;</a>");
}
}

View File

@@ -32,7 +32,8 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:org/springframework/security/web/authentication/DelegatingAuthenticationEntryPointTest-context.xml")
@ContextConfiguration(
locations = "classpath:org/springframework/security/web/authentication/DelegatingAuthenticationEntryPointTest-context.xml")
public class DelegatingAuthenticationEntryPointContextTests {
@Autowired
@@ -54,8 +55,8 @@ public class DelegatingAuthenticationEntryPointContextTests {
request.addHeader("User-Agent", "Mozilla/5.0");
daep.commence(request, null, null);
verify(firstAEP).commence(request, null, null);
verify(defaultAEP, never()).commence(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(AuthenticationException.class));
verify(defaultAEP, never()).commence(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(AuthenticationException.class));
}
@@ -66,8 +67,8 @@ public class DelegatingAuthenticationEntryPointContextTests {
request.setRemoteAddr("192.168.1.10");
daep.commence(request, null, null);
verify(defaultAEP).commence(request, null, null);
verify(firstAEP, never()).commence(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(AuthenticationException.class));
verify(firstAEP, never()).commence(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(AuthenticationException.class));
}

View File

@@ -37,8 +37,11 @@ import org.springframework.security.web.util.matcher.RequestMatcher;
public class DelegatingAuthenticationEntryPointTests {
private DelegatingAuthenticationEntryPoint daep;
private LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPoints;
private AuthenticationEntryPoint defaultEntryPoint;
private HttpServletRequest request = new MockHttpServletRequest();
@Before

View File

@@ -34,8 +34,7 @@ public class ExceptionMappingAuthenticationFailureHandlerTests {
ExceptionMappingAuthenticationFailureHandler fh = new ExceptionMappingAuthenticationFailureHandler();
fh.setDefaultFailureUrl("/failed");
MockHttpServletResponse response = new MockHttpServletResponse();
fh.onAuthenticationFailure(new MockHttpServletRequest(), response,
new BadCredentialsException(""));
fh.onAuthenticationFailure(new MockHttpServletRequest(), response, new BadCredentialsException(""));
assertThat(response.getRedirectedUrl()).isEqualTo("/failed");
}
@@ -44,14 +43,11 @@ public class ExceptionMappingAuthenticationFailureHandlerTests {
public void exceptionMapIsUsedIfMappingExists() throws Exception {
ExceptionMappingAuthenticationFailureHandler fh = new ExceptionMappingAuthenticationFailureHandler();
HashMap<String, String> mapping = new HashMap<>();
mapping.put(
"org.springframework.security.authentication.BadCredentialsException",
"/badcreds");
mapping.put("org.springframework.security.authentication.BadCredentialsException", "/badcreds");
fh.setExceptionMappings(mapping);
fh.setDefaultFailureUrl("/failed");
MockHttpServletResponse response = new MockHttpServletResponse();
fh.onAuthenticationFailure(new MockHttpServletRequest(), response,
new BadCredentialsException(""));
fh.onAuthenticationFailure(new MockHttpServletRequest(), response, new BadCredentialsException(""));
assertThat(response.getRedirectedUrl()).isEqualTo("/badcreds");
}

View File

@@ -1,58 +1,59 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.web.authentication;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.core.Authentication;
import static org.mockito.Mockito.mock;
import static org.assertj.core.api.Assertions.*;
/**
* <p>
* Forward Authentication Failure Handler Tests
* </p>
*
* @author Shazin Sadakath
* @since 4.1
*/
public class ForwardAuthenticaionSuccessHandlerTests {
@Test(expected = IllegalArgumentException.class)
public void invalidForwardUrl() {
new ForwardAuthenticationSuccessHandler("aaa");
}
@Test(expected = IllegalArgumentException.class)
public void emptyForwardUrl() {
new ForwardAuthenticationSuccessHandler("");
}
@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");
}
}
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.web.authentication;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.core.Authentication;
import static org.mockito.Mockito.mock;
import static org.assertj.core.api.Assertions.*;
/**
* <p>
* Forward Authentication Failure Handler Tests
* </p>
*
* @author Shazin Sadakath
* @since 4.1
*/
public class ForwardAuthenticaionSuccessHandlerTests {
@Test(expected = IllegalArgumentException.class)
public void invalidForwardUrl() {
new ForwardAuthenticationSuccessHandler("aaa");
}
@Test(expected = IllegalArgumentException.class)
public void emptyForwardUrl() {
new ForwardAuthenticationSuccessHandler("");
}
@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

@@ -1,60 +1,60 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.web.authentication;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.WebAttributes;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* <p>
* Forward Authentication Failure Handler Tests
* </p>
*
* @author Shazin Sadakath
* @since4.1
*/
public class ForwardAuthenticationFailureHandlerTests {
@Test(expected = IllegalArgumentException.class)
public void invalidForwardUrl() {
new ForwardAuthenticationFailureHandler("aaa");
}
@Test(expected = IllegalArgumentException.class)
public void emptyForwardUrl() {
new ForwardAuthenticationFailureHandler("");
}
@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);
}
}
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.web.authentication;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.WebAttributes;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
/**
* <p>
* Forward Authentication Failure Handler Tests
* </p>
*
* @author Shazin Sadakath @since4.1
*/
public class ForwardAuthenticationFailureHandlerTests {
@Test(expected = IllegalArgumentException.class)
public void invalidForwardUrl() {
new ForwardAuthenticationFailureHandler("aaa");
}
@Test(expected = IllegalArgumentException.class)
public void emptyForwardUrl() {
new ForwardAuthenticationFailureHandler("");
}
@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

@@ -25,13 +25,15 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.core.AuthenticationException;
/**
*
* @author Rob Winch
* @since 4.0
*/
public class HttpStatusEntryPointTests {
MockHttpServletRequest request;
MockHttpServletResponse response;
AuthenticationException authException;
HttpStatusEntryPoint entryPoint;

View File

@@ -33,6 +33,7 @@ import org.springframework.security.web.PortMapperImpl;
* @author colin sampaleanu
*/
public class LoginUrlAuthenticationEntryPointTests {
// ~ Methods
// ========================================================================================================
@@ -43,22 +44,19 @@ public class LoginUrlAuthenticationEntryPointTests {
@Test(expected = IllegalArgumentException.class)
public void testDetectsMissingPortMapper() {
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(
"/login");
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/login");
ep.setPortMapper(null);
}
@Test(expected = IllegalArgumentException.class)
public void testDetectsMissingPortResolver() {
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(
"/login");
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/login");
ep.setPortResolver(null);
}
@Test
public void testGettersSetters() {
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(
"/hello");
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
ep.setPortMapper(new PortMapperImpl());
ep.setPortResolver(new MockPortResolver(8080, 8443));
assertThat(ep.getLoginFormUrl()).isEqualTo("/hello");
@@ -85,8 +83,7 @@ public class LoginUrlAuthenticationEntryPointTests {
MockHttpServletResponse response = new MockHttpServletResponse();
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(
"/hello");
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
ep.setPortMapper(new PortMapperImpl());
ep.setForceHttps(true);
ep.setPortMapper(new PortMapperImpl());
@@ -136,8 +133,7 @@ public class LoginUrlAuthenticationEntryPointTests {
MockHttpServletResponse response = new MockHttpServletResponse();
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(
"/hello");
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
ep.setPortMapper(new PortMapperImpl());
ep.setForceHttps(true);
ep.setPortMapper(new PortMapperImpl());
@@ -156,8 +152,7 @@ public class LoginUrlAuthenticationEntryPointTests {
@Test
public void testNormalOperation() throws Exception {
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(
"/hello");
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
ep.setPortMapper(new PortMapperImpl());
ep.setPortResolver(new MockPortResolver(80, 443));
ep.afterPropertiesSet();
@@ -178,8 +173,7 @@ public class LoginUrlAuthenticationEntryPointTests {
@Test
public void testOperationWhenHttpsRequestsButHttpsPortUnknown() throws Exception {
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(
"/hello");
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
ep.setPortResolver(new MockPortResolver(8888, 1234));
ep.setForceHttps(true);
ep.afterPropertiesSet();
@@ -202,10 +196,8 @@ public class LoginUrlAuthenticationEntryPointTests {
}
@Test
public void testServerSideRedirectWithoutForceHttpsForwardsToLoginPage()
throws Exception {
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(
"/hello");
public void testServerSideRedirectWithoutForceHttpsForwardsToLoginPage() throws Exception {
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
ep.setUseForward(true);
ep.afterPropertiesSet();
MockHttpServletRequest request = new MockHttpServletRequest();
@@ -224,10 +216,8 @@ public class LoginUrlAuthenticationEntryPointTests {
}
@Test
public void testServerSideRedirectWithForceHttpsRedirectsCurrentRequest()
throws Exception {
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(
"/hello");
public void testServerSideRedirectWithForceHttpsRedirectsCurrentRequest() throws Exception {
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
ep.setUseForward(true);
ep.setForceHttps(true);
ep.afterPropertiesSet();
@@ -250,8 +240,7 @@ public class LoginUrlAuthenticationEntryPointTests {
@Test
public void absoluteLoginFormUrlIsSupported() throws Exception {
final String loginFormUrl = "https://somesite.com/login";
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(
loginFormUrl);
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(loginFormUrl);
ep.afterPropertiesSet();
MockHttpServletResponse response = new MockHttpServletResponse();
ep.commence(new MockHttpServletRequest("GET", "/someUrl"), response, null);
@@ -261,9 +250,9 @@ public class LoginUrlAuthenticationEntryPointTests {
@Test(expected = IllegalArgumentException.class)
public void absoluteLoginFormUrlCantBeUsedWithForwarding() throws Exception {
final String loginFormUrl = "https://somesite.com/login";
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(
"https://somesite.com/login");
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("https://somesite.com/login");
ep.setUseForward(true);
ep.afterPropertiesSet();
}
}

View File

@@ -62,4 +62,5 @@ public class SavedRequestAwareAuthenticationSuccessHandlerTests {
verify(redirectStrategy).sendRedirect(request, response, redirectUrl);
}
}

View File

@@ -26,7 +26,6 @@ import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.WebAttributes;
/**
*
* @author Luke Taylor
*/
public class SimpleUrlAuthenticationFailureHandlerTests {
@@ -40,8 +39,7 @@ public class SimpleUrlAuthenticationFailureHandlerTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
afh.onAuthenticationFailure(request, response,
mock(AuthenticationException.class));
afh.onAuthenticationFailure(request, response, mock(AuthenticationException.class));
assertThat(response.getStatus()).isEqualTo(401);
}
@@ -61,23 +59,20 @@ public class SimpleUrlAuthenticationFailureHandlerTests {
@Test
public void exceptionIsNotSavedIfAllowSessionCreationIsFalse() throws Exception {
SimpleUrlAuthenticationFailureHandler afh = new SimpleUrlAuthenticationFailureHandler(
"/target");
SimpleUrlAuthenticationFailureHandler afh = new SimpleUrlAuthenticationFailureHandler("/target");
afh.setAllowSessionCreation(false);
assertThat(afh.isAllowSessionCreation()).isFalse();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
afh.onAuthenticationFailure(request, response,
mock(AuthenticationException.class));
afh.onAuthenticationFailure(request, response, mock(AuthenticationException.class));
assertThat(request.getSession(false)).isNull();
}
// SEC-462
@Test
public void responseIsForwardedIfUseForwardIsTrue() throws Exception {
SimpleUrlAuthenticationFailureHandler afh = new SimpleUrlAuthenticationFailureHandler(
"/target");
SimpleUrlAuthenticationFailureHandler afh = new SimpleUrlAuthenticationFailureHandler("/target");
afh.setUseForward(true);
assertThat(afh.isUseForward()).isTrue();

View File

@@ -24,10 +24,10 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.core.Authentication;
/**
*
* @author Luke Taylor
*/
public class SimpleUrlAuthenticationSuccessHandlerTests {
@Test
public void defaultTargetUrlIsUsedIfNoOtherInformationSet() throws Exception {
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler();
@@ -43,8 +43,7 @@ public class SimpleUrlAuthenticationSuccessHandlerTests {
// SEC-1428
@Test
public void redirectIsNotPerformedIfResponseIsCommitted() throws Exception {
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler(
"/target");
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler("/target");
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
response.setCommitted(true);
@@ -58,8 +57,7 @@ public class SimpleUrlAuthenticationSuccessHandlerTests {
*/
@Test
public void targetUrlParameterIsUsedIfPresentAndParameterNameIsSet() throws Exception {
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler(
"/defaultTarget");
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler("/defaultTarget");
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setParameter("targetUrl", "/target");
@@ -76,8 +74,7 @@ public class SimpleUrlAuthenticationSuccessHandlerTests {
@Test
public void refererIsUsedIfUseRefererIsSet() throws Exception {
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler(
"/defaultTarget");
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler("/defaultTarget");
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
ash.setUseReferer(true);
@@ -91,8 +88,7 @@ public class SimpleUrlAuthenticationSuccessHandlerTests {
* SEC-297 fix.
*/
@Test
public void absoluteDefaultTargetUrlDoesNotHaveContextPathPrepended()
throws Exception {
public void absoluteDefaultTargetUrlDoesNotHaveContextPathPrepended() throws Exception {
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler();
ash.setDefaultTargetUrl("https://monkeymachine.co.uk/");
MockHttpServletRequest request = new MockHttpServletRequest();
@@ -129,4 +125,5 @@ public class SimpleUrlAuthenticationSuccessHandlerTests {
catch (IllegalArgumentException success) {
}
}
}

View File

@@ -34,25 +34,21 @@ import org.springframework.security.core.AuthenticationException;
* @author Ben Alex
*/
public class UsernamePasswordAuthenticationFilterTests {
// ~ Methods
// ========================================================================================================
@Test
public void testNormalOperation() {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
request.addParameter(
UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY,
"rod");
request.addParameter(
UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY,
"koala");
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());
Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse());
assertThat(result != null).isTrue();
assertThat(((WebAuthenticationDetails) result.getDetails()).getRemoteAddress()).isEqualTo("127.0.0.1");
}
@@ -60,15 +56,11 @@ public class UsernamePasswordAuthenticationFilterTests {
@Test
public void testConstructorInjectionOfAuthenticationManager() {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
request.addParameter(
UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY,
"rod");
request.addParameter(
UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY,
"dokdo");
request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod");
request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "dokdo");
UsernamePasswordAuthenticationFilter filter =
new UsernamePasswordAuthenticationFilter(createAuthenticationManager());
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter(
createAuthenticationManager());
Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse());
assertThat(result).isNotNull();
@@ -77,27 +69,21 @@ public class UsernamePasswordAuthenticationFilterTests {
@Test
public void testNullPasswordHandledGracefully() {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
request.addParameter(
UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY,
"rod");
request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod");
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
filter.setAuthenticationManager(createAuthenticationManager());
assertThat(filter
.attemptAuthentication(request, new MockHttpServletResponse())).isNotNull();
assertThat(filter.attemptAuthentication(request, new MockHttpServletResponse())).isNotNull();
}
@Test
public void testNullUsernameHandledGracefully() {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
request.addParameter(
UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY,
"koala");
request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "koala");
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
filter.setAuthenticationManager(createAuthenticationManager());
assertThat(filter
.attemptAuthentication(request, new MockHttpServletResponse())).isNotNull();
assertThat(filter.attemptAuthentication(request, new MockHttpServletResponse())).isNotNull();
}
@Test
@@ -111,8 +97,7 @@ public class UsernamePasswordAuthenticationFilterTests {
request.addParameter("x", "rod");
request.addParameter("y", "koala");
Authentication result = filter.attemptAuthentication(request,
new MockHttpServletResponse());
Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse());
assertThat(result).isNotNull();
assertThat(((WebAuthenticationDetails) result.getDetails()).getRemoteAddress()).isEqualTo("127.0.0.1");
}
@@ -120,31 +105,23 @@ public class UsernamePasswordAuthenticationFilterTests {
@Test
public void testSpacesAreTrimmedCorrectlyFromUsername() {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
request.addParameter(
UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY,
" rod ");
request.addParameter(
UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY,
"koala");
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());
Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse());
assertThat(result.getName()).isEqualTo("rod");
}
@Test
public void testFailedAuthenticationThrowsException() {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
request.addParameter(
UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY,
"rod");
request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod");
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenThrow(
new BadCredentialsException(""));
when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException(""));
filter.setAuthenticationManager(am);
try {
@@ -174,8 +151,8 @@ public class UsernamePasswordAuthenticationFilterTests {
private AuthenticationManager createAuthenticationManager() {
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenAnswer(
(Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
when(am.authenticate(any(Authentication.class)))
.thenAnswer((Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
return am;
}

View File

@@ -64,8 +64,10 @@ public class CompositeLogoutHandlerTests {
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), any(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),
any(Authentication.class));
}
@Test
@@ -78,8 +80,10 @@ public class CompositeLogoutHandlerTests {
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), any(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),
any(Authentication.class));
}
@Test
@@ -87,7 +91,8 @@ public class CompositeLogoutHandlerTests {
LogoutHandler firstLogoutHandler = mock(LogoutHandler.class);
LogoutHandler secondLogoutHandler = mock(LogoutHandler.class);
doThrow(new IllegalArgumentException()).when(firstLogoutHandler).logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class));
doThrow(new IllegalArgumentException()).when(firstLogoutHandler).logout(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(Authentication.class));
List<LogoutHandler> logoutHandlers = Arrays.asList(firstLogoutHandler, secondLogoutHandler);
LogoutHandler handler = new CompositeLogoutHandler(logoutHandlers);
@@ -95,13 +100,16 @@ public class CompositeLogoutHandlerTests {
try {
handler.logout(mock(HttpServletRequest.class), mock(HttpServletResponse.class), mock(Authentication.class));
fail("Expected Exception");
} catch (IllegalArgumentException success) {
}
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), any(HttpServletResponse.class), any(Authentication.class));
logoutHandlersInOrder.verify(firstLogoutHandler, times(1)).logout(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(Authentication.class));
logoutHandlersInOrder.verify(secondLogoutHandler, never()).logout(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(Authentication.class));
}
}

View File

@@ -51,8 +51,7 @@ public class CookieClearingLogoutHandlerTests {
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContextPath("/app");
CookieClearingLogoutHandler handler = new CookieClearingLogoutHandler(
"my_cookie", "my_cookie_too");
CookieClearingLogoutHandler handler = new CookieClearingLogoutHandler("my_cookie", "my_cookie_too");
handler.logout(request, response, mock(Authentication.class));
assertThat(response.getCookies()).hasSize(2);
for (Cookie c : response.getCookies()) {
@@ -106,7 +105,7 @@ public class CookieClearingLogoutHandlerTests {
}
}
@Test(expected=IllegalArgumentException.class)
@Test(expected = IllegalArgumentException.class)
public void invalidAge() {
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest();
@@ -117,4 +116,5 @@ public class CookieClearingLogoutHandlerTests {
CookieClearingLogoutHandler handler = new CookieClearingLogoutHandler(cookie1);
handler.logout(request, response, mock(Authentication.class));
}
}

View File

@@ -44,18 +44,25 @@ public class DelegatingLogoutSuccessHandlerTests {
@Mock
RequestMatcher matcher;
@Mock
RequestMatcher matcher2;
@Mock
LogoutSuccessHandler handler;
@Mock
LogoutSuccessHandler handler2;
@Mock
LogoutSuccessHandler defaultHandler;
@Mock
HttpServletRequest request;
@Mock
MockHttpServletResponse response;
@Mock
Authentication authentication;
@@ -74,11 +81,9 @@ public class DelegatingLogoutSuccessHandlerTests {
this.delegatingHandler.setDefaultLogoutSuccessHandler(this.defaultHandler);
when(this.matcher.matches(this.request)).thenReturn(true);
this.delegatingHandler.onLogoutSuccess(this.request, this.response,
this.authentication);
this.delegatingHandler.onLogoutSuccess(this.request, this.response, this.authentication);
verify(this.handler).onLogoutSuccess(this.request, this.response,
this.authentication);
verify(this.handler).onLogoutSuccess(this.request, this.response, this.authentication);
verifyZeroInteractions(this.matcher2, this.handler2, this.defaultHandler);
}
@@ -87,11 +92,9 @@ public class DelegatingLogoutSuccessHandlerTests {
this.delegatingHandler.setDefaultLogoutSuccessHandler(this.defaultHandler);
when(this.matcher2.matches(this.request)).thenReturn(true);
this.delegatingHandler.onLogoutSuccess(this.request, this.response,
this.authentication);
this.delegatingHandler.onLogoutSuccess(this.request, this.response, this.authentication);
verify(this.handler2).onLogoutSuccess(this.request, this.response,
this.authentication);
verify(this.handler2).onLogoutSuccess(this.request, this.response, this.authentication);
verifyZeroInteractions(this.handler, this.defaultHandler);
}
@@ -99,20 +102,18 @@ public class DelegatingLogoutSuccessHandlerTests {
public void onLogoutSuccessDefault() throws Exception {
this.delegatingHandler.setDefaultLogoutSuccessHandler(this.defaultHandler);
this.delegatingHandler.onLogoutSuccess(this.request, this.response,
this.authentication);
this.delegatingHandler.onLogoutSuccess(this.request, this.response, this.authentication);
verify(this.defaultHandler).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);
this.delegatingHandler.onLogoutSuccess(this.request, this.response, this.authentication);
verifyZeroInteractions(this.handler, this.handler2, this.defaultHandler);
}
}

View File

@@ -30,14 +30,14 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
*
* @author Rafiullah Hamedy
* @author Josh Cummings
*
* @see {@link HeaderWriterLogoutHandler}
*/
public class HeaderWriterLogoutHandlerTests {
private MockHttpServletResponse response;
private MockHttpServletRequest request;
@Rule
@@ -65,4 +65,5 @@ public class HeaderWriterLogoutHandlerTests {
verify(headerWriter).writeHeaders(this.request, this.response);
}
}

View File

@@ -29,7 +29,9 @@ import org.springframework.security.web.firewall.DefaultHttpFirewall;
* @author Luke Taylor
*/
public class LogoutHandlerTests {
LogoutFilter filter;
@Before
public void setUp() {
filter = new LogoutFilter("/success", new SecurityContextLogoutHandler());

View File

@@ -63,5 +63,7 @@ public class LogoutSuccessEventPublishingLogoutHandlerTests {
flag = true;
}
}
}
}

View File

@@ -29,13 +29,15 @@ import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
/**
*
* @author Rob Winch
*
*/
public class SecurityContextLogoutHandlerTests {
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private SecurityContextLogoutHandler handler;
@Before
@@ -46,8 +48,8 @@ public class SecurityContextLogoutHandlerTests {
handler = new SecurityContextLogoutHandler();
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(new TestingAuthenticationToken("user", "password",
AuthorityUtils.createAuthorityList("ROLE_USER")));
context.setAuthentication(
new TestingAuthenticationToken("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER")));
SecurityContextHolder.setContext(context);
}
@@ -60,8 +62,7 @@ public class SecurityContextLogoutHandlerTests {
@Test
public void clearsAuthentication() {
SecurityContext beforeContext = SecurityContextHolder.getContext();
handler.logout(request, response, SecurityContextHolder.getContext()
.getAuthentication());
handler.logout(request, response, SecurityContextHolder.getContext().getAuthentication());
assertThat(beforeContext.getAuthentication()).isNull();
}
@@ -70,10 +71,10 @@ public class SecurityContextLogoutHandlerTests {
handler.setClearAuthentication(false);
SecurityContext beforeContext = SecurityContextHolder.getContext();
Authentication beforeAuthentication = beforeContext.getAuthentication();
handler.logout(request, response, SecurityContextHolder.getContext()
.getAuthentication());
handler.logout(request, response, SecurityContextHolder.getContext().getAuthentication());
assertThat(beforeContext.getAuthentication()).isNotNull();
assertThat(beforeContext.getAuthentication()).isSameAs(beforeAuthentication);
}
}

View File

@@ -24,7 +24,6 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.core.Authentication;
/**
*
* @author Luke Taylor
*/
public class SimpleUrlLogoutSuccessHandlerTests {

View File

@@ -48,12 +48,12 @@ import org.springframework.security.web.authentication.ForwardAuthenticationSucc
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
/**
*
* @author Rob Winch
* @author Tadaya Tsuyukubo
*
*/
public class AbstractPreAuthenticatedProcessingFilterTests {
private AbstractPreAuthenticatedProcessingFilter filter;
@Before
@@ -78,12 +78,10 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
@Test
public void filterChainProceedsOnFailedAuthenticationByDefault() throws Exception {
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenThrow(
new BadCredentialsException(""));
when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException(""));
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(),
mock(FilterChain.class));
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), mock(FilterChain.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -92,13 +90,11 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
public void exceptionIsThrownOnFailedAuthenticationIfContinueFilterChainOnUnsuccessfulAuthenticationSetToFalse()
throws Exception {
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenThrow(
new BadCredentialsException(""));
when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException(""));
filter.setContinueFilterChainOnUnsuccessfulAuthentication(false);
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(),
mock(FilterChain.class));
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), mock(FilterChain.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -139,39 +135,34 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
// SEC-1968
@Test
public void nullPreAuthenticationClearsPreviousUser() throws Exception {
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken("oldUser", "pass", "ROLE_USER"));
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("oldUser", "pass", "ROLE_USER"));
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
filter.principal = null;
filter.setCheckForPrincipalChanges(true);
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(),
new MockFilterChain());
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void nullPreAuthenticationPerservesPreviousUserCheckPrincipalChangesFalse()
throws Exception {
TestingAuthenticationToken authentication = new TestingAuthenticationToken(
"oldUser", "pass", "ROLE_USER");
public void nullPreAuthenticationPerservesPreviousUserCheckPrincipalChangesFalse() throws Exception {
TestingAuthenticationToken authentication = new TestingAuthenticationToken("oldUser", "pass", "ROLE_USER");
SecurityContextHolder.getContext().setAuthentication(authentication);
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
filter.principal = null;
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(),
new MockFilterChain());
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isEqualTo(
authentication);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isEqualTo(authentication);
}
@Test
public void requiresAuthenticationFalsePrincipalString() throws Exception {
Object principal = "sameprincipal";
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken(principal, "something", "ROLE_USER"));
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken(principal, "something", "ROLE_USER"));
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
@@ -191,8 +182,8 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
@Test
public void requiresAuthenticationTruePrincipalString() throws Exception {
Object currentPrincipal = "currentUser";
TestingAuthenticationToken authRequest = new TestingAuthenticationToken(
currentPrincipal, "something", "ROLE_USER");
TestingAuthenticationToken authRequest = new TestingAuthenticationToken(currentPrincipal, "something",
"ROLE_USER");
SecurityContextHolder.getContext().setAuthentication(authRequest);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -213,8 +204,8 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
@Test
public void callsAuthenticationSuccessHandlerOnSuccessfulAuthentication() throws Exception {
Object currentPrincipal = "currentUser";
TestingAuthenticationToken authRequest = new TestingAuthenticationToken(
currentPrincipal, "something", "ROLE_USER");
TestingAuthenticationToken authRequest = new TestingAuthenticationToken(currentPrincipal, "something",
"ROLE_USER");
SecurityContextHolder.getContext().setAuthentication(authRequest);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -244,7 +235,8 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
filter.setAuthenticationFailureHandler(new ForwardAuthenticationFailureHandler("/forwardUrl"));
filter.setCheckForPrincipalChanges(true);
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(PreAuthenticatedAuthenticationToken.class))).thenThrow(new PreAuthenticatedCredentialsNotFoundException("invalid"));
when(am.authenticate(any(PreAuthenticatedAuthenticationToken.class)))
.thenThrow(new PreAuthenticatedCredentialsNotFoundException("invalid"));
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
@@ -259,8 +251,8 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
@Test
public void requiresAuthenticationFalsePrincipalNotString() throws Exception {
Object principal = new Object();
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken(principal, "something", "ROLE_USER"));
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken(principal, "something", "ROLE_USER"));
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
@@ -279,11 +271,9 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
@Test
public void requiresAuthenticationFalsePrincipalUser() throws Exception {
User currentPrincipal = new User("user", "password",
AuthorityUtils.createAuthorityList("ROLE_USER"));
User currentPrincipal = new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER"));
UsernamePasswordAuthenticationToken currentAuthentication = new UsernamePasswordAuthenticationToken(
currentPrincipal, currentPrincipal.getPassword(),
currentPrincipal.getAuthorities());
currentPrincipal, currentPrincipal.getPassword(), currentPrincipal.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(currentAuthentication);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -291,8 +281,8 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
filter.setCheckForPrincipalChanges(true);
filter.principal = new User(currentPrincipal.getUsername(),
currentPrincipal.getPassword(), AuthorityUtils.NO_AUTHORITIES);
filter.principal = new User(currentPrincipal.getUsername(), currentPrincipal.getPassword(),
AuthorityUtils.NO_AUTHORITIES);
AuthenticationManager am = mock(AuthenticationManager.class);
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
@@ -305,8 +295,8 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
@Test
public void requiresAuthenticationTruePrincipalNotString() throws Exception {
Object currentPrincipal = new Object();
TestingAuthenticationToken authRequest = new TestingAuthenticationToken(
currentPrincipal, "something", "ROLE_USER");
TestingAuthenticationToken authRequest = new TestingAuthenticationToken(currentPrincipal, "something",
"ROLE_USER");
SecurityContextHolder.getContext().setAuthentication(authRequest);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -327,16 +317,15 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
@Test
public void requiresAuthenticationOverridePrincipalChangedTrue() throws Exception {
Object principal = new Object();
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken(principal, "something", "ROLE_USER"));
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken(principal, "something", "ROLE_USER"));
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter() {
@Override
protected boolean principalChanged(HttpServletRequest request,
Authentication currentAuthentication) {
protected boolean principalChanged(HttpServletRequest request, Authentication currentAuthentication) {
return true;
}
};
@@ -354,16 +343,15 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
@Test
public void requiresAuthenticationOverridePrincipalChangedFalse() throws Exception {
Object principal = new Object();
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken(principal, "something", "ROLE_USER"));
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken(principal, "something", "ROLE_USER"));
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter() {
@Override
protected boolean principalChanged(HttpServletRequest request,
Authentication currentAuthentication) {
protected boolean principalChanged(HttpServletRequest request, Authentication currentAuthentication) {
return false;
}
};
@@ -419,8 +407,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
MockHttpServletRequest req = new MockHttpServletRequest();
MockHttpServletResponse res = new MockHttpServletResponse();
getFilter(grantAccess).doFilter(req, res, new MockFilterChain());
assertThat(null != SecurityContextHolder.getContext().getAuthentication()).isEqualTo(
grantAccess);
assertThat(null != SecurityContextHolder.getContext().getAuthentication()).isEqualTo(grantAccess);
}
private static ConcretePreAuthenticatedProcessingFilter getFilter(boolean grantAccess) {
@@ -428,12 +415,11 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
AuthenticationManager am = mock(AuthenticationManager.class);
if (!grantAccess) {
when(am.authenticate(any(Authentication.class))).thenThrow(
new BadCredentialsException(""));
when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException(""));
}
else {
when(am.authenticate(any(Authentication.class))).thenAnswer(
(Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
when(am.authenticate(any(Authentication.class)))
.thenAnswer((Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
}
filter.setAuthenticationManager(am);
@@ -441,9 +427,10 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
return filter;
}
private static class ConcretePreAuthenticatedProcessingFilter extends
AbstractPreAuthenticatedProcessingFilter {
private static class ConcretePreAuthenticatedProcessingFilter extends AbstractPreAuthenticatedProcessingFilter {
private Object principal = "testPrincipal";
private boolean initFilterBeanInvoked;
protected Object getPreAuthenticatedPrincipal(HttpServletRequest httpRequest) {
@@ -459,6 +446,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
super.initFilterBean();
initFilterBeanInvoked = true;
}
}
}

View File

@@ -34,13 +34,13 @@ public class Http403ForbiddenEntryPointTests {
MockHttpServletResponse resp = new MockHttpServletResponse();
Http403ForbiddenEntryPoint fep = new Http403ForbiddenEntryPoint();
try {
fep.commence(req, resp,
new AuthenticationCredentialsNotFoundException("test"));
assertThat(resp.getStatus()).withFailMessage("Incorrect status").isEqualTo(
HttpServletResponse.SC_FORBIDDEN);
fep.commence(req, resp, new AuthenticationCredentialsNotFoundException("test"));
assertThat(resp.getStatus()).withFailMessage("Incorrect status")
.isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
catch (IOException e) {
fail("Unexpected exception thrown: " + e);
}
}
}

View File

@@ -27,7 +27,6 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
/**
*
* @author TSARDD
* @since 18-okt-2007
*/
@@ -42,11 +41,9 @@ public class PreAuthenticatedAuthenticationProviderTests {
@Test
public final void authenticateInvalidToken() throws Exception {
UserDetails ud = new User("dummyUser", "dummyPwd", true, true, true, true,
AuthorityUtils.NO_AUTHORITIES);
UserDetails ud = new User("dummyUser", "dummyPwd", true, true, true, true, AuthorityUtils.NO_AUTHORITIES);
PreAuthenticatedAuthenticationProvider provider = getProvider(ud);
Authentication request = new UsernamePasswordAuthenticationToken("dummyUser",
"dummyPwd");
Authentication request = new UsernamePasswordAuthenticationToken("dummyUser", "dummyPwd");
Authentication result = provider.authenticate(request);
assertThat(result).isNull();
}
@@ -54,19 +51,16 @@ public class PreAuthenticatedAuthenticationProviderTests {
@Test
public final void nullPrincipalReturnsNullAuthentication() {
PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
Authentication request = new PreAuthenticatedAuthenticationToken(null,
"dummyPwd");
Authentication request = new PreAuthenticatedAuthenticationToken(null, "dummyPwd");
Authentication result = provider.authenticate(request);
assertThat(result).isNull();
}
@Test
public final void authenticateKnownUser() throws Exception {
UserDetails ud = new User("dummyUser", "dummyPwd", true, true, true, true,
AuthorityUtils.NO_AUTHORITIES);
UserDetails ud = new User("dummyUser", "dummyPwd", true, true, true, true, AuthorityUtils.NO_AUTHORITIES);
PreAuthenticatedAuthenticationProvider provider = getProvider(ud);
Authentication request = new PreAuthenticatedAuthenticationToken("dummyUser",
"dummyPwd");
Authentication request = new PreAuthenticatedAuthenticationToken("dummyUser", "dummyPwd");
Authentication result = provider.authenticate(request);
assertThat(result).isNotNull();
assertThat(ud).isEqualTo(result.getPrincipal());
@@ -75,11 +69,9 @@ public class PreAuthenticatedAuthenticationProviderTests {
@Test
public final void authenticateIgnoreCredentials() throws Exception {
UserDetails ud = new User("dummyUser1", "dummyPwd1", true, true, true, true,
AuthorityUtils.NO_AUTHORITIES);
UserDetails ud = new User("dummyUser1", "dummyPwd1", true, true, true, true, AuthorityUtils.NO_AUTHORITIES);
PreAuthenticatedAuthenticationProvider provider = getProvider(ud);
Authentication request = new PreAuthenticatedAuthenticationToken("dummyUser1",
"dummyPwd2");
Authentication request = new PreAuthenticatedAuthenticationToken("dummyUser1", "dummyPwd2");
Authentication result = provider.authenticate(request);
assertThat(result).isNotNull();
assertThat(ud).isEqualTo(result.getPrincipal());
@@ -88,11 +80,9 @@ public class PreAuthenticatedAuthenticationProviderTests {
@Test(expected = UsernameNotFoundException.class)
public final void authenticateUnknownUserThrowsException() throws Exception {
UserDetails ud = new User("dummyUser1", "dummyPwd", true, true, true, true,
AuthorityUtils.NO_AUTHORITIES);
UserDetails ud = new User("dummyUser1", "dummyPwd", true, true, true, true, AuthorityUtils.NO_AUTHORITIES);
PreAuthenticatedAuthenticationProvider provider = getProvider(ud);
Authentication request = new PreAuthenticatedAuthenticationToken("dummyUser2",
"dummyPwd");
Authentication request = new PreAuthenticatedAuthenticationToken("dummyUser2", "dummyPwd");
provider.authenticate(request);
}
@@ -117,8 +107,7 @@ public class PreAuthenticatedAuthenticationProviderTests {
private PreAuthenticatedAuthenticationProvider getProvider(UserDetails aUserDetails) {
PreAuthenticatedAuthenticationProvider result = new PreAuthenticatedAuthenticationProvider();
result.setPreAuthenticatedUserDetailsService(
getPreAuthenticatedUserDetailsService(aUserDetails));
result.setPreAuthenticatedUserDetailsService(getPreAuthenticatedUserDetailsService(aUserDetails));
result.afterPropertiesSet();
return result;
}
@@ -126,8 +115,7 @@ public class PreAuthenticatedAuthenticationProviderTests {
private AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> getPreAuthenticatedUserDetailsService(
final UserDetails aUserDetails) {
return token -> {
if (aUserDetails != null
&& aUserDetails.getUsername().equals(token.getName())) {
if (aUserDetails != null && aUserDetails.getUsername().equals(token.getName())) {
return aUserDetails;
}

View File

@@ -25,7 +25,6 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
/**
*
* @author TSARDD
* @since 18-okt-2007
*/
@@ -36,8 +35,7 @@ public class PreAuthenticatedAuthenticationTokenTests {
Object principal = "dummyUser";
Object credentials = "dummyCredentials";
Object details = "dummyDetails";
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
principal, credentials);
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, credentials);
token.setDetails(details);
assertThat(token.getPrincipal()).isEqualTo(principal);
assertThat(token.getCredentials()).isEqualTo(credentials);
@@ -49,8 +47,7 @@ public class PreAuthenticatedAuthenticationTokenTests {
public void testPreAuthenticatedAuthenticationTokenRequestWithoutDetails() {
Object principal = "dummyUser";
Object credentials = "dummyCredentials";
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
principal, credentials);
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, credentials);
assertThat(token.getPrincipal()).isEqualTo(principal);
assertThat(token.getCredentials()).isEqualTo(credentials);
assertThat(token.getDetails()).isNull();
@@ -62,8 +59,8 @@ public class PreAuthenticatedAuthenticationTokenTests {
Object principal = "dummyUser";
Object credentials = "dummyCredentials";
List<GrantedAuthority> gas = AuthorityUtils.createAuthorityList("Role1");
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
principal, credentials, gas);
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, credentials,
gas);
assertThat(token.getPrincipal()).isEqualTo(principal);
assertThat(token.getCredentials()).isEqualTo(credentials);
assertThat(token.getDetails()).isNull();
@@ -71,9 +68,9 @@ public class PreAuthenticatedAuthenticationTokenTests {
Collection<GrantedAuthority> resultColl = token.getAuthorities();
assertThat(
gas.containsAll(resultColl) && resultColl.containsAll(gas)).withFailMessage(
"GrantedAuthority collections do not match; result: " + resultColl
+ ", expected: " + gas).isTrue();
gas.containsAll(resultColl) && resultColl.containsAll(gas)).withFailMessage(
"GrantedAuthority collections do not match; result: " + resultColl + ", expected: " + gas)
.isTrue();
}

View File

@@ -26,7 +26,6 @@ import org.springframework.security.core.authority.GrantedAuthoritiesContainer;
import org.springframework.security.core.userdetails.UserDetails;
/**
*
* @author TSARDD
* @since 18-okt-2007
*/
@@ -35,8 +34,7 @@ public class PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests {
@Test(expected = IllegalArgumentException.class)
public void testGetUserDetailsInvalidType() {
PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
"dummy", "dummy");
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken("dummy", "dummy");
token.setDetails(new Object());
svc.loadUserDetails(token);
}
@@ -44,8 +42,7 @@ public class PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests {
@Test(expected = IllegalArgumentException.class)
public void testGetUserDetailsNoDetails() {
PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
"dummy", "dummy");
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken("dummy", "dummy");
token.setDetails(null);
svc.loadUserDetails(token);
}
@@ -62,11 +59,9 @@ public class PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests {
testGetUserDetails(userName, AuthorityUtils.createAuthorityList("Role1", "Role2"));
}
private void testGetUserDetails(final String userName,
final List<GrantedAuthority> gas) {
private void testGetUserDetails(final String userName, final List<GrantedAuthority> gas) {
PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
userName, "dummy");
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(userName, "dummy");
token.setDetails((GrantedAuthoritiesContainer) () -> gas);
UserDetails ud = svc.loadUserDetails(token);
assertThat(ud.isAccountNonExpired()).isTrue();
@@ -79,8 +74,9 @@ public class PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests {
// 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();
assertThat(gas.containsAll(ud.getAuthorities()) && ud.getAuthorities().containsAll(gas)).withFailMessage(
"GrantedAuthority collections do not match; result: " + ud.getAuthorities() + ", expected: " + gas)
.isTrue();
}
}

View File

@@ -32,6 +32,7 @@ import java.util.Set;
* @author TSARDD
*/
public class PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests {
List<GrantedAuthority> gas = AuthorityUtils.createAuthorityList("Role1", "Role2");
@Test
@@ -49,8 +50,9 @@ public class PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests {
getRequest("testUser", new String[] {}), gas);
List<GrantedAuthority> returnedGas = details.getGrantedAuthorities();
assertThat(gas.containsAll(returnedGas) && returnedGas.containsAll(gas))
.withFailMessage("Collections do not contain same elements; expected: " + gas
+ ", returned: " + returnedGas).isTrue();
.withFailMessage(
"Collections do not contain same elements; expected: " + gas + ", returned: " + returnedGas)
.isTrue();
}
private HttpServletRequest getRequest(final String userName, final String[] aRoles) {

View File

@@ -30,7 +30,6 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
/**
*
* @author Milan Sevcik
*/
public class RequestAttributeAuthenticationFilterTests {
@@ -62,11 +61,8 @@ public class RequestAttributeAuthenticationFilterTests {
filter.doFilter(request, response, chain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName())
.isEqualTo("cat");
assertThat(
SecurityContextHolder.getContext().getAuthentication().getCredentials())
.isEqualTo("N/A");
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("cat");
assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("N/A");
}
@Test
@@ -81,8 +77,7 @@ public class RequestAttributeAuthenticationFilterTests {
filter.doFilter(request, response, chain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName())
.isEqualTo("wolfman");
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("wolfman");
}
@Test
@@ -98,14 +93,11 @@ public class RequestAttributeAuthenticationFilterTests {
filter.doFilter(request, response, chain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(
SecurityContextHolder.getContext().getAuthentication().getCredentials())
.isEqualTo("catspassword");
assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("catspassword");
}
@Test
public void userIsReauthenticatedIfPrincipalChangesAndCheckForPrincipalChangesIsSet()
throws Exception {
public void userIsReauthenticatedIfPrincipalChangesAndCheckForPrincipalChangesIsSet() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
RequestAttributeAuthenticationFilter filter = new RequestAttributeAuthenticationFilter();
@@ -139,8 +131,7 @@ public class RequestAttributeAuthenticationFilterTests {
}
@Test
public void missingHeaderIsIgnoredIfExceptionIfHeaderMissingIsFalse()
throws Exception {
public void missingHeaderIsIgnoredIfExceptionIfHeaderMissingIsFalse() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
@@ -160,4 +151,5 @@ public class RequestAttributeAuthenticationFilterTests {
return am;
}
}

View File

@@ -32,7 +32,6 @@ import org.springframework.security.web.authentication.preauth.PreAuthenticatedC
import org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter;
/**
*
* @author Luke Taylor
*/
public class RequestHeaderAuthenticationFilterTests {
@@ -100,8 +99,7 @@ public class RequestHeaderAuthenticationFilterTests {
}
@Test
public void userIsReauthenticatedIfPrincipalChangesAndCheckForPrincipalChangesIsSet()
throws Exception {
public void userIsReauthenticatedIfPrincipalChangesAndCheckForPrincipalChangesIsSet() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
@@ -134,8 +132,7 @@ public class RequestHeaderAuthenticationFilterTests {
}
@Test
public void missingHeaderIsIgnoredIfExceptionIfHeaderMissingIsFalse()
throws Exception {
public void missingHeaderIsIgnoredIfExceptionIfHeaderMissingIsFalse() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
@@ -150,9 +147,10 @@ public class RequestHeaderAuthenticationFilterTests {
*/
private AuthenticationManager createAuthenticationManager() {
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenAnswer(
(Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
when(am.authenticate(any(Authentication.class)))
.thenAnswer((Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
return am;
}
}

View File

@@ -36,7 +36,6 @@ import org.springframework.security.core.authority.mapping.SimpleMappableAttribu
import org.springframework.security.web.authentication.preauth.PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails;
/**
*
* @author TSARDD
*/
public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests {
@@ -111,16 +110,15 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests {
testDetails(mappedRoles, roles, expectedRoles);
}
private void testDetails(String[] mappedRoles, String[] userRoles,
String[] expectedRoles) {
private void testDetails(String[] mappedRoles, String[] userRoles, String[] expectedRoles) {
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource src = getJ2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(
mappedRoles);
Object o = src.buildDetails(getRequest("testUser", userRoles));
assertThat(o).isNotNull();
assertThat(
o instanceof PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails).withFailMessage(
"Returned object not of type PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails, actual type: "
+ o.getClass()).isTrue();
assertThat(o instanceof PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails).withFailMessage(
"Returned object not of type PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails, actual type: "
+ o.getClass())
.isTrue();
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = (PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails) o;
List<GrantedAuthority> gas = details.getGrantedAuthorities();
assertThat(gas).as("Granted authorities should not be null").isNotNull();
@@ -131,17 +129,15 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests {
for (GrantedAuthority grantedAuthority : gas) {
gasRolesSet.add(grantedAuthority.getAuthority());
}
assertThat(expectedRolesColl.containsAll(gasRolesSet)
&& gasRolesSet.containsAll(expectedRolesColl)).withFailMessage(
"Granted Authorities do not match expected roles").isTrue();
assertThat(expectedRolesColl.containsAll(gasRolesSet) && gasRolesSet.containsAll(expectedRolesColl))
.withFailMessage("Granted Authorities do not match expected roles").isTrue();
}
private J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource getJ2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(
String[] mappedRoles) {
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource result = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource();
result.setMappableRolesRetriever(getMappableRolesRetriever(mappedRoles));
result.setUserRoles2GrantedAuthoritiesMapper(
getJ2eeUserRoles2GrantedAuthoritiesMapper());
result.setUserRoles2GrantedAuthoritiesMapper(getJ2eeUserRoles2GrantedAuthoritiesMapper());
try {
result.afterPropertiesSet();
@@ -179,4 +175,5 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests {
req.setRemoteUser(userName);
return req;
}
}

View File

@@ -27,7 +27,6 @@ import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
/**
*
* @author TSARDD
* @since 18-okt-2007
*/
@@ -36,20 +35,17 @@ public class J2eePreAuthenticatedProcessingFilterTests {
@Test
public final void testGetPreAuthenticatedPrincipal() {
String user = "testUser";
assertThat(user).isEqualTo(
new J2eePreAuthenticatedProcessingFilter().getPreAuthenticatedPrincipal(
getRequest(user, new String[] {})));
assertThat(user).isEqualTo(new J2eePreAuthenticatedProcessingFilter()
.getPreAuthenticatedPrincipal(getRequest(user, new String[] {})));
}
@Test
public final void testGetPreAuthenticatedCredentials() {
assertThat("N/A").isEqualTo(
new J2eePreAuthenticatedProcessingFilter().getPreAuthenticatedCredentials(
getRequest("testUser", new String[] {})));
assertThat("N/A").isEqualTo(new J2eePreAuthenticatedProcessingFilter()
.getPreAuthenticatedCredentials(getRequest("testUser", new String[] {})));
}
private HttpServletRequest getRequest(final String aUserName,
final String[] aRoles) {
private HttpServletRequest getRequest(final String aUserName, final String[] aRoles) {
MockHttpServletRequest req = new MockHttpServletRequest() {
private Set<String> roles = new HashSet<>(Arrays.asList(aRoles));

View File

@@ -30,8 +30,7 @@ public class WebXmlJ2eeDefinedRolesRetrieverTests {
@Test
public void testRole1To4Roles() throws Exception {
List<String> ROLE1TO4_EXPECTED_ROLES = Arrays.asList("Role1",
"Role2", "Role3", "Role4");
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();
@@ -67,4 +66,5 @@ public class WebXmlJ2eeDefinedRolesRetrieverTests {
Set<String> j2eeRoles = rolesRetriever.getMappableAttributes();
assertThat(j2eeRoles).isEmpty();
}
}

View File

@@ -46,16 +46,13 @@ public class WebSpherePreAuthenticatedProcessingFilterTests {
new WebSpherePreAuthenticatedProcessingFilter();
WASUsernameAndGroupsExtractor helper = mock(WASUsernameAndGroupsExtractor.class);
when(helper.getCurrentUserName()).thenReturn("jerry");
WebSpherePreAuthenticatedProcessingFilter filter = new WebSpherePreAuthenticatedProcessingFilter(
helper);
assertThat(filter.getPreAuthenticatedPrincipal(new MockHttpServletRequest())).isEqualTo(
"jerry");
assertThat(filter.getPreAuthenticatedCredentials(new MockHttpServletRequest())).isEqualTo(
"N/A");
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);
when(am.authenticate(any(Authentication.class))).thenAnswer(
(Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
when(am.authenticate(any(Authentication.class)))
.thenAnswer((Answer<Authentication>) invocation -> (Authentication) invocation.getArguments()[0]);
filter.setAuthenticationManager(am);
WebSpherePreAuthenticatedWebAuthenticationDetailsSource ads = new WebSpherePreAuthenticatedWebAuthenticationDetailsSource(
@@ -63,8 +60,7 @@ public class WebSpherePreAuthenticatedProcessingFilterTests {
ads.setWebSphereGroups2GrantedAuthoritiesMapper(new SimpleAttributes2GrantedAuthoritiesMapper());
filter.setAuthenticationDetailsSource(ads);
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(),
mock(FilterChain.class));
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), mock(FilterChain.class));
}
}

View File

@@ -28,6 +28,7 @@ import org.junit.Before;
* @author Luke Taylor
*/
public class SubjectDnX509PrincipalExtractorTests {
SubjectDnX509PrincipalExtractor extractor;
@Before
@@ -43,16 +44,14 @@ public class SubjectDnX509PrincipalExtractorTests {
@Test
public void defaultCNPatternReturnsExcpectedPrincipal() throws Exception {
Object principal = extractor.extractPrincipal(X509TestUtils
.buildTestCertificate());
Object principal = extractor.extractPrincipal(X509TestUtils.buildTestCertificate());
assertThat(principal).isEqualTo("Luke Taylor");
}
@Test
public void matchOnEmailReturnsExpectedPrincipal() throws Exception {
extractor.setSubjectDnRegex("emailAddress=(.*?),");
Object principal = extractor.extractPrincipal(X509TestUtils
.buildTestCertificate());
Object principal = extractor.extractPrincipal(X509TestUtils.buildTestCertificate());
assertThat(principal).isEqualTo("luke@monkeymachine");
}
@@ -64,8 +63,8 @@ public class SubjectDnX509PrincipalExtractorTests {
@Test
public void defaultCNPatternReturnsPrincipalAtEndOfDNString() throws Exception {
Object principal = extractor.extractPrincipal(X509TestUtils
.buildTestCertificateWithCnAtEnd());
Object principal = extractor.extractPrincipal(X509TestUtils.buildTestCertificateWithCnAtEnd());
assertThat(principal).isEqualTo("Duke");
}
}

View File

@@ -26,6 +26,7 @@ import java.security.cert.X509Certificate;
* @author Luke Taylor
*/
public class X509TestUtils {
// ~ Methods
// ========================================================================================================
@@ -92,8 +93,7 @@ public class X509TestUtils {
+ "nRB3QPZfRvop0I4oPvwViKt3puLsi9XSSJ1w9yswnIf89iONT7ZyssPg48Bojo8q\n"
+ "lcKwXuDRBWciODK/xWhvQbaegGJ1BtXcEHtvNjrUJLwSMDSr+U5oUYdMohG0h1iJ\n"
+ "R+JQc49I33o2cTc77wfEWLtVdXAyYY4GSJR6VfgvV40x85ItaNS3HHfT/aXU1x4m\n"
+ "W9YQkWlA6t0blGlC+ghTOY1JbgWnEfXMmVgg9a9cWaYQ+NQwqA==\n"
+ "-----END CERTIFICATE-----";
+ "W9YQkWlA6t0blGlC+ghTOY1JbgWnEfXMmVgg9a9cWaYQ+NQwqA==\n" + "-----END CERTIFICATE-----";
ByteArrayInputStream in = new ByteArrayInputStream(cert.getBytes());
CertificateFactory cf = CertificateFactory.getInstance("X.509");
@@ -130,11 +130,12 @@ public class X509TestUtils {
+ "MOvaw6wSSkmEoEvdek3s/bH6Gp0spnykqtb+kunGr/XFxyBhHmfdSroEgzspslFh\n"
+ "Glqe/XfrQmFgPWd13GH8mqzSU1zc+0Ka7s68jcuNfz9ble5rT0IrdjRm5E64mVGk\n"
+ "aJTAO5N87ks5JjkDHDJzcyYRcIpqBGotJtyZTjGpIeAG8xLGlkSsUg88iUOchI7s\n"
+ "dOmse9mpgEjCb4kdZ0PnoxMFjsPR8AoGOz4A5vA19nKqWM8bxK9hqLGKsaiQpQg7\n"
+ "bA==\n" + "-----END CERTIFICATE-----\n";
+ "dOmse9mpgEjCb4kdZ0PnoxMFjsPR8AoGOz4A5vA19nKqWM8bxK9hqLGKsaiQpQg7\n" + "bA==\n"
+ "-----END CERTIFICATE-----\n";
ByteArrayInputStream in = new ByteArrayInputStream(cert.getBytes());
CertificateFactory cf = CertificateFactory.getInstance("X.509");
return (X509Certificate) cf.generateCertificate(in);
}
}

View File

@@ -51,8 +51,7 @@ import org.springframework.util.StringUtils;
@PowerMockIgnore("javax.security.auth.*")
public class AbstractRememberMeServicesTests {
static User joe = new User("joe", "password", true, true, true, true,
AuthorityUtils.createAuthorityList("ROLE_A"));
static User joe = new User("joe", "password", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_A"));
MockUserDetailsService uds;
@@ -100,8 +99,7 @@ public class AbstractRememberMeServicesTests {
@Test
public void cookieWithOpenIDidentifierAsNameIsEncodedAndDecoded() {
String[] cookie = new String[] { "https://id.openid.zz", "cookie", "tokens",
"blah" };
String[] cookie = new String[] { "https://id.openid.zz", "cookie", "tokens", "blah" };
MockRememberMeServices services = new MockRememberMeServices(uds);
String[] decoded = services.decodeCookie(services.encodeCookie(cookie));
@@ -124,16 +122,14 @@ public class AbstractRememberMeServicesTests {
assertThat(services.autoLogin(request, response)).isNull();
// shouldn't try to invalidate our cookie
assertThat(response.getCookie(
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull();
assertThat(response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull();
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
// set non-login cookie
request.setCookies(new Cookie("mycookie", "cookie"));
assertThat(services.autoLogin(request, response)).isNull();
assertThat(response.getCookie(
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull();
assertThat(response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull();
}
@Test
@@ -158,9 +154,7 @@ public class AbstractRememberMeServicesTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setCookies(new Cookie(
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
"ZZZ"));
request.setCookies(new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, "ZZZ"));
Authentication result = services.autoLogin(request, response);
assertThat(result).isNull();
assertCookieCancelled(response);
@@ -172,8 +166,7 @@ public class AbstractRememberMeServicesTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setCookies(new Cookie(
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, ""));
request.setCookies(new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, ""));
Authentication result = services.autoLogin(request, response);
assertThat(result).isNull();
assertCookieCancelled(response);
@@ -181,8 +174,7 @@ public class AbstractRememberMeServicesTests {
@Test
public void autoLoginShouldFailIfInvalidCookieExceptionIsRaised() {
MockRememberMeServices services = new MockRememberMeServices(
new MockUserDetailsService(joe, true));
MockRememberMeServices services = new MockRememberMeServices(new MockUserDetailsService(joe, true));
MockHttpServletRequest request = new MockHttpServletRequest();
// Wrong number of tokens
@@ -216,8 +208,7 @@ public class AbstractRememberMeServicesTests {
public void autoLoginShouldFailIfUserAccountIsLocked() {
MockRememberMeServices services = new MockRememberMeServices(uds);
services.setUserDetailsChecker(new AccountStatusUserDetailsChecker());
uds.toReturn = new User("joe", "password", false, true, true, true,
joe.getAuthorities());
uds.toReturn = new User("joe", "password", false, true, true, true, joe.getAuthorities());
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(createLoginCookie("cookie:1:2"));
@@ -263,8 +254,7 @@ public class AbstractRememberMeServicesTests {
assertCookieCancelled(response);
Cookie returnedCookie = response.getCookie(
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie.getDomain()).isEqualTo("spring.io");
}
@@ -287,8 +277,7 @@ public class AbstractRememberMeServicesTests {
assertCookieCancelled(response);
Cookie returnedCookie = response.getCookie(
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie.getDomain()).isEqualTo("spring.io");
assertThat(returnedCookie.getSecure()).isEqualTo(true);
}
@@ -312,8 +301,7 @@ public class AbstractRememberMeServicesTests {
assertCookieCancelled(response);
Cookie returnedCookie = response.getCookie(
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie.getDomain()).isEqualTo("spring.io");
assertThat(returnedCookie.getSecure()).isEqualTo(true);
}
@@ -322,8 +310,8 @@ public class AbstractRememberMeServicesTests {
public void cookieTheftExceptionShouldBeRethrown() {
MockRememberMeServices services = new MockRememberMeServices(uds) {
protected UserDetails processAutoLoginCookie(String[] cookieTokens,
HttpServletRequest request, HttpServletResponse response) {
protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request,
HttpServletResponse response) {
throw new CookieTheftException("Pretending cookie was stolen");
}
};
@@ -410,8 +398,7 @@ public class AbstractRememberMeServicesTests {
};
services.setUseSecureCookie(true);
services.setCookie(new String[] { "mycookie" }, 1000, request, response);
Cookie cookie = response.getCookie(
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(cookie.getSecure()).isTrue();
}
@@ -423,8 +410,7 @@ public class AbstractRememberMeServicesTests {
MockRememberMeServices services = new MockRememberMeServices(uds);
services.setCookie(new String[] { "mycookie" }, 1000, request, response);
Cookie cookie = response.getCookie(
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(cookie.isHttpOnly()).isTrue();
}
@@ -437,8 +423,7 @@ public class AbstractRememberMeServicesTests {
services.setCookie(new String[] { "value" }, 0, request, response);
Cookie cookie = response.getCookie(
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(cookie.getVersion()).isEqualTo(1);
}
@@ -451,8 +436,7 @@ public class AbstractRememberMeServicesTests {
services.setCookie(new String[] { "value" }, -1, request, response);
Cookie cookie = response.getCookie(
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(cookie.getVersion()).isEqualTo(1);
}
@@ -465,8 +449,7 @@ public class AbstractRememberMeServicesTests {
services.setCookie(new String[] { "value" }, 1, request, response);
Cookie cookie = response.getCookie(
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(cookie.getVersion()).isZero();
}
@@ -487,17 +470,14 @@ public class AbstractRememberMeServicesTests {
private Cookie[] createLoginCookie(String cookieToken) {
MockRememberMeServices services = new MockRememberMeServices(uds);
Cookie cookie = new Cookie(
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
services.encodeCookie(
StringUtils.delimitedListToStringArray(cookieToken, ":")));
Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
services.encodeCookie(StringUtils.delimitedListToStringArray(cookieToken, ":")));
return new Cookie[] { cookie };
}
private void assertCookieCancelled(MockHttpServletResponse response) {
Cookie returnedCookie = response.getCookie(
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
assertThat(returnedCookie.getMaxAge()).isZero();
}
@@ -521,14 +501,13 @@ public class AbstractRememberMeServicesTests {
this(new MockUserDetailsService(null, false));
}
protected void onLoginSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication successfulAuthentication) {
protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication successfulAuthentication) {
loginSuccessCalled = true;
}
protected UserDetails processAutoLoginCookie(String[] cookieTokens,
HttpServletRequest request, HttpServletResponse response)
throws RememberMeAuthenticationException {
protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request,
HttpServletResponse response) throws RememberMeAuthenticationException {
if (cookieTokens.length != 3) {
throw new InvalidCookieException("deliberate exception");
}
@@ -537,6 +516,7 @@ public class AbstractRememberMeServicesTests {
return user;
}
}
public static class MockUserDetailsService implements UserDetailsService {
@@ -565,5 +545,7 @@ public class AbstractRememberMeServicesTests {
public void setThrowException(boolean value) {
this.throwException = value;
}
}
}

View File

@@ -62,8 +62,7 @@ public class JdbcTokenRepositoryImplTests {
@BeforeClass
public static void createDataSource() {
dataSource = new SingleConnectionDataSource("jdbc:hsqldb:mem:tokenrepotest", "sa",
"", true);
dataSource = new SingleConnectionDataSource("jdbc:hsqldb:mem:tokenrepotest", "sa", "", true);
dataSource.setDriverClassName("org.hsqldb.jdbc.JDBCDriver");
}
@@ -80,9 +79,8 @@ public class JdbcTokenRepositoryImplTests {
repo.setDataSource(dataSource);
repo.initDao();
template = repo.getJdbcTemplate();
template.execute(
"create table persistent_logins (username varchar(100) not null, "
+ "series varchar(100) not null, token varchar(500) not null, last_used timestamp not null)");
template.execute("create table persistent_logins (username varchar(100) not null, "
+ "series varchar(100) not null, token varchar(500) not null, last_used timestamp not null)");
}
@After
@@ -93,12 +91,10 @@ public class JdbcTokenRepositoryImplTests {
@Test
public void createNewTokenInsertsCorrectData() {
Timestamp currentDate = new Timestamp(Calendar.getInstance().getTimeInMillis());
PersistentRememberMeToken token = new PersistentRememberMeToken("joeuser",
"joesseries", "atoken", currentDate);
PersistentRememberMeToken token = new PersistentRememberMeToken("joeuser", "joesseries", "atoken", currentDate);
repo.createNewToken(token);
Map<String, Object> results = template.queryForMap(
"select * from persistent_logins");
Map<String, Object> results = template.queryForMap("select * from persistent_logins");
assertThat(results.get("last_used")).isEqualTo(currentDate);
assertThat(results.get("username")).isEqualTo("joeuser");
@@ -109,26 +105,22 @@ public class JdbcTokenRepositoryImplTests {
@Test
public void retrievingTokenReturnsCorrectData() {
template.execute(
"insert into persistent_logins (series, username, token, last_used) values "
+ "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')");
template.execute("insert into persistent_logins (series, username, token, last_used) values "
+ "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')");
PersistentRememberMeToken token = repo.getTokenForSeries("joesseries");
assertThat(token.getUsername()).isEqualTo("joeuser");
assertThat(token.getSeries()).isEqualTo("joesseries");
assertThat(token.getTokenValue()).isEqualTo("atoken");
assertThat(token.getDate()).isEqualTo(
Timestamp.valueOf("2007-10-09 18:19:25.000000000"));
assertThat(token.getDate()).isEqualTo(Timestamp.valueOf("2007-10-09 18:19:25.000000000"));
}
@Test
public void retrievingTokenWithDuplicateSeriesReturnsNull() {
template.execute(
"insert into persistent_logins (series, username, token, last_used) values "
+ "('joesseries', 'joeuser', 'atoken2', '2007-10-19 18:19:25.000000000')");
template.execute(
"insert into persistent_logins (series, username, token, last_used) values "
+ "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')");
template.execute("insert into persistent_logins (series, username, token, last_used) values "
+ "('joesseries', 'joeuser', 'atoken2', '2007-10-19 18:19:25.000000000')");
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 =
@@ -145,20 +137,17 @@ public class JdbcTokenRepositoryImplTests {
assertThat(repo.getTokenForSeries("missingSeries")).isNull();
verify(logger).isDebugEnabled();
verify(logger).debug(
eq("Querying token for series 'missingSeries' returned no results."),
verify(logger).debug(eq("Querying token for series 'missingSeries' returned no results."),
any(EmptyResultDataAccessException.class));
verifyNoMoreInteractions(logger);
}
@Test
public void removingUserTokensDeletesData() {
template.execute(
"insert into persistent_logins (series, username, token, last_used) values "
+ "('joesseries2', 'joeuser', 'atoken2', '2007-10-19 18:19:25.000000000')");
template.execute(
"insert into persistent_logins (series, username, token, last_used) values "
+ "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')");
template.execute("insert into persistent_logins (series, username, token, last_used) values "
+ "('joesseries2', 'joeuser', 'atoken2', '2007-10-19 18:19:25.000000000')");
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 =
@@ -166,8 +155,8 @@ public class JdbcTokenRepositoryImplTests {
repo.removeUserTokens("joeuser");
List<Map<String, Object>> results = template.queryForList(
"select * from persistent_logins where username = 'joeuser'");
List<Map<String, Object>> results = template
.queryForList("select * from persistent_logins where username = 'joeuser'");
assertThat(results).isEmpty();
}
@@ -175,13 +164,12 @@ public class JdbcTokenRepositoryImplTests {
@Test
public void updatingTokenModifiesTokenValueAndLastUsed() {
Timestamp ts = new Timestamp(System.currentTimeMillis() - 1);
template.execute(
"insert into persistent_logins (series, username, token, last_used) values "
+ "('joesseries', 'joeuser', 'atoken', '" + ts.toString() + "')");
template.execute("insert into persistent_logins (series, username, token, last_used) values "
+ "('joesseries', 'joeuser', 'atoken', '" + ts.toString() + "')");
repo.updateToken("joesseries", "newtoken", new Date());
Map<String, Object> results = template.queryForMap(
"select * from persistent_logins where series = 'joesseries'");
Map<String, Object> results = template
.queryForMap("select * from persistent_logins where series = 'joesseries'");
assertThat(results.get("username")).isEqualTo("joeuser");
assertThat(results.get("series")).isEqualTo("joesseries");
@@ -198,8 +186,7 @@ public class JdbcTokenRepositoryImplTests {
repo.setCreateTableOnStartup(true);
repo.initDao();
template.queryForList(
"select username,series,token,last_used from persistent_logins");
template.queryForList("select username,series,token,last_used from persistent_logins");
}
// SEC-2879

View File

@@ -27,6 +27,7 @@ import org.springframework.security.web.authentication.NullRememberMeServices;
* @author Ben Alex
*/
public class NullRememberMeServicesTests {
// ~ Methods
// ========================================================================================================
@Test
@@ -37,4 +38,5 @@ public class NullRememberMeServicesTests {
services.loginSuccess(null, null, null);
}
}

View File

@@ -35,11 +35,11 @@ import org.springframework.security.web.authentication.rememberme.PersistentToke
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException;
/**
* @author Luke Taylor
*/
public class PersistentTokenBasedRememberMeServicesTests {
private PersistentTokenBasedRememberMeServices services;
private MockTokenRepository repo;
@@ -47,8 +47,7 @@ public class PersistentTokenBasedRememberMeServicesTests {
@Before
public void setUpData() throws Exception {
services = new PersistentTokenBasedRememberMeServices("key",
new AbstractRememberMeServicesTests.MockUserDetailsService(
AbstractRememberMeServicesTests.joe, false),
new AbstractRememberMeServicesTests.MockUserDetailsService(AbstractRememberMeServicesTests.joe, false),
new InMemoryTokenRepositoryImpl());
services.setCookieName("mycookiename");
// Default to 100 days (see SEC-1081).
@@ -58,15 +57,15 @@ public class PersistentTokenBasedRememberMeServicesTests {
@Test(expected = InvalidCookieException.class)
public void loginIsRejectedWithWrongNumberOfCookieTokens() {
services.processAutoLoginCookie(new String[] { "series", "token", "extra" },
new MockHttpServletRequest(), new MockHttpServletResponse());
services.processAutoLoginCookie(new String[] { "series", "token", "extra" }, new MockHttpServletRequest(),
new MockHttpServletResponse());
}
@Test(expected = RememberMeAuthenticationException.class)
public void loginIsRejectedWhenNoTokenMatchingSeriesIsFound() {
services = create(null);
services.processAutoLoginCookie(new String[] { "series", "token" },
new MockHttpServletRequest(), new MockHttpServletResponse());
services.processAutoLoginCookie(new String[] { "series", "token" }, new MockHttpServletRequest(),
new MockHttpServletResponse());
}
@Test(expected = RememberMeAuthenticationException.class)
@@ -75,31 +74,27 @@ public class PersistentTokenBasedRememberMeServicesTests {
new Date(System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(1) - 100)));
services.setTokenValiditySeconds(1);
services.processAutoLoginCookie(new String[] { "series", "token" },
new MockHttpServletRequest(), new MockHttpServletResponse());
services.processAutoLoginCookie(new String[] { "series", "token" }, new MockHttpServletRequest(),
new MockHttpServletResponse());
}
@Test(expected = CookieTheftException.class)
public void cookieTheftIsDetectedWhenSeriesAndTokenDontMatch() {
services = create(new PersistentRememberMeToken("joe", "series", "wrongtoken",
new Date()));
services.processAutoLoginCookie(new String[] { "series", "token" },
new MockHttpServletRequest(), new MockHttpServletResponse());
services = create(new PersistentRememberMeToken("joe", "series", "wrongtoken", new Date()));
services.processAutoLoginCookie(new String[] { "series", "token" }, new MockHttpServletRequest(),
new MockHttpServletResponse());
}
@Test
public void successfulAutoLoginCreatesNewTokenAndCookieWithSameSeries() {
services = create(new PersistentRememberMeToken("joe", "series", "token",
new Date()));
services = create(new PersistentRememberMeToken("joe", "series", "token", new Date()));
// 12 => b64 length will be 16
services.setTokenLength(12);
MockHttpServletResponse response = new MockHttpServletResponse();
services.processAutoLoginCookie(new String[] { "series", "token" },
new MockHttpServletRequest(), response);
services.processAutoLoginCookie(new String[] { "series", "token" }, new MockHttpServletRequest(), response);
assertThat(repo.getStoredToken().getSeries()).isEqualTo("series");
assertThat(repo.getStoredToken().getTokenValue().length()).isEqualTo(16);
String[] cookie = services.decodeCookie(response.getCookie("mycookiename")
.getValue());
String[] cookie = services.decodeCookie(response.getCookie("mycookiename").getValue());
assertThat(cookie[0]).isEqualTo("series");
assertThat(cookie[1]).isEqualTo(repo.getStoredToken().getTokenValue());
}
@@ -116,8 +111,7 @@ public class PersistentTokenBasedRememberMeServicesTests {
assertThat(repo.getStoredToken().getSeries().length()).isEqualTo(16);
assertThat(repo.getStoredToken().getTokenValue().length()).isEqualTo(16);
String[] cookie = services.decodeCookie(response.getCookie("mycookiename")
.getValue());
String[] cookie = services.decodeCookie(response.getCookie("mycookiename").getValue());
assertThat(cookie[0]).isEqualTo(repo.getStoredToken().getSeries());
assertThat(cookie[1]).isEqualTo(repo.getStoredToken().getTokenValue());
@@ -129,10 +123,8 @@ public class PersistentTokenBasedRememberMeServicesTests {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
MockHttpServletResponse response = new MockHttpServletResponse();
services = create(new PersistentRememberMeToken("joe", "series", "token",
new Date()));
services.logout(request, response, new TestingAuthenticationToken("joe",
"somepass", "SOME_AUTH"));
services = create(new PersistentRememberMeToken("joe", "series", "token", new Date()));
services.logout(request, response, new TestingAuthenticationToken("joe", "somepass", "SOME_AUTH"));
Cookie returnedCookie = response.getCookie("mycookiename");
assertThat(returnedCookie).isNotNull();
assertThat(returnedCookie.getMaxAge()).isZero();
@@ -143,15 +135,16 @@ public class PersistentTokenBasedRememberMeServicesTests {
private PersistentTokenBasedRememberMeServices create(PersistentRememberMeToken token) {
repo = new MockTokenRepository(token);
PersistentTokenBasedRememberMeServices services = new PersistentTokenBasedRememberMeServices(
"key", new AbstractRememberMeServicesTests.MockUserDetailsService(
AbstractRememberMeServicesTests.joe, false), repo);
PersistentTokenBasedRememberMeServices services = new PersistentTokenBasedRememberMeServices("key",
new AbstractRememberMeServicesTests.MockUserDetailsService(AbstractRememberMeServicesTests.joe, false),
repo);
services.setCookieName("mycookiename");
return services;
}
private class MockTokenRepository implements PersistentTokenRepository {
private PersistentRememberMeToken storedToken;
private MockTokenRepository(PersistentRememberMeToken token) {
@@ -163,8 +156,8 @@ public class PersistentTokenBasedRememberMeServicesTests {
}
public void updateToken(String series, String tokenValue, Date lastUsed) {
storedToken = new PersistentRememberMeToken(storedToken.getUsername(),
storedToken.getSeries(), tokenValue, lastUsed);
storedToken = new PersistentRememberMeToken(storedToken.getUsername(), storedToken.getSeries(), tokenValue,
lastUsed);
}
public PersistentRememberMeToken getTokenForSeries(String seriesId) {
@@ -177,5 +170,7 @@ public class PersistentTokenBasedRememberMeServicesTests {
PersistentRememberMeToken getStoredToken() {
return storedToken;
}
}
}

View File

@@ -43,8 +43,8 @@ import javax.servlet.http.HttpServletResponse;
* @author Ben Alex
*/
public class RememberMeAuthenticationFilterTests {
Authentication remembered = new TestingAuthenticationToken("remembered", "password",
"ROLE_REMEMBERED");
Authentication remembered = new TestingAuthenticationToken("remembered", "password", "ROLE_REMEMBERED");
// ~ Methods
// ========================================================================================================
@@ -72,13 +72,12 @@ public class RememberMeAuthenticationFilterTests {
@Test
public void testOperationWhenAuthenticationExistsInContextHolder() throws Exception {
// Put an Authentication object into the SecurityContextHolder
Authentication originalAuth = new TestingAuthenticationToken("user", "password",
"ROLE_A");
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(remembered));
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(mock(AuthenticationManager.class),
new MockRememberMeServices(remembered));
filter.afterPropertiesSet();
// Test
@@ -89,8 +88,7 @@ public class RememberMeAuthenticationFilterTests {
// Ensure filter didn't change our original object
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(originalAuth);
verify(fc)
.doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@Test
@@ -109,21 +107,19 @@ public class RememberMeAuthenticationFilterTests {
// Ensure filter setup with our remembered authentication object
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(remembered);
verify(fc)
.doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@Test
public void onUnsuccessfulLoginIsCalledWhenProviderRejectsAuth() throws Exception {
final Authentication failedAuth = new TestingAuthenticationToken("failed", "");
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(any(Authentication.class))).thenThrow(
new BadCredentialsException(""));
when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException(""));
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am,
new MockRememberMeServices(remembered)) {
protected void onUnsuccessfulAuthentication(HttpServletRequest request,
HttpServletResponse response, AuthenticationException failed) {
protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
AuthenticationException failed) {
super.onUnsuccessfulAuthentication(request, response, failed);
SecurityContextHolder.getContext().setAuthentication(failedAuth);
}
@@ -137,19 +133,16 @@ public class RememberMeAuthenticationFilterTests {
filter.doFilter(request, new MockHttpServletResponse(), fc);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(failedAuth);
verify(fc)
.doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@Test
public void authenticationSuccessHandlerIsInvokedOnSuccessfulAuthenticationIfSet()
throws Exception {
public void authenticationSuccessHandlerIsInvokedOnSuccessfulAuthenticationIfSet() throws Exception {
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(remembered)).thenReturn(remembered);
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am,
new MockRememberMeServices(remembered));
filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler(
"/target"));
filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/target"));
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain fc = mock(FilterChain.class);
@@ -166,22 +159,24 @@ public class RememberMeAuthenticationFilterTests {
// ==================================================================================================
private class MockRememberMeServices implements RememberMeServices {
private Authentication authToReturn;
MockRememberMeServices(Authentication authToReturn) {
this.authToReturn = authToReturn;
}
public Authentication autoLogin(HttpServletRequest request,
HttpServletResponse response) {
public Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) {
return authToReturn;
}
public void loginFail(HttpServletRequest request, HttpServletResponse response) {
}
public void loginSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication successfulAuthentication) {
public void loginSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication successfulAuthentication) {
}
}
}

View File

@@ -46,9 +46,12 @@ import org.springframework.util.StringUtils;
* @author Ben Alex
*/
public class TokenBasedRememberMeServicesTests {
private UserDetailsService uds;
private UserDetails user = new User("someone", "password", true, true, true, true,
AuthorityUtils.createAuthorityList("ROLE_ABC"));
private TokenBasedRememberMeServices services;
// ~ Methods
@@ -65,8 +68,7 @@ public class TokenBasedRememberMeServicesTests {
}
void udsWillThrowNotFound() {
when(uds.loadUserByUsername(any(String.class))).thenThrow(
new UsernameNotFoundException(""));
when(uds.loadUserByUsername(any(String.class))).thenThrow(new UsernameNotFoundException(""));
}
void udsWillReturnNull() {
@@ -75,8 +77,7 @@ public class TokenBasedRememberMeServicesTests {
private long determineExpiryTimeFromBased64EncodedToken(String validToken) {
String cookieAsPlainText = new String(Base64.decodeBase64(validToken.getBytes()));
String[] cookieTokens = StringUtils.delimitedListToStringArray(cookieAsPlainText,
":");
String[] cookieTokens = StringUtils.delimitedListToStringArray(cookieAsPlainText, ":");
if (cookieTokens.length == 3) {
try {
@@ -89,13 +90,11 @@ public class TokenBasedRememberMeServicesTests {
return -1;
}
private String generateCorrectCookieContentForToken(long expiryTime, String username,
String password, String key) {
private String generateCorrectCookieContentForToken(long expiryTime, String username, String password, String key) {
// format is:
// username + ":" + expiryTime + ":" + Md5Hex(username + ":" + expiryTime + ":" +
// password + ":" + key)
String signatureValue = DigestUtils.md5Hex(username + ":" + expiryTime + ":"
+ password + ":" + key);
String signatureValue = DigestUtils.md5Hex(username + ":" + expiryTime + ":" + password + ":" + key);
String tokenValue = username + ":" + expiryTime + ":" + signatureValue;
return new String(Base64.encodeBase64(tokenValue.getBytes()));
@@ -105,8 +104,7 @@ public class TokenBasedRememberMeServicesTests {
public void autoLoginReturnsNullIfNoCookiePresented() {
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication result = services
.autoLogin(new MockHttpServletRequest(), response);
Authentication result = services.autoLogin(new MockHttpServletRequest(), response);
assertThat(result).isNull();
// No cookie set
assertThat(response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull();
@@ -127,50 +125,44 @@ public class TokenBasedRememberMeServicesTests {
@Test
public void autoLoginReturnsNullForExpiredCookieAndClearsCookie() {
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
generateCorrectCookieContentForToken(
System.currentTimeMillis() - 1000000, "someone", "password",
"key"));
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForToken(
System.currentTimeMillis() - 1000000, "someone", "password", "key"));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(services.autoLogin(request, response)).isNull();
Cookie returnedCookie = response
.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
assertThat(returnedCookie.getMaxAge()).isZero();
}
@Test
public void autoLoginReturnsNullAndClearsCookieIfMissingThreeTokensInCookieValue() {
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, new String(
Base64.encodeBase64("x".getBytes())));
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
new String(Base64.encodeBase64("x".getBytes())));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(services.autoLogin(request, response)).isNull();
Cookie returnedCookie = response
.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
assertThat(returnedCookie.getMaxAge()).isZero();
}
@Test
public void autoLoginClearsNonBase64EncodedCookie() {
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
"NOT_BASE_64_ENCODED");
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, "NOT_BASE_64_ENCODED");
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(services.autoLogin(request, response)).isNull();
Cookie returnedCookie = response
.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
assertThat(returnedCookie.getMaxAge()).isZero();
}
@@ -178,10 +170,8 @@ public class TokenBasedRememberMeServicesTests {
@Test
public void autoLoginClearsCookieIfSignatureBlocksDoesNotMatchExpectedValue() {
udsWillReturnUser();
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
generateCorrectCookieContentForToken(
System.currentTimeMillis() + 1000000, "someone", "password",
"WRONG_KEY"));
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForToken(
System.currentTimeMillis() + 1000000, "someone", "password", "WRONG_KEY"));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
@@ -189,24 +179,22 @@ public class TokenBasedRememberMeServicesTests {
assertThat(services.autoLogin(request, response)).isNull();
Cookie returnedCookie = response
.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
assertThat(returnedCookie.getMaxAge()).isZero();
}
@Test
public void autoLoginClearsCookieIfTokenDoesNotContainANumberInCookieValue() {
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, new String(
Base64.encodeBase64("username:NOT_A_NUMBER:signature".getBytes())));
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
new String(Base64.encodeBase64("username:NOT_A_NUMBER:signature".getBytes())));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(services.autoLogin(request, response)).isNull();
Cookie returnedCookie = response
.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
assertThat(returnedCookie.getMaxAge()).isZero();
}
@@ -214,10 +202,8 @@ public class TokenBasedRememberMeServicesTests {
@Test
public void autoLoginClearsCookieIfUserNotFound() {
udsWillThrowNotFound();
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
generateCorrectCookieContentForToken(
System.currentTimeMillis() + 1000000, "someone", "password",
"key"));
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForToken(
System.currentTimeMillis() + 1000000, "someone", "password", "key"));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
@@ -225,8 +211,7 @@ public class TokenBasedRememberMeServicesTests {
assertThat(services.autoLogin(request, response)).isNull();
Cookie returnedCookie = response
.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
assertThat(returnedCookie.getMaxAge()).isZero();
}
@@ -234,10 +219,8 @@ public class TokenBasedRememberMeServicesTests {
@Test(expected = IllegalArgumentException.class)
public void autoLoginClearsCookieIfUserServiceMisconfigured() {
udsWillReturnNull();
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
generateCorrectCookieContentForToken(
System.currentTimeMillis() + 1000000, "someone", "password",
"key"));
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForToken(
System.currentTimeMillis() + 1000000, "someone", "password", "key"));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
@@ -249,10 +232,8 @@ public class TokenBasedRememberMeServicesTests {
@Test
public void autoLoginWithValidTokenAndUserSucceeds() {
udsWillReturnUser();
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
generateCorrectCookieContentForToken(
System.currentTimeMillis() + 1000000, "someone", "password",
"key"));
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForToken(
System.currentTimeMillis() + 1000000, "someone", "password", "key"));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
@@ -297,8 +278,7 @@ public class TokenBasedRememberMeServicesTests {
request.addParameter(DEFAULT_PARAMETER, "false");
MockHttpServletResponse response = new MockHttpServletResponse();
services.loginSuccess(request, response, new TestingAuthenticationToken(
"someone", "password", "ROLE_ABC"));
services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password", "ROLE_ABC"));
Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(cookie).isNull();
@@ -312,8 +292,7 @@ public class TokenBasedRememberMeServicesTests {
request.addParameter(TokenBasedRememberMeServices.DEFAULT_PARAMETER, "true");
MockHttpServletResponse response = new MockHttpServletResponse();
services.loginSuccess(request, response, new TestingAuthenticationToken(
"someone", "password", "ROLE_ABC"));
services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password", "ROLE_ABC"));
Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
String expiryTime = services.decodeCookie(cookie.getValue())[1];
@@ -323,8 +302,7 @@ public class TokenBasedRememberMeServicesTests {
assertThat(cookie).isNotNull();
assertThat(cookie.getMaxAge()).isEqualTo(services.getTokenValiditySeconds());
assertThat(Base64.isArrayByteBase64(cookie.getValue().getBytes())).isTrue();
assertThat(new Date().before(new Date(
determineExpiryTimeFromBased64EncodedToken(cookie.getValue())))).isTrue();
assertThat(new Date().before(new Date(determineExpiryTimeFromBased64EncodedToken(cookie.getValue())))).isTrue();
}
@Test
@@ -333,22 +311,19 @@ public class TokenBasedRememberMeServicesTests {
request.addParameter(TokenBasedRememberMeServices.DEFAULT_PARAMETER, "true");
MockHttpServletResponse response = new MockHttpServletResponse();
services.loginSuccess(request, response, new TestingAuthenticationToken(
"someone", "password", "ROLE_ABC"));
services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password", "ROLE_ABC"));
Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(cookie).isNotNull();
assertThat(cookie.getMaxAge()).isEqualTo(services.getTokenValiditySeconds());
assertThat(Base64.isArrayByteBase64(cookie.getValue().getBytes())).isTrue();
assertThat(new Date().before(new Date(
determineExpiryTimeFromBased64EncodedToken(cookie.getValue())))).isTrue();
assertThat(new Date().before(new Date(determineExpiryTimeFromBased64EncodedToken(cookie.getValue())))).isTrue();
}
// SEC-933
@Test
public void obtainPasswordReturnsNullForTokenWithNullCredentials() {
TestingAuthenticationToken token = new TestingAuthenticationToken("username",
null);
TestingAuthenticationToken token = new TestingAuthenticationToken("username", null);
assertThat(services.retrievePassword(token)).isNull();
}
@@ -360,8 +335,7 @@ public class TokenBasedRememberMeServicesTests {
MockHttpServletResponse response = new MockHttpServletResponse();
services.setTokenValiditySeconds(-1);
services.loginSuccess(request, response, new TestingAuthenticationToken(
"someone", "password", "ROLE_ABC"));
services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password", "ROLE_ABC"));
Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(cookie).isNotNull();
@@ -371,4 +345,5 @@ public class TokenBasedRememberMeServicesTests {
assertThat(cookie.getMaxAge()).isEqualTo(-1);
assertThat(Base64.isArrayByteBase64(cookie.getValue().getBytes())).isTrue();
}
}

View File

@@ -37,4 +37,5 @@ public class ChangeSessionIdAuthenticationStrategyTests {
new ChangeSessionIdAuthenticationStrategy().applySessionFixation(request);
assertThat(request.getSession().getId()).isNotEqualTo(id);
}
}

View File

@@ -62,14 +62,12 @@ public class CompositeSessionAuthenticationStrategyTests {
@Test(expected = IllegalArgumentException.class)
public void constructorEmptyDelegates() {
new CompositeSessionAuthenticationStrategy(
Collections.<SessionAuthenticationStrategy> emptyList());
new CompositeSessionAuthenticationStrategy(Collections.<SessionAuthenticationStrategy>emptyList());
}
@Test(expected = IllegalArgumentException.class)
public void constructorDelegatesContainNull() {
new CompositeSessionAuthenticationStrategy(
Collections.<SessionAuthenticationStrategy> singletonList(null));
new CompositeSessionAuthenticationStrategy(Collections.<SessionAuthenticationStrategy>singletonList(null));
}
@Test
@@ -84,8 +82,8 @@ public class CompositeSessionAuthenticationStrategyTests {
@Test
public void delegateShortCircuits() {
doThrow(new SessionAuthenticationException("oops")).when(
strategy1).onAuthentication(authentication, request, response);
doThrow(new SessionAuthenticationException("oops")).when(strategy1).onAuthentication(authentication, request,
response);
CompositeSessionAuthenticationStrategy strategy = new CompositeSessionAuthenticationStrategy(
Arrays.asList(strategy1, strategy2));
@@ -100,4 +98,5 @@ public class CompositeSessionAuthenticationStrategyTests {
verify(strategy1).onAuthentication(authentication, request, response);
verify(strategy2, times(0)).onAuthentication(authentication, request, response);
}
}

View File

@@ -40,18 +40,21 @@ import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
/**
*
* @author Rob Winch
*
*/
@RunWith(MockitoJUnitRunner.class)
public class ConcurrentSessionControlAuthenticationStrategyTests {
@Mock
private SessionRegistry sessionRegistry;
private Authentication authentication;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private SessionInformation sessionInformation;
private ConcurrentSessionControlAuthenticationStrategy strategy;
@@ -61,8 +64,7 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
sessionInformation = new SessionInformation(authentication.getPrincipal(),
"unique", new Date(1374766134216L));
sessionInformation = new SessionInformation(authentication.getPrincipal(), "unique", new Date(1374766134216L));
strategy = new ConcurrentSessionControlAuthenticationStrategy(sessionRegistry);
}
@@ -74,8 +76,8 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
@Test
public void noRegisteredSession() {
when(sessionRegistry.getAllSessions(any(), anyBoolean())).thenReturn(
Collections.<SessionInformation> emptyList());
when(sessionRegistry.getAllSessions(any(), anyBoolean()))
.thenReturn(Collections.<SessionInformation>emptyList());
strategy.setMaximumSessions(1);
strategy.setExceptionIfMaximumExceeded(true);
@@ -86,11 +88,10 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
@Test
public void maxSessionsSameSessionId() {
MockHttpSession session = new MockHttpSession(new MockServletContext(),
sessionInformation.getSessionId());
MockHttpSession session = new MockHttpSession(new MockServletContext(), sessionInformation.getSessionId());
request.setSession(session);
when(sessionRegistry.getAllSessions(any(), anyBoolean())).thenReturn(
Collections.<SessionInformation> singletonList(sessionInformation));
when(sessionRegistry.getAllSessions(any(), anyBoolean()))
.thenReturn(Collections.<SessionInformation>singletonList(sessionInformation));
strategy.setMaximumSessions(1);
strategy.setExceptionIfMaximumExceeded(true);
@@ -101,8 +102,8 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
@Test(expected = SessionAuthenticationException.class)
public void maxSessionsWithException() {
when(sessionRegistry.getAllSessions(any(), anyBoolean())).thenReturn(
Collections.<SessionInformation> singletonList(sessionInformation));
when(sessionRegistry.getAllSessions(any(), anyBoolean()))
.thenReturn(Collections.<SessionInformation>singletonList(sessionInformation));
strategy.setMaximumSessions(1);
strategy.setExceptionIfMaximumExceeded(true);
@@ -111,8 +112,8 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
@Test
public void maxSessionsExpireExistingUser() {
when(sessionRegistry.getAllSessions(any(), anyBoolean())).thenReturn(
Collections.<SessionInformation> singletonList(sessionInformation));
when(sessionRegistry.getAllSessions(any(), anyBoolean()))
.thenReturn(Collections.<SessionInformation>singletonList(sessionInformation));
strategy.setMaximumSessions(1);
strategy.onAuthentication(authentication, request, response);
@@ -122,11 +123,10 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
@Test
public void maxSessionsExpireLeastRecentExistingUser() {
SessionInformation moreRecentSessionInfo = new SessionInformation(
authentication.getPrincipal(), "unique", new Date(1374766999999L));
when(sessionRegistry.getAllSessions(any(), anyBoolean())).thenReturn(
Arrays.<SessionInformation> asList(moreRecentSessionInfo,
sessionInformation));
SessionInformation moreRecentSessionInfo = new SessionInformation(authentication.getPrincipal(), "unique",
new Date(1374766999999L));
when(sessionRegistry.getAllSessions(any(), anyBoolean()))
.thenReturn(Arrays.<SessionInformation>asList(moreRecentSessionInfo, sessionInformation));
strategy.setMaximumSessions(2);
strategy.onAuthentication(authentication, request, response);
@@ -136,14 +136,12 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
@Test
public void onAuthenticationWhenMaxSessionsExceededByTwoThenTwoSessionsExpired() {
SessionInformation oldestSessionInfo = new SessionInformation(
authentication.getPrincipal(), "unique1", new Date(1374766134214L));
SessionInformation secondOldestSessionInfo = new SessionInformation(
authentication.getPrincipal(), "unique2", new Date(1374766134215L));
SessionInformation oldestSessionInfo = new SessionInformation(authentication.getPrincipal(), "unique1",
new Date(1374766134214L));
SessionInformation secondOldestSessionInfo = new SessionInformation(authentication.getPrincipal(), "unique2",
new Date(1374766134215L));
when(sessionRegistry.getAllSessions(any(), anyBoolean())).thenReturn(
Arrays.<SessionInformation> asList(oldestSessionInfo,
secondOldestSessionInfo,
sessionInformation));
Arrays.<SessionInformation>asList(oldestSessionInfo, secondOldestSessionInfo, sessionInformation));
strategy.setMaximumSessions(2);
strategy.onAuthentication(authentication, request, response);
@@ -157,4 +155,5 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
public void setMessageSourceNull() {
strategy.setMessageSource(null);
}
}

View File

@@ -41,7 +41,9 @@ public class RegisterSessionAuthenticationStrategyTests {
private RegisterSessionAuthenticationStrategy authenticationStrategy;
private Authentication authentication;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
@Before
@@ -61,8 +63,7 @@ public class RegisterSessionAuthenticationStrategyTests {
public void onAuthenticationRegistersSession() {
authenticationStrategy.onAuthentication(authentication, request, response);
verify(registry).registerNewSession(request.getSession().getId(),
authentication.getPrincipal());
verify(registry).registerNewSession(request.getSession().getId(), authentication.getPrincipal());
}
}

View File

@@ -60,15 +60,15 @@ import static org.mockito.Mockito.verify;
* @author Luke Taylor
*/
public class SwitchUserFilterTests {
private final static List<GrantedAuthority> ROLES_12 = AuthorityUtils
.createAuthorityList("ROLE_ONE", "ROLE_TWO");
private final static List<GrantedAuthority> ROLES_12 = AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO");
@Rule
public ExpectedException thrown = ExpectedException.none();
@Before
public void authenticateCurrentUser() {
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
"dano", "hawaii50");
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("dano", "hawaii50");
SecurityContextHolder.getContext().setAuthentication(auth);
}
@@ -210,8 +210,7 @@ public class SwitchUserFilterTests {
public void attemptSwitchToUnknownUserFails() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY,
"user-that-doesnt-exist");
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "user-that-doesnt-exist");
SwitchUserFilter filter = new SwitchUserFilter();
filter.setUserDetailsService(new MockUserDetailsService());
@@ -247,8 +246,7 @@ public class SwitchUserFilterTests {
public void switchToLockedAccountCausesRedirectToSwitchFailureUrl() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/login/impersonate");
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY,
"mcgarrett");
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "mcgarrett");
MockHttpServletResponse response = new MockHttpServletResponse();
SwitchUserFilter filter = new SwitchUserFilter();
filter.setTargetUrl("/target");
@@ -312,15 +310,15 @@ public class SwitchUserFilterTests {
@Test
public void exitUserJackLordToDanoSucceeds() throws Exception {
// original user
UsernamePasswordAuthenticationToken source = new UsernamePasswordAuthenticationToken(
"dano", "hawaii50", ROLES_12);
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);
UsernamePasswordAuthenticationToken admin = new UsernamePasswordAuthenticationToken("jacklord", "hawaii50",
adminAuths);
SecurityContextHolder.getContext().setAuthentication(admin);
@@ -331,8 +329,7 @@ public class SwitchUserFilterTests {
SwitchUserFilter filter = new SwitchUserFilter();
filter.setUserDetailsService(new MockUserDetailsService());
filter.setExitUserUrl("/logout/impersonate");
filter.setSuccessHandler(new SimpleUrlAuthenticationSuccessHandler(
"/webapp/someOtherUrl"));
filter.setSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/webapp/someOtherUrl"));
// run 'exit'
FilterChain chain = mock(FilterChain.class);
@@ -342,8 +339,7 @@ public class SwitchUserFilterTests {
verify(chain, never()).doFilter(request, response);
// check current user, should be back to original user (dano)
Authentication targetAuth = SecurityContextHolder.getContext()
.getAuthentication();
Authentication targetAuth = SecurityContextHolder.getContext().getAuthentication();
assertThat(targetAuth).isNotNull();
assertThat(targetAuth.getPrincipal()).isEqualTo("dano");
}
@@ -373,14 +369,12 @@ public class SwitchUserFilterTests {
public void redirectToTargetUrlIsCorrect() throws Exception {
MockHttpServletRequest request = createMockSwitchRequest();
request.setContextPath("/webapp");
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY,
"jacklord");
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.setSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/someOtherUrl"));
filter.setUserDetailsService(new MockUserDetailsService());
FilterChain chain = mock(FilterChain.class);
@@ -395,14 +389,12 @@ public class SwitchUserFilterTests {
@Test
public void redirectOmitsContextPathIfUseRelativeContextSet() throws Exception {
// set current user
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
"dano", "hawaii50");
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.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "jacklord");
request.setRequestURI("/webapp/login/impersonate");
SwitchUserFilter filter = new SwitchUserFilter();
@@ -428,16 +420,14 @@ public class SwitchUserFilterTests {
@Test
public void testSwitchRequestFromDanoToJackLord() throws Exception {
// set current user
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
"dano", "hawaii50");
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");
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "jacklord");
// http response
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -446,8 +436,7 @@ public class SwitchUserFilterTests {
SwitchUserFilter filter = new SwitchUserFilter();
filter.setUserDetailsService(new MockUserDetailsService());
filter.setSwitchUserUrl("/login/impersonate");
filter.setSuccessHandler(new SimpleUrlAuthenticationSuccessHandler(
"/webapp/someOtherUrl"));
filter.setSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/webapp/someOtherUrl"));
FilterChain chain = mock(FilterChain.class);
@@ -456,8 +445,7 @@ public class SwitchUserFilterTests {
verify(chain, never()).doFilter(request, response);
// check current user
Authentication targetAuth = SecurityContextHolder.getContext()
.getAuthentication();
Authentication targetAuth = SecurityContextHolder.getContext().getAuthentication();
assertThat(targetAuth).isNotNull();
assertThat(targetAuth.getPrincipal() instanceof UserDetails).isTrue();
assertThat(((User) targetAuth.getPrincipal()).getUsername()).isEqualTo("jacklord");
@@ -465,13 +453,11 @@ public class SwitchUserFilterTests {
@Test
public void modificationOfAuthoritiesWorks() {
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
"dano", "hawaii50");
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("dano", "hawaii50");
SecurityContextHolder.getContext().setAuthentication(auth);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY,
"jacklord");
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "jacklord");
SwitchUserFilter filter = new SwitchUserFilter();
filter.setUserDetailsService(new MockUserDetailsService());
@@ -484,16 +470,15 @@ public class SwitchUserFilterTests {
Authentication result = filter.attemptSwitchUser(request);
assertThat(result != null).isTrue();
assertThat(result.getAuthorities()).hasSize(2);
assertThat(AuthorityUtils.authorityListToSet(result.getAuthorities())).contains(
"ROLE_NEW");
assertThat(AuthorityUtils.authorityListToSet(result.getAuthorities())).contains("ROLE_NEW");
}
// SEC-1763
@Test
public void nestedSwitchesAreNotAllowed() {
// original user
UsernamePasswordAuthenticationToken source = new UsernamePasswordAuthenticationToken(
"orig", "hawaii50", ROLES_12);
UsernamePasswordAuthenticationToken source = new UsernamePasswordAuthenticationToken("orig", "hawaii50",
ROLES_12);
SecurityContextHolder.getContext().setAuthentication(source);
SecurityContextHolder.getContext().setAuthentication(switchToUser("jacklord"));
Authentication switched = switchToUser("dano");
@@ -525,8 +510,8 @@ public class SwitchUserFilterTests {
String switchAuthorityRole = "PREVIOUS_ADMINISTRATOR";
// original user
UsernamePasswordAuthenticationToken source = new UsernamePasswordAuthenticationToken(
"orig", "hawaii50", ROLES_12);
UsernamePasswordAuthenticationToken source = new UsernamePasswordAuthenticationToken("orig", "hawaii50",
ROLES_12);
SecurityContextHolder.getContext().setAuthentication(source);
SecurityContextHolder.getContext().setAuthentication(switchToUser("jacklord"));
Authentication switched = switchToUserWithAuthorityRole("dano", switchAuthorityRole);
@@ -566,10 +551,10 @@ public class SwitchUserFilterTests {
// ==================================================================================================
private class MockUserDetailsService implements UserDetailsService {
private String password = "hawaii50";
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// jacklord, dano (active)
// mcgarrett (disabled)
// wofat (account expired)
@@ -590,5 +575,7 @@ public class SwitchUserFilterTests {
throw new UsernameNotFoundException("Could not find: " + username);
}
}
}
}

View File

@@ -21,7 +21,6 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.springframework.security.web.authentication.switchuser.SwitchUserGrantedAuthority;
/**
*
* @author Clement Ng
*
*/
@@ -32,8 +31,7 @@ public class SwitchUserGrantedAuthorityTests {
@Test
public void authorityWithNullRoleFailsAssertion() {
assertThatThrownBy(() -> new SwitchUserGrantedAuthority(null, null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("role cannot be null");
.isInstanceOf(IllegalArgumentException.class).hasMessage("role cannot be null");
}
/**
@@ -41,7 +39,7 @@ public class SwitchUserGrantedAuthorityTests {
@Test
public void authorityWithNullSourceFailsAssertion() {
assertThatThrownBy(() -> new SwitchUserGrantedAuthority("role", null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("source cannot be null");
.isInstanceOf(IllegalArgumentException.class).hasMessage("source cannot be null");
}
}

View File

@@ -31,56 +31,43 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
* @since 5.1
*/
public class DefaultLogoutPageGeneratingFilterTests {
private DefaultLogoutPageGeneratingFilter filter = new DefaultLogoutPageGeneratingFilter();
@Test
public void doFilterWhenNoHiddenInputsThenPageRendered() throws Exception {
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new Object())
.addFilter(this.filter)
.build();
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"
+ " <meta name=\"description\" content=\"\">\n"
+ " <meta name=\"author\" content=\"\">\n"
+ " <title>Confirm Log Out?</title>\n"
+ " <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M\" crossorigin=\"anonymous\">\n"
+ " <link href=\"https://getbootstrap.com/docs/4.0/examples/signin/signin.css\" rel=\"stylesheet\" crossorigin=\"anonymous\"/>\n"
+ " </head>\n"
+ " <body>\n"
+ " <div class=\"container\">\n"
+ " <form class=\"form-signin\" method=\"post\" action=\"/logout\">\n"
+ " <h2 class=\"form-signin-heading\">Are you sure you want to log out?</h2>\n"
+ " <button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\">Log Out</button>\n"
+ " </form>\n"
+ " </div>\n"
+ " </body>\n"
+ "</html>"))
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"
+ " <meta name=\"description\" content=\"\">\n" + " <meta name=\"author\" content=\"\">\n"
+ " <title>Confirm Log Out?</title>\n"
+ " <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M\" crossorigin=\"anonymous\">\n"
+ " <link href=\"https://getbootstrap.com/docs/4.0/examples/signin/signin.css\" rel=\"stylesheet\" crossorigin=\"anonymous\"/>\n"
+ " </head>\n" + " <body>\n" + " <div class=\"container\">\n"
+ " <form class=\"form-signin\" method=\"post\" action=\"/logout\">\n"
+ " <h2 class=\"form-signin-heading\">Are you sure you want to log out?</h2>\n"
+ " <button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\">Log Out</button>\n"
+ " </form>\n" + " </div>\n" + " </body>\n" + "</html>"))
.andExpect(content().contentType("text/html;charset=UTF-8"));
}
@Test
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 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\" />")));
mockMvc.perform(get("/logout")).andExpect(
content().string(containsString("<input name=\"_csrf\" type=\"hidden\" value=\"csrf-token-1\" />")));
}
@Test
public void doFilterWhenRequestContextThenActionContainsRequestContext() throws Exception {
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new Object())
.addFilters(this.filter)
.build();
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

@@ -42,6 +42,7 @@ public class BasicAuthenticationConverterTests {
@Mock
private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource;
private BasicAuthenticationConverter converter;
@Before

View File

@@ -71,7 +71,7 @@ public class BasicAuthenticationEntryPointTests {
assertThat(response.getStatus()).isEqualTo(401);
assertThat(response.getErrorMessage()).isEqualTo(HttpStatus.UNAUTHORIZED.getReasonPhrase());
assertThat(response.getHeader("WWW-Authenticate"))
.isEqualTo("Basic realm=\"hello\"");
assertThat(response.getHeader("WWW-Authenticate")).isEqualTo("Basic realm=\"hello\"");
}
}

View File

@@ -49,10 +49,12 @@ import java.nio.charset.StandardCharsets;
* @author Ben Alex
*/
public class BasicAuthenticationFilterTests {
// ~ Instance fields
// ================================================================================================
private BasicAuthenticationFilter filter;
private AuthenticationManager manager;
// ~ Methods
@@ -61,19 +63,16 @@ public class BasicAuthenticationFilterTests {
@Before
public void setUp() {
SecurityContextHolder.clearContext();
UsernamePasswordAuthenticationToken rodRequest = new UsernamePasswordAuthenticationToken(
"rod", "koala");
UsernamePasswordAuthenticationToken rodRequest = new UsernamePasswordAuthenticationToken("rod", "koala");
rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
Authentication rod = new UsernamePasswordAuthenticationToken("rod", "koala",
AuthorityUtils.createAuthorityList("ROLE_1"));
manager = mock(AuthenticationManager.class);
when(manager.authenticate(rodRequest)).thenReturn(rod);
when(manager.authenticate(not(eq(rodRequest)))).thenThrow(
new BadCredentialsException(""));
when(manager.authenticate(not(eq(rodRequest)))).thenThrow(new BadCredentialsException(""));
filter = new BasicAuthenticationFilter(manager,
new BasicAuthenticationEntryPoint());
filter = new BasicAuthenticationFilter(manager, new BasicAuthenticationEntryPoint());
}
@After
@@ -82,8 +81,7 @@ public class BasicAuthenticationFilterTests {
}
@Test
public void testFilterIgnoresRequestsContainingNoAuthorizationHeader()
throws Exception {
public void testFilterIgnoresRequestsContainingNoAuthorizationHeader() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServletPath("/some_file.html");
@@ -108,8 +106,7 @@ public class BasicAuthenticationFilterTests {
public void testInvalidBasicAuthorizationTokenIsIgnored() throws Exception {
String token = "NOT_A_VALID_TOKEN_AS_MISSING_COLON";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization",
"Basic " + new String(Base64.encodeBase64(token.getBytes())));
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
request.setServletPath("/some_file.html");
request.setSession(new MockHttpSession());
final MockHttpServletResponse response = new MockHttpServletResponse();
@@ -117,8 +114,7 @@ public class BasicAuthenticationFilterTests {
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(any(ServletRequest.class),
any(ServletResponse.class));
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
}
@@ -134,8 +130,7 @@ public class BasicAuthenticationFilterTests {
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
// The filter chain shouldn't proceed
verify(chain, never()).doFilter(any(ServletRequest.class),
any(ServletResponse.class));
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
}
@@ -144,8 +139,7 @@ public class BasicAuthenticationFilterTests {
public void testNormalOperation() throws Exception {
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization",
"Basic " + new String(Base64.encodeBase64(token.getBytes())));
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
request.setServletPath("/some_file.html");
// Test
@@ -155,8 +149,7 @@ public class BasicAuthenticationFilterTests {
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName())
.isEqualTo("rod");
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
}
// gh-5586
@@ -164,8 +157,7 @@ public class BasicAuthenticationFilterTests {
public void doFilterWhenSchemeLowercaseThenCaseInsensitveMatchWorks() throws Exception {
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization",
"basic " + new String(Base64.encodeBase64(token.getBytes())));
request.addHeader("Authorization", "basic " + new String(Base64.encodeBase64(token.getBytes())));
request.setServletPath("/some_file.html");
// Test
@@ -175,16 +167,14 @@ public class BasicAuthenticationFilterTests {
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName())
.isEqualTo("rod");
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
}
@Test
public void doFilterWhenSchemeMixedCaseThenCaseInsensitiveMatchWorks() throws Exception {
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization",
"BaSiC " + new String(Base64.encodeBase64(token.getBytes())));
request.addHeader("Authorization", "BaSiC " + new String(Base64.encodeBase64(token.getBytes())));
request.setServletPath("/some_file.html");
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
@@ -193,8 +183,7 @@ public class BasicAuthenticationFilterTests {
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName())
.isEqualTo("rod");
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
}
@Test
@@ -221,12 +210,10 @@ public class BasicAuthenticationFilterTests {
}
@Test
public void testSuccessLoginThenFailureLoginResultsInSessionLosingToken()
throws Exception {
public void testSuccessLoginThenFailureLoginResultsInSessionLosingToken() throws Exception {
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization",
"Basic " + new String(Base64.encodeBase64(token.getBytes())));
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
request.setServletPath("/some_file.html");
final MockHttpServletResponse response1 = new MockHttpServletResponse();
@@ -237,22 +224,19 @@ public class BasicAuthenticationFilterTests {
// Test
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getName())
.isEqualTo("rod");
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())));
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
final MockHttpServletResponse response2 = new MockHttpServletResponse();
chain = mock(FilterChain.class);
filter.doFilter(request, response2, chain);
verify(chain, never()).doFilter(any(ServletRequest.class),
any(ServletResponse.class));
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
@@ -263,12 +247,10 @@ public class BasicAuthenticationFilterTests {
}
@Test
public void testWrongPasswordContinuesFilterChainIfIgnoreFailureIsTrue()
throws Exception {
public void testWrongPasswordContinuesFilterChainIfIgnoreFailureIsTrue() throws Exception {
String token = "rod:WRONG_PASSWORD";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization",
"Basic " + new String(Base64.encodeBase64(token.getBytes())));
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
request.setServletPath("/some_file.html");
request.setSession(new MockHttpSession());
@@ -284,12 +266,10 @@ public class BasicAuthenticationFilterTests {
}
@Test
public void testWrongPasswordReturnsForbiddenIfIgnoreFailureIsFalse()
throws Exception {
public void testWrongPasswordReturnsForbiddenIfIgnoreFailureIsFalse() throws Exception {
String token = "rod:WRONG_PASSWORD";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization",
"Basic " + new String(Base64.encodeBase64(token.getBytes())));
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
request.setServletPath("/some_file.html");
request.setSession(new MockHttpSession());
assertThat(filter.isIgnoreFailure()).isFalse();
@@ -299,8 +279,7 @@ public class BasicAuthenticationFilterTests {
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));
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
}
@@ -311,8 +290,7 @@ public class BasicAuthenticationFilterTests {
String token = "bad:credentials";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization",
"Basic " + new String(Base64.encodeBase64(token.getBytes())));
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();
@@ -330,7 +308,8 @@ public class BasicAuthenticationFilterTests {
UsernamePasswordAuthenticationToken rodRequest = new UsernamePasswordAuthenticationToken("rod", "äöü");
rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
Authentication rod = new UsernamePasswordAuthenticationToken("rod", "äöü", AuthorityUtils.createAuthorityList("ROLE_1"));
Authentication rod = new UsernamePasswordAuthenticationToken("rod", "äöü",
AuthorityUtils.createAuthorityList("ROLE_1"));
manager = mock(AuthenticationManager.class);
when(manager.authenticate(rodRequest)).thenReturn(rod);
@@ -340,7 +319,8 @@ public class BasicAuthenticationFilterTests {
String token = "rod:äöü";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes(StandardCharsets.UTF_8))));
request.addHeader("Authorization",
"Basic " + new String(Base64.encodeBase64(token.getBytes(StandardCharsets.UTF_8))));
request.setServletPath("/some_file.html");
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -363,7 +343,8 @@ public class BasicAuthenticationFilterTests {
UsernamePasswordAuthenticationToken rodRequest = new UsernamePasswordAuthenticationToken("rod", "äöü");
rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
Authentication rod = new UsernamePasswordAuthenticationToken("rod", "äöü", AuthorityUtils.createAuthorityList("ROLE_1"));
Authentication rod = new UsernamePasswordAuthenticationToken("rod", "äöü",
AuthorityUtils.createAuthorityList("ROLE_1"));
manager = mock(AuthenticationManager.class);
when(manager.authenticate(rodRequest)).thenReturn(rod);
@@ -374,7 +355,8 @@ public class BasicAuthenticationFilterTests {
String token = "rod:äöü";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes(StandardCharsets.ISO_8859_1))));
request.addHeader("Authorization",
"Basic " + new String(Base64.encodeBase64(token.getBytes(StandardCharsets.ISO_8859_1))));
request.setServletPath("/some_file.html");
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -397,7 +379,8 @@ public class BasicAuthenticationFilterTests {
UsernamePasswordAuthenticationToken rodRequest = new UsernamePasswordAuthenticationToken("rod", "äöü");
rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
Authentication rod = new UsernamePasswordAuthenticationToken("rod", "äöü", AuthorityUtils.createAuthorityList("ROLE_1"));
Authentication rod = new UsernamePasswordAuthenticationToken("rod", "äöü",
AuthorityUtils.createAuthorityList("ROLE_1"));
manager = mock(AuthenticationManager.class);
when(manager.authenticate(rodRequest)).thenReturn(rod);
@@ -408,7 +391,8 @@ public class BasicAuthenticationFilterTests {
String token = "rod:äöü";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes(StandardCharsets.UTF_8))));
request.addHeader("Authorization",
"Basic " + new String(Base64.encodeBase64(token.getBytes(StandardCharsets.UTF_8))));
request.setServletPath("/some_file.html");
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -434,8 +418,7 @@ public class BasicAuthenticationFilterTests {
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(any(ServletRequest.class),
any(ServletResponse.class));
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
}

View File

@@ -30,6 +30,7 @@ import org.springframework.util.StringUtils;
* @author Ben Alex
*/
public class DigestAuthUtilsTests {
// ~ Constructors
// ===================================================================================================
@@ -40,17 +41,15 @@ public class DigestAuthUtilsTests {
// note it ignores malformed entries (ie those without an equals sign)
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, "=", "\"");
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
assertThat(headerMap.get("username")).isEqualTo("rod");
assertThat(headerMap.get("realm")).isEqualTo("Contacts Realm");
assertThat(headerMap.get("nonce")).isEqualTo(
"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==");
assertThat(headerMap.get("uri")).isEqualTo(
"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4");
assertThat(headerMap.get("response")).isEqualTo(
"38644211cf9ac3da63ab639807e2baff");
assertThat(headerMap.get("nonce"))
.isEqualTo("MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==");
assertThat(headerMap.get("uri"))
.isEqualTo("/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4");
assertThat(headerMap.get("response")).isEqualTo("38644211cf9ac3da63ab639807e2baff");
assertThat(headerMap.get("qop")).isEqualTo("auth");
assertThat(headerMap.get("nc")).isEqualTo("00000004");
assertThat(headerMap.get("cnonce")).isEqualTo("2b8d329a8571b99a");
@@ -61,17 +60,15 @@ public class DigestAuthUtilsTests {
public void testSplitEachArrayElementAndCreateMapRespectsInstructionNotToRemoveCharacters() {
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);
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")).isEqualTo(
"\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\"");
assertThat(headerMap.get("uri")).isEqualTo(
"\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\"");
assertThat(headerMap.get("response")).isEqualTo(
"\"38644211cf9ac3da63ab639807e2baff\"");
assertThat(headerMap.get("nonce"))
.isEqualTo("\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\"");
assertThat(headerMap.get("uri"))
.isEqualTo("\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\"");
assertThat(headerMap.get("response")).isEqualTo("\"38644211cf9ac3da63ab639807e2baff\"");
assertThat(headerMap.get("qop")).isEqualTo("auth");
assertThat(headerMap.get("nc")).isEqualTo("00000004");
assertThat(headerMap.get("cnonce")).isEqualTo("\"2b8d329a8571b99a\"");
@@ -80,10 +77,8 @@ public class DigestAuthUtilsTests {
@Test
public void testSplitEachArrayElementAndCreateMapReturnsNullIfArrayEmptyOrNull() {
assertThat(DigestAuthUtils.splitEachArrayElementAndCreateMap(null, "=",
"\"")).isNull();
assertThat(DigestAuthUtils.splitEachArrayElementAndCreateMap(new String[] {}, "=",
"\"")).isNull();
assertThat(DigestAuthUtils.splitEachArrayElementAndCreateMap(null, "=", "\"")).isNull();
assertThat(DigestAuthUtils.splitEachArrayElementAndCreateMap(new String[] {}, "=", "\"")).isNull();
}
@Test
@@ -159,4 +154,5 @@ public class DigestAuthUtilsTests {
assertThat(parts).hasSize(8);
}
}

View File

@@ -36,6 +36,7 @@ import static org.assertj.core.api.Assertions.fail;
* @author Ben Alex
*/
public class DigestAuthenticationEntryPointTests {
// ~ Methods
// ========================================================================================================
@@ -111,14 +112,12 @@ public class DigestAuthenticationEntryPointTests {
// Check response is properly formed
assertThat(response.getStatus()).isEqualTo(401);
assertThat(response.getHeader("WWW-Authenticate").toString())
.startsWith("Digest ");
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, "=", "\"");
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
assertThat(headerMap.get("realm")).isEqualTo("hello");
assertThat(headerMap.get("qop")).isEqualTo("auth");
@@ -144,14 +143,12 @@ public class DigestAuthenticationEntryPointTests {
// Check response is properly formed
assertThat(response.getStatus()).isEqualTo(401);
assertThat(response.getHeader("WWW-Authenticate").toString())
.startsWith("Digest ");
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, "=", "\"");
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
assertThat(headerMap.get("realm")).isEqualTo("hello");
assertThat(headerMap.get("qop")).isEqualTo("auth");
@@ -159,4 +156,5 @@ public class DigestAuthenticationEntryPointTests {
checkNonceValid(headerMap.get("nonce"));
}
}

View File

@@ -53,6 +53,7 @@ import static org.mockito.Mockito.verify;
* @author Luke Taylor
*/
public class DigestAuthenticationFilterTests {
// ~ Static fields/initializers
// =====================================================================================
@@ -88,16 +89,14 @@ public class DigestAuthenticationFilterTests {
// ~ Methods
// ========================================================================================================
private String createAuthorizationHeader(String username, String realm, String nonce,
String uri, String responseDigest, String qop, String nc, String cnonce) {
return "Digest username=\"" + username + "\", realm=\"" + realm + "\", nonce=\""
+ nonce + "\", uri=\"" + uri + "\", response=\"" + responseDigest
+ "\", qop=" + qop + ", nc=" + nc + ", cnonce=\"" + cnonce + "\"";
private String createAuthorizationHeader(String username, String realm, String nonce, String uri,
String responseDigest, String qop, String nc, String cnonce) {
return "Digest username=\"" + username + "\", realm=\"" + realm + "\", nonce=\"" + nonce + "\", uri=\"" + uri
+ "\", response=\"" + responseDigest + "\", qop=" + qop + ", nc=" + nc + ", cnonce=\"" + cnonce + "\"";
}
private MockHttpServletResponse executeFilterInContainerSimulator(Filter filter,
final ServletRequest request, final boolean expectChainToProceed)
throws ServletException, IOException {
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);
@@ -148,46 +147,42 @@ public class DigestAuthenticationFilterTests {
@Test
public void testExpiredNonceReturnsForbiddenWithStaleHeader() throws Exception {
String nonce = generateNonce(0);
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM,
PASSWORD, "GET", REQUEST_URI, QOP, nonce, NC, CNONCE);
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, nonce, NC, CNONCE);
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
Thread.sleep(1000); // ensures token expired
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, 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, "=", "\"");
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
assertThat(headerMap.get("stale")).isEqualTo("true");
}
@Test
public void doFilterWhenNonceHasBadKeyThenGeneratesError() throws Exception {
String badNonce = generateNonce(60, "badkey");
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM,
PASSWORD, "GET", REQUEST_URI, QOP, badNonce, NC, CNONCE);
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, badNonce, NC, CNONCE);
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
badNonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, badNonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response =
executeFilterInContainerSimulator(filter, request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
assertThat(response.getStatus()).isEqualTo(401);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void testFilterIgnoresRequestsContainingNoAuthorizationHeader()
throws Exception {
public void testFilterIgnoresRequestsContainingNoAuthorizationHeader() throws Exception {
executeFilterInContainerSimulator(filter, request, true);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
@@ -212,11 +207,9 @@ public class DigestAuthenticationFilterTests {
public void testInvalidDigestAuthorizationTokenGeneratesError() throws Exception {
String token = "NOT_A_VALID_TOKEN_AS_MISSING_COLON";
request.addHeader("Authorization",
"Digest " + new String(Base64.encodeBase64(token.getBytes())));
request.addHeader("Authorization", "Digest " + new String(Base64.encodeBase64(token.getBytes())));
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
assertThat(response.getStatus()).isEqualTo(401);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
@@ -226,8 +219,7 @@ public class DigestAuthenticationFilterTests {
public void testMalformedHeaderReturnsForbidden() throws Exception {
request.addHeader("Authorization", "Digest scsdcsdc");
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
@@ -237,32 +229,28 @@ public class DigestAuthenticationFilterTests {
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);
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, nonce, NC, CNONCE);
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
}
@Test
public void testNonceWithIncorrectSignatureForNumericFieldReturnsForbidden()
throws Exception {
String nonce = new String(
Base64.encodeBase64("123456:incorrectStringPassword".getBytes()));
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM,
PASSWORD, "GET", REQUEST_URI, QOP, nonce, NC, CNONCE);
public void testNonceWithIncorrectSignatureForNumericFieldReturnsForbidden() throws Exception {
String nonce = new String(Base64.encodeBase64("123456:incorrectStringPassword".getBytes()));
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, nonce, NC, CNONCE);
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
@@ -270,34 +258,29 @@ public class DigestAuthenticationFilterTests {
@Test
public void testNonceWithNonNumericFirstElementReturnsForbidden() throws Exception {
String nonce = new String(
Base64.encodeBase64("hello:ignoredSecondElement".getBytes()));
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM,
PASSWORD, "GET", REQUEST_URI, QOP, nonce, NC, CNONCE);
String nonce = new String(Base64.encodeBase64("hello:ignoredSecondElement".getBytes()));
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, nonce, NC, CNONCE);
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
}
@Test
public void testNonceWithoutTwoColonSeparatedElementsReturnsForbidden()
throws Exception {
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);
public void testNonceWithoutTwoColonSeparatedElementsReturnsForbidden() throws Exception {
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);
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
@@ -305,61 +288,53 @@ public class DigestAuthenticationFilterTests {
@Test
public void testNormalOperationWhenPasswordIsAlreadyEncoded() throws Exception {
String encodedPassword = DigestAuthUtils.encodePasswordInA1Format(USERNAME, REALM,
PASSWORD);
String responseDigest = DigestAuthUtils.generateDigest(true, USERNAME, REALM,
encodedPassword, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE);
String encodedPassword = DigestAuthUtils.encodePasswordInA1Format(USERNAME, REALM, PASSWORD);
String responseDigest = DigestAuthUtils.generateDigest(true, USERNAME, REALM, encodedPassword, "GET",
REQUEST_URI, QOP, NONCE, NC, CNONCE);
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
executeFilterInContainerSimulator(filter, request, true);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()).isEqualTo(
USERNAME);
assertThat(((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername())
.isEqualTo(USERNAME);
}
@Test
public void testNormalOperationWhenPasswordNotAlreadyEncoded() throws Exception {
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM,
PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE);
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, NONCE, NC, CNONCE);
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
executeFilterInContainerSimulator(filter, request, true);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()).isEqualTo(
USERNAME);
assertThat(
SecurityContextHolder.getContext().getAuthentication().isAuthenticated()).isFalse();
assertThat(((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername())
.isEqualTo(USERNAME);
assertThat(SecurityContextHolder.getContext().getAuthentication().isAuthenticated()).isFalse();
}
@Test
public void testNormalOperationWhenPasswordNotAlreadyEncodedAndWithoutReAuthentication()
throws Exception {
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM,
PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE);
public void testNormalOperationWhenPasswordNotAlreadyEncodedAndWithoutReAuthentication() throws Exception {
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, NONCE, NC, CNONCE);
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
filter.setCreateAuthenticatedToken(true);
executeFilterInContainerSimulator(filter, request, true);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()).isEqualTo(
USERNAME);
assertThat(
SecurityContextHolder.getContext().getAuthentication().isAuthenticated()).isTrue();
assertThat(
SecurityContextHolder.getContext().getAuthentication().getAuthorities()).isEqualTo(
AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
assertThat(((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername())
.isEqualTo(USERNAME);
assertThat(SecurityContextHolder.getContext().getAuthentication().isAuthenticated()).isTrue();
assertThat(SecurityContextHolder.getContext().getAuthentication().getAuthorities())
.isEqualTo(AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
}
@Test
@@ -386,28 +361,26 @@ public class DigestAuthenticationFilterTests {
}
@Test
public void successfulLoginThenFailedLoginResultsInSessionLosingToken()
throws Exception {
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM,
PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE);
public void successfulLoginThenFailedLoginResultsInSessionLosingToken() throws Exception {
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, NONCE, NC, CNONCE);
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
executeFilterInContainerSimulator(filter, 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);
responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, "WRONG_PASSWORD", "GET", REQUEST_URI,
QOP, NONCE, NC, CNONCE);
request = new MockHttpServletRequest();
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
// Check we lost our previous authentication
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
@@ -418,14 +391,13 @@ public class DigestAuthenticationFilterTests {
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");
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, NONCE, NC, "DIFFERENT_CNONCE");
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
NONCE, REQUEST_URI, responseDigest, QOP, NC, cnonce));
request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, cnonce));
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
@@ -434,14 +406,13 @@ public class DigestAuthenticationFilterTests {
@Test
public void wrongDigestReturnsForbidden() throws Exception {
String password = "WRONG_PASSWORD";
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM,
password, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE);
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, password, "GET", REQUEST_URI,
QOP, NONCE, NC, CNONCE);
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
@@ -450,14 +421,13 @@ public class DigestAuthenticationFilterTests {
@Test
public void wrongRealmReturnsForbidden() throws Exception {
String realm = "WRONG_REALM";
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, realm,
PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE);
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, realm, PASSWORD, "GET", REQUEST_URI,
QOP, NONCE, NC, CNONCE);
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, realm,
NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, realm, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
@@ -465,14 +435,13 @@ public class DigestAuthenticationFilterTests {
@Test
public void wrongUsernameReturnsForbidden() throws Exception {
String responseDigest = DigestAuthUtils.generateDigest(false, "NOT_A_KNOWN_USER",
REALM, PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, CNONCE);
String responseDigest = DigestAuthUtils.generateDigest(false, "NOT_A_KNOWN_USER", REALM, PASSWORD, "GET",
REQUEST_URI, QOP, NONCE, NC, CNONCE);
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
@@ -482,21 +451,22 @@ public class DigestAuthenticationFilterTests {
@Test
public void authenticationCreatesEmptyContext() throws Exception {
SecurityContext existingContext = SecurityContextHolder.createEmptyContext();
TestingAuthenticationToken existingAuthentication = new TestingAuthenticationToken(
"existingauthenitcated", "pass", "ROLE_USER");
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);
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, NONCE, NC, CNONCE);
request.addHeader("Authorization", createAuthorizationHeader(USERNAME, REALM,
NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
filter.setCreateAuthenticatedToken(true);
executeFilterInContainerSimulator(filter, request, true);
assertThat(existingAuthentication).isSameAs(existingContext.getAuthentication());
}
}

View File

@@ -41,7 +41,9 @@ import org.springframework.util.ReflectionUtils;
*/
@SuppressWarnings("deprecation")
public class AuthenticationPrincipalArgumentResolverTests {
private Object expectedPrincipal;
private AuthenticationPrincipalArgumentResolver resolver;
@Before
@@ -71,60 +73,51 @@ public class AuthenticationPrincipalArgumentResolverTests {
@Test
public void resolveArgumentNullAuthentication() throws Exception {
assertThat(resolver.resolveArgument(showUserAnnotationString(), null, null, null))
.isNull();
assertThat(resolver.resolveArgument(showUserAnnotationString(), null, null, null)).isNull();
}
@Test
public void resolveArgumentNullPrincipal() throws Exception {
setAuthenticationPrincipal(null);
assertThat(resolver.resolveArgument(showUserAnnotationString(), null, null, null))
.isNull();
assertThat(resolver.resolveArgument(showUserAnnotationString(), null, null, null)).isNull();
}
@Test
public void resolveArgumentString() throws Exception {
setAuthenticationPrincipal("john");
assertThat(resolver.resolveArgument(showUserAnnotationString(), null, null, null))
.isEqualTo(expectedPrincipal);
assertThat(resolver.resolveArgument(showUserAnnotationString(), null, null, null)).isEqualTo(expectedPrincipal);
}
@Test
public void resolveArgumentPrincipalStringOnObject() throws Exception {
setAuthenticationPrincipal("john");
assertThat(resolver.resolveArgument(showUserAnnotationObject(), null, null, null))
.isEqualTo(expectedPrincipal);
assertThat(resolver.resolveArgument(showUserAnnotationObject(), null, null, null)).isEqualTo(expectedPrincipal);
}
@Test
public void resolveArgumentUserDetails() throws Exception {
setAuthenticationPrincipal(new User("user", "password",
AuthorityUtils.createAuthorityList("ROLE_USER")));
assertThat(
resolver.resolveArgument(showUserAnnotationUserDetails(), null, null,
null)).isEqualTo(expectedPrincipal);
setAuthenticationPrincipal(new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER")));
assertThat(resolver.resolveArgument(showUserAnnotationUserDetails(), null, null, null))
.isEqualTo(expectedPrincipal);
}
@Test
public void resolveArgumentCustomUserPrincipal() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
assertThat(
resolver.resolveArgument(showUserAnnotationCustomUserPrincipal(), null,
null, null)).isEqualTo(expectedPrincipal);
assertThat(resolver.resolveArgument(showUserAnnotationCustomUserPrincipal(), null, null, null))
.isEqualTo(expectedPrincipal);
}
@Test
public void resolveArgumentCustomAnnotation() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
assertThat(resolver.resolveArgument(showUserCustomAnnotation(), null, null, null))
.isEqualTo(expectedPrincipal);
assertThat(resolver.resolveArgument(showUserCustomAnnotation(), null, null, null)).isEqualTo(expectedPrincipal);
}
@Test
public void resolveArgumentNullOnInvalidType() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
assertThat(resolver.resolveArgument(showUserAnnotationString(), null, null, null))
.isNull();
assertThat(resolver.resolveArgument(showUserAnnotationString(), null, null, null)).isNull();
}
@Test(expected = ClassCastException.class)
@@ -136,15 +129,13 @@ public class AuthenticationPrincipalArgumentResolverTests {
@Test(expected = ClassCastException.class)
public void resolveArgumentCustomserErrorOnInvalidType() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
resolver.resolveArgument(showUserAnnotationCurrentUserErrorOnInvalidType(), null,
null, null);
resolver.resolveArgument(showUserAnnotationCurrentUserErrorOnInvalidType(), null, null, null);
}
@Test
public void resolveArgumentObject() throws Exception {
setAuthenticationPrincipal(new Object());
assertThat(resolver.resolveArgument(showUserAnnotationObject(), null, null, null))
.isEqualTo(expectedPrincipal);
assertThat(resolver.resolveArgument(showUserAnnotationObject(), null, null, null)).isEqualTo(expectedPrincipal);
}
private MethodParameter showUserNoAnnotation() {
@@ -160,8 +151,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
}
private MethodParameter showUserAnnotationCurrentUserErrorOnInvalidType() {
return getMethodParameter("showUserAnnotationCurrentUserErrorOnInvalidType",
String.class);
return getMethodParameter("showUserAnnotationCurrentUserErrorOnInvalidType", String.class);
}
private MethodParameter showUserAnnotationUserDetails() {
@@ -181,8 +171,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
}
private MethodParameter getMethodParameter(String methodName, Class<?>... paramTypes) {
Method method = ReflectionUtils.findMethod(TestController.class, methodName,
paramTypes);
Method method = ReflectionUtils.findMethod(TestController.class, methodName, paramTypes);
return new MethodParameter(method, 0);
}
@@ -190,15 +179,18 @@ public class AuthenticationPrincipalArgumentResolverTests {
@Retention(RetentionPolicy.RUNTIME)
@AuthenticationPrincipal
static @interface CurrentUser {
}
@Target({ ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@AuthenticationPrincipal(errorOnInvalidType = true)
static @interface CurrentUserErrorOnInvalidType {
}
public static class TestController {
public void showUserNoAnnotation(String user) {
}
@@ -209,8 +201,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
@AuthenticationPrincipal(errorOnInvalidType = true) String user) {
}
public void showUserAnnotationCurrentUserErrorOnInvalidType(
@CurrentUserErrorOnInvalidType String user) {
public void showUserAnnotationCurrentUserErrorOnInvalidType(@CurrentUserErrorOnInvalidType String user) {
}
public void showUserAnnotation(@AuthenticationPrincipal UserDetails user) {
@@ -224,16 +215,17 @@ public class AuthenticationPrincipalArgumentResolverTests {
public void showUserAnnotation(@AuthenticationPrincipal Object user) {
}
}
private static class CustomUserPrincipal {
}
private void setAuthenticationPrincipal(Object principal) {
this.expectedPrincipal = principal;
SecurityContextHolder.getContext()
.setAuthentication(
new TestingAuthenticationToken(expectedPrincipal, "password",
"ROLE_USER"));
.setAuthentication(new TestingAuthenticationToken(expectedPrincipal, "password", "ROLE_USER"));
}
}

View File

@@ -100,7 +100,8 @@ public class ConcurrentSessionFilterTests {
// Setup our test fixture and registry to want this session to be expired
SimpleRedirectSessionInformationExpiredStrategy expiredSessionStrategy = new SimpleRedirectSessionInformationExpiredStrategy("/expired.jsp");
SimpleRedirectSessionInformationExpiredStrategy expiredSessionStrategy = new SimpleRedirectSessionInformationExpiredStrategy(
"/expired.jsp");
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, expiredSessionStrategy);
filter.setLogoutHandlers(new LogoutHandler[] { new SecurityContextLogoutHandler() });
filter.afterPropertiesSet();
@@ -131,7 +132,8 @@ public class ConcurrentSessionFilterTests {
filter.doFilter(request, response, fc);
verifyZeroInteractions(fc);
assertThat(response.getContentAsString()).isEqualTo("This session has been expired (possibly due to multiple concurrent logins being "
assertThat(response.getContentAsString())
.isEqualTo("This session has been expired (possibly due to multiple concurrent logins being "
+ "attempted as the same user).");
}
@@ -153,7 +155,8 @@ public class ConcurrentSessionFilterTests {
// Setup our test fixture
SessionRegistry registry = new SessionRegistryImpl();
registry.registerNewSession(session.getId(), "principal");
SimpleRedirectSessionInformationExpiredStrategy expiredSessionStrategy = new SimpleRedirectSessionInformationExpiredStrategy("/expired.jsp");
SimpleRedirectSessionInformationExpiredStrategy expiredSessionStrategy = new SimpleRedirectSessionInformationExpiredStrategy(
"/expired.jsp");
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, expiredSessionStrategy);
Date lastRequest = registry.getSessionInformation(session.getId()).getLastRequest();
@@ -173,14 +176,13 @@ public class ConcurrentSessionFilterTests {
RedirectStrategy redirect = mock(RedirectStrategy.class);
SessionRegistry registry = mock(SessionRegistry.class);
SessionInformation information = new SessionInformation("user", "sessionId", new Date(System.currentTimeMillis() - 1000));
SessionInformation information = new SessionInformation("user", "sessionId",
new Date(System.currentTimeMillis() - 1000));
information.expireNow();
when(registry.getSessionInformation(anyString())).thenReturn(information);
String expiredUrl = "/expired";
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry,
expiredUrl);
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, expiredUrl);
filter.setRedirectStrategy(redirect);
MockFilterChain chain = new MockFilterChain();
@@ -199,10 +201,8 @@ public class ConcurrentSessionFilterTests {
RedirectStrategy redirect = mock(RedirectStrategy.class);
SessionRegistry registry = mock(SessionRegistry.class);
String expiredUrl = "/expired";
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry,
expiredUrl);
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, expiredUrl);
filter.setRedirectStrategy(redirect);
MockFilterChain chain = new MockFilterChain();
@@ -221,14 +221,13 @@ public class ConcurrentSessionFilterTests {
RedirectStrategy redirect = mock(RedirectStrategy.class);
SessionRegistry registry = mock(SessionRegistry.class);
SessionInformation information = new SessionInformation("user", "sessionId", new Date(System.currentTimeMillis() - 1000));
SessionInformation information = new SessionInformation("user", "sessionId",
new Date(System.currentTimeMillis() - 1000));
information.expireNow();
when(registry.getSessionInformation(anyString())).thenReturn(information);
String expiredUrl = "/expired";
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry,
expiredUrl);
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, expiredUrl);
filter.setRedirectStrategy(redirect);
filter.doFilter(request, response, new MockFilterChain());
@@ -245,22 +244,24 @@ public class ConcurrentSessionFilterTests {
RedirectStrategy redirect = mock(RedirectStrategy.class);
SessionRegistry registry = mock(SessionRegistry.class);
SessionInformation information = new SessionInformation("user", "sessionId", new Date(System.currentTimeMillis() - 1000));
SessionInformation information = new SessionInformation("user", "sessionId",
new Date(System.currentTimeMillis() - 1000));
information.expireNow();
when(registry.getSessionInformation(anyString())).thenReturn(information);
final String expiredUrl = "/expired";
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry,
expiredUrl + "will-be-overrridden") {
/* (non-Javadoc)
* @see org.springframework.security.web.session.ConcurrentSessionFilter#determineExpiredUrl(javax.servlet.http.HttpServletRequest, org.springframework.security.core.session.SessionInformation)
*/
@Override
protected String determineExpiredUrl(HttpServletRequest request,
SessionInformation info) {
return expiredUrl;
}
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, expiredUrl + "will-be-overrridden") {
/*
* (non-Javadoc)
*
* @see org.springframework.security.web.session.ConcurrentSessionFilter#
* determineExpiredUrl(javax.servlet.http.HttpServletRequest,
* org.springframework.security.core.session.SessionInformation)
*/
@Override
protected String determineExpiredUrl(HttpServletRequest request, SessionInformation info) {
return expiredUrl;
}
};
filter.setRedirectStrategy(redirect);
@@ -278,11 +279,11 @@ public class ConcurrentSessionFilterTests {
MockHttpServletResponse response = new MockHttpServletResponse();
SessionRegistry registry = mock(SessionRegistry.class);
SessionInformation information = new SessionInformation("user", "sessionId", new Date(System.currentTimeMillis() - 1000));
SessionInformation information = new SessionInformation("user", "sessionId",
new Date(System.currentTimeMillis() - 1000));
information.expireNow();
when(registry.getSessionInformation(anyString())).thenReturn(information);
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry);
filter.doFilter(request, response, new MockFilterChain());
@@ -300,13 +301,13 @@ public class ConcurrentSessionFilterTests {
MockHttpServletResponse response = new MockHttpServletResponse();
SessionRegistry registry = mock(SessionRegistry.class);
SessionInformation information = new SessionInformation("user", "sessionId", new Date(System.currentTimeMillis() - 1000));
SessionInformation information = new SessionInformation("user", "sessionId",
new Date(System.currentTimeMillis() - 1000));
information.expireNow();
when(registry.getSessionInformation(anyString())).thenReturn(information);
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry);
filter.setLogoutHandlers(new LogoutHandler[] { handler } );
filter.setLogoutHandlers(new LogoutHandler[] { handler });
filter.doFilter(request, response, new MockFilterChain());
@@ -326,4 +327,5 @@ public class ConcurrentSessionFilterTests {
filter.setLogoutHandlers(new LogoutHandler[0]);
}
}

View File

@@ -50,8 +50,9 @@ import static org.powermock.api.mockito.PowerMockito.when;
* @author Josh Cummings
*/
public class AbstractSecurityWebApplicationInitializerTests {
private static final EnumSet<DispatcherType> DEFAULT_DISPATCH =
EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.ASYNC);
private static final EnumSet<DispatcherType> DEFAULT_DISPATCH = EnumSet.of(DispatcherType.REQUEST,
DispatcherType.ERROR, DispatcherType.ASYNC);
@Test
public void onStartupWhenDefaultContextThenRegistersSpringSecurityFilterChain() {
@@ -59,10 +60,10 @@ public class AbstractSecurityWebApplicationInitializerTests {
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture()))
.thenReturn(registration);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
new AbstractSecurityWebApplicationInitializer() {}.onStartup(context);
new AbstractSecurityWebApplicationInitializer() {
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
@@ -78,10 +79,10 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture()))
.thenReturn(registration);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
new AbstractSecurityWebApplicationInitializer(MyRootConfiguration.class) {}.onStartup(context);
new AbstractSecurityWebApplicationInitializer(MyRootConfiguration.class) {
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
@@ -91,7 +92,9 @@ public class AbstractSecurityWebApplicationInitializerTests {
}
@Configuration
static class MyRootConfiguration {}
static class MyRootConfiguration {
}
@Test
public void onStartupWhenEnableHttpSessionEventPublisherIsTrueThenAddsHttpSessionEventPublisher() {
@@ -100,8 +103,7 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture()))
.thenReturn(registration);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
protected boolean enableHttpSessionEventPublisher() {
@@ -123,8 +125,7 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture()))
.thenReturn(registration);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
protected EnumSet<DispatcherType> getSecurityDispatcherTypes() {
@@ -134,7 +135,8 @@ public class AbstractSecurityWebApplicationInitializerTests {
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.FORWARD), false, "/*");
verify(registration).addMappingForUrlPatterns(
EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.FORWARD), false, "/*");
verify(registration).setAsyncSupported(true);
verifyNoAddListener(context);
}
@@ -146,8 +148,7 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture()))
.thenReturn(registration);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
protected String getDispatcherWebApplicationContextSuffix() {
@@ -169,11 +170,10 @@ public class AbstractSecurityWebApplicationInitializerTests {
public void onStartupWhenSpringSecurityFilterChainAlreadyRegisteredThenException() {
ServletContext context = mock(ServletContext.class);
assertThatCode(() ->
new AbstractSecurityWebApplicationInitializer() {}.onStartup(context))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Duplicate Filter registration for 'springSecurityFilterChain'. " +
"Check to ensure the Filter is only configured once.");
assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() {
}.onStartup(context)).isInstanceOf(IllegalStateException.class)
.hasMessage("Duplicate Filter registration for 'springSecurityFilterChain'. "
+ "Check to ensure the Filter is only configured once.");
}
@Test
@@ -185,8 +185,7 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture()))
.thenReturn(registration);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
when(context.addFilter(anyString(), eq(filter1))).thenReturn(registration);
when(context.addFilter(anyString(), eq(filter2))).thenReturn(registration);
@@ -213,18 +212,14 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture()))
.thenReturn(registration);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
assertThatCode(() ->
new AbstractSecurityWebApplicationInitializer() {
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context, filter1);
}
}.onStartup(context))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Duplicate Filter registration for 'object'. " +
"Check to ensure the Filter is only configured once.");
assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() {
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context, filter1);
}
}.onStartup(context)).isInstanceOf(IllegalStateException.class).hasMessage(
"Duplicate Filter registration for 'object'. " + "Check to ensure the Filter is only configured once.");
assertProxyDefaults(proxyCaptor.getValue());
@@ -239,16 +234,13 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture()))
.thenReturn(registration);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
assertThatCode(() ->
new AbstractSecurityWebApplicationInitializer() {
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context);
}
}.onStartup(context))
.isInstanceOf(IllegalArgumentException.class)
assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() {
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context);
}
}.onStartup(context)).isInstanceOf(IllegalArgumentException.class)
.hasMessage("filters cannot be null or empty");
assertProxyDefaults(proxyCaptor.getValue());
@@ -262,17 +254,14 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture()))
.thenReturn(registration);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
when(context.addFilter(anyString(), eq(filter))).thenReturn(registration);
assertThatCode(() ->
new AbstractSecurityWebApplicationInitializer() {
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context, filter, null);
}
}.onStartup(context))
.isInstanceOf(IllegalArgumentException.class)
assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() {
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
insertFilters(context, filter, null);
}
}.onStartup(context)).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("filters cannot contain null values");
verify(context, times(2)).addFilter(anyString(), any(Filter.class));
@@ -287,8 +276,7 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture()))
.thenReturn(registration);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
when(context.addFilter(anyString(), eq(filter1))).thenReturn(registration);
when(context.addFilter(anyString(), eq(filter2))).thenReturn(registration);
@@ -313,18 +301,14 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture()))
.thenReturn(registration);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
assertThatCode(() ->
new AbstractSecurityWebApplicationInitializer() {
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context, filter1);
}
}.onStartup(context))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Duplicate Filter registration for 'object'. " +
"Check to ensure the Filter is only configured once.");
assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() {
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context, filter1);
}
}.onStartup(context)).isInstanceOf(IllegalStateException.class).hasMessage(
"Duplicate Filter registration for 'object'. " + "Check to ensure the Filter is only configured once.");
assertProxyDefaults(proxyCaptor.getValue());
@@ -332,7 +316,6 @@ public class AbstractSecurityWebApplicationInitializerTests {
verify(context).addFilter(anyString(), eq(filter1));
}
@Test
public void onStartupWhenAppendFiltersEmptyThenException() {
ServletContext context = mock(ServletContext.class);
@@ -340,16 +323,13 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture()))
.thenReturn(registration);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
assertThatCode(() ->
new AbstractSecurityWebApplicationInitializer() {
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context);
}
}.onStartup(context))
.isInstanceOf(IllegalArgumentException.class)
assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() {
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context);
}
}.onStartup(context)).isInstanceOf(IllegalArgumentException.class)
.hasMessage("filters cannot be null or empty");
assertProxyDefaults(proxyCaptor.getValue());
@@ -363,17 +343,14 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture()))
.thenReturn(registration);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
when(context.addFilter(anyString(), eq(filter))).thenReturn(registration);
assertThatCode(() ->
new AbstractSecurityWebApplicationInitializer() {
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context, filter, null);
}
}.onStartup(context))
.isInstanceOf(IllegalArgumentException.class)
assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() {
protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
appendFilters(context, filter, null);
}
}.onStartup(context)).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("filters cannot contain null values");
verify(context, times(2)).addFilter(anyString(), any(Filter.class));
@@ -385,14 +362,15 @@ public class AbstractSecurityWebApplicationInitializerTests {
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture()))
.thenReturn(registration);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
ArgumentCaptor<Set<SessionTrackingMode>> modesCaptor = ArgumentCaptor
.forClass(new HashSet<SessionTrackingMode>(){}.getClass());
.forClass(new HashSet<SessionTrackingMode>() {
}.getClass());
doNothing().when(context).setSessionTrackingModes(modesCaptor.capture());
new AbstractSecurityWebApplicationInitializer() { }.onStartup(context);
new AbstractSecurityWebApplicationInitializer() {
}.onStartup(context);
assertProxyDefaults(proxyCaptor.getValue());
@@ -407,11 +385,11 @@ public class AbstractSecurityWebApplicationInitializerTests {
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture()))
.thenReturn(registration);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
ArgumentCaptor<Set<SessionTrackingMode>> modesCaptor = ArgumentCaptor
.forClass(new HashSet<SessionTrackingMode>(){}.getClass());
.forClass(new HashSet<SessionTrackingMode>() {
}.getClass());
doNothing().when(context).setSessionTrackingModes(modesCaptor.capture());
new AbstractSecurityWebApplicationInitializer() {
@@ -444,4 +422,5 @@ public class AbstractSecurityWebApplicationInitializerTests {
assertThat(proxy.getContextAttribute()).isNull();
assertThat(proxy).hasFieldOrPropertyWithValue("targetBeanName", "springSecurityFilterChain");
}
}

View File

@@ -57,8 +57,7 @@ import static org.springframework.security.web.context.HttpSessionSecurityContex
*/
public class HttpSessionSecurityContextRepositoryTests {
private final TestingAuthenticationToken testToken = new TestingAuthenticationToken(
"someone", "passwd", "ROLE_A");
private final TestingAuthenticationToken testToken = new TestingAuthenticationToken("someone", "passwd", "ROLE_A");
@After
public void tearDown() {
@@ -70,8 +69,7 @@ public class HttpSessionSecurityContextRepositoryTests {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
HttpServletRequest request = mock(HttpServletRequest.class);
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
response);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
repo.loadContext(holder);
reset(request);
@@ -88,8 +86,7 @@ public class HttpSessionSecurityContextRepositoryTests {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
HttpServletRequest request = mock(HttpServletRequest.class);
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
response);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
repo.loadContext(holder);
reset(request);
@@ -106,8 +103,7 @@ public class HttpSessionSecurityContextRepositoryTests {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
response);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContext context = repo.loadContext(holder);
assertThat(request.getSession(false)).isNull();
repo.saveContext(context, holder.getRequest(), holder.getResponse());
@@ -120,8 +116,7 @@ public class HttpSessionSecurityContextRepositoryTests {
repo.setAllowSessionCreation(false);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
response);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContext context = repo.loadContext(holder);
// Change context
context.setAuthentication(testToken);
@@ -135,11 +130,9 @@ public class HttpSessionSecurityContextRepositoryTests {
repo.setSpringSecurityContextKey("imTheContext");
MockHttpServletRequest request = new MockHttpServletRequest();
SecurityContextHolder.getContext().setAuthentication(testToken);
request.getSession().setAttribute("imTheContext",
SecurityContextHolder.getContext());
request.getSession().setAttribute("imTheContext", SecurityContextHolder.getContext());
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
response);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContext context = repo.loadContext(holder);
assertThat(context).isNotNull();
assertThat(context.getAuthentication()).isEqualTo(testToken);
@@ -161,13 +154,12 @@ public class HttpSessionSecurityContextRepositoryTests {
HttpSession session = mock(HttpSession.class);
when(session.getAttribute(SPRING_SECURITY_CONTEXT_KEY)).thenReturn(ctx);
request.setSession(session);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
new MockHttpServletResponse());
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"));
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
@@ -179,11 +171,9 @@ public class HttpSessionSecurityContextRepositoryTests {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
MockHttpServletRequest request = new MockHttpServletRequest();
SecurityContextHolder.getContext().setAuthentication(testToken);
request.getSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY,
"NotASecurityContextInstance");
request.getSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY, "NotASecurityContextInstance");
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
response);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContext context = repo.loadContext(holder);
assertThat(context).isNotNull();
assertThat(context.getAuthentication()).isNull();
@@ -194,17 +184,14 @@ public class HttpSessionSecurityContextRepositoryTests {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
response);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContext context = repo.loadContext(holder);
assertThat(request.getSession(false)).isNull();
// Simulate authentication during the request
context.setAuthentication(testToken);
repo.saveContext(context, holder.getRequest(), holder.getResponse());
assertThat(request.getSession(false)).isNotNull();
assertThat(
request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isEqualTo(
context);
assertThat(request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isEqualTo(context);
}
@Test
@@ -213,20 +200,15 @@ public class HttpSessionSecurityContextRepositoryTests {
repo.setSpringSecurityContextKey("imTheContext");
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
response);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(testToken);
holder.getResponse().sendRedirect("/doesntmatter");
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
SecurityContextHolder.getContext());
assertThat(
((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue();
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
holder.getResponse());
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
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
SecurityContextHolder.getContext());
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext());
}
@Test
@@ -235,21 +217,16 @@ public class HttpSessionSecurityContextRepositoryTests {
repo.setSpringSecurityContextKey("imTheContext");
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
response);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(testToken);
holder.getResponse().sendError(404);
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
SecurityContextHolder.getContext());
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext());
assertThat(
((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue();
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
holder.getResponse());
assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue();
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
// Check it's still the same
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
SecurityContextHolder.getContext());
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext());
}
// SEC-2005
@@ -259,20 +236,15 @@ public class HttpSessionSecurityContextRepositoryTests {
repo.setSpringSecurityContextKey("imTheContext");
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
response);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(testToken);
holder.getResponse().flushBuffer();
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
SecurityContextHolder.getContext());
assertThat(
((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue();
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
holder.getResponse());
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
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
SecurityContextHolder.getContext());
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext());
}
// SEC-2005
@@ -282,20 +254,15 @@ public class HttpSessionSecurityContextRepositoryTests {
repo.setSpringSecurityContextKey("imTheContext");
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
response);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(testToken);
holder.getResponse().getWriter().flush();
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
SecurityContextHolder.getContext());
assertThat(
((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue();
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
holder.getResponse());
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
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
SecurityContextHolder.getContext());
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext());
}
// SEC-2005
@@ -305,20 +272,15 @@ public class HttpSessionSecurityContextRepositoryTests {
repo.setSpringSecurityContextKey("imTheContext");
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
response);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(testToken);
holder.getResponse().getWriter().close();
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
SecurityContextHolder.getContext());
assertThat(
((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue();
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
holder.getResponse());
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
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
SecurityContextHolder.getContext());
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext());
}
// SEC-2005
@@ -328,20 +290,15 @@ public class HttpSessionSecurityContextRepositoryTests {
repo.setSpringSecurityContextKey("imTheContext");
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
response);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(testToken);
holder.getResponse().getOutputStream().flush();
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
SecurityContextHolder.getContext());
assertThat(
((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue();
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
holder.getResponse());
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
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
SecurityContextHolder.getContext());
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext());
}
// SEC-2005
@@ -351,20 +308,15 @@ public class HttpSessionSecurityContextRepositoryTests {
repo.setSpringSecurityContextKey("imTheContext");
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
response);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(testToken);
holder.getResponse().getOutputStream().close();
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
SecurityContextHolder.getContext());
assertThat(
((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue();
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
holder.getResponse());
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
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(
SecurityContextHolder.getContext());
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext());
}
// SEC-SEC-2055
@@ -376,8 +328,7 @@ public class HttpSessionSecurityContextRepositoryTests {
HttpServletResponse response = mock(HttpServletResponse.class);
ServletOutputStream outputstream = mock(ServletOutputStream.class);
when(response.getOutputStream()).thenReturn(outputstream);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
response);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(testToken);
holder.getResponse().getOutputStream().close();
@@ -393,8 +344,7 @@ public class HttpSessionSecurityContextRepositoryTests {
HttpServletResponse response = mock(HttpServletResponse.class);
ServletOutputStream outputstream = mock(ServletOutputStream.class);
when(response.getOutputStream()).thenReturn(outputstream);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
response);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(testToken);
holder.getResponse().getOutputStream().flush();
@@ -407,13 +357,11 @@ public class HttpSessionSecurityContextRepositoryTests {
MockHttpServletRequest request = new MockHttpServletRequest();
request.getSession();
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
response);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(testToken);
request.getSession().invalidate();
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
holder.getResponse());
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
assertThat(request.getSession(false)).isNull();
}
@@ -423,14 +371,11 @@ public class HttpSessionSecurityContextRepositoryTests {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
response);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(
new AnonymousAuthenticationToken("key", "anon",
AuthorityUtils.createAuthorityList("ANON")));
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
holder.getResponse());
new AnonymousAuthenticationToken("key", "anon", AuthorityUtils.createAuthorityList("ANON")));
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
assertThat(request.getSession(false)).isNull();
}
@@ -442,15 +387,12 @@ public class HttpSessionSecurityContextRepositoryTests {
SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext();
ctxInSession.setAuthentication(testToken);
request.getSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY, ctxInSession);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
new MockHttpServletResponse());
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse());
repo.loadContext(holder);
SecurityContextHolder.getContext().setAuthentication(
new AnonymousAuthenticationToken("x", "x", testToken.getAuthorities()));
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
holder.getResponse());
assertThat(
request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isNull();
SecurityContextHolder.getContext()
.setAuthentication(new AnonymousAuthenticationToken("x", "x", testToken.getAuthorities()));
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
assertThat(request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isNull();
}
@Test
@@ -461,12 +403,10 @@ public class HttpSessionSecurityContextRepositoryTests {
SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext();
ctxInSession.setAuthentication(testToken);
request.getSession().setAttribute("imTheContext", ctxInSession);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
new MockHttpServletResponse());
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse());
repo.loadContext(holder);
// Save an empty context
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
holder.getResponse());
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
assertThat(request.getSession().getAttribute("imTheContext")).isNull();
}
@@ -475,19 +415,15 @@ public class HttpSessionSecurityContextRepositoryTests {
public void contextIsNotRemovedFromSessionIfContextBeforeExecutionDefault() {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
MockHttpServletRequest request = new MockHttpServletRequest();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
new MockHttpServletResponse());
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse());
repo.loadContext(holder);
SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext();
ctxInSession.setAuthentication(testToken);
request.getSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY, ctxInSession);
SecurityContextHolder.getContext().setAuthentication(
new AnonymousAuthenticationToken("x", "x",
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
holder.getResponse());
assertThat(ctxInSession).isSameAs(
request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY));
new AnonymousAuthenticationToken("x", "x", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
assertThat(ctxInSession).isSameAs(request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY));
}
// SEC-3070
@@ -499,15 +435,13 @@ public class HttpSessionSecurityContextRepositoryTests {
ctxInSession.setAuthentication(testToken);
request.getSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY, ctxInSession);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
new MockHttpServletResponse());
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse());
repo.loadContext(holder);
ctxInSession.setAuthentication(null);
repo.saveContext(ctxInSession, holder.getRequest(), holder.getResponse());
assertThat(
request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isNull();
assertThat(request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isNull();
}
@Test
@@ -538,14 +472,11 @@ public class HttpSessionSecurityContextRepositoryTests {
return url + sessionId;
}
};
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
response);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
repo.loadContext(holder);
String url = "/aUrl";
assertThat(holder.getResponse().encodeRedirectUrl(url)).isEqualTo(
url + sessionId);
assertThat(holder.getResponse().encodeRedirectURL(url)).isEqualTo(
url + sessionId);
assertThat(holder.getResponse().encodeRedirectUrl(url)).isEqualTo(url + sessionId);
assertThat(holder.getResponse().encodeRedirectURL(url)).isEqualTo(url + sessionId);
assertThat(holder.getResponse().encodeUrl(url)).isEqualTo(url + sessionId);
assertThat(holder.getResponse().encodeURL(url)).isEqualTo(url + sessionId);
repo.setDisableUrlRewriting(true);
@@ -563,11 +494,9 @@ public class HttpSessionSecurityContextRepositoryTests {
contextToSave.setAuthentication(testToken);
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
MockHttpServletRequest request = new MockHttpServletRequest();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
new MockHttpServletResponse());
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse());
repo.loadContext(holder);
AuthenticationTrustResolver trustResolver = mock(
AuthenticationTrustResolver.class);
AuthenticationTrustResolver trustResolver = mock(AuthenticationTrustResolver.class);
repo.setTrustResolver(trustResolver);
repo.saveContext(contextToSave, holder.getRequest(), holder.getResponse());
@@ -587,8 +516,7 @@ public class HttpSessionSecurityContextRepositoryTests {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
response);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContext context = repo.loadContext(holder);
assertThat(request.getSession(false)).isNull();
// Simulate authentication during the request
@@ -598,9 +526,7 @@ public class HttpSessionSecurityContextRepositoryTests {
new HttpServletResponseWrapper(holder.getResponse()));
assertThat(request.getSession(false)).isNotNull();
assertThat(
request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isEqualTo(
context);
assertThat(request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isEqualTo(context);
}
@Test(expected = IllegalStateException.class)
@@ -619,8 +545,7 @@ public class HttpSessionSecurityContextRepositoryTests {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
response);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContext context = repo.loadContext(holder);
SomeTransientAuthentication authentication = new SomeTransientAuthentication();
@@ -637,8 +562,7 @@ public class HttpSessionSecurityContextRepositoryTests {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
response);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContext context = repo.loadContext(holder);
SomeTransientAuthenticationSubclass authentication = new SomeTransientAuthenticationSubclass();
@@ -655,8 +579,7 @@ public class HttpSessionSecurityContextRepositoryTests {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
response);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContext context = repo.loadContext(holder);
SomeOtherTransientAuthentication authentication = new SomeOtherTransientAuthentication();
@@ -670,6 +593,7 @@ public class HttpSessionSecurityContextRepositoryTests {
@Transient
private static class SomeTransientAuthentication extends AbstractAuthenticationToken {
SomeTransientAuthentication() {
super(null);
}
@@ -683,6 +607,7 @@ public class HttpSessionSecurityContextRepositoryTests {
public Object getPrincipal() {
return null;
}
}
private static class SomeTransientAuthenticationSubclass extends SomeTransientAuthentication {
@@ -693,10 +618,12 @@ public class HttpSessionSecurityContextRepositoryTests {
@Retention(RetentionPolicy.RUNTIME)
@Transient
public @interface TestTransientAuthentication {
}
@TestTransientAuthentication
private static class SomeOtherTransientAuthentication extends AbstractAuthenticationToken {
SomeOtherTransientAuthentication() {
super(null);
}
@@ -710,5 +637,7 @@ public class HttpSessionSecurityContextRepositoryTests {
public Object getPrincipal() {
return null;
}
}
}

View File

@@ -30,24 +30,24 @@ import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
/**
*
* @author Rob Winch
*
*/
@RunWith(MockitoJUnitRunner.class)
public class SaveContextOnUpdateOrErrorResponseWrapperTests {
@Mock
private SecurityContext securityContext;
private MockHttpServletResponse response;
private SaveContextOnUpdateOrErrorResponseWrapperStub wrappedResponse;
@Before
public void setUp() {
response = new MockHttpServletResponse();
wrappedResponse = new SaveContextOnUpdateOrErrorResponseWrapperStub(response,
true);
wrappedResponse = new SaveContextOnUpdateOrErrorResponseWrapperStub(response, true);
SecurityContextHolder.setContext(securityContext);
}
@@ -176,12 +176,12 @@ public class SaveContextOnUpdateOrErrorResponseWrapperTests {
assertThat(wrappedResponse.securityContext).isNull();
}
private static class SaveContextOnUpdateOrErrorResponseWrapperStub extends
SaveContextOnUpdateOrErrorResponseWrapper {
private static class SaveContextOnUpdateOrErrorResponseWrapperStub
extends SaveContextOnUpdateOrErrorResponseWrapper {
private SecurityContext securityContext;
SaveContextOnUpdateOrErrorResponseWrapperStub(
HttpServletResponse response, boolean disableUrlRewriting) {
SaveContextOnUpdateOrErrorResponseWrapperStub(HttpServletResponse response, boolean disableUrlRewriting) {
super(response, disableUrlRewriting);
}
@@ -189,5 +189,7 @@ public class SaveContextOnUpdateOrErrorResponseWrapperTests {
protected void saveContext(SecurityContext context) {
securityContext = context;
}
}
}

View File

@@ -33,8 +33,8 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
public class SecurityContextPersistenceFilterTests {
TestingAuthenticationToken testToken = new TestingAuthenticationToken("someone",
"passwd", "ROLE_A");
TestingAuthenticationToken testToken = new TestingAuthenticationToken("someone", "passwd", "ROLE_A");
@After
public void clearContext() {
@@ -61,8 +61,7 @@ public class SecurityContextPersistenceFilterTests {
final MockHttpServletResponse response = new MockHttpServletResponse();
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
SecurityContextHolder.getContext().setAuthentication(testToken);
doThrow(new IOException()).when(chain).doFilter(any(ServletRequest.class),
any(ServletResponse.class));
doThrow(new IOException()).when(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
try {
filter.doFilter(request, response, chain);
fail("IOException should have been thrown");
@@ -74,19 +73,16 @@ public class SecurityContextPersistenceFilterTests {
}
@Test
public void loadedContextContextIsCopiedToSecurityContextHolderAndUpdatedContextIsStored()
throws Exception {
public void loadedContextContextIsCopiedToSecurityContextHolderAndUpdatedContextIsStored() throws Exception {
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpServletResponse response = new MockHttpServletResponse();
final TestingAuthenticationToken beforeAuth = new TestingAuthenticationToken(
"someoneelse", "passwd", "ROLE_B");
final TestingAuthenticationToken beforeAuth = new TestingAuthenticationToken("someoneelse", "passwd", "ROLE_B");
final SecurityContext scBefore = new SecurityContextImpl();
final SecurityContext scExpectedAfter = new SecurityContextImpl();
scExpectedAfter.setAuthentication(testToken);
scBefore.setAuthentication(beforeAuth);
final SecurityContextRepository repo = mock(SecurityContextRepository.class);
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(
repo);
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(repo);
when(repo.loadContext(any(HttpRequestResponseHolder.class))).thenReturn(scBefore);
@@ -109,8 +105,7 @@ public class SecurityContextPersistenceFilterTests {
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(
mock(SecurityContextRepository.class));
request.setAttribute(SecurityContextPersistenceFilter.FILTER_APPLIED,
Boolean.TRUE);
request.setAttribute(SecurityContextPersistenceFilter.FILTER_APPLIED, Boolean.TRUE);
filter.doFilter(request, response, chain);
verify(chain).doFilter(request, response);
}
@@ -127,16 +122,15 @@ public class SecurityContextPersistenceFilterTests {
}
@Test
public void nullSecurityContextRepoDoesntSaveContextOrCreateSession()
throws Exception {
public void nullSecurityContextRepoDoesntSaveContextOrCreateSession() throws Exception {
final FilterChain chain = mock(FilterChain.class);
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpServletResponse response = new MockHttpServletResponse();
SecurityContextRepository repo = new NullSecurityContextRepository();
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(
repo);
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(repo);
filter.doFilter(request, response, chain);
assertThat(repo.containsContext(request)).isFalse();
assertThat(request.getSession(false)).isNull();
}
}

View File

@@ -29,16 +29,18 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.NativeWebRequest;
/**
*
* @author Rob Winch
*
*/
@RunWith(MockitoJUnitRunner.class)
public class SecurityContextCallableProcessingInterceptorTests {
@Mock
private SecurityContext securityContext;
@Mock
private Callable<?> callable;
@Mock
private NativeWebRequest webRequest;
@@ -77,4 +79,5 @@ public class SecurityContextCallableProcessingInterceptorTests {
interceptor.postProcess(webRequest, callable, null);
assertThat(SecurityContextHolder.getContext()).isNotSameAs(securityContext);
}
}

View File

@@ -41,21 +41,26 @@ import org.springframework.web.context.request.async.WebAsyncManager;
import org.springframework.web.context.request.async.WebAsyncUtils;
/**
*
* @author Rob Winch
*
*/
@RunWith(MockitoJUnitRunner.class)
public class WebAsyncManagerIntegrationFilterTests {
@Mock
private SecurityContext securityContext;
@Mock
private HttpServletRequest request;
@Mock
private HttpServletResponse response;
@Mock
private AsyncWebRequest asyncWebRequest;
private WebAsyncManager asyncManager;
private JoinableThreadFactory threadFactory;
private MockFilterChain filterChain;
@@ -73,8 +78,7 @@ public class WebAsyncManagerIntegrationFilterTests {
asyncManager = WebAsyncUtils.getAsyncManager(request);
asyncManager.setAsyncWebRequest(asyncWebRequest);
asyncManager.setTaskExecutor(executor);
when(request.getAttribute(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE)).thenReturn(
asyncManager);
when(request.getAttribute(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE)).thenReturn(asyncManager);
filter = new WebAsyncManagerIntegrationFilter();
}
@@ -85,18 +89,14 @@ public class WebAsyncManagerIntegrationFilterTests {
}
@Test
public void doFilterInternalRegistersSecurityContextCallableProcessor()
throws Exception {
public void doFilterInternalRegistersSecurityContextCallableProcessor() throws Exception {
SecurityContextHolder.setContext(securityContext);
asyncManager
.registerCallableInterceptors(new CallableProcessingInterceptorAdapter() {
@Override
public <T> void postProcess(NativeWebRequest request,
Callable<T> task, Object concurrentResult) {
assertThat(SecurityContextHolder.getContext()).isNotSameAs(
securityContext);
}
});
asyncManager.registerCallableInterceptors(new CallableProcessingInterceptorAdapter() {
@Override
public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) {
assertThat(SecurityContextHolder.getContext()).isNotSameAs(securityContext);
}
});
filter.doFilterInternal(request, response, filterChain);
VerifyingCallable verifyingCallable = new VerifyingCallable();
@@ -106,18 +106,14 @@ public class WebAsyncManagerIntegrationFilterTests {
}
@Test
public void doFilterInternalRegistersSecurityContextCallableProcessorContextUpdated()
throws Exception {
public void doFilterInternalRegistersSecurityContextCallableProcessorContextUpdated() throws Exception {
SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext());
asyncManager
.registerCallableInterceptors(new CallableProcessingInterceptorAdapter() {
@Override
public <T> void postProcess(NativeWebRequest request,
Callable<T> task, Object concurrentResult) {
assertThat(SecurityContextHolder.getContext()).isNotSameAs(
securityContext);
}
});
asyncManager.registerCallableInterceptors(new CallableProcessingInterceptorAdapter() {
@Override
public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) {
assertThat(SecurityContextHolder.getContext()).isNotSameAs(securityContext);
}
});
filter.doFilterInternal(request, response, filterChain);
SecurityContextHolder.setContext(securityContext);
@@ -128,6 +124,7 @@ public class WebAsyncManagerIntegrationFilterTests {
}
private static final class JoinableThreadFactory implements ThreadFactory {
private Thread t;
public Thread newThread(Runnable r) {
@@ -138,6 +135,7 @@ public class WebAsyncManagerIntegrationFilterTests {
public void join() throws InterruptedException {
t.join();
}
}
private class VerifyingCallable implements Callable<SecurityContext> {
@@ -147,4 +145,5 @@ public class WebAsyncManagerIntegrationFilterTests {
}
}
}

View File

@@ -30,8 +30,11 @@ import static org.assertj.core.api.Assertions.assertThat;
* @since 4.1
*/
public class CookieCsrfTokenRepositoryTests {
CookieCsrfTokenRepository repository;
MockHttpServletResponse response;
MockHttpServletRequest request;
@Before
@@ -47,10 +50,8 @@ public class CookieCsrfTokenRepositoryTests {
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);
assertThat(generateToken.getHeaderName()).isEqualTo(CookieCsrfTokenRepository.DEFAULT_CSRF_HEADER_NAME);
assertThat(generateToken.getParameterName()).isEqualTo(CookieCsrfTokenRepository.DEFAULT_CSRF_PARAMETER_NAME);
assertThat(generateToken.getToken()).isNotEmpty();
}
@@ -74,12 +75,10 @@ public class CookieCsrfTokenRepositoryTests {
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);
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.getName()).isEqualTo(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getPath()).isEqualTo(this.request.getContextPath());
assertThat(tokenCookie.getSecure()).isEqualTo(this.request.isSecure());
assertThat(tokenCookie.getValue()).isEqualTo(token.getToken());
@@ -92,8 +91,7 @@ public class CookieCsrfTokenRepositoryTests {
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);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getSecure()).isTrue();
}
@@ -105,8 +103,7 @@ public class CookieCsrfTokenRepositoryTests {
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);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getSecure()).isTrue();
}
@@ -118,24 +115,20 @@ public class CookieCsrfTokenRepositoryTests {
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);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getSecure()).isFalse();
}
@Test
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);
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.getName()).isEqualTo(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getPath()).isEqualTo(this.request.getContextPath());
assertThat(tokenCookie.getSecure()).isEqualTo(this.request.isSecure());
assertThat(tokenCookie.getValue()).isEmpty();
@@ -147,8 +140,7 @@ public class CookieCsrfTokenRepositoryTests {
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);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.isHttpOnly()).isTrue();
}
@@ -159,8 +151,7 @@ public class CookieCsrfTokenRepositoryTests {
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);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.isHttpOnly()).isFalse();
}
@@ -171,8 +162,7 @@ public class CookieCsrfTokenRepositoryTests {
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);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.isHttpOnly()).isFalse();
}
@@ -184,8 +174,7 @@ public class CookieCsrfTokenRepositoryTests {
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);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getPath()).isEqualTo(this.repository.getCookiePath());
}
@@ -197,8 +186,7 @@ public class CookieCsrfTokenRepositoryTests {
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);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getPath()).isEqualTo(this.request.getContextPath());
}
@@ -210,8 +198,7 @@ public class CookieCsrfTokenRepositoryTests {
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);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getPath()).isEqualTo(this.request.getContextPath());
}
@@ -224,8 +211,7 @@ public class CookieCsrfTokenRepositoryTests {
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);
Cookie tokenCookie = this.response.getCookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME);
assertThat(tokenCookie.getDomain()).isEqualTo(domainName);
}
@@ -244,8 +230,7 @@ public class CookieCsrfTokenRepositoryTests {
@Test
public void loadTokenCookieValueEmptyString() {
this.request.setCookies(
new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, ""));
this.request.setCookies(new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, ""));
assertThat(this.repository.loadToken(this.request)).isNull();
}
@@ -255,15 +240,13 @@ public class CookieCsrfTokenRepositoryTests {
CsrfToken generateToken = this.repository.generateToken(this.request);
this.request
.setCookies(new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME,
generateToken.getToken()));
.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());
assertThat(loadToken.getParameterName()).isEqualTo(generateToken.getParameterName());
assertThat(loadToken.getToken()).isNotEmpty();
}

View File

@@ -41,6 +41,7 @@ import static org.mockito.Mockito.when;
*/
@RunWith(MockitoJUnitRunner.class)
public class CsrfAuthenticationStrategyTests {
@Mock
private CsrfTokenRepository csrfTokenRepository;
@@ -71,61 +72,49 @@ public class CsrfAuthenticationStrategyTests {
@Test
public void logoutRemovesCsrfTokenAndSavesNew() {
when(this.csrfTokenRepository.loadToken(this.request))
.thenReturn(this.existingToken);
when(this.csrfTokenRepository.generateToken(this.request))
.thenReturn(this.generatedToken);
this.strategy.onAuthentication(
new TestingAuthenticationToken("user", "password", "ROLE_USER"),
this.request, this.response);
when(this.csrfTokenRepository.loadToken(this.request)).thenReturn(this.existingToken);
when(this.csrfTokenRepository.generateToken(this.request)).thenReturn(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));
verify(this.csrfTokenRepository).saveToken(eq(this.generatedToken), any(HttpServletRequest.class),
any(HttpServletResponse.class));
// SEC-2404, SEC-2832
CsrfToken tokenInRequest = (CsrfToken) this.request
.getAttribute(CsrfToken.class.getName());
CsrfToken tokenInRequest = (CsrfToken) this.request.getAttribute(CsrfToken.class.getName());
assertThat(tokenInRequest.getToken()).isSameAs(this.generatedToken.getToken());
assertThat(tokenInRequest.getHeaderName())
.isSameAs(this.generatedToken.getHeaderName());
assertThat(tokenInRequest.getParameterName())
.isSameAs(this.generatedToken.getParameterName());
assertThat(this.request.getAttribute(this.generatedToken.getParameterName()))
.isSameAs(tokenInRequest);
assertThat(tokenInRequest.getHeaderName()).isSameAs(this.generatedToken.getHeaderName());
assertThat(tokenInRequest.getParameterName()).isSameAs(this.generatedToken.getParameterName());
assertThat(this.request.getAttribute(this.generatedToken.getParameterName())).isSameAs(tokenInRequest);
}
// SEC-2872
@Test
public void delaySavingCsrf() {
this.strategy = new CsrfAuthenticationStrategy(
new LazyCsrfTokenRepository(this.csrfTokenRepository));
this.strategy = new CsrfAuthenticationStrategy(new LazyCsrfTokenRepository(this.csrfTokenRepository));
when(this.csrfTokenRepository.loadToken(this.request))
.thenReturn(this.existingToken);
when(this.csrfTokenRepository.generateToken(this.request))
.thenReturn(this.generatedToken);
this.strategy.onAuthentication(
new TestingAuthenticationToken("user", "password", "ROLE_USER"),
this.request, this.response);
when(this.csrfTokenRepository.loadToken(this.request)).thenReturn(this.existingToken);
when(this.csrfTokenRepository.generateToken(this.request)).thenReturn(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));
verify(this.csrfTokenRepository, never()).saveToken(eq(this.generatedToken), any(HttpServletRequest.class),
any(HttpServletResponse.class));
CsrfToken tokenInRequest = (CsrfToken) this.request
.getAttribute(CsrfToken.class.getName());
CsrfToken tokenInRequest = (CsrfToken) this.request.getAttribute(CsrfToken.class.getName());
tokenInRequest.getToken();
verify(this.csrfTokenRepository).saveToken(eq(this.generatedToken),
any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(this.csrfTokenRepository).saveToken(eq(this.generatedToken), any(HttpServletRequest.class),
any(HttpServletResponse.class));
}
@Test
public void logoutRemovesNoActionIfNullToken() {
this.strategy.onAuthentication(
new TestingAuthenticationToken("user", "password", "ROLE_USER"),
this.request, this.response);
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));
verify(this.csrfTokenRepository, never()).saveToken(any(CsrfToken.class), any(HttpServletRequest.class),
any(HttpServletResponse.class));
}
}

View File

@@ -57,15 +57,20 @@ public class CsrfFilterTests {
@Mock
private RequestMatcher requestMatcher;
@Mock
private CsrfTokenRepository tokenRepository;
@Mock
private FilterChain filterChain;
@Mock
private AccessDeniedHandler deniedHandler;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private CsrfToken token;
private CsrfFilter filter;
@@ -96,84 +101,68 @@ public class CsrfFilterTests {
// SEC-2276
@Test
public void doFilterDoesNotSaveCsrfTokenUntilAccessed()
throws ServletException, IOException {
public void doFilterDoesNotSaveCsrfTokenUntilAccessed() throws ServletException, IOException {
this.filter = createCsrfFilter(new LazyCsrfTokenRepository(this.tokenRepository));
when(this.requestMatcher.matches(this.request)).thenReturn(false);
when(this.tokenRepository.generateToken(this.request)).thenReturn(this.token);
this.filter.doFilter(this.request, this.response, this.filterChain);
CsrfToken attrToken = (CsrfToken) this.request
.getAttribute(this.token.getParameterName());
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.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));
verify(this.tokenRepository).saveToken(eq(this.token), any(HttpServletRequest.class),
any(HttpServletResponse.class));
}
@Test
public void doFilterAccessDeniedNoTokenPresent()
throws ServletException, IOException {
public void doFilterAccessDeniedNoTokenPresent() throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.loadToken(this.request)).thenReturn(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.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));
verify(this.deniedHandler).handle(eq(this.request), eq(this.response), any(InvalidCsrfTokenException.class));
verifyZeroInteractions(this.filterChain);
}
@Test
public void doFilterAccessDeniedIncorrectTokenPresent()
throws ServletException, IOException {
public void doFilterAccessDeniedIncorrectTokenPresent() throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
this.request.setParameter(this.token.getParameterName(),
this.token.getToken() + " INVALID");
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);
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));
verify(this.deniedHandler).handle(eq(this.request), eq(this.response), any(InvalidCsrfTokenException.class));
verifyZeroInteractions(this.filterChain);
}
@Test
public void doFilterAccessDeniedIncorrectTokenPresentHeader()
throws ServletException, IOException {
public void doFilterAccessDeniedIncorrectTokenPresentHeader() throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
this.request.addHeader(this.token.getHeaderName(),
this.token.getToken() + " INVALID");
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);
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));
verify(this.deniedHandler).handle(eq(this.request), eq(this.response), any(InvalidCsrfTokenException.class));
verifyZeroInteractions(this.filterChain);
}
@@ -183,68 +172,55 @@ public class CsrfFilterTests {
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
this.request.setParameter(this.token.getParameterName(), this.token.getToken());
this.request.addHeader(this.token.getHeaderName(),
this.token.getToken() + " INVALID");
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);
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));
verify(this.deniedHandler).handle(eq(this.request), eq(this.response), any(InvalidCsrfTokenException.class));
verifyZeroInteractions(this.filterChain);
}
@Test
public void doFilterNotCsrfRequestExistingToken()
throws ServletException, IOException {
public void doFilterNotCsrfRequestExistingToken() throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(false);
when(this.tokenRepository.loadToken(this.request)).thenReturn(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.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);
}
@Test
public void doFilterNotCsrfRequestGenerateToken()
throws ServletException, IOException {
public void doFilterNotCsrfRequestGenerateToken() throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(false);
when(this.tokenRepository.generateToken(this.request)).thenReturn(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);
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);
}
@Test
public void doFilterIsCsrfRequestExistingTokenHeader()
throws ServletException, IOException {
public void doFilterIsCsrfRequestExistingTokenHeader() throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.loadToken(this.request)).thenReturn(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);
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);
@@ -255,58 +231,48 @@ public class CsrfFilterTests {
throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.loadToken(this.request)).thenReturn(this.token);
this.request.setParameter(this.token.getParameterName(),
this.token.getToken() + " INVALID");
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);
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);
}
@Test
public void doFilterIsCsrfRequestExistingToken()
throws ServletException, IOException {
public void doFilterIsCsrfRequestExistingToken() throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.loadToken(this.request)).thenReturn(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);
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), any(HttpServletResponse.class));
verify(this.tokenRepository, never()).saveToken(any(CsrfToken.class), any(HttpServletRequest.class),
any(HttpServletResponse.class));
}
@Test
public void doFilterIsCsrfRequestGenerateToken()
throws ServletException, IOException {
public void doFilterIsCsrfRequestGenerateToken() throws ServletException, IOException {
when(this.requestMatcher.matches(this.request)).thenReturn(true);
when(this.tokenRepository.generateToken(this.request)).thenReturn(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);
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);
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);
@@ -314,8 +280,7 @@ public class CsrfFilterTests {
}
@Test
public void doFilterDefaultRequireCsrfProtectionMatcherAllowedMethods()
throws ServletException, IOException {
public void doFilterDefaultRequireCsrfProtectionMatcherAllowedMethods() throws ServletException, IOException {
this.filter = new CsrfFilter(this.tokenRepository);
this.filter.setAccessDeniedHandler(this.deniedHandler);
@@ -338,8 +303,7 @@ public class CsrfFilterTests {
*
*/
@Test
public void doFilterDefaultRequireCsrfProtectionMatcherAllowedMethodsCaseSensitive()
throws Exception {
public void doFilterDefaultRequireCsrfProtectionMatcherAllowedMethodsCaseSensitive() throws Exception {
this.filter = new CsrfFilter(this.tokenRepository);
this.filter.setAccessDeniedHandler(this.deniedHandler);
@@ -357,8 +321,7 @@ public class CsrfFilterTests {
}
@Test
public void doFilterDefaultRequireCsrfProtectionMatcherDeniedMethods()
throws ServletException, IOException {
public void doFilterDefaultRequireCsrfProtectionMatcherDeniedMethods() throws ServletException, IOException {
this.filter = new CsrfFilter(this.tokenRepository);
this.filter.setAccessDeniedHandler(this.deniedHandler);
@@ -384,18 +347,15 @@ public class CsrfFilterTests {
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.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 {
public void doFilterWhenSkipRequestInvokedThenSkips() throws Exception {
CsrfTokenRepository repository = mock(CsrfTokenRepository.class);
CsrfFilter filter = new CsrfFilter(repository);
@@ -423,12 +383,10 @@ public class CsrfFilterTests {
return new CsrfTokenAssert((CsrfToken) token);
}
private static class CsrfTokenAssert
extends AbstractObjectAssert<CsrfTokenAssert, CsrfToken> {
private static class CsrfTokenAssert extends AbstractObjectAssert<CsrfTokenAssert, CsrfToken> {
/**
* Creates a new </code>{@link ObjectAssert}</code>.
*
* @param actual the target to verify.
*/
protected CsrfTokenAssert(CsrfToken actual) {
@@ -437,10 +395,11 @@ public class CsrfFilterTests {
public CsrfTokenAssert isEqualTo(CsrfToken expected) {
assertThat(this.actual.getHeaderName()).isEqualTo(expected.getHeaderName());
assertThat(this.actual.getParameterName())
.isEqualTo(expected.getParameterName());
assertThat(this.actual.getParameterName()).isEqualTo(expected.getParameterName());
assertThat(this.actual.getToken()).isEqualTo(expected.getToken());
return this;
}
}
}

View File

@@ -32,6 +32,7 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
*/
@RunWith(MockitoJUnitRunner.class)
public class CsrfLogoutHandlerTests {
@Mock
private CsrfTokenRepository csrfTokenRepository;
@@ -55,8 +56,7 @@ public class CsrfLogoutHandlerTests {
@Test
public void logoutRemovesCsrfToken() {
handler.logout(request, response, new TestingAuthenticationToken("user",
"password", "ROLE_USER"));
handler.logout(request, response, new TestingAuthenticationToken("user", "password", "ROLE_USER"));
verify(csrfTokenRepository).saveToken(null, request, response);
}

View File

@@ -22,8 +22,11 @@ import org.junit.Test;
*
*/
public class DefaultCsrfTokenTests {
private final String headerName = "headerName";
private final String parameterName = "parameterName";
private final String tokenValue = "tokenValue";
@Test(expected = IllegalArgumentException.class)
@@ -55,4 +58,5 @@ public class DefaultCsrfTokenTests {
public void constructorEmptyTokenValue() {
new DefaultCsrfToken(headerName, parameterName, "");
}
}

View File

@@ -27,11 +27,13 @@ import org.springframework.mock.web.MockHttpServletResponse;
*
*/
public class HttpSessionCsrfTokenRepositoryTests {
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private CsrfToken token;
private HttpSessionCsrfTokenRepository repo;
@Before
@@ -105,8 +107,7 @@ public class HttpSessionCsrfTokenRepositoryTests {
repo.setSessionAttributeName(sessionAttributeName);
repo.saveToken(tokenToSave, request, response);
CsrfToken loadedToken = (CsrfToken) request.getSession().getAttribute(
sessionAttributeName);
CsrfToken loadedToken = (CsrfToken) request.getSession().getAttribute(sessionAttributeName);
assertThat(loadedToken).isEqualTo(tokenToSave);
}
@@ -147,4 +148,5 @@ public class HttpSessionCsrfTokenRepositoryTests {
public void setParameterNameNull() {
repo.setParameterName(null);
}
}

View File

@@ -37,10 +37,13 @@ import static org.mockito.Mockito.when;
*/
@RunWith(MockitoJUnitRunner.class)
public class LazyCsrfTokenRepositoryTests {
@Mock
CsrfTokenRepository delegate;
@Mock
HttpServletRequest request;
@Mock
HttpServletResponse response;
@@ -53,8 +56,7 @@ public class LazyCsrfTokenRepositoryTests {
public void setup() {
this.token = new DefaultCsrfToken("header", "param", "token");
when(this.delegate.generateToken(this.request)).thenReturn(this.token);
when(this.request.getAttribute(HttpServletResponse.class.getName()))
.thenReturn(this.response);
when(this.request.getAttribute(HttpServletResponse.class.getName())).thenReturn(this.response);
}
@Test(expected = IllegalArgumentException.class)
@@ -99,4 +101,5 @@ public class LazyCsrfTokenRepositoryTests {
verify(this.delegate).loadToken(this.request);
}
}

View File

@@ -18,7 +18,6 @@ package org.springframework.security.web.csrf;
import org.junit.Test;
/**
*
* @author Rob Winch
*
*/

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