SEC-2915: Updated Java Code Formatting
This commit is contained in:
@@ -22,41 +22,43 @@ import java.util.Map;
|
||||
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();
|
||||
// ~ Instance fields
|
||||
// ================================================================================================
|
||||
private Map map = new HashMap();
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
public String getFilterName() {
|
||||
throw new UnsupportedOperationException("mock method not implemented");
|
||||
}
|
||||
public String getFilterName() {
|
||||
throw new UnsupportedOperationException("mock method not implemented");
|
||||
}
|
||||
|
||||
public String getInitParameter(String arg0) {
|
||||
Object result = map.get(arg0);
|
||||
public String getInitParameter(String arg0) {
|
||||
Object result = map.get(arg0);
|
||||
|
||||
if (result != null) {
|
||||
return (String) result;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (result != null) {
|
||||
return (String) result;
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public Enumeration getInitParameterNames() {
|
||||
throw new UnsupportedOperationException("mock method not implemented");
|
||||
}
|
||||
public Enumeration getInitParameterNames() {
|
||||
throw new UnsupportedOperationException("mock method not implemented");
|
||||
}
|
||||
|
||||
public ServletContext getServletContext() {
|
||||
throw new UnsupportedOperationException("mock method not implemented");
|
||||
}
|
||||
public ServletContext getServletContext() {
|
||||
throw new UnsupportedOperationException("mock method not implemented");
|
||||
}
|
||||
|
||||
public void setInitParmeter(String parameter, String value) {
|
||||
map.put(parameter, value);
|
||||
}
|
||||
public void setInitParmeter(String parameter, String value) {
|
||||
map.put(parameter, value);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,32 +19,35 @@ import org.springframework.security.web.PortResolver;
|
||||
|
||||
import javax.servlet.ServletRequest;
|
||||
|
||||
|
||||
/**
|
||||
* Always returns the constructor-specified HTTP and HTTPS ports.
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class MockPortResolver implements PortResolver {
|
||||
//~ Instance fields ================================================================================================
|
||||
// ~ Instance fields
|
||||
// ================================================================================================
|
||||
|
||||
private int http = 80;
|
||||
private int https = 443;
|
||||
private int http = 80;
|
||||
private int https = 443;
|
||||
|
||||
//~ Constructors ===================================================================================================
|
||||
// ~ Constructors
|
||||
// ===================================================================================================
|
||||
|
||||
public MockPortResolver(int http, int https) {
|
||||
this.http = http;
|
||||
this.https = https;
|
||||
}
|
||||
public MockPortResolver(int http, int https) {
|
||||
this.http = http;
|
||||
this.https = https;
|
||||
}
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
public int getServerPort(ServletRequest request) {
|
||||
if ((request.getScheme() != null) && request.getScheme().equals("https")) {
|
||||
return https;
|
||||
} else {
|
||||
return http;
|
||||
}
|
||||
}
|
||||
public int getServerPort(ServletRequest request) {
|
||||
if ((request.getScheme() != null) && request.getScheme().equals("https")) {
|
||||
return https;
|
||||
}
|
||||
else {
|
||||
return http;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,30 +12,33 @@ import org.springframework.mock.web.MockHttpServletResponse;
|
||||
* @since 3.0
|
||||
*/
|
||||
public class DefaultRedirectStrategyTests {
|
||||
@Test
|
||||
public void contextRelativeUrlWithContextNameInHostnameIsHandledCorrectly() throws Exception {
|
||||
DefaultRedirectStrategy rds = new DefaultRedirectStrategy();
|
||||
rds.setContextRelative(true);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setContextPath("/context");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
@Test
|
||||
public void contextRelativeUrlWithContextNameInHostnameIsHandledCorrectly()
|
||||
throws Exception {
|
||||
DefaultRedirectStrategy rds = new DefaultRedirectStrategy();
|
||||
rds.setContextRelative(true);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setContextPath("/context");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
rds.sendRedirect(request, response, "http://context.blah.com/context/remainder");
|
||||
rds.sendRedirect(request, response, "http://context.blah.com/context/remainder");
|
||||
|
||||
assertEquals("remainder", response.getRedirectedUrl());
|
||||
}
|
||||
assertEquals("remainder", response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
// SEC-2177
|
||||
@Test
|
||||
public void contextRelativeUrlWithMultipleSchemesInHostnameIsHandledCorrectly() throws Exception {
|
||||
DefaultRedirectStrategy rds = new DefaultRedirectStrategy();
|
||||
rds.setContextRelative(true);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setContextPath("/context");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
// SEC-2177
|
||||
@Test
|
||||
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, "http://http://context.blah.com/context/remainder");
|
||||
rds.sendRedirect(request, response,
|
||||
"http://http://context.blah.com/context/remainder");
|
||||
|
||||
assertEquals("remainder", response.getRedirectedUrl());
|
||||
}
|
||||
assertEquals("remainder", response.getRedirectedUrl());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,189 +29,215 @@ 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;
|
||||
private FilterChainProxy fcp;
|
||||
private RequestMatcher matcher;
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletResponse response;
|
||||
private FilterChain chain;
|
||||
private Filter filter;
|
||||
|
||||
@Before
|
||||
public void setup() throws Exception {
|
||||
matcher = mock(RequestMatcher.class);
|
||||
filter = mock(Filter.class);
|
||||
doAnswer(new Answer<Object>() {
|
||||
public Object answer(InvocationOnMock inv) throws Throwable {
|
||||
Object[] args = inv.getArguments();
|
||||
FilterChain fc = (FilterChain) args[2];
|
||||
HttpServletRequestWrapper extraWrapper =
|
||||
new HttpServletRequestWrapper((HttpServletRequest) args[0]);
|
||||
fc.doFilter(extraWrapper, (HttpServletResponse) args[1]);
|
||||
return null;
|
||||
}
|
||||
}).when(filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), any(FilterChain.class));
|
||||
fcp = new FilterChainProxy(new DefaultSecurityFilterChain(matcher, Arrays.asList(filter)));
|
||||
fcp.setFilterChainValidator(mock(FilterChainProxy.FilterChainValidator.class));
|
||||
request = new MockHttpServletRequest();
|
||||
request.setServletPath("/path");
|
||||
response = new MockHttpServletResponse();
|
||||
chain = mock(FilterChain.class);
|
||||
}
|
||||
@Before
|
||||
public void setup() throws Exception {
|
||||
matcher = mock(RequestMatcher.class);
|
||||
filter = mock(Filter.class);
|
||||
doAnswer(new Answer<Object>() {
|
||||
public Object answer(InvocationOnMock inv) throws Throwable {
|
||||
Object[] args = inv.getArguments();
|
||||
FilterChain fc = (FilterChain) args[2];
|
||||
HttpServletRequestWrapper extraWrapper = new HttpServletRequestWrapper(
|
||||
(HttpServletRequest) args[0]);
|
||||
fc.doFilter(extraWrapper, (HttpServletResponse) args[1]);
|
||||
return null;
|
||||
}
|
||||
}).when(filter).doFilter(any(HttpServletRequest.class),
|
||||
any(HttpServletResponse.class), any(FilterChain.class));
|
||||
fcp = new FilterChainProxy(new DefaultSecurityFilterChain(matcher,
|
||||
Arrays.asList(filter)));
|
||||
fcp.setFilterChainValidator(mock(FilterChainProxy.FilterChainValidator.class));
|
||||
request = new MockHttpServletRequest();
|
||||
request.setServletPath("/path");
|
||||
response = new MockHttpServletResponse();
|
||||
chain = mock(FilterChain.class);
|
||||
}
|
||||
|
||||
@After
|
||||
public void teardown() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
@After
|
||||
public void teardown() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void toStringCallSucceeds() throws Exception {
|
||||
fcp.afterPropertiesSet();
|
||||
fcp.toString();
|
||||
}
|
||||
@Test
|
||||
public void toStringCallSucceeds() throws Exception {
|
||||
fcp.afterPropertiesSet();
|
||||
fcp.toString();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void securityFilterChainIsNotInvokedIfMatchFails() throws Exception {
|
||||
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(false);
|
||||
fcp.doFilter(request, response, chain);
|
||||
assertEquals(1, fcp.getFilterChains().size());
|
||||
assertSame(filter, fcp.getFilterChains().get(0).getFilters().get(0));
|
||||
@Test
|
||||
public void securityFilterChainIsNotInvokedIfMatchFails() throws Exception {
|
||||
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(false);
|
||||
fcp.doFilter(request, response, chain);
|
||||
assertEquals(1, fcp.getFilterChains().size());
|
||||
assertSame(filter, fcp.getFilterChains().get(0).getFilters().get(0));
|
||||
|
||||
verifyZeroInteractions(filter);
|
||||
// The actual filter chain should be invoked though
|
||||
verify(chain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
}
|
||||
verifyZeroInteractions(filter);
|
||||
// The actual filter chain should be invoked though
|
||||
verify(chain).doFilter(any(HttpServletRequest.class),
|
||||
any(HttpServletResponse.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void originalChainIsInvokedAfterSecurityChainIfMatchSucceeds() throws Exception {
|
||||
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
|
||||
fcp.doFilter(request, response, chain);
|
||||
@Test
|
||||
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 {
|
||||
List<Filter> noFilters = Collections.emptyList();
|
||||
fcp = new FilterChainProxy(new DefaultSecurityFilterChain(matcher, noFilters));
|
||||
@Test
|
||||
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);
|
||||
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 {
|
||||
when(matcher.matches(any(HttpServletRequest.class))).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(FirewalledRequest.class), any(HttpServletResponse.class));
|
||||
}
|
||||
@Test
|
||||
public void requestIsWrappedForMatchingAndFilteringWhenMatchIsFound()
|
||||
throws Exception {
|
||||
when(matcher.matches(any(HttpServletRequest.class))).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(FirewalledRequest.class),
|
||||
any(HttpServletResponse.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
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));
|
||||
}
|
||||
@Test
|
||||
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));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void wrapperIsResetWhenNoMatchingFilters() throws Exception {
|
||||
HttpFirewall fw = mock(HttpFirewall.class);
|
||||
FirewalledRequest fwr = mock (FirewalledRequest.class);
|
||||
when(fwr.getRequestURI()).thenReturn("/");
|
||||
when(fwr.getContextPath()).thenReturn("");
|
||||
fcp.setFirewall(fw);
|
||||
when(fw.getFirewalledRequest(request)).thenReturn(fwr);
|
||||
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(false);
|
||||
fcp.doFilter(request, response, chain);
|
||||
verify(fwr).reset();
|
||||
}
|
||||
@Test
|
||||
public void wrapperIsResetWhenNoMatchingFilters() throws Exception {
|
||||
HttpFirewall fw = mock(HttpFirewall.class);
|
||||
FirewalledRequest fwr = mock(FirewalledRequest.class);
|
||||
when(fwr.getRequestURI()).thenReturn("/");
|
||||
when(fwr.getContextPath()).thenReturn("");
|
||||
fcp.setFirewall(fw);
|
||||
when(fw.getFirewalledRequest(request)).thenReturn(fwr);
|
||||
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(false);
|
||||
fcp.doFilter(request, response, chain);
|
||||
verify(fwr).reset();
|
||||
}
|
||||
|
||||
// SEC-1639
|
||||
@Test
|
||||
public void bothWrappersAreResetWithNestedFcps() throws Exception {
|
||||
HttpFirewall fw = mock(HttpFirewall.class);
|
||||
FilterChainProxy firstFcp = new FilterChainProxy(new DefaultSecurityFilterChain(matcher, fcp));
|
||||
firstFcp.setFirewall(fw);
|
||||
fcp.setFirewall(fw);
|
||||
FirewalledRequest firstFwr = mock(FirewalledRequest.class, "firstFwr");
|
||||
when(firstFwr.getRequestURI()).thenReturn("/");
|
||||
when(firstFwr.getContextPath()).thenReturn("");
|
||||
FirewalledRequest fwr = mock(FirewalledRequest.class, "fwr");
|
||||
when(fwr.getRequestURI()).thenReturn("/");
|
||||
when(fwr.getContextPath()).thenReturn("");
|
||||
when(fw.getFirewalledRequest(request)).thenReturn(firstFwr);
|
||||
when(fw.getFirewalledRequest(firstFwr)).thenReturn(fwr);
|
||||
when(fwr.getRequest()).thenReturn(firstFwr);
|
||||
when(firstFwr.getRequest()).thenReturn(request);
|
||||
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
|
||||
firstFcp.doFilter(request, response, chain);
|
||||
verify(firstFwr).reset();
|
||||
verify(fwr).reset();
|
||||
}
|
||||
// SEC-1639
|
||||
@Test
|
||||
public void bothWrappersAreResetWithNestedFcps() throws Exception {
|
||||
HttpFirewall fw = mock(HttpFirewall.class);
|
||||
FilterChainProxy firstFcp = new FilterChainProxy(new DefaultSecurityFilterChain(
|
||||
matcher, fcp));
|
||||
firstFcp.setFirewall(fw);
|
||||
fcp.setFirewall(fw);
|
||||
FirewalledRequest firstFwr = mock(FirewalledRequest.class, "firstFwr");
|
||||
when(firstFwr.getRequestURI()).thenReturn("/");
|
||||
when(firstFwr.getContextPath()).thenReturn("");
|
||||
FirewalledRequest fwr = mock(FirewalledRequest.class, "fwr");
|
||||
when(fwr.getRequestURI()).thenReturn("/");
|
||||
when(fwr.getContextPath()).thenReturn("");
|
||||
when(fw.getFirewalledRequest(request)).thenReturn(firstFwr);
|
||||
when(fw.getFirewalledRequest(firstFwr)).thenReturn(fwr);
|
||||
when(fwr.getRequest()).thenReturn(firstFwr);
|
||||
when(firstFwr.getRequest()).thenReturn(request);
|
||||
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
|
||||
firstFcp.doFilter(request, response, chain);
|
||||
verify(firstFwr).reset();
|
||||
verify(fwr).reset();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterClearsSecurityContextHolder() throws Exception {
|
||||
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
|
||||
doAnswer(new Answer<Object>() {
|
||||
public Object answer(InvocationOnMock inv) throws Throwable {
|
||||
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("username", "password"));
|
||||
return null;
|
||||
}
|
||||
}).when(filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), any(FilterChain.class));
|
||||
@Test
|
||||
public void doFilterClearsSecurityContextHolder() throws Exception {
|
||||
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
|
||||
doAnswer(new Answer<Object>() {
|
||||
public Object answer(InvocationOnMock inv) throws Throwable {
|
||||
SecurityContextHolder.getContext().setAuthentication(
|
||||
new TestingAuthenticationToken("username", "password"));
|
||||
return null;
|
||||
}
|
||||
}).when(filter).doFilter(any(HttpServletRequest.class),
|
||||
any(HttpServletResponse.class), any(FilterChain.class));
|
||||
|
||||
fcp.doFilter(request, response, chain);
|
||||
fcp.doFilter(request, response, chain);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterClearsSecurityContextHolderWithException() throws Exception {
|
||||
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
|
||||
doAnswer(new Answer<Object>() {
|
||||
public Object answer(InvocationOnMock inv) throws Throwable {
|
||||
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("username", "password"));
|
||||
throw new ServletException("oops");
|
||||
}
|
||||
}).when(filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), any(FilterChain.class));
|
||||
@Test
|
||||
public void doFilterClearsSecurityContextHolderWithException() throws Exception {
|
||||
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
|
||||
doAnswer(new Answer<Object>() {
|
||||
public Object answer(InvocationOnMock inv) throws Throwable {
|
||||
SecurityContextHolder.getContext().setAuthentication(
|
||||
new TestingAuthenticationToken("username", "password"));
|
||||
throw new ServletException("oops");
|
||||
}
|
||||
}).when(filter).doFilter(any(HttpServletRequest.class),
|
||||
any(HttpServletResponse.class), any(FilterChain.class));
|
||||
|
||||
try {
|
||||
fcp.doFilter(request, response, chain);
|
||||
fail("Expected Exception");
|
||||
}catch(ServletException success) {}
|
||||
try {
|
||||
fcp.doFilter(request, response, chain);
|
||||
fail("Expected Exception");
|
||||
}
|
||||
catch (ServletException success) {
|
||||
}
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
// SEC-2027
|
||||
@Test
|
||||
public void doFilterClearsSecurityContextHolderOnceOnForwards() throws Exception {
|
||||
final FilterChain innerChain = mock(FilterChain.class);
|
||||
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
|
||||
doAnswer(new Answer<Object>() {
|
||||
public Object answer(InvocationOnMock inv) throws Throwable {
|
||||
TestingAuthenticationToken expected = new TestingAuthenticationToken("username", "password");
|
||||
SecurityContextHolder.getContext().setAuthentication(expected);
|
||||
doAnswer(new Answer<Object>() {
|
||||
public Object answer(InvocationOnMock inv) throws Throwable {
|
||||
innerChain.doFilter(request, response);
|
||||
return null;
|
||||
}
|
||||
}).when(filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), any(FilterChain.class));;
|
||||
fcp.doFilter(request, response, innerChain);
|
||||
assertSame(expected, SecurityContextHolder.getContext().getAuthentication());
|
||||
return null;
|
||||
}
|
||||
}).when(filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), any(FilterChain.class));
|
||||
// SEC-2027
|
||||
@Test
|
||||
public void doFilterClearsSecurityContextHolderOnceOnForwards() throws Exception {
|
||||
final FilterChain innerChain = mock(FilterChain.class);
|
||||
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
|
||||
doAnswer(new Answer<Object>() {
|
||||
public Object answer(InvocationOnMock inv) throws Throwable {
|
||||
TestingAuthenticationToken expected = new TestingAuthenticationToken(
|
||||
"username", "password");
|
||||
SecurityContextHolder.getContext().setAuthentication(expected);
|
||||
doAnswer(new Answer<Object>() {
|
||||
public Object answer(InvocationOnMock inv) throws Throwable {
|
||||
innerChain.doFilter(request, response);
|
||||
return null;
|
||||
}
|
||||
}).when(filter).doFilter(any(HttpServletRequest.class),
|
||||
any(HttpServletResponse.class), any(FilterChain.class));
|
||||
;
|
||||
fcp.doFilter(request, response, innerChain);
|
||||
assertSame(expected, SecurityContextHolder.getContext()
|
||||
.getAuthentication());
|
||||
return null;
|
||||
}
|
||||
}).when(filter).doFilter(any(HttpServletRequest.class),
|
||||
any(HttpServletResponse.class), any(FilterChain.class));
|
||||
|
||||
fcp.doFilter(request, response, chain);
|
||||
fcp.doFilter(request, response, chain);
|
||||
|
||||
verify(innerChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
verify(innerChain).doFilter(any(HttpServletRequest.class),
|
||||
any(HttpServletResponse.class));
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,100 +36,109 @@ import org.springframework.security.web.util.UrlUtils;
|
||||
*/
|
||||
public class FilterInvocationTests {
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
@Test
|
||||
public void testGettersAndStringMethods() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
|
||||
request.setServletPath("/HelloWorld");
|
||||
request.setPathInfo("/some/more/segments.html");
|
||||
request.setServerName("www.example.com");
|
||||
request.setScheme("http");
|
||||
request.setServerPort(80);
|
||||
request.setContextPath("/mycontext");
|
||||
request.setRequestURI("/mycontext/HelloWorld/some/more/segments.html");
|
||||
@Test
|
||||
public void testGettersAndStringMethods() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
|
||||
request.setServletPath("/HelloWorld");
|
||||
request.setPathInfo("/some/more/segments.html");
|
||||
request.setServerName("www.example.com");
|
||||
request.setScheme("http");
|
||||
request.setServerPort(80);
|
||||
request.setContextPath("/mycontext");
|
||||
request.setRequestURI("/mycontext/HelloWorld/some/more/segments.html");
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
FilterInvocation fi = new FilterInvocation(request, response, chain);
|
||||
assertEquals(request, fi.getRequest());
|
||||
assertEquals(request, fi.getHttpRequest());
|
||||
assertEquals(response, fi.getResponse());
|
||||
assertEquals(response, fi.getHttpResponse());
|
||||
assertEquals(chain, fi.getChain());
|
||||
assertEquals("/HelloWorld/some/more/segments.html", fi.getRequestUrl());
|
||||
assertEquals("FilterInvocation: URL: /HelloWorld/some/more/segments.html", fi.toString());
|
||||
assertEquals("http://www.example.com/mycontext/HelloWorld/some/more/segments.html", fi.getFullRequestUrl());
|
||||
}
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
FilterInvocation fi = new FilterInvocation(request, response, chain);
|
||||
assertEquals(request, fi.getRequest());
|
||||
assertEquals(request, fi.getHttpRequest());
|
||||
assertEquals(response, fi.getResponse());
|
||||
assertEquals(response, fi.getHttpResponse());
|
||||
assertEquals(chain, fi.getChain());
|
||||
assertEquals("/HelloWorld/some/more/segments.html", fi.getRequestUrl());
|
||||
assertEquals("FilterInvocation: URL: /HelloWorld/some/more/segments.html",
|
||||
fi.toString());
|
||||
assertEquals(
|
||||
"http://www.example.com/mycontext/HelloWorld/some/more/segments.html",
|
||||
fi.getFullRequestUrl());
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testRejectsNullFilterChain() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testRejectsNullFilterChain() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
new FilterInvocation(request, response, null);
|
||||
}
|
||||
new FilterInvocation(request, response, null);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testRejectsNullServletRequest() {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testRejectsNullServletRequest() {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
new FilterInvocation(null, response, mock(FilterChain.class));
|
||||
}
|
||||
new FilterInvocation(null, response, mock(FilterChain.class));
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testRejectsNullServletResponse() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testRejectsNullServletResponse() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
|
||||
|
||||
new FilterInvocation(request, null, mock(FilterChain.class));
|
||||
}
|
||||
new FilterInvocation(request, null, mock(FilterChain.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStringMethodsWithAQueryString() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setQueryString("foo=bar");
|
||||
request.setServletPath("/HelloWorld");
|
||||
request.setServerName("www.example.com");
|
||||
request.setScheme("http");
|
||||
request.setServerPort(80);
|
||||
request.setContextPath("/mycontext");
|
||||
request.setRequestURI("/mycontext/HelloWorld");
|
||||
@Test
|
||||
public void testStringMethodsWithAQueryString() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setQueryString("foo=bar");
|
||||
request.setServletPath("/HelloWorld");
|
||||
request.setServerName("www.example.com");
|
||||
request.setScheme("http");
|
||||
request.setServerPort(80);
|
||||
request.setContextPath("/mycontext");
|
||||
request.setRequestURI("/mycontext/HelloWorld");
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
|
||||
assertEquals("/HelloWorld?foo=bar", fi.getRequestUrl());
|
||||
assertEquals("FilterInvocation: URL: /HelloWorld?foo=bar", fi.toString());
|
||||
assertEquals("http://www.example.com/mycontext/HelloWorld?foo=bar", fi.getFullRequestUrl());
|
||||
}
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterInvocation fi = new FilterInvocation(request, response,
|
||||
mock(FilterChain.class));
|
||||
assertEquals("/HelloWorld?foo=bar", fi.getRequestUrl());
|
||||
assertEquals("FilterInvocation: URL: /HelloWorld?foo=bar", fi.toString());
|
||||
assertEquals("http://www.example.com/mycontext/HelloWorld?foo=bar",
|
||||
fi.getFullRequestUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStringMethodsWithoutAnyQueryString() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
|
||||
request.setServletPath("/HelloWorld");
|
||||
request.setServerName("www.example.com");
|
||||
request.setScheme("http");
|
||||
request.setServerPort(80);
|
||||
request.setContextPath("/mycontext");
|
||||
request.setRequestURI("/mycontext/HelloWorld");
|
||||
@Test
|
||||
public void testStringMethodsWithoutAnyQueryString() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
|
||||
request.setServletPath("/HelloWorld");
|
||||
request.setServerName("www.example.com");
|
||||
request.setScheme("http");
|
||||
request.setServerPort(80);
|
||||
request.setContextPath("/mycontext");
|
||||
request.setRequestURI("/mycontext/HelloWorld");
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
|
||||
assertEquals("/HelloWorld", fi.getRequestUrl());
|
||||
assertEquals("FilterInvocation: URL: /HelloWorld", fi.toString());
|
||||
assertEquals("http://www.example.com/mycontext/HelloWorld", fi.getFullRequestUrl());
|
||||
}
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterInvocation fi = new FilterInvocation(request, response,
|
||||
mock(FilterChain.class));
|
||||
assertEquals("/HelloWorld", fi.getRequestUrl());
|
||||
assertEquals("FilterInvocation: URL: /HelloWorld", fi.toString());
|
||||
assertEquals("http://www.example.com/mycontext/HelloWorld",
|
||||
fi.getFullRequestUrl());
|
||||
}
|
||||
|
||||
@Test(expected=UnsupportedOperationException.class)
|
||||
public void dummyChainRejectsInvocation() throws Exception {
|
||||
FilterInvocation.DUMMY_CHAIN.doFilter(mock(HttpServletRequest.class), mock(HttpServletResponse.class));
|
||||
}
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void dummyChainRejectsInvocation() throws Exception {
|
||||
FilterInvocation.DUMMY_CHAIN.doFilter(mock(HttpServletRequest.class),
|
||||
mock(HttpServletResponse.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void dummyRequestIsSupportedByUrlUtils() throws Exception {
|
||||
DummyRequest request = new DummyRequest();
|
||||
request.setContextPath("");
|
||||
request.setRequestURI("/something");
|
||||
UrlUtils.buildRequestUrl(request);
|
||||
}
|
||||
@Test
|
||||
public void dummyRequestIsSupportedByUrlUtils() throws Exception {
|
||||
DummyRequest request = new DummyRequest();
|
||||
request.setContextPath("");
|
||||
request.setRequestURI("/something");
|
||||
UrlUtils.buildRequestUrl(request);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -22,76 +22,83 @@ import java.util.Map;
|
||||
|
||||
import org.springframework.security.web.PortMapperImpl;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link PortMapperImpl}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class PortMapperImplTests extends TestCase {
|
||||
//~ Methods ========================================================================================================
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
public void testDefaultMappingsAreKnown() throws Exception {
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
assertEquals(Integer.valueOf(80), portMapper.lookupHttpPort(Integer.valueOf(443)));
|
||||
assertEquals(Integer.valueOf(8080), portMapper.lookupHttpPort(Integer.valueOf(8443)));
|
||||
assertEquals(Integer.valueOf(443), portMapper.lookupHttpsPort(Integer.valueOf(80)));
|
||||
assertEquals(Integer.valueOf(8443), portMapper.lookupHttpsPort(Integer.valueOf(8080)));
|
||||
}
|
||||
public void testDefaultMappingsAreKnown() throws Exception {
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
assertEquals(Integer.valueOf(80), portMapper.lookupHttpPort(Integer.valueOf(443)));
|
||||
assertEquals(Integer.valueOf(8080),
|
||||
portMapper.lookupHttpPort(Integer.valueOf(8443)));
|
||||
assertEquals(Integer.valueOf(443),
|
||||
portMapper.lookupHttpsPort(Integer.valueOf(80)));
|
||||
assertEquals(Integer.valueOf(8443),
|
||||
portMapper.lookupHttpsPort(Integer.valueOf(8080)));
|
||||
}
|
||||
|
||||
public void testDetectsEmptyMap() throws Exception {
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
public void testDetectsEmptyMap() throws Exception {
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
|
||||
try {
|
||||
portMapper.setPortMappings(new HashMap<String,String>());
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
try {
|
||||
portMapper.setPortMappings(new HashMap<String, String>());
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testDetectsNullMap() throws Exception {
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
public void testDetectsNullMap() throws Exception {
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
|
||||
try {
|
||||
portMapper.setPortMappings(null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
try {
|
||||
portMapper.setPortMappings(null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testGetTranslatedPortMappings() {
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
assertEquals(2, portMapper.getTranslatedPortMappings().size());
|
||||
}
|
||||
public void testGetTranslatedPortMappings() {
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
assertEquals(2, portMapper.getTranslatedPortMappings().size());
|
||||
}
|
||||
|
||||
public void testRejectsOutOfRangeMappings() {
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
Map<String, String> map = new HashMap<String, String>();
|
||||
map.put("79", "80559");
|
||||
public void testRejectsOutOfRangeMappings() {
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
Map<String, String> map = new HashMap<String, String>();
|
||||
map.put("79", "80559");
|
||||
|
||||
try {
|
||||
portMapper.setPortMappings(map);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
try {
|
||||
portMapper.setPortMappings(map);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testReturnsNullIfHttpPortCannotBeFound() {
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
assertTrue(portMapper.lookupHttpPort(Integer.valueOf("34343")) == null);
|
||||
}
|
||||
public void testReturnsNullIfHttpPortCannotBeFound() {
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
assertTrue(portMapper.lookupHttpPort(Integer.valueOf("34343")) == null);
|
||||
}
|
||||
|
||||
public void testSupportsCustomMappings() {
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
Map<String, String> map = new HashMap<String, String>();
|
||||
map.put("79", "442");
|
||||
public void testSupportsCustomMappings() {
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
Map<String, String> map = new HashMap<String, String>();
|
||||
map.put("79", "442");
|
||||
|
||||
portMapper.setPortMappings(map);
|
||||
portMapper.setPortMappings(map);
|
||||
|
||||
assertEquals(Integer.valueOf(79), portMapper.lookupHttpPort(Integer.valueOf(442)));
|
||||
assertEquals(Integer.valueOf(442), portMapper.lookupHttpsPort(Integer.valueOf(79)));
|
||||
}
|
||||
assertEquals(Integer.valueOf(79), portMapper.lookupHttpPort(Integer.valueOf(442)));
|
||||
assertEquals(Integer.valueOf(442),
|
||||
portMapper.lookupHttpsPort(Integer.valueOf(79)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,71 +21,73 @@ import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.security.web.PortMapperImpl;
|
||||
import org.springframework.security.web.PortResolverImpl;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link PortResolverImpl}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class PortResolverImplTests extends TestCase {
|
||||
//~ Constructors ===================================================================================================
|
||||
// ~ Constructors
|
||||
// ===================================================================================================
|
||||
|
||||
public PortResolverImplTests() {
|
||||
super();
|
||||
}
|
||||
public PortResolverImplTests() {
|
||||
super();
|
||||
}
|
||||
|
||||
public PortResolverImplTests(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
public PortResolverImplTests(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
public final void setUp() throws Exception {
|
||||
super.setUp();
|
||||
}
|
||||
public final void setUp() throws Exception {
|
||||
super.setUp();
|
||||
}
|
||||
|
||||
public void testDetectsBuggyIeHttpRequest() throws Exception {
|
||||
PortResolverImpl pr = new PortResolverImpl();
|
||||
public void testDetectsBuggyIeHttpRequest() throws Exception {
|
||||
PortResolverImpl pr = new PortResolverImpl();
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setServerPort(8443);
|
||||
request.setScheme("HTtP"); // proves case insensitive handling
|
||||
assertEquals(8080, pr.getServerPort(request));
|
||||
}
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setServerPort(8443);
|
||||
request.setScheme("HTtP"); // proves case insensitive handling
|
||||
assertEquals(8080, pr.getServerPort(request));
|
||||
}
|
||||
|
||||
public void testDetectsBuggyIeHttpsRequest() throws Exception {
|
||||
PortResolverImpl pr = new PortResolverImpl();
|
||||
public void testDetectsBuggyIeHttpsRequest() throws Exception {
|
||||
PortResolverImpl pr = new PortResolverImpl();
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setServerPort(8080);
|
||||
request.setScheme("HTtPs"); // proves case insensitive handling
|
||||
assertEquals(8443, pr.getServerPort(request));
|
||||
}
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setServerPort(8080);
|
||||
request.setScheme("HTtPs"); // proves case insensitive handling
|
||||
assertEquals(8443, pr.getServerPort(request));
|
||||
}
|
||||
|
||||
public void testDetectsEmptyPortMapper() throws Exception {
|
||||
PortResolverImpl pr = new PortResolverImpl();
|
||||
public void testDetectsEmptyPortMapper() throws Exception {
|
||||
PortResolverImpl pr = new PortResolverImpl();
|
||||
|
||||
try {
|
||||
pr.setPortMapper(null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
try {
|
||||
pr.setPortMapper(null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testGettersSetters() throws Exception {
|
||||
PortResolverImpl pr = new PortResolverImpl();
|
||||
assertTrue(pr.getPortMapper() != null);
|
||||
pr.setPortMapper(new PortMapperImpl());
|
||||
assertTrue(pr.getPortMapper() != null);
|
||||
}
|
||||
public void testGettersSetters() throws Exception {
|
||||
PortResolverImpl pr = new PortResolverImpl();
|
||||
assertTrue(pr.getPortMapper() != null);
|
||||
pr.setPortMapper(new PortMapperImpl());
|
||||
assertTrue(pr.getPortMapper() != null);
|
||||
}
|
||||
|
||||
public void testNormalOperation() throws Exception {
|
||||
PortResolverImpl pr = new PortResolverImpl();
|
||||
public void testNormalOperation() throws Exception {
|
||||
PortResolverImpl pr = new PortResolverImpl();
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setScheme("http");
|
||||
request.setServerPort(1021);
|
||||
assertEquals(1021, pr.getServerPort(request));
|
||||
}
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setScheme("http");
|
||||
request.setServerPort(1021);
|
||||
assertEquals(1021, pr.getServerPort(request));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,70 +32,83 @@ import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
|
||||
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator}.
|
||||
* Tests
|
||||
* {@link org.springframework.security.web.access.DefaultWebInvocationPrivilegeEvaluator}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class DefaultWebInvocationPrivilegeEvaluatorTests {
|
||||
private AccessDecisionManager adm;
|
||||
private FilterInvocationSecurityMetadataSource ods;
|
||||
private RunAsManager ram;
|
||||
private FilterSecurityInterceptor interceptor;
|
||||
private AccessDecisionManager adm;
|
||||
private FilterInvocationSecurityMetadataSource ods;
|
||||
private RunAsManager ram;
|
||||
private FilterSecurityInterceptor interceptor;
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
@Before
|
||||
public final void setUp() {
|
||||
interceptor = new FilterSecurityInterceptor();
|
||||
ods = mock(FilterInvocationSecurityMetadataSource.class);
|
||||
adm = mock(AccessDecisionManager.class);
|
||||
ram = mock(RunAsManager.class);
|
||||
interceptor.setAuthenticationManager(mock(AuthenticationManager.class));
|
||||
interceptor.setSecurityMetadataSource(ods);
|
||||
interceptor.setAccessDecisionManager(adm);
|
||||
interceptor.setRunAsManager(ram);
|
||||
interceptor.setApplicationEventPublisher(mock(ApplicationEventPublisher.class));
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
@Before
|
||||
public final void setUp() {
|
||||
interceptor = new FilterSecurityInterceptor();
|
||||
ods = mock(FilterInvocationSecurityMetadataSource.class);
|
||||
adm = mock(AccessDecisionManager.class);
|
||||
ram = mock(RunAsManager.class);
|
||||
interceptor.setAuthenticationManager(mock(AuthenticationManager.class));
|
||||
interceptor.setSecurityMetadataSource(ods);
|
||||
interceptor.setAccessDecisionManager(adm);
|
||||
interceptor.setRunAsManager(ram);
|
||||
interceptor.setApplicationEventPublisher(mock(ApplicationEventPublisher.class));
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void permitsAccessIfNoMatchingAttributesAndPublicInvocationsAllowed() throws Exception {
|
||||
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(interceptor);
|
||||
when(ods.getAttributes(anyObject())).thenReturn(null);
|
||||
assertTrue(wipe.isAllowed("/context", "/foo/index.jsp", "GET", mock(Authentication.class)));
|
||||
}
|
||||
@Test
|
||||
public void permitsAccessIfNoMatchingAttributesAndPublicInvocationsAllowed()
|
||||
throws Exception {
|
||||
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(
|
||||
interceptor);
|
||||
when(ods.getAttributes(anyObject())).thenReturn(null);
|
||||
assertTrue(wipe.isAllowed("/context", "/foo/index.jsp", "GET",
|
||||
mock(Authentication.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deniesAccessIfNoMatchingAttributesAndPublicInvocationsNotAllowed() throws Exception {
|
||||
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(interceptor);
|
||||
when(ods.getAttributes(anyObject())).thenReturn(null);
|
||||
interceptor.setRejectPublicInvocations(true);
|
||||
assertFalse(wipe.isAllowed("/context", "/foo/index.jsp", "GET", mock(Authentication.class)));
|
||||
}
|
||||
@Test
|
||||
public void deniesAccessIfNoMatchingAttributesAndPublicInvocationsNotAllowed()
|
||||
throws Exception {
|
||||
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(
|
||||
interceptor);
|
||||
when(ods.getAttributes(anyObject())).thenReturn(null);
|
||||
interceptor.setRejectPublicInvocations(true);
|
||||
assertFalse(wipe.isAllowed("/context", "/foo/index.jsp", "GET",
|
||||
mock(Authentication.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deniesAccessIfAuthenticationIsNull() throws Exception {
|
||||
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(interceptor);
|
||||
assertFalse(wipe.isAllowed("/foo/index.jsp", null));
|
||||
}
|
||||
@Test
|
||||
public void deniesAccessIfAuthenticationIsNull() throws Exception {
|
||||
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(
|
||||
interceptor);
|
||||
assertFalse(wipe.isAllowed("/foo/index.jsp", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void allowsAccessIfAccessDecisionMangerDoes() throws Exception {
|
||||
Authentication token = new TestingAuthenticationToken("test", "Password", "MOCK_INDEX");
|
||||
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(interceptor);
|
||||
assertTrue(wipe.isAllowed("/foo/index.jsp", token));
|
||||
}
|
||||
@Test
|
||||
public void allowsAccessIfAccessDecisionMangerDoes() throws Exception {
|
||||
Authentication token = new TestingAuthenticationToken("test", "Password",
|
||||
"MOCK_INDEX");
|
||||
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(
|
||||
interceptor);
|
||||
assertTrue(wipe.isAllowed("/foo/index.jsp", token));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void deniesAccessIfAccessDecisionMangerDoes() throws Exception {
|
||||
Authentication token = new TestingAuthenticationToken("test", "Password", "MOCK_INDEX");
|
||||
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(interceptor);
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void deniesAccessIfAccessDecisionMangerDoes() throws Exception {
|
||||
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());
|
||||
|
||||
assertFalse(wipe.isAllowed("/foo/index.jsp", token));
|
||||
}
|
||||
assertFalse(wipe.isAllowed("/foo/index.jsp", token));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,49 +36,52 @@ 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;
|
||||
@Mock
|
||||
private AccessDeniedHandler handler1;
|
||||
@Mock
|
||||
private AccessDeniedHandler handler2;
|
||||
@Mock
|
||||
private AccessDeniedHandler handler3;
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
@Mock
|
||||
private HttpServletResponse response;
|
||||
|
||||
private LinkedHashMap<Class<? extends AccessDeniedException>,AccessDeniedHandler> handlers;
|
||||
private LinkedHashMap<Class<? extends AccessDeniedException>, AccessDeniedHandler> handlers;
|
||||
|
||||
private DelegatingAccessDeniedHandler handler;
|
||||
private DelegatingAccessDeniedHandler handler;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
handlers = new LinkedHashMap<Class<? extends AccessDeniedException>, AccessDeniedHandler>();
|
||||
}
|
||||
@Before
|
||||
public void setup() {
|
||||
handlers = new LinkedHashMap<Class<? extends AccessDeniedException>, AccessDeniedHandler>();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void moreSpecificDoesNotInvokeLessSpecific() throws Exception {
|
||||
handlers.put(CsrfException.class, handler1);
|
||||
handler = new DelegatingAccessDeniedHandler(handlers, handler3);
|
||||
@Test
|
||||
public void moreSpecificDoesNotInvokeLessSpecific() throws Exception {
|
||||
handlers.put(CsrfException.class, handler1);
|
||||
handler = new DelegatingAccessDeniedHandler(handlers, handler3);
|
||||
|
||||
AccessDeniedException accessDeniedException = new AccessDeniedException("");
|
||||
handler.handle(request, response, accessDeniedException);
|
||||
AccessDeniedException accessDeniedException = new AccessDeniedException("");
|
||||
handler.handle(request, response, accessDeniedException);
|
||||
|
||||
verify(handler1,never()).handle(any(HttpServletRequest.class), any(HttpServletResponse.class), any(AccessDeniedException.class));
|
||||
verify(handler3).handle(request, response, accessDeniedException);
|
||||
}
|
||||
verify(handler1, never()).handle(any(HttpServletRequest.class),
|
||||
any(HttpServletResponse.class), any(AccessDeniedException.class));
|
||||
verify(handler3).handle(request, response, accessDeniedException);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchesDoesNotInvokeDefault() throws Exception {
|
||||
handlers.put(InvalidCsrfTokenException.class, handler1);
|
||||
handlers.put(MissingCsrfTokenException.class, handler2);
|
||||
handler = new DelegatingAccessDeniedHandler(handlers, handler3);
|
||||
@Test
|
||||
public void matchesDoesNotInvokeDefault() throws Exception {
|
||||
handlers.put(InvalidCsrfTokenException.class, handler1);
|
||||
handlers.put(MissingCsrfTokenException.class, handler2);
|
||||
handler = new DelegatingAccessDeniedHandler(handlers, handler3);
|
||||
|
||||
AccessDeniedException accessDeniedException = new MissingCsrfTokenException("123");
|
||||
handler.handle(request, response, accessDeniedException);
|
||||
AccessDeniedException accessDeniedException = new MissingCsrfTokenException("123");
|
||||
handler.handle(request, response, accessDeniedException);
|
||||
|
||||
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(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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,183 +53,200 @@ import java.io.IOException;
|
||||
*/
|
||||
public class ExceptionTranslationFilterTests {
|
||||
|
||||
@After
|
||||
@Before
|
||||
public void clearContext() throws Exception {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
@After
|
||||
@Before
|
||||
public void clearContext() throws Exception {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
private static String getSavedRequestUrl(HttpServletRequest request) {
|
||||
HttpSession session = request.getSession(false);
|
||||
private static String getSavedRequestUrl(HttpServletRequest request) {
|
||||
HttpSession session = request.getSession(false);
|
||||
|
||||
if (session == null) {
|
||||
return null;
|
||||
}
|
||||
if (session == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
HttpSessionRequestCache rc = new HttpSessionRequestCache();
|
||||
SavedRequest sr = rc.getRequest(request, new MockHttpServletResponse());
|
||||
HttpSessionRequestCache rc = new HttpSessionRequestCache();
|
||||
SavedRequest sr = rc.getRequest(request, new MockHttpServletResponse());
|
||||
|
||||
return sr.getRedirectUrl();
|
||||
}
|
||||
return sr.getRedirectUrl();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAccessDeniedWhenAnonymous() throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setServletPath("/secure/page.html");
|
||||
request.setServerPort(80);
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setContextPath("/mycontext");
|
||||
request.setRequestURI("/mycontext/secure/page.html");
|
||||
@Test
|
||||
public void testAccessDeniedWhenAnonymous() throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setServletPath("/secure/page.html");
|
||||
request.setServerPort(80);
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setContextPath("/mycontext");
|
||||
request.setRequestURI("/mycontext/secure/page.html");
|
||||
|
||||
// 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));
|
||||
// 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));
|
||||
|
||||
// Setup SecurityContextHolder, as filter needs to check if user is
|
||||
// anonymous
|
||||
SecurityContextHolder.getContext().setAuthentication(
|
||||
new AnonymousAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("IGNORED")));
|
||||
// Setup SecurityContextHolder, as filter needs to check if user is
|
||||
// anonymous
|
||||
SecurityContextHolder.getContext().setAuthentication(
|
||||
new AnonymousAuthenticationToken("ignored", "ignored", AuthorityUtils
|
||||
.createAuthorityList("IGNORED")));
|
||||
|
||||
// Test
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
|
||||
filter.setAuthenticationTrustResolver(new AuthenticationTrustResolverImpl());
|
||||
assertNotNull(filter.getAuthenticationTrustResolver());
|
||||
// Test
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
|
||||
filter.setAuthenticationTrustResolver(new AuthenticationTrustResolverImpl());
|
||||
assertNotNull(filter.getAuthenticationTrustResolver());
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
filter.doFilter(request, response, fc);
|
||||
assertEquals("/mycontext/login.jsp", response.getRedirectedUrl());
|
||||
assertEquals("http://www.example.com/mycontext/secure/page.html", getSavedRequestUrl(request));
|
||||
}
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
filter.doFilter(request, response, fc);
|
||||
assertEquals("/mycontext/login.jsp", response.getRedirectedUrl());
|
||||
assertEquals("http://www.example.com/mycontext/secure/page.html",
|
||||
getSavedRequestUrl(request));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAccessDeniedWhenNonAnonymous() throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setServletPath("/secure/page.html");
|
||||
@Test
|
||||
public void testAccessDeniedWhenNonAnonymous() throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setServletPath("/secure/page.html");
|
||||
|
||||
// Setup the FilterChain to thrown an access denied exception
|
||||
FilterChain fc = mock(FilterChain.class);
|
||||
doThrow(new AccessDeniedException("")).when(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
// 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));
|
||||
|
||||
// Setup SecurityContextHolder, as filter needs to check if user is
|
||||
// anonymous
|
||||
SecurityContextHolder.clearContext();
|
||||
// Setup SecurityContextHolder, as filter needs to check if user is
|
||||
// anonymous
|
||||
SecurityContextHolder.clearContext();
|
||||
|
||||
// Setup a new AccessDeniedHandlerImpl that will do a "forward"
|
||||
AccessDeniedHandlerImpl adh = new AccessDeniedHandlerImpl();
|
||||
adh.setErrorPage("/error.jsp");
|
||||
// Setup a new AccessDeniedHandlerImpl that will do a "forward"
|
||||
AccessDeniedHandlerImpl adh = new AccessDeniedHandlerImpl();
|
||||
adh.setErrorPage("/error.jsp");
|
||||
|
||||
// Test
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
|
||||
filter.setAccessDeniedHandler(adh);
|
||||
// Test
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
|
||||
filter.setAccessDeniedHandler(adh);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
filter.doFilter(request, response, fc);
|
||||
assertEquals(403, response.getStatus());
|
||||
assertEquals(AccessDeniedException.class, request.getAttribute(WebAttributes.ACCESS_DENIED_403).getClass());
|
||||
}
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
filter.doFilter(request, response, fc);
|
||||
assertEquals(403, response.getStatus());
|
||||
assertEquals(AccessDeniedException.class,
|
||||
request.getAttribute(WebAttributes.ACCESS_DENIED_403).getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void redirectedToLoginFormAndSessionShowsOriginalTargetWhenAuthenticationException() throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setServletPath("/secure/page.html");
|
||||
request.setServerPort(80);
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setContextPath("/mycontext");
|
||||
request.setRequestURI("/mycontext/secure/page.html");
|
||||
@Test
|
||||
public void redirectedToLoginFormAndSessionShowsOriginalTargetWhenAuthenticationException()
|
||||
throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setServletPath("/secure/page.html");
|
||||
request.setServerPort(80);
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setContextPath("/mycontext");
|
||||
request.setRequestURI("/mycontext/secure/page.html");
|
||||
|
||||
// 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));
|
||||
// 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));
|
||||
|
||||
// Test
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
|
||||
filter.afterPropertiesSet();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
filter.doFilter(request, response, fc);
|
||||
assertEquals("/mycontext/login.jsp", response.getRedirectedUrl());
|
||||
assertEquals("http://www.example.com/mycontext/secure/page.html", getSavedRequestUrl(request));
|
||||
}
|
||||
// Test
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
|
||||
filter.afterPropertiesSet();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
filter.doFilter(request, response, fc);
|
||||
assertEquals("/mycontext/login.jsp", response.getRedirectedUrl());
|
||||
assertEquals("http://www.example.com/mycontext/secure/page.html",
|
||||
getSavedRequestUrl(request));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void redirectedToLoginFormAndSessionShowsOriginalTargetWithExoticPortWhenAuthenticationException()
|
||||
throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setServletPath("/secure/page.html");
|
||||
request.setServerPort(8080);
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setContextPath("/mycontext");
|
||||
request.setRequestURI("/mycontext/secure/page.html");
|
||||
@Test
|
||||
public void redirectedToLoginFormAndSessionShowsOriginalTargetWithExoticPortWhenAuthenticationException()
|
||||
throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setServletPath("/secure/page.html");
|
||||
request.setServerPort(8080);
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setContextPath("/mycontext");
|
||||
request.setRequestURI("/mycontext/secure/page.html");
|
||||
|
||||
// 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));
|
||||
// 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));
|
||||
|
||||
// Test
|
||||
HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint, requestCache);
|
||||
requestCache.setPortResolver(new MockPortResolver(8080, 8443));
|
||||
filter.afterPropertiesSet();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
filter.doFilter(request, response, fc);
|
||||
assertEquals("/mycontext/login.jsp", response.getRedirectedUrl());
|
||||
assertEquals("http://www.example.com:8080/mycontext/secure/page.html", getSavedRequestUrl(request));
|
||||
}
|
||||
// Test
|
||||
HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(
|
||||
mockEntryPoint, requestCache);
|
||||
requestCache.setPortResolver(new MockPortResolver(8080, 8443));
|
||||
filter.afterPropertiesSet();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
filter.doFilter(request, response, fc);
|
||||
assertEquals("/mycontext/login.jsp", response.getRedirectedUrl());
|
||||
assertEquals("http://www.example.com:8080/mycontext/secure/page.html",
|
||||
getSavedRequestUrl(request));
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void startupDetectsMissingAuthenticationEntryPoint() throws Exception {
|
||||
new ExceptionTranslationFilter(null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void startupDetectsMissingAuthenticationEntryPoint() throws Exception {
|
||||
new ExceptionTranslationFilter(null);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void startupDetectsMissingRequestCache() throws Exception {
|
||||
new ExceptionTranslationFilter(mockEntryPoint, null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void startupDetectsMissingRequestCache() throws Exception {
|
||||
new ExceptionTranslationFilter(mockEntryPoint, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void successfulAccessGrant() throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setServletPath("/secure/page.html");
|
||||
@Test
|
||||
public void successfulAccessGrant() throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setServletPath("/secure/page.html");
|
||||
|
||||
// Test
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
|
||||
assertSame(mockEntryPoint, filter.getAuthenticationEntryPoint());
|
||||
// Test
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
|
||||
assertSame(mockEntryPoint, filter.getAuthenticationEntryPoint());
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
filter.doFilter(request, response, mock(FilterChain.class));
|
||||
}
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
filter.doFilter(request, response, mock(FilterChain.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void thrownIOExceptionServletExceptionAndRuntimeExceptionsAreRethrown() throws Exception {
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
|
||||
@Test
|
||||
public void thrownIOExceptionServletExceptionAndRuntimeExceptionsAreRethrown()
|
||||
throws Exception {
|
||||
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
|
||||
|
||||
filter.afterPropertiesSet();
|
||||
Exception[] exceptions = {new IOException(), new ServletException(), new RuntimeException()};
|
||||
for (Exception e : exceptions) {
|
||||
FilterChain fc = mock(FilterChain.class);
|
||||
filter.afterPropertiesSet();
|
||||
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));
|
||||
try {
|
||||
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), fc);
|
||||
fail("Should have thrown Exception");
|
||||
}
|
||||
catch (Exception expected) {
|
||||
assertSame("The exception thrown should not have been wrapped", e, expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
doThrow(e).when(fc).doFilter(any(HttpServletRequest.class),
|
||||
any(HttpServletResponse.class));
|
||||
try {
|
||||
filter.doFilter(new MockHttpServletRequest(),
|
||||
new MockHttpServletResponse(), fc);
|
||||
fail("Should have thrown Exception");
|
||||
}
|
||||
catch (Exception expected) {
|
||||
assertSame("The exception thrown should not have been wrapped", e,
|
||||
expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private final AuthenticationEntryPoint mockEntryPoint = new AuthenticationEntryPoint() {
|
||||
public void commence(HttpServletRequest request, HttpServletResponse response,
|
||||
AuthenticationException authException) throws IOException, ServletException {
|
||||
response.sendRedirect(request.getContextPath() + "/login.jsp");
|
||||
}
|
||||
};
|
||||
private final AuthenticationEntryPoint mockEntryPoint = new AuthenticationEntryPoint() {
|
||||
public void commence(HttpServletRequest request, HttpServletResponse response,
|
||||
AuthenticationException authException) throws IOException,
|
||||
ServletException {
|
||||
response.sendRedirect(request.getContextPath() + "/login.jsp");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -36,7 +36,6 @@ import org.springframework.security.web.FilterInvocation;
|
||||
import org.springframework.security.web.access.channel.ChannelDecisionManagerImpl;
|
||||
import org.springframework.security.web.access.channel.ChannelProcessor;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link ChannelDecisionManagerImpl}.
|
||||
*
|
||||
@@ -44,175 +43,186 @@ import org.springframework.security.web.access.channel.ChannelProcessor;
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public class ChannelDecisionManagerImplTests extends TestCase {
|
||||
//~ Methods ========================================================================================================
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
public void testCannotSetEmptyChannelProcessorsList() throws Exception {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
public void testCannotSetEmptyChannelProcessorsList() throws Exception {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
|
||||
try {
|
||||
cdm.setChannelProcessors(new Vector());
|
||||
cdm.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("A list of ChannelProcessors is required", expected.getMessage());
|
||||
}
|
||||
}
|
||||
try {
|
||||
cdm.setChannelProcessors(new Vector());
|
||||
cdm.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertEquals("A list of ChannelProcessors is required", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testCannotSetIncorrectObjectTypesIntoChannelProcessorsList() throws Exception {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
List list = new Vector();
|
||||
list.add("THIS IS NOT A CHANNELPROCESSOR");
|
||||
public void testCannotSetIncorrectObjectTypesIntoChannelProcessorsList()
|
||||
throws Exception {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
List list = new Vector();
|
||||
list.add("THIS IS NOT A CHANNELPROCESSOR");
|
||||
|
||||
try {
|
||||
cdm.setChannelProcessors(list);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
try {
|
||||
cdm.setChannelProcessors(list);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testCannotSetNullChannelProcessorsList() throws Exception {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
public void testCannotSetNullChannelProcessorsList() throws Exception {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
|
||||
try {
|
||||
cdm.setChannelProcessors(null);
|
||||
cdm.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("A list of ChannelProcessors is required", expected.getMessage());
|
||||
}
|
||||
}
|
||||
try {
|
||||
cdm.setChannelProcessors(null);
|
||||
cdm.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertEquals("A list of ChannelProcessors is required", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testDecideIsOperational() throws Exception {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false);
|
||||
MockChannelProcessor cpAbc = new MockChannelProcessor("abc", true);
|
||||
List list = new Vector();
|
||||
list.add(cpXyz);
|
||||
list.add(cpAbc);
|
||||
cdm.setChannelProcessors(list);
|
||||
cdm.afterPropertiesSet();
|
||||
public void testDecideIsOperational() throws Exception {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false);
|
||||
MockChannelProcessor cpAbc = new MockChannelProcessor("abc", true);
|
||||
List list = new Vector();
|
||||
list.add(cpXyz);
|
||||
list.add(cpAbc);
|
||||
cdm.setChannelProcessors(list);
|
||||
cdm.afterPropertiesSet();
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterInvocation fi = new FilterInvocation(request, response,
|
||||
mock(FilterChain.class));
|
||||
|
||||
List<ConfigAttribute> cad = SecurityConfig.createList("xyz");
|
||||
List<ConfigAttribute> cad = SecurityConfig.createList("xyz");
|
||||
|
||||
cdm.decide(fi, cad);
|
||||
assertTrue(fi.getResponse().isCommitted());
|
||||
}
|
||||
cdm.decide(fi, cad);
|
||||
assertTrue(fi.getResponse().isCommitted());
|
||||
}
|
||||
|
||||
public void testAnyChannelAttributeCausesProcessorsToBeSkipped() throws Exception {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
MockChannelProcessor cpAbc = new MockChannelProcessor("abc", true);
|
||||
List list = new Vector();
|
||||
list.add(cpAbc);
|
||||
cdm.setChannelProcessors(list);
|
||||
cdm.afterPropertiesSet();
|
||||
public void testAnyChannelAttributeCausesProcessorsToBeSkipped() throws Exception {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
MockChannelProcessor cpAbc = new MockChannelProcessor("abc", true);
|
||||
List list = new Vector();
|
||||
list.add(cpAbc);
|
||||
cdm.setChannelProcessors(list);
|
||||
cdm.afterPropertiesSet();
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterInvocation fi = new FilterInvocation(request, response,
|
||||
mock(FilterChain.class));
|
||||
|
||||
cdm.decide(fi, SecurityConfig.createList(new String[]{"abc", "ANY_CHANNEL"}));
|
||||
assertFalse(fi.getResponse().isCommitted());
|
||||
}
|
||||
cdm.decide(fi, SecurityConfig.createList(new String[] { "abc", "ANY_CHANNEL" }));
|
||||
assertFalse(fi.getResponse().isCommitted());
|
||||
}
|
||||
|
||||
public void testDecideIteratesAllProcessorsIfNoneCommitAResponse() throws Exception {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false);
|
||||
MockChannelProcessor cpAbc = new MockChannelProcessor("abc", false);
|
||||
List list = new Vector();
|
||||
list.add(cpXyz);
|
||||
list.add(cpAbc);
|
||||
cdm.setChannelProcessors(list);
|
||||
cdm.afterPropertiesSet();
|
||||
public void testDecideIteratesAllProcessorsIfNoneCommitAResponse() throws Exception {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false);
|
||||
MockChannelProcessor cpAbc = new MockChannelProcessor("abc", false);
|
||||
List list = new Vector();
|
||||
list.add(cpXyz);
|
||||
list.add(cpAbc);
|
||||
cdm.setChannelProcessors(list);
|
||||
cdm.afterPropertiesSet();
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterInvocation fi = new FilterInvocation(request, response,
|
||||
mock(FilterChain.class));
|
||||
|
||||
cdm.decide(fi, SecurityConfig.createList("SOME_ATTRIBUTE_NO_PROCESSORS_SUPPORT"));
|
||||
assertFalse(fi.getResponse().isCommitted());
|
||||
}
|
||||
cdm.decide(fi, SecurityConfig.createList("SOME_ATTRIBUTE_NO_PROCESSORS_SUPPORT"));
|
||||
assertFalse(fi.getResponse().isCommitted());
|
||||
}
|
||||
|
||||
public void testDelegatesSupports() throws Exception {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false);
|
||||
MockChannelProcessor cpAbc = new MockChannelProcessor("abc", false);
|
||||
List list = new Vector();
|
||||
list.add(cpXyz);
|
||||
list.add(cpAbc);
|
||||
cdm.setChannelProcessors(list);
|
||||
cdm.afterPropertiesSet();
|
||||
public void testDelegatesSupports() throws Exception {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false);
|
||||
MockChannelProcessor cpAbc = new MockChannelProcessor("abc", false);
|
||||
List list = new Vector();
|
||||
list.add(cpXyz);
|
||||
list.add(cpAbc);
|
||||
cdm.setChannelProcessors(list);
|
||||
cdm.afterPropertiesSet();
|
||||
|
||||
assertTrue(cdm.supports(new SecurityConfig("xyz")));
|
||||
assertTrue(cdm.supports(new SecurityConfig("abc")));
|
||||
assertFalse(cdm.supports(new SecurityConfig("UNSUPPORTED")));
|
||||
}
|
||||
assertTrue(cdm.supports(new SecurityConfig("xyz")));
|
||||
assertTrue(cdm.supports(new SecurityConfig("abc")));
|
||||
assertFalse(cdm.supports(new SecurityConfig("UNSUPPORTED")));
|
||||
}
|
||||
|
||||
public void testGettersSetters() {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
assertNull(cdm.getChannelProcessors());
|
||||
public void testGettersSetters() {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
assertNull(cdm.getChannelProcessors());
|
||||
|
||||
MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false);
|
||||
MockChannelProcessor cpAbc = new MockChannelProcessor("abc", false);
|
||||
List list = new Vector();
|
||||
list.add(cpXyz);
|
||||
list.add(cpAbc);
|
||||
cdm.setChannelProcessors(list);
|
||||
MockChannelProcessor cpXyz = new MockChannelProcessor("xyz", false);
|
||||
MockChannelProcessor cpAbc = new MockChannelProcessor("abc", false);
|
||||
List list = new Vector();
|
||||
list.add(cpXyz);
|
||||
list.add(cpAbc);
|
||||
cdm.setChannelProcessors(list);
|
||||
|
||||
assertEquals(list, cdm.getChannelProcessors());
|
||||
}
|
||||
assertEquals(list, cdm.getChannelProcessors());
|
||||
}
|
||||
|
||||
public void testStartupFailsWithEmptyChannelProcessorsList() throws Exception {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
public void testStartupFailsWithEmptyChannelProcessorsList() throws Exception {
|
||||
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
|
||||
|
||||
try {
|
||||
cdm.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("A list of ChannelProcessors is required", expected.getMessage());
|
||||
}
|
||||
}
|
||||
try {
|
||||
cdm.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertEquals("A list of ChannelProcessors is required", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
//~ Inner Classes ==================================================================================================
|
||||
// ~ Inner Classes
|
||||
// ==================================================================================================
|
||||
|
||||
private class MockChannelProcessor implements ChannelProcessor {
|
||||
private String configAttribute;
|
||||
private boolean failIfCalled;
|
||||
private class MockChannelProcessor implements ChannelProcessor {
|
||||
private String configAttribute;
|
||||
private boolean failIfCalled;
|
||||
|
||||
public MockChannelProcessor(String configAttribute, boolean failIfCalled) {
|
||||
this.configAttribute = configAttribute;
|
||||
this.failIfCalled = failIfCalled;
|
||||
}
|
||||
public MockChannelProcessor(String configAttribute, boolean failIfCalled) {
|
||||
this.configAttribute = configAttribute;
|
||||
this.failIfCalled = failIfCalled;
|
||||
}
|
||||
|
||||
public void decide(FilterInvocation invocation, Collection<ConfigAttribute> config)
|
||||
throws IOException, ServletException {
|
||||
Iterator iter = config.iterator();
|
||||
public void decide(FilterInvocation invocation, Collection<ConfigAttribute> config)
|
||||
throws IOException, ServletException {
|
||||
Iterator iter = config.iterator();
|
||||
|
||||
if (failIfCalled) {
|
||||
fail("Should not have called this channel processor: " + configAttribute);
|
||||
}
|
||||
if (failIfCalled) {
|
||||
fail("Should not have called this channel processor: " + configAttribute);
|
||||
}
|
||||
|
||||
while (iter.hasNext()) {
|
||||
ConfigAttribute attr = (ConfigAttribute) iter.next();
|
||||
while (iter.hasNext()) {
|
||||
ConfigAttribute attr = (ConfigAttribute) iter.next();
|
||||
|
||||
if (attr.getAttribute().equals(configAttribute)) {
|
||||
invocation.getHttpResponse().sendRedirect("/redirected");
|
||||
if (attr.getAttribute().equals(configAttribute)) {
|
||||
invocation.getHttpResponse().sendRedirect("/redirected");
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean supports(ConfigAttribute attribute) {
|
||||
if (attribute.getAttribute().equals(configAttribute)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
public boolean supports(ConfigAttribute attribute) {
|
||||
if (attribute.getAttribute().equals(configAttribute)) {
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,182 +32,199 @@ import org.springframework.security.access.SecurityConfig;
|
||||
import org.springframework.security.web.FilterInvocation;
|
||||
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link ChannelProcessingFilter}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class ChannelProcessingFilterTests {
|
||||
//~ Methods ========================================================================================================
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testDetectsMissingChannelDecisionManager() throws Exception {
|
||||
ChannelProcessingFilter filter = new ChannelProcessingFilter();
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testDetectsMissingChannelDecisionManager() throws Exception {
|
||||
ChannelProcessingFilter filter = new ChannelProcessingFilter();
|
||||
|
||||
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap("/path", true, "MOCK");
|
||||
filter.setSecurityMetadataSource(fids);
|
||||
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap(
|
||||
"/path", true, "MOCK");
|
||||
filter.setSecurityMetadataSource(fids);
|
||||
|
||||
filter.afterPropertiesSet();
|
||||
}
|
||||
filter.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testDetectsMissingFilterInvocationSecurityMetadataSource() throws Exception {
|
||||
ChannelProcessingFilter filter = new ChannelProcessingFilter();
|
||||
filter.setChannelDecisionManager(new MockChannelDecisionManager(false, "MOCK"));
|
||||
filter.afterPropertiesSet();
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testDetectsMissingFilterInvocationSecurityMetadataSource()
|
||||
throws Exception {
|
||||
ChannelProcessingFilter filter = new ChannelProcessingFilter();
|
||||
filter.setChannelDecisionManager(new MockChannelDecisionManager(false, "MOCK"));
|
||||
filter.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDetectsSupportedConfigAttribute() throws Exception {
|
||||
ChannelProcessingFilter filter = new ChannelProcessingFilter();
|
||||
filter.setChannelDecisionManager(new MockChannelDecisionManager(false, "SUPPORTS_MOCK_ONLY"));
|
||||
@Test
|
||||
public void testDetectsSupportedConfigAttribute() throws Exception {
|
||||
ChannelProcessingFilter filter = new ChannelProcessingFilter();
|
||||
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);
|
||||
filter.setSecurityMetadataSource(fids);
|
||||
|
||||
filter.afterPropertiesSet();
|
||||
}
|
||||
filter.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testDetectsUnsupportedConfigAttribute() throws Exception {
|
||||
ChannelProcessingFilter filter = new ChannelProcessingFilter();
|
||||
filter.setChannelDecisionManager(new MockChannelDecisionManager(false, "SUPPORTS_MOCK_ONLY"));
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testDetectsUnsupportedConfigAttribute() throws Exception {
|
||||
ChannelProcessingFilter filter = new ChannelProcessingFilter();
|
||||
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();
|
||||
}
|
||||
filter.setSecurityMetadataSource(fids);
|
||||
filter.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDoFilterWhenManagerDoesCommitResponse() throws Exception {
|
||||
ChannelProcessingFilter filter = new ChannelProcessingFilter();
|
||||
filter.setChannelDecisionManager(new MockChannelDecisionManager(true, "SOME_ATTRIBUTE"));
|
||||
@Test
|
||||
public void testDoFilterWhenManagerDoesCommitResponse() throws Exception {
|
||||
ChannelProcessingFilter filter = new ChannelProcessingFilter();
|
||||
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);
|
||||
filter.setSecurityMetadataSource(fids);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setQueryString("info=now");
|
||||
request.setServletPath("/path");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setQueryString("info=now");
|
||||
request.setServletPath("/path");
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
filter.doFilter(request, response, mock(FilterChain.class));
|
||||
}
|
||||
filter.doFilter(request, response, mock(FilterChain.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDoFilterWhenManagerDoesNotCommitResponse() throws Exception {
|
||||
ChannelProcessingFilter filter = new ChannelProcessingFilter();
|
||||
filter.setChannelDecisionManager(new MockChannelDecisionManager(false, "SOME_ATTRIBUTE"));
|
||||
@Test
|
||||
public void testDoFilterWhenManagerDoesNotCommitResponse() throws Exception {
|
||||
ChannelProcessingFilter filter = new ChannelProcessingFilter();
|
||||
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);
|
||||
filter.setSecurityMetadataSource(fids);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setQueryString("info=now");
|
||||
request.setServletPath("/path");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setQueryString("info=now");
|
||||
request.setServletPath("/path");
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
filter.doFilter(request, response, mock(FilterChain.class));
|
||||
}
|
||||
filter.doFilter(request, response, mock(FilterChain.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDoFilterWhenNullConfigAttributeReturned() throws Exception {
|
||||
ChannelProcessingFilter filter = new ChannelProcessingFilter();
|
||||
filter.setChannelDecisionManager(new MockChannelDecisionManager(false, "NOT_USED"));
|
||||
@Test
|
||||
public void testDoFilterWhenNullConfigAttributeReturned() throws Exception {
|
||||
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);
|
||||
filter.setSecurityMetadataSource(fids);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setQueryString("info=now");
|
||||
request.setServletPath("/PATH_NOT_MATCHING_CONFIG_ATTRIBUTE");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setQueryString("info=now");
|
||||
request.setServletPath("/PATH_NOT_MATCHING_CONFIG_ATTRIBUTE");
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
filter.doFilter(request, response, mock(FilterChain.class));
|
||||
}
|
||||
filter.doFilter(request, response, mock(FilterChain.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetterSetters() throws Exception {
|
||||
ChannelProcessingFilter filter = new ChannelProcessingFilter();
|
||||
filter.setChannelDecisionManager(new MockChannelDecisionManager(false, "MOCK"));
|
||||
assertTrue(filter.getChannelDecisionManager() != null);
|
||||
@Test
|
||||
public void testGetterSetters() throws Exception {
|
||||
ChannelProcessingFilter filter = new ChannelProcessingFilter();
|
||||
filter.setChannelDecisionManager(new MockChannelDecisionManager(false, "MOCK"));
|
||||
assertTrue(filter.getChannelDecisionManager() != null);
|
||||
|
||||
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap("/path", false, "MOCK");
|
||||
MockFilterInvocationDefinitionMap fids = new MockFilterInvocationDefinitionMap(
|
||||
"/path", false, "MOCK");
|
||||
|
||||
filter.setSecurityMetadataSource(fids);
|
||||
assertSame(fids, filter.getSecurityMetadataSource());
|
||||
filter.setSecurityMetadataSource(fids);
|
||||
assertSame(fids, filter.getSecurityMetadataSource());
|
||||
|
||||
filter.afterPropertiesSet();
|
||||
}
|
||||
filter.afterPropertiesSet();
|
||||
}
|
||||
|
||||
//~ Inner Classes ==================================================================================================
|
||||
// ~ Inner Classes
|
||||
// ==================================================================================================
|
||||
|
||||
private class MockChannelDecisionManager implements ChannelDecisionManager {
|
||||
private String supportAttribute;
|
||||
private boolean commitAResponse;
|
||||
private class MockChannelDecisionManager implements ChannelDecisionManager {
|
||||
private String supportAttribute;
|
||||
private boolean commitAResponse;
|
||||
|
||||
public MockChannelDecisionManager(boolean commitAResponse, String supportAttribute) {
|
||||
this.commitAResponse = commitAResponse;
|
||||
this.supportAttribute = supportAttribute;
|
||||
}
|
||||
public MockChannelDecisionManager(boolean commitAResponse, String supportAttribute) {
|
||||
this.commitAResponse = commitAResponse;
|
||||
this.supportAttribute = supportAttribute;
|
||||
}
|
||||
|
||||
public void decide(FilterInvocation invocation, Collection<ConfigAttribute> config)
|
||||
throws IOException, ServletException {
|
||||
if (commitAResponse) {
|
||||
invocation.getHttpResponse().sendRedirect("/redirected");
|
||||
}
|
||||
}
|
||||
public void decide(FilterInvocation invocation, Collection<ConfigAttribute> config)
|
||||
throws IOException, ServletException {
|
||||
if (commitAResponse) {
|
||||
invocation.getHttpResponse().sendRedirect("/redirected");
|
||||
}
|
||||
}
|
||||
|
||||
public boolean supports(ConfigAttribute attribute) {
|
||||
if (attribute.getAttribute().equals(supportAttribute)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
public boolean supports(ConfigAttribute attribute) {
|
||||
if (attribute.getAttribute().equals(supportAttribute)) {
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class MockFilterInvocationDefinitionMap implements FilterInvocationSecurityMetadataSource {
|
||||
private Collection<ConfigAttribute> toReturn;
|
||||
private String servletPath;
|
||||
private boolean provideIterator;
|
||||
private class MockFilterInvocationDefinitionMap implements
|
||||
FilterInvocationSecurityMetadataSource {
|
||||
private Collection<ConfigAttribute> toReturn;
|
||||
private String servletPath;
|
||||
private boolean provideIterator;
|
||||
|
||||
public MockFilterInvocationDefinitionMap(String servletPath, boolean provideIterator, String... toReturn) {
|
||||
this.servletPath = servletPath;
|
||||
this.toReturn = SecurityConfig.createList(toReturn);
|
||||
this.provideIterator = provideIterator;
|
||||
}
|
||||
public 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 {
|
||||
FilterInvocation fi = (FilterInvocation) object;
|
||||
public Collection<ConfigAttribute> getAttributes(Object object)
|
||||
throws IllegalArgumentException {
|
||||
FilterInvocation fi = (FilterInvocation) object;
|
||||
|
||||
if (servletPath.equals(fi.getHttpRequest().getServletPath())) {
|
||||
return toReturn;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (servletPath.equals(fi.getHttpRequest().getServletPath())) {
|
||||
return toReturn;
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public Collection<ConfigAttribute> getAllConfigAttributes() {
|
||||
if (!provideIterator) {
|
||||
return null;
|
||||
}
|
||||
public Collection<ConfigAttribute> getAllConfigAttributes() {
|
||||
if (!provideIterator) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return toReturn;
|
||||
}
|
||||
return toReturn;
|
||||
}
|
||||
|
||||
public boolean supports(Class<?> clazz) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
public boolean supports(Class<?> clazz) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,7 +27,6 @@ import org.springframework.security.access.SecurityConfig;
|
||||
import org.springframework.security.web.FilterInvocation;
|
||||
import org.springframework.security.web.access.channel.InsecureChannelProcessor;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link InsecureChannelProcessor}.
|
||||
*
|
||||
@@ -35,104 +34,113 @@ import org.springframework.security.web.access.channel.InsecureChannelProcessor;
|
||||
*/
|
||||
public class InsecureChannelProcessorTests extends TestCase {
|
||||
|
||||
public void testDecideDetectsAcceptableChannel() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setQueryString("info=true");
|
||||
request.setServerName("localhost");
|
||||
request.setContextPath("/bigapp");
|
||||
request.setServletPath("/servlet");
|
||||
request.setScheme("http");
|
||||
request.setServerPort(8080);
|
||||
public void testDecideDetectsAcceptableChannel() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setQueryString("info=true");
|
||||
request.setServerName("localhost");
|
||||
request.setContextPath("/bigapp");
|
||||
request.setServletPath("/servlet");
|
||||
request.setScheme("http");
|
||||
request.setServerPort(8080);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterInvocation fi = new FilterInvocation(request, response,
|
||||
mock(FilterChain.class));
|
||||
|
||||
InsecureChannelProcessor processor = new InsecureChannelProcessor();
|
||||
processor.decide(fi, SecurityConfig.createList("SOME_IGNORED_ATTRIBUTE", "REQUIRES_INSECURE_CHANNEL"));
|
||||
InsecureChannelProcessor processor = new InsecureChannelProcessor();
|
||||
processor.decide(fi, SecurityConfig.createList("SOME_IGNORED_ATTRIBUTE",
|
||||
"REQUIRES_INSECURE_CHANNEL"));
|
||||
|
||||
assertFalse(fi.getResponse().isCommitted());
|
||||
}
|
||||
assertFalse(fi.getResponse().isCommitted());
|
||||
}
|
||||
|
||||
public void testDecideDetectsUnacceptableChannel()
|
||||
throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setQueryString("info=true");
|
||||
request.setServerName("localhost");
|
||||
request.setContextPath("/bigapp");
|
||||
request.setServletPath("/servlet");
|
||||
request.setScheme("https");
|
||||
request.setSecure(true);
|
||||
request.setServerPort(8443);
|
||||
public void testDecideDetectsUnacceptableChannel() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setQueryString("info=true");
|
||||
request.setServerName("localhost");
|
||||
request.setContextPath("/bigapp");
|
||||
request.setServletPath("/servlet");
|
||||
request.setScheme("https");
|
||||
request.setSecure(true);
|
||||
request.setServerPort(8443);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterInvocation fi = new FilterInvocation(request, response,
|
||||
mock(FilterChain.class));
|
||||
|
||||
InsecureChannelProcessor processor = new InsecureChannelProcessor();
|
||||
processor.decide(fi, SecurityConfig.createList(new String[]{"SOME_IGNORED_ATTRIBUTE", "REQUIRES_INSECURE_CHANNEL"}));
|
||||
InsecureChannelProcessor processor = new InsecureChannelProcessor();
|
||||
processor.decide(
|
||||
fi,
|
||||
SecurityConfig.createList(new String[] { "SOME_IGNORED_ATTRIBUTE",
|
||||
"REQUIRES_INSECURE_CHANNEL" }));
|
||||
|
||||
assertTrue(fi.getResponse().isCommitted());
|
||||
}
|
||||
assertTrue(fi.getResponse().isCommitted());
|
||||
}
|
||||
|
||||
public void testDecideRejectsNulls() throws Exception {
|
||||
InsecureChannelProcessor processor = new InsecureChannelProcessor();
|
||||
processor.afterPropertiesSet();
|
||||
public void testDecideRejectsNulls() throws Exception {
|
||||
InsecureChannelProcessor processor = new InsecureChannelProcessor();
|
||||
processor.afterPropertiesSet();
|
||||
|
||||
try {
|
||||
processor.decide(null, null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
try {
|
||||
processor.decide(null, null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testGettersSetters() {
|
||||
InsecureChannelProcessor processor = new InsecureChannelProcessor();
|
||||
assertEquals("REQUIRES_INSECURE_CHANNEL", processor.getInsecureKeyword());
|
||||
processor.setInsecureKeyword("X");
|
||||
assertEquals("X", processor.getInsecureKeyword());
|
||||
public void testGettersSetters() {
|
||||
InsecureChannelProcessor processor = new InsecureChannelProcessor();
|
||||
assertEquals("REQUIRES_INSECURE_CHANNEL", processor.getInsecureKeyword());
|
||||
processor.setInsecureKeyword("X");
|
||||
assertEquals("X", processor.getInsecureKeyword());
|
||||
|
||||
assertTrue(processor.getEntryPoint() != null);
|
||||
processor.setEntryPoint(null);
|
||||
assertTrue(processor.getEntryPoint() == null);
|
||||
}
|
||||
assertTrue(processor.getEntryPoint() != null);
|
||||
processor.setEntryPoint(null);
|
||||
assertTrue(processor.getEntryPoint() == null);
|
||||
}
|
||||
|
||||
public void testMissingEntryPoint() throws Exception {
|
||||
InsecureChannelProcessor processor = new InsecureChannelProcessor();
|
||||
processor.setEntryPoint(null);
|
||||
public void testMissingEntryPoint() throws Exception {
|
||||
InsecureChannelProcessor processor = new InsecureChannelProcessor();
|
||||
processor.setEntryPoint(null);
|
||||
|
||||
try {
|
||||
processor.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("entryPoint required", expected.getMessage());
|
||||
}
|
||||
}
|
||||
try {
|
||||
processor.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertEquals("entryPoint required", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testMissingSecureChannelKeyword() throws Exception {
|
||||
InsecureChannelProcessor processor = new InsecureChannelProcessor();
|
||||
processor.setInsecureKeyword(null);
|
||||
public void testMissingSecureChannelKeyword() throws Exception {
|
||||
InsecureChannelProcessor processor = new InsecureChannelProcessor();
|
||||
processor.setInsecureKeyword(null);
|
||||
|
||||
try {
|
||||
processor.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("insecureKeyword required", expected.getMessage());
|
||||
}
|
||||
try {
|
||||
processor.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertEquals("insecureKeyword required", expected.getMessage());
|
||||
}
|
||||
|
||||
processor.setInsecureKeyword("");
|
||||
processor.setInsecureKeyword("");
|
||||
|
||||
try {
|
||||
processor.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("insecureKeyword required", expected.getMessage());
|
||||
}
|
||||
}
|
||||
try {
|
||||
processor.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertEquals("insecureKeyword required", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testSupports() {
|
||||
InsecureChannelProcessor processor = new InsecureChannelProcessor();
|
||||
assertTrue(processor.supports(new SecurityConfig("REQUIRES_INSECURE_CHANNEL")));
|
||||
assertFalse(processor.supports(null));
|
||||
assertFalse(processor.supports(new SecurityConfig("NOT_SUPPORTED")));
|
||||
}
|
||||
public void testSupports() {
|
||||
InsecureChannelProcessor processor = new InsecureChannelProcessor();
|
||||
assertTrue(processor.supports(new SecurityConfig("REQUIRES_INSECURE_CHANNEL")));
|
||||
assertFalse(processor.supports(null));
|
||||
assertFalse(processor.supports(new SecurityConfig("NOT_SUPPORTED")));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,117 +33,126 @@ import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link RetryWithHttpEntryPoint}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class RetryWithHttpEntryPointTests extends TestCase {
|
||||
//~ Methods ========================================================================================================
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
public void testDetectsMissingPortMapper() throws Exception {
|
||||
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
|
||||
public void testDetectsMissingPortMapper() throws Exception {
|
||||
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
|
||||
|
||||
try {
|
||||
ep.setPortMapper(null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
}
|
||||
}
|
||||
try {
|
||||
ep.setPortMapper(null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
}
|
||||
|
||||
public void testDetectsMissingPortResolver() throws Exception {
|
||||
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
|
||||
public void testDetectsMissingPortResolver() throws Exception {
|
||||
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
|
||||
|
||||
try {
|
||||
ep.setPortResolver(null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
}
|
||||
}
|
||||
try {
|
||||
ep.setPortResolver(null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
}
|
||||
|
||||
public void testGettersSetters() {
|
||||
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
|
||||
PortMapper portMapper = mock(PortMapper.class);
|
||||
PortResolver portResolver = mock(PortResolver.class);
|
||||
RedirectStrategy redirector = mock(RedirectStrategy.class);
|
||||
ep.setPortMapper(portMapper);
|
||||
ep.setPortResolver(portResolver);
|
||||
ep.setRedirectStrategy(redirector);
|
||||
assertSame(portMapper, ep.getPortMapper());
|
||||
assertSame(portResolver, ep.getPortResolver());
|
||||
assertSame(redirector, ep.getRedirectStrategy());
|
||||
}
|
||||
public void testGettersSetters() {
|
||||
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
|
||||
PortMapper portMapper = mock(PortMapper.class);
|
||||
PortResolver portResolver = mock(PortResolver.class);
|
||||
RedirectStrategy redirector = mock(RedirectStrategy.class);
|
||||
ep.setPortMapper(portMapper);
|
||||
ep.setPortResolver(portResolver);
|
||||
ep.setRedirectStrategy(redirector);
|
||||
assertSame(portMapper, ep.getPortMapper());
|
||||
assertSame(portResolver, ep.getPortResolver());
|
||||
assertSame(redirector, ep.getRedirectStrategy());
|
||||
}
|
||||
|
||||
public void testNormalOperation() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello/pathInfo.html");
|
||||
request.setQueryString("open=true");
|
||||
request.setScheme("https");
|
||||
request.setServerName("www.example.com");
|
||||
request.setServerPort(443);
|
||||
public void testNormalOperation() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET",
|
||||
"/bigWebApp/hello/pathInfo.html");
|
||||
request.setQueryString("open=true");
|
||||
request.setScheme("https");
|
||||
request.setServerName("www.example.com");
|
||||
request.setServerPort(443);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(80, 443));
|
||||
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(80, 443));
|
||||
|
||||
ep.commence(request, response);
|
||||
assertEquals("http://www.example.com/bigWebApp/hello/pathInfo.html?open=true", response.getRedirectedUrl());
|
||||
}
|
||||
ep.commence(request, response);
|
||||
assertEquals("http://www.example.com/bigWebApp/hello/pathInfo.html?open=true",
|
||||
response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
public void testNormalOperationWithNullQueryString() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello");
|
||||
request.setScheme("https");
|
||||
request.setServerName("www.example.com");
|
||||
request.setServerPort(443);
|
||||
public void testNormalOperationWithNullQueryString() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET",
|
||||
"/bigWebApp/hello");
|
||||
request.setScheme("https");
|
||||
request.setServerName("www.example.com");
|
||||
request.setServerPort(443);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(80, 443));
|
||||
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(80, 443));
|
||||
|
||||
ep.commence(request, response);
|
||||
assertEquals("http://www.example.com/bigWebApp/hello", response.getRedirectedUrl());
|
||||
}
|
||||
ep.commence(request, response);
|
||||
assertEquals("http://www.example.com/bigWebApp/hello",
|
||||
response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
public void testOperationWhenTargetPortIsUnknown() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp");
|
||||
request.setQueryString("open=true");
|
||||
request.setScheme("https");
|
||||
request.setServerName("www.example.com");
|
||||
request.setServerPort(8768);
|
||||
public void testOperationWhenTargetPortIsUnknown() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp");
|
||||
request.setQueryString("open=true");
|
||||
request.setScheme("https");
|
||||
request.setServerName("www.example.com");
|
||||
request.setServerPort(8768);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(8768, 1234));
|
||||
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(8768, 1234));
|
||||
|
||||
ep.commence(request, response);
|
||||
assertEquals("/bigWebApp?open=true", response.getRedirectedUrl());
|
||||
}
|
||||
ep.commence(request, response);
|
||||
assertEquals("/bigWebApp?open=true", response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
public void testOperationWithNonStandardPort() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello/pathInfo.html");
|
||||
request.setQueryString("open=true");
|
||||
request.setScheme("https");
|
||||
request.setServerName("www.example.com");
|
||||
request.setServerPort(9999);
|
||||
public void testOperationWithNonStandardPort() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET",
|
||||
"/bigWebApp/hello/pathInfo.html");
|
||||
request.setQueryString("open=true");
|
||||
request.setScheme("https");
|
||||
request.setServerName("www.example.com");
|
||||
request.setServerPort(9999);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
Map<String, String> map = new HashMap<String, String>();
|
||||
map.put("8888", "9999");
|
||||
portMapper.setPortMappings(map);
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
Map<String, String> map = new HashMap<String, String>();
|
||||
map.put("8888", "9999");
|
||||
portMapper.setPortMappings(map);
|
||||
|
||||
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
|
||||
ep.setPortResolver(new MockPortResolver(8888, 9999));
|
||||
ep.setPortMapper(portMapper);
|
||||
RetryWithHttpEntryPoint ep = new RetryWithHttpEntryPoint();
|
||||
ep.setPortResolver(new MockPortResolver(8888, 9999));
|
||||
ep.setPortMapper(portMapper);
|
||||
|
||||
ep.commence(request, response);
|
||||
assertEquals("http://www.example.com:8888/bigWebApp/hello/pathInfo.html?open=true", response.getRedirectedUrl());
|
||||
}
|
||||
ep.commence(request, response);
|
||||
assertEquals(
|
||||
"http://www.example.com:8888/bigWebApp/hello/pathInfo.html?open=true",
|
||||
response.getRedirectedUrl());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,112 +28,121 @@ import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link RetryWithHttpsEntryPoint}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class RetryWithHttpsEntryPointTests extends TestCase {
|
||||
//~ Methods ========================================================================================================
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
public void testDetectsMissingPortMapper() throws Exception {
|
||||
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
|
||||
public void testDetectsMissingPortMapper() throws Exception {
|
||||
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
|
||||
|
||||
try {
|
||||
ep.setPortMapper(null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
}
|
||||
}
|
||||
try {
|
||||
ep.setPortMapper(null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
}
|
||||
|
||||
public void testDetectsMissingPortResolver() throws Exception {
|
||||
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
|
||||
public void testDetectsMissingPortResolver() throws Exception {
|
||||
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
|
||||
|
||||
try {
|
||||
ep.setPortResolver(null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
}
|
||||
}
|
||||
try {
|
||||
ep.setPortResolver(null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
}
|
||||
|
||||
public void testGettersSetters() {
|
||||
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(8080, 8443));
|
||||
assertTrue(ep.getPortMapper() != null);
|
||||
assertTrue(ep.getPortResolver() != null);
|
||||
}
|
||||
public void testGettersSetters() {
|
||||
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(8080, 8443));
|
||||
assertTrue(ep.getPortMapper() != null);
|
||||
assertTrue(ep.getPortResolver() != null);
|
||||
}
|
||||
|
||||
public void testNormalOperation() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello/pathInfo.html");
|
||||
request.setQueryString("open=true");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setServerPort(80);
|
||||
public void testNormalOperation() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET",
|
||||
"/bigWebApp/hello/pathInfo.html");
|
||||
request.setQueryString("open=true");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setServerPort(80);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(80, 443));
|
||||
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(80, 443));
|
||||
|
||||
ep.commence(request, response);
|
||||
assertEquals("https://www.example.com/bigWebApp/hello/pathInfo.html?open=true", response.getRedirectedUrl());
|
||||
}
|
||||
ep.commence(request, response);
|
||||
assertEquals("https://www.example.com/bigWebApp/hello/pathInfo.html?open=true",
|
||||
response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
public void testNormalOperationWithNullQueryString() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setServerPort(80);
|
||||
public void testNormalOperationWithNullQueryString() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET",
|
||||
"/bigWebApp/hello");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setServerPort(80);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(80, 443));
|
||||
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(80, 443));
|
||||
|
||||
ep.commence(request, response);
|
||||
assertEquals("https://www.example.com/bigWebApp/hello", response.getRedirectedUrl());
|
||||
}
|
||||
ep.commence(request, response);
|
||||
assertEquals("https://www.example.com/bigWebApp/hello",
|
||||
response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
public void testOperationWhenTargetPortIsUnknown() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp");
|
||||
request.setQueryString("open=true");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setServerPort(8768);
|
||||
public void testOperationWhenTargetPortIsUnknown() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp");
|
||||
request.setQueryString("open=true");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setServerPort(8768);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(8768, 1234));
|
||||
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(8768, 1234));
|
||||
|
||||
ep.commence(request, response);
|
||||
assertEquals("/bigWebApp?open=true", response.getRedirectedUrl());
|
||||
}
|
||||
ep.commence(request, response);
|
||||
assertEquals("/bigWebApp?open=true", response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
public void testOperationWithNonStandardPort() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/bigWebApp/hello/pathInfo.html");
|
||||
request.setQueryString("open=true");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setServerPort(8888);
|
||||
public void testOperationWithNonStandardPort() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET",
|
||||
"/bigWebApp/hello/pathInfo.html");
|
||||
request.setQueryString("open=true");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setServerPort(8888);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
Map<String, String> map = new HashMap<String, String>();
|
||||
map.put("8888", "9999");
|
||||
portMapper.setPortMappings(map);
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
Map<String, String> map = new HashMap<String, String>();
|
||||
map.put("8888", "9999");
|
||||
portMapper.setPortMappings(map);
|
||||
|
||||
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
|
||||
ep.setPortResolver(new MockPortResolver(8888, 9999));
|
||||
ep.setPortMapper(portMapper);
|
||||
RetryWithHttpsEntryPoint ep = new RetryWithHttpsEntryPoint();
|
||||
ep.setPortResolver(new MockPortResolver(8888, 9999));
|
||||
ep.setPortMapper(portMapper);
|
||||
|
||||
ep.commence(request, response);
|
||||
assertEquals("https://www.example.com:9999/bigWebApp/hello/pathInfo.html?open=true", response.getRedirectedUrl());
|
||||
}
|
||||
ep.commence(request, response);
|
||||
assertEquals(
|
||||
"https://www.example.com:9999/bigWebApp/hello/pathInfo.html?open=true",
|
||||
response.getRedirectedUrl());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,112 +27,122 @@ import org.springframework.security.access.SecurityConfig;
|
||||
import org.springframework.security.web.FilterInvocation;
|
||||
import org.springframework.security.web.access.channel.SecureChannelProcessor;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link SecureChannelProcessor}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class SecureChannelProcessorTests extends TestCase {
|
||||
//~ Methods ========================================================================================================
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
public void testDecideDetectsAcceptableChannel() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setQueryString("info=true");
|
||||
request.setServerName("localhost");
|
||||
request.setContextPath("/bigapp");
|
||||
request.setServletPath("/servlet");
|
||||
request.setScheme("https");
|
||||
request.setSecure(true);
|
||||
request.setServerPort(8443);
|
||||
public void testDecideDetectsAcceptableChannel() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setQueryString("info=true");
|
||||
request.setServerName("localhost");
|
||||
request.setContextPath("/bigapp");
|
||||
request.setServletPath("/servlet");
|
||||
request.setScheme("https");
|
||||
request.setSecure(true);
|
||||
request.setServerPort(8443);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterInvocation fi = new FilterInvocation(request, response,
|
||||
mock(FilterChain.class));
|
||||
|
||||
SecureChannelProcessor processor = new SecureChannelProcessor();
|
||||
processor.decide(fi, SecurityConfig.createList("SOME_IGNORED_ATTRIBUTE", "REQUIRES_SECURE_CHANNEL"));
|
||||
SecureChannelProcessor processor = new SecureChannelProcessor();
|
||||
processor.decide(fi, SecurityConfig.createList("SOME_IGNORED_ATTRIBUTE",
|
||||
"REQUIRES_SECURE_CHANNEL"));
|
||||
|
||||
assertFalse(fi.getResponse().isCommitted());
|
||||
}
|
||||
assertFalse(fi.getResponse().isCommitted());
|
||||
}
|
||||
|
||||
public void testDecideDetectsUnacceptableChannel() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setQueryString("info=true");
|
||||
request.setServerName("localhost");
|
||||
request.setContextPath("/bigapp");
|
||||
request.setServletPath("/servlet");
|
||||
request.setScheme("http");
|
||||
request.setServerPort(8080);
|
||||
public void testDecideDetectsUnacceptableChannel() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setQueryString("info=true");
|
||||
request.setServerName("localhost");
|
||||
request.setContextPath("/bigapp");
|
||||
request.setServletPath("/servlet");
|
||||
request.setScheme("http");
|
||||
request.setServerPort(8080);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterInvocation fi = new FilterInvocation(request, response,
|
||||
mock(FilterChain.class));
|
||||
|
||||
SecureChannelProcessor processor = new SecureChannelProcessor();
|
||||
processor.decide(fi, SecurityConfig.createList(new String[]{"SOME_IGNORED_ATTRIBUTE", "REQUIRES_SECURE_CHANNEL"}));
|
||||
SecureChannelProcessor processor = new SecureChannelProcessor();
|
||||
processor.decide(
|
||||
fi,
|
||||
SecurityConfig.createList(new String[] { "SOME_IGNORED_ATTRIBUTE",
|
||||
"REQUIRES_SECURE_CHANNEL" }));
|
||||
|
||||
assertTrue(fi.getResponse().isCommitted());
|
||||
}
|
||||
assertTrue(fi.getResponse().isCommitted());
|
||||
}
|
||||
|
||||
public void testDecideRejectsNulls() throws Exception {
|
||||
SecureChannelProcessor processor = new SecureChannelProcessor();
|
||||
processor.afterPropertiesSet();
|
||||
public void testDecideRejectsNulls() throws Exception {
|
||||
SecureChannelProcessor processor = new SecureChannelProcessor();
|
||||
processor.afterPropertiesSet();
|
||||
|
||||
try {
|
||||
processor.decide(null, null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
try {
|
||||
processor.decide(null, null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testGettersSetters() {
|
||||
SecureChannelProcessor processor = new SecureChannelProcessor();
|
||||
assertEquals("REQUIRES_SECURE_CHANNEL", processor.getSecureKeyword());
|
||||
processor.setSecureKeyword("X");
|
||||
assertEquals("X", processor.getSecureKeyword());
|
||||
public void testGettersSetters() {
|
||||
SecureChannelProcessor processor = new SecureChannelProcessor();
|
||||
assertEquals("REQUIRES_SECURE_CHANNEL", processor.getSecureKeyword());
|
||||
processor.setSecureKeyword("X");
|
||||
assertEquals("X", processor.getSecureKeyword());
|
||||
|
||||
assertTrue(processor.getEntryPoint() != null);
|
||||
processor.setEntryPoint(null);
|
||||
assertTrue(processor.getEntryPoint() == null);
|
||||
}
|
||||
assertTrue(processor.getEntryPoint() != null);
|
||||
processor.setEntryPoint(null);
|
||||
assertTrue(processor.getEntryPoint() == null);
|
||||
}
|
||||
|
||||
public void testMissingEntryPoint() throws Exception {
|
||||
SecureChannelProcessor processor = new SecureChannelProcessor();
|
||||
processor.setEntryPoint(null);
|
||||
public void testMissingEntryPoint() throws Exception {
|
||||
SecureChannelProcessor processor = new SecureChannelProcessor();
|
||||
processor.setEntryPoint(null);
|
||||
|
||||
try {
|
||||
processor.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("entryPoint required", expected.getMessage());
|
||||
}
|
||||
}
|
||||
try {
|
||||
processor.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertEquals("entryPoint required", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testMissingSecureChannelKeyword() throws Exception {
|
||||
SecureChannelProcessor processor = new SecureChannelProcessor();
|
||||
processor.setSecureKeyword(null);
|
||||
public void testMissingSecureChannelKeyword() throws Exception {
|
||||
SecureChannelProcessor processor = new SecureChannelProcessor();
|
||||
processor.setSecureKeyword(null);
|
||||
|
||||
try {
|
||||
processor.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("secureKeyword required", expected.getMessage());
|
||||
}
|
||||
try {
|
||||
processor.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertEquals("secureKeyword required", expected.getMessage());
|
||||
}
|
||||
|
||||
processor.setSecureKeyword("");
|
||||
processor.setSecureKeyword("");
|
||||
|
||||
try {
|
||||
processor.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("secureKeyword required", expected.getMessage());
|
||||
}
|
||||
}
|
||||
try {
|
||||
processor.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertEquals("secureKeyword required", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testSupports() {
|
||||
SecureChannelProcessor processor = new SecureChannelProcessor();
|
||||
assertTrue(processor.supports(new SecurityConfig("REQUIRES_SECURE_CHANNEL")));
|
||||
assertFalse(processor.supports(null));
|
||||
assertFalse(processor.supports(new SecurityConfig("NOT_SUPPORTED")));
|
||||
}
|
||||
public void testSupports() {
|
||||
SecureChannelProcessor processor = new SecureChannelProcessor();
|
||||
assertTrue(processor.supports(new SecurityConfig("REQUIRES_SECURE_CHANNEL")));
|
||||
assertFalse(processor.supports(null));
|
||||
assertFalse(processor.supports(new SecurityConfig("NOT_SUPPORTED")));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,55 +39,59 @@ import org.springframework.security.web.FilterInvocation;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class DefaultWebSecurityExpressionHandlerTests {
|
||||
@Mock
|
||||
private AuthenticationTrustResolver trustResolver;
|
||||
@Mock
|
||||
private AuthenticationTrustResolver trustResolver;
|
||||
|
||||
@Mock
|
||||
private Authentication authentication;
|
||||
@Mock
|
||||
private Authentication authentication;
|
||||
|
||||
@Mock
|
||||
private FilterInvocation invocation;
|
||||
@Mock
|
||||
private FilterInvocation invocation;
|
||||
|
||||
private DefaultWebSecurityExpressionHandler handler;
|
||||
private DefaultWebSecurityExpressionHandler handler;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
handler = new DefaultWebSecurityExpressionHandler();
|
||||
}
|
||||
@Before
|
||||
public void setup() {
|
||||
handler = new DefaultWebSecurityExpressionHandler();
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
@After
|
||||
public void cleanup() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void expressionPropertiesAreResolvedAgainsAppContextBeans() throws Exception {
|
||||
StaticApplicationContext appContext = new StaticApplicationContext();
|
||||
RootBeanDefinition bean = new RootBeanDefinition(SecurityConfig.class);
|
||||
bean.getConstructorArgumentValues().addGenericArgumentValue("ROLE_A");
|
||||
appContext.registerBeanDefinition("role", bean);
|
||||
handler.setApplicationContext(appContext);
|
||||
@Test
|
||||
public void expressionPropertiesAreResolvedAgainsAppContextBeans() throws Exception {
|
||||
StaticApplicationContext appContext = new StaticApplicationContext();
|
||||
RootBeanDefinition bean = new RootBeanDefinition(SecurityConfig.class);
|
||||
bean.getConstructorArgumentValues().addGenericArgumentValue("ROLE_A");
|
||||
appContext.registerBeanDefinition("role", bean);
|
||||
handler.setApplicationContext(appContext);
|
||||
|
||||
EvaluationContext ctx = handler.createEvaluationContext(mock(Authentication.class), mock(FilterInvocation.class));
|
||||
ExpressionParser parser = handler.getExpressionParser();
|
||||
assertTrue(parser.parseExpression("@role.getAttribute() == 'ROLE_A'").getValue(ctx, Boolean.class));
|
||||
assertTrue(parser.parseExpression("@role.attribute == 'ROLE_A'").getValue(ctx, Boolean.class));
|
||||
}
|
||||
EvaluationContext ctx = handler.createEvaluationContext(
|
||||
mock(Authentication.class), mock(FilterInvocation.class));
|
||||
ExpressionParser parser = handler.getExpressionParser();
|
||||
assertTrue(parser.parseExpression("@role.getAttribute() == 'ROLE_A'").getValue(
|
||||
ctx, Boolean.class));
|
||||
assertTrue(parser.parseExpression("@role.attribute == 'ROLE_A'").getValue(ctx,
|
||||
Boolean.class));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setTrustResolverNull() {
|
||||
handler.setTrustResolver(null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setTrustResolverNull() {
|
||||
handler.setTrustResolver(null);
|
||||
}
|
||||
@Test
|
||||
public void createEvaluationContextCustomTrustResolver() {
|
||||
handler.setTrustResolver(trustResolver);
|
||||
|
||||
@Test
|
||||
public void createEvaluationContextCustomTrustResolver() {
|
||||
handler.setTrustResolver(trustResolver);
|
||||
Expression expression = handler.getExpressionParser()
|
||||
.parseExpression("anonymous");
|
||||
EvaluationContext context = handler.createEvaluationContext(authentication,
|
||||
invocation);
|
||||
assertThat(expression.getValue(context, Boolean.class)).isFalse();
|
||||
|
||||
Expression expression = handler.getExpressionParser().parseExpression("anonymous");
|
||||
EvaluationContext context = handler.createEvaluationContext(authentication, invocation);
|
||||
assertThat(expression.getValue(context, Boolean.class)).isFalse();
|
||||
|
||||
verify(trustResolver).isAnonymous(authentication);
|
||||
}
|
||||
verify(trustResolver).isAnonymous(authentication);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package org.springframework.security.web.access.expression;
|
||||
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
@@ -18,27 +17,30 @@ import java.util.LinkedHashMap;
|
||||
*/
|
||||
public class ExpressionBasedFilterInvocationSecurityMetadataSourceTests {
|
||||
|
||||
@Test
|
||||
public void expectedAttributeIsReturned() {
|
||||
final String expression = "hasRole('X')";
|
||||
LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();
|
||||
requestMap.put(AnyRequestMatcher.INSTANCE, SecurityConfig.createList(expression));
|
||||
ExpressionBasedFilterInvocationSecurityMetadataSource mds =
|
||||
new ExpressionBasedFilterInvocationSecurityMetadataSource(requestMap, new DefaultWebSecurityExpressionHandler());
|
||||
assertEquals(1, mds.getAllConfigAttributes().size());
|
||||
Collection<ConfigAttribute> attrs = mds.getAttributes(new FilterInvocation("/path", "GET"));
|
||||
assertEquals(1, attrs.size());
|
||||
WebExpressionConfigAttribute attribute = (WebExpressionConfigAttribute) attrs.toArray()[0];
|
||||
assertNull(attribute.getAttribute());
|
||||
assertEquals(expression, attribute.getAuthorizeExpression().getExpressionString());
|
||||
assertEquals(expression, attribute.toString());
|
||||
}
|
||||
@Test
|
||||
public void expectedAttributeIsReturned() {
|
||||
final String expression = "hasRole('X')";
|
||||
LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();
|
||||
requestMap.put(AnyRequestMatcher.INSTANCE, SecurityConfig.createList(expression));
|
||||
ExpressionBasedFilterInvocationSecurityMetadataSource mds = new ExpressionBasedFilterInvocationSecurityMetadataSource(
|
||||
requestMap, new DefaultWebSecurityExpressionHandler());
|
||||
assertEquals(1, mds.getAllConfigAttributes().size());
|
||||
Collection<ConfigAttribute> attrs = mds.getAttributes(new FilterInvocation(
|
||||
"/path", "GET"));
|
||||
assertEquals(1, attrs.size());
|
||||
WebExpressionConfigAttribute attribute = (WebExpressionConfigAttribute) attrs
|
||||
.toArray()[0];
|
||||
assertNull(attribute.getAttribute());
|
||||
assertEquals(expression, attribute.getAuthorizeExpression().getExpressionString());
|
||||
assertEquals(expression, attribute.toString());
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void invalidExpressionIsRejected() throws Exception {
|
||||
LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();
|
||||
requestMap.put(AnyRequestMatcher.INSTANCE, SecurityConfig.createList("hasRole('X'"));
|
||||
ExpressionBasedFilterInvocationSecurityMetadataSource mds =
|
||||
new ExpressionBasedFilterInvocationSecurityMetadataSource(requestMap, new DefaultWebSecurityExpressionHandler());
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void invalidExpressionIsRejected() throws Exception {
|
||||
LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();
|
||||
requestMap.put(AnyRequestMatcher.INSTANCE,
|
||||
SecurityConfig.createList("hasRole('X'"));
|
||||
ExpressionBasedFilterInvocationSecurityMetadataSource mds = new ExpressionBasedFilterInvocationSecurityMetadataSource(
|
||||
requestMap, new DefaultWebSecurityExpressionHandler());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,70 +27,74 @@ import javax.servlet.ServletResponse;
|
||||
/**
|
||||
* @author Luke Taylor
|
||||
*/
|
||||
@SuppressWarnings({"unchecked"})
|
||||
@SuppressWarnings({ "unchecked" })
|
||||
public class WebExpressionVoterTests {
|
||||
private Authentication user = new TestingAuthenticationToken("user","pass", "X");
|
||||
private Authentication user = new TestingAuthenticationToken("user", "pass", "X");
|
||||
|
||||
@Test
|
||||
public void supportsWebConfigAttributeAndFilterInvocation() throws Exception {
|
||||
WebExpressionVoter voter = new WebExpressionVoter();
|
||||
assertTrue(voter.supports(new WebExpressionConfigAttribute(mock(Expression.class))));
|
||||
assertTrue(voter.supports(FilterInvocation.class));
|
||||
assertFalse(voter.supports(MethodInvocation.class));
|
||||
@Test
|
||||
public void supportsWebConfigAttributeAndFilterInvocation() throws Exception {
|
||||
WebExpressionVoter voter = new WebExpressionVoter();
|
||||
assertTrue(voter
|
||||
.supports(new WebExpressionConfigAttribute(mock(Expression.class))));
|
||||
assertTrue(voter.supports(FilterInvocation.class));
|
||||
assertFalse(voter.supports(MethodInvocation.class));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void abstainsIfNoAttributeFound() {
|
||||
WebExpressionVoter voter = new WebExpressionVoter();
|
||||
assertEquals(AccessDecisionVoter.ACCESS_ABSTAIN,
|
||||
voter.vote(user, new FilterInvocation("/path", "GET"), SecurityConfig.createList("A", "B", "C")));
|
||||
}
|
||||
@Test
|
||||
public void abstainsIfNoAttributeFound() {
|
||||
WebExpressionVoter voter = new WebExpressionVoter();
|
||||
assertEquals(
|
||||
AccessDecisionVoter.ACCESS_ABSTAIN,
|
||||
voter.vote(user, new FilterInvocation("/path", "GET"),
|
||||
SecurityConfig.createList("A", "B", "C")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void grantsAccessIfExpressionIsTrueDeniesIfFalse() {
|
||||
WebExpressionVoter voter = new WebExpressionVoter();
|
||||
Expression ex = mock(Expression.class);
|
||||
WebExpressionConfigAttribute weca = new WebExpressionConfigAttribute(ex);
|
||||
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);
|
||||
ArrayList attributes = new ArrayList();
|
||||
attributes.addAll(SecurityConfig.createList("A","B","C"));
|
||||
attributes.add(weca);
|
||||
@Test
|
||||
public void grantsAccessIfExpressionIsTrueDeniesIfFalse() {
|
||||
WebExpressionVoter voter = new WebExpressionVoter();
|
||||
Expression ex = mock(Expression.class);
|
||||
WebExpressionConfigAttribute weca = new WebExpressionConfigAttribute(ex);
|
||||
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);
|
||||
ArrayList attributes = new ArrayList();
|
||||
attributes.addAll(SecurityConfig.createList("A", "B", "C"));
|
||||
attributes.add(weca);
|
||||
|
||||
assertEquals(AccessDecisionVoter.ACCESS_GRANTED, voter.vote(user, fi, attributes));
|
||||
assertEquals(AccessDecisionVoter.ACCESS_GRANTED, voter.vote(user, fi, attributes));
|
||||
|
||||
// Second time false
|
||||
assertEquals(AccessDecisionVoter.ACCESS_DENIED, voter.vote(user, fi, attributes));
|
||||
}
|
||||
// Second time false
|
||||
assertEquals(AccessDecisionVoter.ACCESS_DENIED, voter.vote(user, fi, attributes));
|
||||
}
|
||||
|
||||
// SEC-2507
|
||||
@Test
|
||||
public void supportFilterInvocationSubClass() {
|
||||
WebExpressionVoter voter = new WebExpressionVoter();
|
||||
assertThat(voter.supports(FilterInvocationChild.class)).isTrue();
|
||||
}
|
||||
// SEC-2507
|
||||
@Test
|
||||
public void supportFilterInvocationSubClass() {
|
||||
WebExpressionVoter voter = new WebExpressionVoter();
|
||||
assertThat(voter.supports(FilterInvocationChild.class)).isTrue();
|
||||
}
|
||||
|
||||
private static class FilterInvocationChild extends FilterInvocation {
|
||||
public FilterInvocationChild(ServletRequest request,
|
||||
ServletResponse response, FilterChain chain) {
|
||||
super(request, response, chain);
|
||||
}
|
||||
}
|
||||
private static class FilterInvocationChild extends FilterInvocation {
|
||||
public FilterInvocationChild(ServletRequest request, ServletResponse response,
|
||||
FilterChain chain) {
|
||||
super(request, response, chain);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void supportFilterInvocation() {
|
||||
WebExpressionVoter voter = new WebExpressionVoter();
|
||||
assertThat(voter.supports(FilterInvocation.class)).isTrue();
|
||||
}
|
||||
@Test
|
||||
public void supportFilterInvocation() {
|
||||
WebExpressionVoter voter = new WebExpressionVoter();
|
||||
assertThat(voter.supports(FilterInvocation.class)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void supportsObjectIsFalse() {
|
||||
WebExpressionVoter voter = new WebExpressionVoter();
|
||||
assertThat(voter.supports(Object.class)).isFalse();
|
||||
}
|
||||
@Test
|
||||
public void supportsObjectIsFalse() {
|
||||
WebExpressionVoter voter = new WebExpressionVoter();
|
||||
assertThat(voter.supports(Object.class)).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,52 +20,54 @@ import org.springframework.security.web.access.expression.WebSecurityExpressionR
|
||||
*/
|
||||
public class WebSecurityExpressionRootTests {
|
||||
|
||||
@Test
|
||||
public void ipAddressMatchesForEqualIpAddresses() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
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)));
|
||||
@Test
|
||||
public void ipAddressMatchesForEqualIpAddresses() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
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)));
|
||||
|
||||
assertTrue(root.hasIpAddress("192.168.1.1"));
|
||||
assertTrue(root.hasIpAddress("192.168.1.1"));
|
||||
|
||||
// IPv6 Address
|
||||
request.setRemoteAddr("fa:db8:85a3::8a2e:370:7334");
|
||||
assertTrue(root.hasIpAddress("fa:db8:85a3::8a2e:370:7334"));
|
||||
}
|
||||
// IPv6 Address
|
||||
request.setRemoteAddr("fa:db8:85a3::8a2e:370:7334");
|
||||
assertTrue(root.hasIpAddress("fa:db8:85a3::8a2e:370:7334"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addressesInIpRangeMatch() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/test");
|
||||
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);
|
||||
assertTrue(root.hasIpAddress("192.168.1.0/24"));
|
||||
}
|
||||
@Test
|
||||
public void addressesInIpRangeMatch() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/test");
|
||||
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);
|
||||
assertTrue(root.hasIpAddress("192.168.1.0/24"));
|
||||
}
|
||||
|
||||
request.setRemoteAddr("192.168.1.127");
|
||||
// 25 = FF FF FF 80
|
||||
assertTrue(root.hasIpAddress("192.168.1.0/25"));
|
||||
// encroach on the mask
|
||||
request.setRemoteAddr("192.168.1.128");
|
||||
assertFalse(root.hasIpAddress("192.168.1.0/25"));
|
||||
request.setRemoteAddr("192.168.1.255");
|
||||
assertTrue(root.hasIpAddress("192.168.1.128/25"));
|
||||
assertTrue(root.hasIpAddress("192.168.1.192/26"));
|
||||
assertTrue(root.hasIpAddress("192.168.1.224/27"));
|
||||
assertTrue(root.hasIpAddress("192.168.1.240/27"));
|
||||
assertTrue(root.hasIpAddress("192.168.1.255/32"));
|
||||
request.setRemoteAddr("192.168.1.127");
|
||||
// 25 = FF FF FF 80
|
||||
assertTrue(root.hasIpAddress("192.168.1.0/25"));
|
||||
// encroach on the mask
|
||||
request.setRemoteAddr("192.168.1.128");
|
||||
assertFalse(root.hasIpAddress("192.168.1.0/25"));
|
||||
request.setRemoteAddr("192.168.1.255");
|
||||
assertTrue(root.hasIpAddress("192.168.1.128/25"));
|
||||
assertTrue(root.hasIpAddress("192.168.1.192/26"));
|
||||
assertTrue(root.hasIpAddress("192.168.1.224/27"));
|
||||
assertTrue(root.hasIpAddress("192.168.1.240/27"));
|
||||
assertTrue(root.hasIpAddress("192.168.1.255/32"));
|
||||
|
||||
request.setRemoteAddr("202.24.199.127");
|
||||
assertTrue(root.hasIpAddress("202.24.0.0/14"));
|
||||
request.setRemoteAddr("202.25.179.135");
|
||||
assertTrue(root.hasIpAddress("202.24.0.0/14"));
|
||||
request.setRemoteAddr("202.26.179.135");
|
||||
assertTrue(root.hasIpAddress("202.24.0.0/14"));
|
||||
}
|
||||
request.setRemoteAddr("202.24.199.127");
|
||||
assertTrue(root.hasIpAddress("202.24.0.0/14"));
|
||||
request.setRemoteAddr("202.25.179.135");
|
||||
assertTrue(root.hasIpAddress("202.24.0.0/14"));
|
||||
request.setRemoteAddr("202.26.179.135");
|
||||
assertTrue(root.hasIpAddress("202.24.0.0/14"));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -38,133 +38,141 @@ import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class DefaultFilterInvocationSecurityMetadataSourceTests {
|
||||
private DefaultFilterInvocationSecurityMetadataSource fids;
|
||||
private Collection<ConfigAttribute> def = SecurityConfig.createList("ROLE_ONE");
|
||||
private DefaultFilterInvocationSecurityMetadataSource fids;
|
||||
private Collection<ConfigAttribute> def = SecurityConfig.createList("ROLE_ONE");
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
private void createFids(String pattern, String method) {
|
||||
LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap =
|
||||
new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();
|
||||
requestMap.put(new AntPathRequestMatcher(pattern, method), def);
|
||||
fids = new DefaultFilterInvocationSecurityMetadataSource(requestMap);
|
||||
}
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
private void createFids(String pattern, String method) {
|
||||
LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();
|
||||
requestMap.put(new AntPathRequestMatcher(pattern, method), def);
|
||||
fids = new DefaultFilterInvocationSecurityMetadataSource(requestMap);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void lookupNotRequiringExactMatchSucceedsIfNotMatching() {
|
||||
createFids("/secure/super/**", null);
|
||||
@Test
|
||||
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);
|
||||
|
||||
assertEquals(def, fids.getAttributes(fi));
|
||||
}
|
||||
assertEquals(def, fids.getAttributes(fi));
|
||||
}
|
||||
|
||||
/**
|
||||
* SEC-501. Note that as of 2.0, lower case comparisons are the default for this class.
|
||||
*/
|
||||
@Test
|
||||
public void lookupNotRequiringExactMatchSucceedsIfSecureUrlPathContainsUpperCase() {
|
||||
createFids("/SeCuRE/super/**", null);
|
||||
/**
|
||||
* SEC-501. Note that as of 2.0, lower case comparisons are the default for this
|
||||
* class.
|
||||
*/
|
||||
@Test
|
||||
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 = fids.getAttributes(fi);
|
||||
assertEquals(def, response);
|
||||
}
|
||||
Collection<ConfigAttribute> response = fids.getAttributes(fi);
|
||||
assertEquals(def, response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void lookupRequiringExactMatchIsSuccessful() {
|
||||
createFids("/SeCurE/super/**", null);
|
||||
@Test
|
||||
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 = fids.getAttributes(fi);
|
||||
assertEquals(def, response);
|
||||
}
|
||||
Collection<ConfigAttribute> response = fids.getAttributes(fi);
|
||||
assertEquals(def, response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void lookupRequiringExactMatchWithAdditionalSlashesIsSuccessful() {
|
||||
createFids("/someAdminPage.html**", null);
|
||||
@Test
|
||||
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 = fids.getAttributes(fi);
|
||||
assertEquals(def, response); // see SEC-161 (it should truncate after ? sign)
|
||||
}
|
||||
Collection<ConfigAttribute> response = fids.getAttributes(fi);
|
||||
assertEquals(def, response); // see SEC-161 (it should truncate after ? sign)
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void unknownHttpMethodIsRejected() {
|
||||
createFids("/someAdminPage.html**", "UNKNOWN");
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void unknownHttpMethodIsRejected() {
|
||||
createFids("/someAdminPage.html**", "UNKNOWN");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void httpMethodLookupSucceeds() {
|
||||
createFids("/somepage**", "GET");
|
||||
@Test
|
||||
public void httpMethodLookupSucceeds() {
|
||||
createFids("/somepage**", "GET");
|
||||
|
||||
FilterInvocation fi = createFilterInvocation("/somepage", null, null, "GET");
|
||||
Collection<ConfigAttribute> attrs = fids.getAttributes(fi);
|
||||
assertEquals(def, attrs);
|
||||
}
|
||||
FilterInvocation fi = createFilterInvocation("/somepage", null, null, "GET");
|
||||
Collection<ConfigAttribute> attrs = fids.getAttributes(fi);
|
||||
assertEquals(def, attrs);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void generalMatchIsUsedIfNoMethodSpecificMatchExists() {
|
||||
createFids("/somepage**", null);
|
||||
@Test
|
||||
public void generalMatchIsUsedIfNoMethodSpecificMatchExists() {
|
||||
createFids("/somepage**", null);
|
||||
|
||||
FilterInvocation fi = createFilterInvocation("/somepage", null, null, "GET");
|
||||
Collection<ConfigAttribute> attrs = fids.getAttributes(fi);
|
||||
assertEquals(def, attrs);
|
||||
}
|
||||
FilterInvocation fi = createFilterInvocation("/somepage", null, null, "GET");
|
||||
Collection<ConfigAttribute> attrs = fids.getAttributes(fi);
|
||||
assertEquals(def, attrs);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestWithDifferentHttpMethodDoesntMatch() {
|
||||
createFids("/somepage**", "GET");
|
||||
@Test
|
||||
public void requestWithDifferentHttpMethodDoesntMatch() {
|
||||
createFids("/somepage**", "GET");
|
||||
|
||||
FilterInvocation fi = createFilterInvocation("/somepage", null, null, "POST");
|
||||
Collection<ConfigAttribute> attrs = fids.getAttributes(fi);
|
||||
assertNull(attrs);
|
||||
}
|
||||
FilterInvocation fi = createFilterInvocation("/somepage", null, null, "POST");
|
||||
Collection<ConfigAttribute> attrs = fids.getAttributes(fi);
|
||||
assertNull(attrs);
|
||||
}
|
||||
|
||||
// SEC-1236
|
||||
@Test
|
||||
public void mixingPatternsWithAndWithoutHttpMethodsIsSupported() throws Exception {
|
||||
LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap =
|
||||
new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();
|
||||
Collection<ConfigAttribute> userAttrs = SecurityConfig.createList("A");
|
||||
// SEC-1236
|
||||
@Test
|
||||
public void mixingPatternsWithAndWithoutHttpMethodsIsSupported() throws Exception {
|
||||
LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>>();
|
||||
Collection<ConfigAttribute> userAttrs = SecurityConfig.createList("A");
|
||||
|
||||
requestMap.put(new AntPathRequestMatcher("/user/**", null), userAttrs);
|
||||
requestMap.put(new AntPathRequestMatcher("/teller/**", "GET"), SecurityConfig.createList("B"));
|
||||
fids = new DefaultFilterInvocationSecurityMetadataSource(requestMap);
|
||||
requestMap.put(new AntPathRequestMatcher("/user/**", null), userAttrs);
|
||||
requestMap.put(new AntPathRequestMatcher("/teller/**", "GET"),
|
||||
SecurityConfig.createList("B"));
|
||||
fids = new DefaultFilterInvocationSecurityMetadataSource(requestMap);
|
||||
|
||||
FilterInvocation fi = createFilterInvocation("/user", null, null, "GET");
|
||||
Collection<ConfigAttribute> attrs = fids.getAttributes(fi);
|
||||
assertEquals(userAttrs, attrs);
|
||||
}
|
||||
FilterInvocation fi = createFilterInvocation("/user", null, null, "GET");
|
||||
Collection<ConfigAttribute> attrs = fids.getAttributes(fi);
|
||||
assertEquals(userAttrs, attrs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check fixes for SEC-321
|
||||
*/
|
||||
@Test
|
||||
public void extraQuestionMarkStillMatches() {
|
||||
createFids("/someAdminPage.html*", null);
|
||||
/**
|
||||
* Check fixes for SEC-321
|
||||
*/
|
||||
@Test
|
||||
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 = fids.getAttributes(fi);
|
||||
assertEquals(def, response);
|
||||
Collection<ConfigAttribute> response = fids.getAttributes(fi);
|
||||
assertEquals(def, response);
|
||||
|
||||
fi = createFilterInvocation("/someAdminPage.html", null, "?", null);
|
||||
fi = createFilterInvocation("/someAdminPage.html", null, "?", null);
|
||||
|
||||
response = fids.getAttributes(fi);
|
||||
assertEquals(def, response);
|
||||
}
|
||||
response = fids.getAttributes(fi);
|
||||
assertEquals(def, response);
|
||||
}
|
||||
|
||||
private FilterInvocation createFilterInvocation(String servletPath, String pathInfo, String queryString, String method) {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI(null);
|
||||
request.setMethod(method);
|
||||
request.setServletPath(servletPath);
|
||||
request.setPathInfo(pathInfo);
|
||||
request.setQueryString(queryString);
|
||||
private FilterInvocation createFilterInvocation(String servletPath, String pathInfo,
|
||||
String queryString, String method) {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI(null);
|
||||
request.setMethod(method);
|
||||
request.setServletPath(servletPath);
|
||||
request.setPathInfo(pathInfo);
|
||||
request.setQueryString(queryString);
|
||||
|
||||
return new FilterInvocation(request, new MockHttpServletResponse(), mock(FilterChain.class));
|
||||
}
|
||||
return new FilterInvocation(request, new MockHttpServletResponse(),
|
||||
mock(FilterChain.class));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,7 +40,6 @@ import javax.servlet.FilterChain;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link FilterSecurityInterceptor}.
|
||||
*
|
||||
@@ -49,134 +48,145 @@ 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;
|
||||
private AuthenticationManager am;
|
||||
private AccessDecisionManager adm;
|
||||
private FilterInvocationSecurityMetadataSource ods;
|
||||
private RunAsManager ram;
|
||||
private FilterSecurityInterceptor interceptor;
|
||||
private ApplicationEventPublisher publisher;
|
||||
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
@Before
|
||||
public final void setUp() throws Exception {
|
||||
interceptor = new FilterSecurityInterceptor();
|
||||
am = mock(AuthenticationManager.class);
|
||||
ods = mock(FilterInvocationSecurityMetadataSource.class);
|
||||
adm = mock(AccessDecisionManager.class);
|
||||
ram = mock(RunAsManager.class);
|
||||
publisher = mock(ApplicationEventPublisher.class);
|
||||
interceptor.setAuthenticationManager(am);
|
||||
interceptor.setSecurityMetadataSource(ods);
|
||||
interceptor.setAccessDecisionManager(adm);
|
||||
interceptor.setRunAsManager(ram);
|
||||
interceptor.setApplicationEventPublisher(publisher);
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Before
|
||||
public final void setUp() throws Exception {
|
||||
interceptor = new FilterSecurityInterceptor();
|
||||
am = mock(AuthenticationManager.class);
|
||||
ods = mock(FilterInvocationSecurityMetadataSource.class);
|
||||
adm = mock(AccessDecisionManager.class);
|
||||
ram = mock(RunAsManager.class);
|
||||
publisher = mock(ApplicationEventPublisher.class);
|
||||
interceptor.setAuthenticationManager(am);
|
||||
interceptor.setSecurityMetadataSource(ods);
|
||||
interceptor.setAccessDecisionManager(adm);
|
||||
interceptor.setRunAsManager(ram);
|
||||
interceptor.setApplicationEventPublisher(publisher);
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testEnsuresAccessDecisionManagerSupportsFilterInvocationClass()
|
||||
throws Exception {
|
||||
when(adm.supports(FilterInvocation.class)).thenReturn(true);
|
||||
interceptor.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testEnsuresAccessDecisionManagerSupportsFilterInvocationClass() throws Exception {
|
||||
when(adm.supports(FilterInvocation.class)).thenReturn(true);
|
||||
interceptor.afterPropertiesSet();
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testEnsuresRunAsManagerSupportsFilterInvocationClass() throws Exception {
|
||||
when(adm.supports(FilterInvocation.class)).thenReturn(false);
|
||||
interceptor.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testEnsuresRunAsManagerSupportsFilterInvocationClass() throws Exception {
|
||||
when(adm.supports(FilterInvocation.class)).thenReturn(false);
|
||||
interceptor.afterPropertiesSet();
|
||||
}
|
||||
/**
|
||||
* We just test invocation works in a success event. There is no need to test access
|
||||
* denied events as the abstract parent enforces that logic, which is extensively
|
||||
* tested separately.
|
||||
*/
|
||||
@Test
|
||||
public void testSuccessfulInvocation() throws Throwable {
|
||||
// Setup a Context
|
||||
Authentication token = new TestingAuthenticationToken("Test", "Password",
|
||||
"NOT_USED");
|
||||
SecurityContextHolder.getContext().setAuthentication(token);
|
||||
|
||||
/**
|
||||
* We just test invocation works in a success event. There is no need to test access denied events as the
|
||||
* abstract parent enforces that logic, which is extensively tested separately.
|
||||
*/
|
||||
@Test
|
||||
public void testSuccessfulInvocation() throws Throwable {
|
||||
// Setup a Context
|
||||
Authentication token = new TestingAuthenticationToken("Test", "Password", "NOT_USED");
|
||||
SecurityContextHolder.getContext().setAuthentication(token);
|
||||
FilterInvocation fi = createinvocation();
|
||||
|
||||
FilterInvocation fi = createinvocation();
|
||||
when(ods.getAttributes(fi)).thenReturn(SecurityConfig.createList("MOCK_OK"));
|
||||
|
||||
when(ods.getAttributes(fi)).thenReturn(SecurityConfig.createList("MOCK_OK"));
|
||||
interceptor.invoke(fi);
|
||||
|
||||
interceptor.invoke(fi);
|
||||
// SEC-1697
|
||||
verify(publisher, never()).publishEvent(any(AuthorizedEvent.class));
|
||||
}
|
||||
|
||||
// SEC-1697
|
||||
verify(publisher, never()).publishEvent(any(AuthorizedEvent.class));
|
||||
}
|
||||
@Test
|
||||
public void afterInvocationIsNotInvokedIfExceptionThrown() throws Exception {
|
||||
Authentication token = new TestingAuthenticationToken("Test", "Password",
|
||||
"NOT_USED");
|
||||
SecurityContextHolder.getContext().setAuthentication(token);
|
||||
|
||||
@Test
|
||||
public void afterInvocationIsNotInvokedIfExceptionThrown() throws Exception {
|
||||
Authentication token = new TestingAuthenticationToken("Test", "Password", "NOT_USED");
|
||||
SecurityContextHolder.getContext().setAuthentication(token);
|
||||
FilterInvocation fi = createinvocation();
|
||||
FilterChain chain = fi.getChain();
|
||||
|
||||
FilterInvocation fi = createinvocation();
|
||||
FilterChain chain = fi.getChain();
|
||||
doThrow(new RuntimeException()).when(chain).doFilter(
|
||||
any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
when(ods.getAttributes(fi)).thenReturn(SecurityConfig.createList("MOCK_OK"));
|
||||
|
||||
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);
|
||||
interceptor.setAfterInvocationManager(aim);
|
||||
|
||||
AfterInvocationManager aim = mock(AfterInvocationManager.class);
|
||||
interceptor.setAfterInvocationManager(aim);
|
||||
try {
|
||||
interceptor.invoke(fi);
|
||||
fail("Expected exception");
|
||||
}
|
||||
catch (RuntimeException expected) {
|
||||
}
|
||||
|
||||
try {
|
||||
interceptor.invoke(fi);
|
||||
fail("Expected exception");
|
||||
} catch (RuntimeException expected) {
|
||||
}
|
||||
verifyZeroInteractions(aim);
|
||||
}
|
||||
|
||||
verifyZeroInteractions(aim);
|
||||
}
|
||||
// SEC-1967
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void finallyInvocationIsInvokedIfExceptionThrown() throws Exception {
|
||||
SecurityContext ctx = SecurityContextHolder.getContext();
|
||||
Authentication token = new TestingAuthenticationToken("Test", "Password",
|
||||
"NOT_USED");
|
||||
token.setAuthenticated(true);
|
||||
ctx.setAuthentication(token);
|
||||
|
||||
// SEC-1967
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
public void finallyInvocationIsInvokedIfExceptionThrown() throws Exception {
|
||||
SecurityContext ctx = SecurityContextHolder.getContext();
|
||||
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()));
|
||||
interceptor.setRunAsManager(runAsManager);
|
||||
|
||||
RunAsManager runAsManager = mock(RunAsManager.class);
|
||||
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();
|
||||
|
||||
FilterInvocation fi = createinvocation();
|
||||
FilterChain chain = fi.getChain();
|
||||
doThrow(new RuntimeException()).when(chain).doFilter(
|
||||
any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
when(ods.getAttributes(fi)).thenReturn(SecurityConfig.createList("MOCK_OK"));
|
||||
|
||||
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);
|
||||
interceptor.setAfterInvocationManager(aim);
|
||||
|
||||
AfterInvocationManager aim = mock(AfterInvocationManager.class);
|
||||
interceptor.setAfterInvocationManager(aim);
|
||||
try {
|
||||
interceptor.invoke(fi);
|
||||
fail("Expected exception");
|
||||
}
|
||||
catch (RuntimeException expected) {
|
||||
}
|
||||
|
||||
try {
|
||||
interceptor.invoke(fi);
|
||||
fail("Expected exception");
|
||||
} catch (RuntimeException expected) {
|
||||
}
|
||||
// Check we've changed back
|
||||
assertSame(ctx, SecurityContextHolder.getContext());
|
||||
assertSame(token, SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
// Check we've changed back
|
||||
assertSame(ctx, SecurityContextHolder.getContext());
|
||||
assertSame(token, SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
private FilterInvocation createinvocation() {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setServletPath("/secure/page.html");
|
||||
|
||||
private FilterInvocation createinvocation() {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setServletPath("/secure/page.html");
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
FilterInvocation fi = new FilterInvocation(request, response, chain);
|
||||
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
FilterInvocation fi = new FilterInvocation(request, response, chain);
|
||||
|
||||
return fi;
|
||||
}
|
||||
return fi;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -12,40 +12,40 @@ import org.springframework.security.web.access.intercept.RequestKey;
|
||||
*/
|
||||
public class RequestKeyTests {
|
||||
|
||||
@Test
|
||||
public void equalsWorksWithNullHttpMethod() {
|
||||
RequestKey key1 = new RequestKey("/someurl");
|
||||
RequestKey key2 = new RequestKey("/someurl");
|
||||
@Test
|
||||
public void equalsWorksWithNullHttpMethod() {
|
||||
RequestKey key1 = new RequestKey("/someurl");
|
||||
RequestKey key2 = new RequestKey("/someurl");
|
||||
|
||||
assertEquals(key1, key2);
|
||||
key1 = new RequestKey("/someurl","GET");
|
||||
assertFalse(key1.equals(key2));
|
||||
assertFalse(key2.equals(key1));
|
||||
}
|
||||
assertEquals(key1, key2);
|
||||
key1 = new RequestKey("/someurl", "GET");
|
||||
assertFalse(key1.equals(key2));
|
||||
assertFalse(key2.equals(key1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void keysWithSameUrlAndHttpMethodAreEqual() {
|
||||
RequestKey key1 = new RequestKey("/someurl", "GET");
|
||||
RequestKey key2 = new RequestKey("/someurl", "GET");
|
||||
@Test
|
||||
public void keysWithSameUrlAndHttpMethodAreEqual() {
|
||||
RequestKey key1 = new RequestKey("/someurl", "GET");
|
||||
RequestKey key2 = new RequestKey("/someurl", "GET");
|
||||
|
||||
assertEquals(key1, key2);
|
||||
}
|
||||
assertEquals(key1, key2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void keysWithSameUrlAndDifferentHttpMethodAreNotEqual() {
|
||||
RequestKey key1 = new RequestKey("/someurl", "GET");
|
||||
RequestKey key2 = new RequestKey("/someurl", "POST");
|
||||
@Test
|
||||
public void keysWithSameUrlAndDifferentHttpMethodAreNotEqual() {
|
||||
RequestKey key1 = new RequestKey("/someurl", "GET");
|
||||
RequestKey key2 = new RequestKey("/someurl", "POST");
|
||||
|
||||
assertFalse(key1.equals(key2));
|
||||
assertFalse(key2.equals(key1));
|
||||
}
|
||||
assertFalse(key1.equals(key2));
|
||||
assertFalse(key2.equals(key1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void keysWithDifferentUrlsAreNotEquals() {
|
||||
RequestKey key1 = new RequestKey("/someurl", "GET");
|
||||
RequestKey key2 = new RequestKey("/anotherurl", "GET");
|
||||
@Test
|
||||
public void keysWithDifferentUrlsAreNotEquals() {
|
||||
RequestKey key1 = new RequestKey("/someurl", "GET");
|
||||
RequestKey key2 = new RequestKey("/anotherurl", "GET");
|
||||
|
||||
assertFalse(key1.equals(key2));
|
||||
assertFalse(key2.equals(key1));
|
||||
}
|
||||
assertFalse(key1.equals(key2));
|
||||
assertFalse(key2.equals(key1));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,7 +57,6 @@ import org.springframework.security.web.authentication.session.SessionAuthentica
|
||||
import org.springframework.security.web.firewall.DefaultHttpFirewall;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link AbstractAuthenticationProcessingFilter}.
|
||||
*
|
||||
@@ -67,370 +66,395 @@ import org.springframework.test.util.ReflectionTestUtils;
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
public class AbstractAuthenticationProcessingFilterTests {
|
||||
SavedRequestAwareAuthenticationSuccessHandler successHandler;
|
||||
SimpleUrlAuthenticationFailureHandler failureHandler;
|
||||
//~ Methods ========================================================================================================
|
||||
|
||||
private MockHttpServletRequest createMockAuthenticationRequest() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
request.setServletPath("/j_mock_post");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setRequestURI("/mycontext/j_mock_post");
|
||||
request.setContextPath("/mycontext");
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
|
||||
successHandler.setDefaultTargetUrl("/logged_in.jsp");
|
||||
failureHandler = new SimpleUrlAuthenticationFailureHandler();
|
||||
failureHandler.setDefaultFailureUrl("/failed.jsp");
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDefaultProcessesFilterUrlMatchesWithPathParameter() {
|
||||
MockHttpServletRequest request = createMockAuthenticationRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter();
|
||||
filter.setFilterProcessesUrl("/login");
|
||||
|
||||
DefaultHttpFirewall firewall = new DefaultHttpFirewall();
|
||||
request.setServletPath("/login;jsessionid=I8MIONOSTHOR");
|
||||
|
||||
// the firewall ensures that path parameters are ignored
|
||||
HttpServletRequest firewallRequest = firewall.getFirewalledRequest(request);
|
||||
assertTrue(filter.requiresAuthentication(firewallRequest, response));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFilterProcessesUrlVariationsRespected() throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = createMockAuthenticationRequest();
|
||||
request.setServletPath("/j_OTHER_LOCATION");
|
||||
request.setRequestURI("/mycontext/j_OTHER_LOCATION");
|
||||
|
||||
// Setup our filter configuration
|
||||
MockFilterConfig config = new MockFilterConfig(null, null);
|
||||
|
||||
// Setup our expectation that the filter chain will not be invoked, as we redirect to defaultTargetUrl
|
||||
MockFilterChain chain = new MockFilterChain(false);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
// Setup our test object, to grant access
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter(true);
|
||||
filter.setFilterProcessesUrl("/j_OTHER_LOCATION");
|
||||
filter.setAuthenticationSuccessHandler(successHandler);
|
||||
|
||||
// Test
|
||||
filter.doFilter(request, response, chain);
|
||||
assertEquals("/mycontext/logged_in.jsp", response.getRedirectedUrl());
|
||||
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals("test", SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGettersSetters() throws Exception {
|
||||
AbstractAuthenticationProcessingFilter filter = new MockAuthenticationFilter();
|
||||
filter.setAuthenticationManager(mock(AuthenticationManager.class));
|
||||
filter.setFilterProcessesUrl("/p");
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
assertNotNull(filter.getRememberMeServices());
|
||||
filter.setRememberMeServices(new TokenBasedRememberMeServices("key", new AbstractRememberMeServicesTests.MockUserDetailsService()));
|
||||
assertEquals(TokenBasedRememberMeServices.class, filter.getRememberMeServices().getClass());
|
||||
assertTrue(filter.getAuthenticationManager() != null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIgnoresAnyServletPathOtherThanFilterProcessesUrl() throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = createMockAuthenticationRequest();
|
||||
request.setServletPath("/some.file.html");
|
||||
request.setRequestURI("/mycontext/some.file.html");
|
||||
|
||||
// Setup our filter configuration
|
||||
MockFilterConfig config = new MockFilterConfig(null, null);
|
||||
|
||||
// Setup our expectation that the filter chain will be invoked, as our request is for a page the filter isn't monitoring
|
||||
MockFilterChain chain = new MockFilterChain(true);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
// Setup our test object, to deny access
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
|
||||
|
||||
// Test
|
||||
filter.doFilter(request, response, chain);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNormalOperationWithDefaultFilterProcessesUrl() throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = createMockAuthenticationRequest();
|
||||
HttpSession sessionPreAuth = request.getSession();
|
||||
|
||||
// Setup our filter configuration
|
||||
MockFilterConfig config = new MockFilterConfig(null, null);
|
||||
|
||||
// Setup our expectation that the filter chain will not be invoked, as we redirect to defaultTargetUrl
|
||||
MockFilterChain chain = new MockFilterChain(false);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
// Setup our test object, to grant access
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter(true);
|
||||
|
||||
filter.setFilterProcessesUrl("/j_mock_post");
|
||||
filter.setSessionAuthenticationStrategy(mock(SessionAuthenticationStrategy.class));
|
||||
filter.setAuthenticationSuccessHandler(successHandler);
|
||||
filter.setAuthenticationFailureHandler(failureHandler);
|
||||
filter.setAuthenticationManager(mock(AuthenticationManager.class));
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
// Test
|
||||
filter.doFilter(request, response, chain);
|
||||
assertEquals("/mycontext/logged_in.jsp", response.getRedirectedUrl());
|
||||
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals("test", SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
|
||||
// Should still have the same session
|
||||
assertEquals(sessionPreAuth, request.getSession());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStartupDetectsInvalidAuthenticationManager() throws Exception {
|
||||
AbstractAuthenticationProcessingFilter filter = new MockAuthenticationFilter();
|
||||
filter.setAuthenticationFailureHandler(failureHandler);
|
||||
successHandler.setDefaultTargetUrl("/");
|
||||
filter.setAuthenticationSuccessHandler(successHandler);
|
||||
filter.setFilterProcessesUrl("/login");
|
||||
|
||||
try {
|
||||
filter.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("authenticationManager must be specified", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStartupDetectsInvalidFilterProcessesUrl() throws Exception {
|
||||
AbstractAuthenticationProcessingFilter filter = new MockAuthenticationFilter();
|
||||
filter.setAuthenticationFailureHandler(failureHandler);
|
||||
filter.setAuthenticationManager(mock(AuthenticationManager.class));
|
||||
filter.setAuthenticationSuccessHandler(successHandler);
|
||||
|
||||
try {
|
||||
filter.setFilterProcessesUrl(null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("Pattern cannot be null or empty", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSuccessLoginThenFailureLoginResultsInSessionLosingToken() throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = createMockAuthenticationRequest();
|
||||
|
||||
// Setup our filter configuration
|
||||
MockFilterConfig config = new MockFilterConfig(null, null);
|
||||
|
||||
// Setup our expectation that the filter chain will not be invoked, as we redirect to defaultTargetUrl
|
||||
MockFilterChain chain = new MockFilterChain(false);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
// Setup our test object, to grant access
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter(true);
|
||||
filter.setFilterProcessesUrl("/j_mock_post");
|
||||
filter.setAuthenticationSuccessHandler(successHandler);
|
||||
|
||||
// Test
|
||||
filter.doFilter(request, response, chain);
|
||||
assertEquals("/mycontext/logged_in.jsp", response.getRedirectedUrl());
|
||||
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals("test", SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
|
||||
|
||||
// Now try again but this time have filter deny access
|
||||
// Setup our HTTP request
|
||||
// Setup our expectation that the filter chain will not be invoked, as we redirect to authenticationFailureUrl
|
||||
chain = new MockFilterChain(false);
|
||||
response = new MockHttpServletResponse();
|
||||
|
||||
// Setup our test object, to deny access
|
||||
filter = new MockAuthenticationFilter(false);
|
||||
filter.setFilterProcessesUrl("/j_mock_post");
|
||||
filter.setAuthenticationFailureHandler(failureHandler);
|
||||
|
||||
// Test
|
||||
filter.doFilter(request, response, chain);
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSuccessfulAuthenticationInvokesSuccessHandlerAndSetsContext() throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = createMockAuthenticationRequest();
|
||||
|
||||
// Setup our filter configuration
|
||||
MockFilterConfig config = new MockFilterConfig(null, null);
|
||||
|
||||
// Setup our expectation that the filter chain will be invoked, as we want to go to the location requested in the session
|
||||
MockFilterChain chain = new MockFilterChain(true);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
// Setup our test object, to grant access
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter(true);
|
||||
filter.setFilterProcessesUrl("/j_mock_post");
|
||||
AuthenticationSuccessHandler successHandler = mock(AuthenticationSuccessHandler.class);
|
||||
filter.setAuthenticationSuccessHandler(successHandler);
|
||||
|
||||
// Test
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
verify(successHandler).onAuthenticationSuccess(any(HttpServletRequest.class), any(HttpServletResponse.class),
|
||||
any(Authentication.class));
|
||||
|
||||
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFailedAuthenticationInvokesFailureHandler() throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = createMockAuthenticationRequest();
|
||||
|
||||
// Setup our filter configuration
|
||||
MockFilterConfig config = new MockFilterConfig(null, null);
|
||||
|
||||
// Setup our expectation that the filter chain will not be invoked, as we redirect to authenticationFailureUrl
|
||||
MockFilterChain chain = new MockFilterChain(false);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
// Setup our test object, to deny access
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
|
||||
AuthenticationFailureHandler failureHandler = mock(AuthenticationFailureHandler.class);
|
||||
filter.setAuthenticationFailureHandler(failureHandler);
|
||||
|
||||
// Test
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
verify(failureHandler).onAuthenticationFailure(any(HttpServletRequest.class), any(HttpServletResponse.class),
|
||||
any(AuthenticationException.class));
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
/**
|
||||
* SEC-571
|
||||
*/
|
||||
@Test
|
||||
public void testNoSessionIsCreatedIfAllowSessionCreationIsFalse() throws Exception {
|
||||
MockHttpServletRequest request = createMockAuthenticationRequest();
|
||||
|
||||
MockFilterConfig config = new MockFilterConfig(null, null);
|
||||
MockFilterChain chain = new MockFilterChain(true);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
// Reject authentication, so exception would normally be stored in session
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
|
||||
failureHandler.setAllowSessionCreation(false);
|
||||
filter.setAuthenticationFailureHandler(failureHandler);
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
assertNull(request.getSession(false));
|
||||
}
|
||||
|
||||
/**
|
||||
* SEC-462
|
||||
*/
|
||||
@Test
|
||||
public void testLoginErrorWithNoFailureUrlSendsUnauthorizedStatus() throws Exception {
|
||||
MockHttpServletRequest request = createMockAuthenticationRequest();
|
||||
|
||||
MockFilterConfig config = new MockFilterConfig(null, null);
|
||||
MockFilterChain chain = new MockFilterChain(true);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
|
||||
successHandler.setDefaultTargetUrl("http://monkeymachine.co.uk/");
|
||||
filter.setAuthenticationSuccessHandler(successHandler);
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
|
||||
}
|
||||
|
||||
/**
|
||||
* SEC-1919
|
||||
*/
|
||||
@Test
|
||||
public void loginErrorWithInternAuthenticationServiceExceptionLogsError() throws Exception {
|
||||
MockHttpServletRequest request = createMockAuthenticationRequest();
|
||||
|
||||
MockFilterChain chain = new MockFilterChain(true);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
Log logger = mock(Log.class);
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
|
||||
ReflectionTestUtils.setField(filter, "logger", logger);
|
||||
filter.exceptionToThrow = new InternalAuthenticationServiceException("Mock requested to do so");
|
||||
successHandler.setDefaultTargetUrl("http://monkeymachine.co.uk/");
|
||||
filter.setAuthenticationSuccessHandler(successHandler);
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
verify(logger).error(anyString(), eq(filter.exceptionToThrow));
|
||||
assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
|
||||
}
|
||||
|
||||
//~ Inner Classes ==================================================================================================
|
||||
|
||||
private class MockAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
|
||||
private AuthenticationException exceptionToThrow;
|
||||
private boolean grantAccess;
|
||||
|
||||
public MockAuthenticationFilter(boolean grantAccess) {
|
||||
this();
|
||||
setRememberMeServices(new NullRememberMeServices());
|
||||
this.grantAccess = grantAccess;
|
||||
this.exceptionToThrow = new BadCredentialsException("Mock requested to do so");
|
||||
}
|
||||
|
||||
private MockAuthenticationFilter() {
|
||||
super("/j_mock_post");
|
||||
}
|
||||
|
||||
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
|
||||
if (grantAccess) {
|
||||
return new UsernamePasswordAuthenticationToken("test", "test", AuthorityUtils.createAuthorityList("TEST"));
|
||||
} else {
|
||||
throw exceptionToThrow;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class MockFilterChain implements FilterChain {
|
||||
private boolean expectToProceed;
|
||||
|
||||
public MockFilterChain(boolean expectToProceed) {
|
||||
this.expectToProceed = expectToProceed;
|
||||
}
|
||||
|
||||
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
|
||||
if (expectToProceed) {
|
||||
assertTrue(true);
|
||||
} else {
|
||||
fail("Did not expect filter chain to proceed");
|
||||
}
|
||||
}
|
||||
}
|
||||
SavedRequestAwareAuthenticationSuccessHandler successHandler;
|
||||
SimpleUrlAuthenticationFailureHandler failureHandler;
|
||||
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
private MockHttpServletRequest createMockAuthenticationRequest() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
request.setServletPath("/j_mock_post");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setRequestURI("/mycontext/j_mock_post");
|
||||
request.setContextPath("/mycontext");
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
|
||||
successHandler.setDefaultTargetUrl("/logged_in.jsp");
|
||||
failureHandler = new SimpleUrlAuthenticationFailureHandler();
|
||||
failureHandler.setDefaultFailureUrl("/failed.jsp");
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws Exception {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDefaultProcessesFilterUrlMatchesWithPathParameter() {
|
||||
MockHttpServletRequest request = createMockAuthenticationRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter();
|
||||
filter.setFilterProcessesUrl("/login");
|
||||
|
||||
DefaultHttpFirewall firewall = new DefaultHttpFirewall();
|
||||
request.setServletPath("/login;jsessionid=I8MIONOSTHOR");
|
||||
|
||||
// the firewall ensures that path parameters are ignored
|
||||
HttpServletRequest firewallRequest = firewall.getFirewalledRequest(request);
|
||||
assertTrue(filter.requiresAuthentication(firewallRequest, response));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFilterProcessesUrlVariationsRespected() throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = createMockAuthenticationRequest();
|
||||
request.setServletPath("/j_OTHER_LOCATION");
|
||||
request.setRequestURI("/mycontext/j_OTHER_LOCATION");
|
||||
|
||||
// Setup our filter configuration
|
||||
MockFilterConfig config = new MockFilterConfig(null, null);
|
||||
|
||||
// Setup our expectation that the filter chain will not be invoked, as we redirect
|
||||
// to defaultTargetUrl
|
||||
MockFilterChain chain = new MockFilterChain(false);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
// Setup our test object, to grant access
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter(true);
|
||||
filter.setFilterProcessesUrl("/j_OTHER_LOCATION");
|
||||
filter.setAuthenticationSuccessHandler(successHandler);
|
||||
|
||||
// Test
|
||||
filter.doFilter(request, response, chain);
|
||||
assertEquals("/mycontext/logged_in.jsp", response.getRedirectedUrl());
|
||||
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals("test", SecurityContextHolder.getContext().getAuthentication()
|
||||
.getPrincipal().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGettersSetters() throws Exception {
|
||||
AbstractAuthenticationProcessingFilter filter = new MockAuthenticationFilter();
|
||||
filter.setAuthenticationManager(mock(AuthenticationManager.class));
|
||||
filter.setFilterProcessesUrl("/p");
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
assertNotNull(filter.getRememberMeServices());
|
||||
filter.setRememberMeServices(new TokenBasedRememberMeServices("key",
|
||||
new AbstractRememberMeServicesTests.MockUserDetailsService()));
|
||||
assertEquals(TokenBasedRememberMeServices.class, filter.getRememberMeServices()
|
||||
.getClass());
|
||||
assertTrue(filter.getAuthenticationManager() != null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIgnoresAnyServletPathOtherThanFilterProcessesUrl() throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = createMockAuthenticationRequest();
|
||||
request.setServletPath("/some.file.html");
|
||||
request.setRequestURI("/mycontext/some.file.html");
|
||||
|
||||
// Setup our filter configuration
|
||||
MockFilterConfig config = new MockFilterConfig(null, null);
|
||||
|
||||
// Setup our expectation that the filter chain will be invoked, as our request is
|
||||
// for a page the filter isn't monitoring
|
||||
MockFilterChain chain = new MockFilterChain(true);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
// Setup our test object, to deny access
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
|
||||
|
||||
// Test
|
||||
filter.doFilter(request, response, chain);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNormalOperationWithDefaultFilterProcessesUrl() throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = createMockAuthenticationRequest();
|
||||
HttpSession sessionPreAuth = request.getSession();
|
||||
|
||||
// Setup our filter configuration
|
||||
MockFilterConfig config = new MockFilterConfig(null, null);
|
||||
|
||||
// Setup our expectation that the filter chain will not be invoked, as we redirect
|
||||
// to defaultTargetUrl
|
||||
MockFilterChain chain = new MockFilterChain(false);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
// Setup our test object, to grant access
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter(true);
|
||||
|
||||
filter.setFilterProcessesUrl("/j_mock_post");
|
||||
filter.setSessionAuthenticationStrategy(mock(SessionAuthenticationStrategy.class));
|
||||
filter.setAuthenticationSuccessHandler(successHandler);
|
||||
filter.setAuthenticationFailureHandler(failureHandler);
|
||||
filter.setAuthenticationManager(mock(AuthenticationManager.class));
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
// Test
|
||||
filter.doFilter(request, response, chain);
|
||||
assertEquals("/mycontext/logged_in.jsp", response.getRedirectedUrl());
|
||||
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals("test", SecurityContextHolder.getContext().getAuthentication()
|
||||
.getPrincipal().toString());
|
||||
// Should still have the same session
|
||||
assertEquals(sessionPreAuth, request.getSession());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStartupDetectsInvalidAuthenticationManager() throws Exception {
|
||||
AbstractAuthenticationProcessingFilter filter = new MockAuthenticationFilter();
|
||||
filter.setAuthenticationFailureHandler(failureHandler);
|
||||
successHandler.setDefaultTargetUrl("/");
|
||||
filter.setAuthenticationSuccessHandler(successHandler);
|
||||
filter.setFilterProcessesUrl("/login");
|
||||
|
||||
try {
|
||||
filter.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertEquals("authenticationManager must be specified", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStartupDetectsInvalidFilterProcessesUrl() throws Exception {
|
||||
AbstractAuthenticationProcessingFilter filter = new MockAuthenticationFilter();
|
||||
filter.setAuthenticationFailureHandler(failureHandler);
|
||||
filter.setAuthenticationManager(mock(AuthenticationManager.class));
|
||||
filter.setAuthenticationSuccessHandler(successHandler);
|
||||
|
||||
try {
|
||||
filter.setFilterProcessesUrl(null);
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertEquals("Pattern cannot be null or empty", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSuccessLoginThenFailureLoginResultsInSessionLosingToken()
|
||||
throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = createMockAuthenticationRequest();
|
||||
|
||||
// Setup our filter configuration
|
||||
MockFilterConfig config = new MockFilterConfig(null, null);
|
||||
|
||||
// Setup our expectation that the filter chain will not be invoked, as we redirect
|
||||
// to defaultTargetUrl
|
||||
MockFilterChain chain = new MockFilterChain(false);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
// Setup our test object, to grant access
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter(true);
|
||||
filter.setFilterProcessesUrl("/j_mock_post");
|
||||
filter.setAuthenticationSuccessHandler(successHandler);
|
||||
|
||||
// Test
|
||||
filter.doFilter(request, response, chain);
|
||||
assertEquals("/mycontext/logged_in.jsp", response.getRedirectedUrl());
|
||||
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals("test", SecurityContextHolder.getContext().getAuthentication()
|
||||
.getPrincipal().toString());
|
||||
|
||||
// Now try again but this time have filter deny access
|
||||
// Setup our HTTP request
|
||||
// Setup our expectation that the filter chain will not be invoked, as we redirect
|
||||
// to authenticationFailureUrl
|
||||
chain = new MockFilterChain(false);
|
||||
response = new MockHttpServletResponse();
|
||||
|
||||
// Setup our test object, to deny access
|
||||
filter = new MockAuthenticationFilter(false);
|
||||
filter.setFilterProcessesUrl("/j_mock_post");
|
||||
filter.setAuthenticationFailureHandler(failureHandler);
|
||||
|
||||
// Test
|
||||
filter.doFilter(request, response, chain);
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSuccessfulAuthenticationInvokesSuccessHandlerAndSetsContext()
|
||||
throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = createMockAuthenticationRequest();
|
||||
|
||||
// Setup our filter configuration
|
||||
MockFilterConfig config = new MockFilterConfig(null, null);
|
||||
|
||||
// Setup our expectation that the filter chain will be invoked, as we want to go
|
||||
// to the location requested in the session
|
||||
MockFilterChain chain = new MockFilterChain(true);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
// Setup our test object, to grant access
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter(true);
|
||||
filter.setFilterProcessesUrl("/j_mock_post");
|
||||
AuthenticationSuccessHandler successHandler = mock(AuthenticationSuccessHandler.class);
|
||||
filter.setAuthenticationSuccessHandler(successHandler);
|
||||
|
||||
// Test
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
verify(successHandler).onAuthenticationSuccess(any(HttpServletRequest.class),
|
||||
any(HttpServletResponse.class), any(Authentication.class));
|
||||
|
||||
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFailedAuthenticationInvokesFailureHandler() throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = createMockAuthenticationRequest();
|
||||
|
||||
// Setup our filter configuration
|
||||
MockFilterConfig config = new MockFilterConfig(null, null);
|
||||
|
||||
// Setup our expectation that the filter chain will not be invoked, as we redirect
|
||||
// to authenticationFailureUrl
|
||||
MockFilterChain chain = new MockFilterChain(false);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
// Setup our test object, to deny access
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
|
||||
AuthenticationFailureHandler failureHandler = mock(AuthenticationFailureHandler.class);
|
||||
filter.setAuthenticationFailureHandler(failureHandler);
|
||||
|
||||
// Test
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
verify(failureHandler).onAuthenticationFailure(any(HttpServletRequest.class),
|
||||
any(HttpServletResponse.class), any(AuthenticationException.class));
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
/**
|
||||
* SEC-571
|
||||
*/
|
||||
@Test
|
||||
public void testNoSessionIsCreatedIfAllowSessionCreationIsFalse() throws Exception {
|
||||
MockHttpServletRequest request = createMockAuthenticationRequest();
|
||||
|
||||
MockFilterConfig config = new MockFilterConfig(null, null);
|
||||
MockFilterChain chain = new MockFilterChain(true);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
// Reject authentication, so exception would normally be stored in session
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
|
||||
failureHandler.setAllowSessionCreation(false);
|
||||
filter.setAuthenticationFailureHandler(failureHandler);
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
assertNull(request.getSession(false));
|
||||
}
|
||||
|
||||
/**
|
||||
* SEC-462
|
||||
*/
|
||||
@Test
|
||||
public void testLoginErrorWithNoFailureUrlSendsUnauthorizedStatus() throws Exception {
|
||||
MockHttpServletRequest request = createMockAuthenticationRequest();
|
||||
|
||||
MockFilterConfig config = new MockFilterConfig(null, null);
|
||||
MockFilterChain chain = new MockFilterChain(true);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
|
||||
successHandler.setDefaultTargetUrl("http://monkeymachine.co.uk/");
|
||||
filter.setAuthenticationSuccessHandler(successHandler);
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
|
||||
}
|
||||
|
||||
/**
|
||||
* SEC-1919
|
||||
*/
|
||||
@Test
|
||||
public void loginErrorWithInternAuthenticationServiceExceptionLogsError()
|
||||
throws Exception {
|
||||
MockHttpServletRequest request = createMockAuthenticationRequest();
|
||||
|
||||
MockFilterChain chain = new MockFilterChain(true);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
Log logger = mock(Log.class);
|
||||
MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
|
||||
ReflectionTestUtils.setField(filter, "logger", logger);
|
||||
filter.exceptionToThrow = new InternalAuthenticationServiceException(
|
||||
"Mock requested to do so");
|
||||
successHandler.setDefaultTargetUrl("http://monkeymachine.co.uk/");
|
||||
filter.setAuthenticationSuccessHandler(successHandler);
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
verify(logger).error(anyString(), eq(filter.exceptionToThrow));
|
||||
assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
|
||||
}
|
||||
|
||||
// ~ Inner Classes
|
||||
// ==================================================================================================
|
||||
|
||||
private class MockAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
|
||||
private AuthenticationException exceptionToThrow;
|
||||
private boolean grantAccess;
|
||||
|
||||
public MockAuthenticationFilter(boolean grantAccess) {
|
||||
this();
|
||||
setRememberMeServices(new NullRememberMeServices());
|
||||
this.grantAccess = grantAccess;
|
||||
this.exceptionToThrow = new BadCredentialsException("Mock requested to do so");
|
||||
}
|
||||
|
||||
private MockAuthenticationFilter() {
|
||||
super("/j_mock_post");
|
||||
}
|
||||
|
||||
public Authentication attemptAuthentication(HttpServletRequest request,
|
||||
HttpServletResponse response) throws AuthenticationException {
|
||||
if (grantAccess) {
|
||||
return new UsernamePasswordAuthenticationToken("test", "test",
|
||||
AuthorityUtils.createAuthorityList("TEST"));
|
||||
}
|
||||
else {
|
||||
throw exceptionToThrow;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class MockFilterChain implements FilterChain {
|
||||
private boolean expectToProceed;
|
||||
|
||||
public MockFilterChain(boolean expectToProceed) {
|
||||
this.expectToProceed = expectToProceed;
|
||||
}
|
||||
|
||||
public void doFilter(ServletRequest request, ServletResponse response)
|
||||
throws IOException, ServletException {
|
||||
if (expectToProceed) {
|
||||
assertTrue(true);
|
||||
}
|
||||
else {
|
||||
fail("Did not expect filter chain to proceed");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,7 +34,6 @@ import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link AnonymousAuthenticationFilter}.
|
||||
*
|
||||
@@ -42,77 +41,88 @@ import java.io.IOException;
|
||||
*/
|
||||
public class AnonymousAuthenticationFilterTests {
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
private void executeFilterInContainerSimulator(FilterConfig filterConfig, Filter filter, ServletRequest request,
|
||||
ServletResponse response, FilterChain filterChain) throws ServletException, IOException {
|
||||
filter.doFilter(request, response, filterChain);
|
||||
}
|
||||
private void executeFilterInContainerSimulator(FilterConfig filterConfig,
|
||||
Filter filter, ServletRequest request, ServletResponse response,
|
||||
FilterChain filterChain) throws ServletException, IOException {
|
||||
filter.doFilter(request, response, filterChain);
|
||||
}
|
||||
|
||||
@Before
|
||||
@After
|
||||
public void clearContext() throws Exception {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
@Before
|
||||
@After
|
||||
public void clearContext() throws Exception {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testDetectsMissingKey() throws Exception {
|
||||
new AnonymousAuthenticationFilter(null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testDetectsMissingKey() throws Exception {
|
||||
new AnonymousAuthenticationFilter(null);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testDetectsUserAttribute() throws Exception {
|
||||
new AnonymousAuthenticationFilter("qwerty", null, null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testDetectsUserAttribute() throws Exception {
|
||||
new AnonymousAuthenticationFilter("qwerty", null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOperationWhenAuthenticationExistsInContextHolder() throws Exception {
|
||||
// Put an Authentication object into the SecurityContextHolder
|
||||
Authentication originalAuth = new TestingAuthenticationToken("user", "password", "ROLE_A");
|
||||
SecurityContextHolder.getContext().setAuthentication(originalAuth);
|
||||
@Test
|
||||
public void testOperationWhenAuthenticationExistsInContextHolder() throws Exception {
|
||||
// Put an Authentication object into the SecurityContextHolder
|
||||
Authentication originalAuth = new TestingAuthenticationToken("user", "password",
|
||||
"ROLE_A");
|
||||
SecurityContextHolder.getContext().setAuthentication(originalAuth);
|
||||
|
||||
AnonymousAuthenticationFilter filter =
|
||||
new AnonymousAuthenticationFilter("qwerty", "anonymousUsername", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
|
||||
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));
|
||||
// Test
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("x");
|
||||
executeFilterInContainerSimulator(mock(FilterConfig.class), filter, request,
|
||||
new MockHttpServletResponse(), new MockFilterChain(true));
|
||||
|
||||
// Ensure filter didn't change our original object
|
||||
assertEquals(originalAuth, SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
// Ensure filter didn't change our original object
|
||||
assertEquals(originalAuth, SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOperationWhenNoAuthenticationInSecurityContextHolder() throws Exception {
|
||||
AnonymousAuthenticationFilter filter = new AnonymousAuthenticationFilter("qwerty", "anonymousUsername", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
|
||||
filter.afterPropertiesSet();
|
||||
@Test
|
||||
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));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("x");
|
||||
executeFilterInContainerSimulator(mock(FilterConfig.class), filter, request,
|
||||
new MockHttpServletResponse(), new MockFilterChain(true));
|
||||
|
||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
assertEquals("anonymousUsername", auth.getPrincipal());
|
||||
assertTrue(AuthorityUtils.authorityListToSet(auth.getAuthorities()).contains("ROLE_ANONYMOUS"));
|
||||
SecurityContextHolder.getContext().setAuthentication(null); // so anonymous fires again
|
||||
}
|
||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
assertEquals("anonymousUsername", auth.getPrincipal());
|
||||
assertTrue(AuthorityUtils.authorityListToSet(auth.getAuthorities()).contains(
|
||||
"ROLE_ANONYMOUS"));
|
||||
SecurityContextHolder.getContext().setAuthentication(null); // so anonymous fires
|
||||
// again
|
||||
}
|
||||
|
||||
//~ Inner Classes ==================================================================================================
|
||||
// ~ Inner Classes
|
||||
// ==================================================================================================
|
||||
|
||||
private class MockFilterChain implements FilterChain {
|
||||
private boolean expectToProceed;
|
||||
private class MockFilterChain implements FilterChain {
|
||||
private boolean expectToProceed;
|
||||
|
||||
public MockFilterChain(boolean expectToProceed) {
|
||||
this.expectToProceed = expectToProceed;
|
||||
}
|
||||
public MockFilterChain(boolean expectToProceed) {
|
||||
this.expectToProceed = expectToProceed;
|
||||
}
|
||||
|
||||
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
|
||||
if (!expectToProceed) {
|
||||
fail("Did not expect filter chain to proceed");
|
||||
}
|
||||
}
|
||||
}
|
||||
public void doFilter(ServletRequest request, ServletResponse response)
|
||||
throws IOException, ServletException {
|
||||
if (!expectToProceed) {
|
||||
fail("Did not expect filter chain to proceed");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,118 +26,136 @@ import org.springframework.security.web.authentication.ui.DefaultLoginPageGenera
|
||||
* @since 3.0
|
||||
*/
|
||||
public class DefaultLoginPageGeneratingFilterTests {
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
|
||||
@Test
|
||||
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);
|
||||
}
|
||||
@Test
|
||||
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);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void generatesForGetLogin() throws Exception {
|
||||
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(new UsernamePasswordAuthenticationFilter());
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
@Test
|
||||
public void generatesForGetLogin() throws Exception {
|
||||
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(
|
||||
new UsernamePasswordAuthenticationFilter());
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
filter.doFilter(new MockHttpServletRequest("GET", "/login"), response, chain);
|
||||
filter.doFilter(new MockHttpServletRequest("GET", "/login"), response, chain);
|
||||
|
||||
assertThat(response.getContentAsString()).isNotEmpty();
|
||||
}
|
||||
assertThat(response.getContentAsString()).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void generatesForPostLogin() throws Exception {
|
||||
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(new UsernamePasswordAuthenticationFilter());
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
@Test
|
||||
public void generatesForPostLogin() throws Exception {
|
||||
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(
|
||||
new UsernamePasswordAuthenticationFilter());
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/login");
|
||||
filter.doFilter(request, response, chain);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/login");
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
assertThat(response.getContentAsString()).isEmpty();
|
||||
}
|
||||
assertThat(response.getContentAsString()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void generatesForNotEmptyContextLogin() throws Exception {
|
||||
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(new UsernamePasswordAuthenticationFilter());
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
@Test
|
||||
public void generatesForNotEmptyContextLogin() throws Exception {
|
||||
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(
|
||||
new UsernamePasswordAuthenticationFilter());
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/context/login");
|
||||
request.setContextPath("/context");
|
||||
filter.doFilter(request, response, chain);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET",
|
||||
"/context/login");
|
||||
request.setContextPath("/context");
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
assertThat(response.getContentAsString()).isNotEmpty();
|
||||
}
|
||||
assertThat(response.getContentAsString()).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void generatesForGetApiLogin() throws Exception {
|
||||
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(new UsernamePasswordAuthenticationFilter());
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
@Test
|
||||
public void generatesForGetApiLogin() throws Exception {
|
||||
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(
|
||||
new UsernamePasswordAuthenticationFilter());
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
filter.doFilter(new MockHttpServletRequest("GET", "/api/login"), response, chain);
|
||||
filter.doFilter(new MockHttpServletRequest("GET", "/api/login"), response, chain);
|
||||
|
||||
assertThat(response.getContentAsString()).isEmpty();
|
||||
}
|
||||
assertThat(response.getContentAsString()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void generatesForWithQueryMatch() throws Exception {
|
||||
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(new UsernamePasswordAuthenticationFilter());
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
@Test
|
||||
public void generatesForWithQueryMatch() throws Exception {
|
||||
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(
|
||||
new UsernamePasswordAuthenticationFilter());
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/login");
|
||||
request.setQueryString("error");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/login");
|
||||
request.setQueryString("error");
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
assertThat(response.getContentAsString()).isNotEmpty();
|
||||
}
|
||||
assertThat(response.getContentAsString()).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void generatesForWithQueryNoMatch() throws Exception {
|
||||
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(new UsernamePasswordAuthenticationFilter());
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
@Test
|
||||
public void generatesForWithQueryNoMatch() throws Exception {
|
||||
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(
|
||||
new UsernamePasswordAuthenticationFilter());
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/login");
|
||||
request.setQueryString("not");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/login");
|
||||
request.setQueryString("not");
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
assertThat(response.getContentAsString()).isEmpty();
|
||||
}
|
||||
assertThat(response.getContentAsString()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void generatingPageWithOpenIdFilterOnlyIsSuccessFul() throws Exception {
|
||||
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(new MockProcessingFilter());
|
||||
filter.doFilter(new MockHttpServletRequest("GET", "/login"), new MockHttpServletResponse(), chain);
|
||||
}
|
||||
@Test
|
||||
public void generatingPageWithOpenIdFilterOnlyIsSuccessFul() throws Exception {
|
||||
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 {
|
||||
protected MockProcessingFilter() {
|
||||
super("/someurl");
|
||||
}
|
||||
// Fake OpenID filter (since it's not in this module
|
||||
@SuppressWarnings("unused")
|
||||
private static class MockProcessingFilter extends
|
||||
AbstractAuthenticationProcessingFilter {
|
||||
protected MockProcessingFilter() {
|
||||
super("/someurl");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
|
||||
return null;
|
||||
}
|
||||
@Override
|
||||
public Authentication attemptAuthentication(HttpServletRequest request,
|
||||
HttpServletResponse response) throws AuthenticationException {
|
||||
return null;
|
||||
}
|
||||
|
||||
public String getClaimedIdentityFieldName() {
|
||||
return "unused";
|
||||
}
|
||||
}
|
||||
public String getClaimedIdentityFieldName() {
|
||||
return "unused";
|
||||
}
|
||||
}
|
||||
|
||||
/* SEC-1111 */
|
||||
@Test
|
||||
public void handlesNonIso8859CharsInErrorMessage() throws Exception {
|
||||
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(new UsernamePasswordAuthenticationFilter());
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/login");
|
||||
request.addParameter("login_error", "true");
|
||||
MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
|
||||
String message = messages.getMessage(
|
||||
"AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials", Locale.KOREA);
|
||||
request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, new BadCredentialsException(message));
|
||||
/* SEC-1111 */
|
||||
@Test
|
||||
public void handlesNonIso8859CharsInErrorMessage() throws Exception {
|
||||
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(
|
||||
new UsernamePasswordAuthenticationFilter());
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/login");
|
||||
request.addParameter("login_error", "true");
|
||||
MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
|
||||
String message = messages.getMessage(
|
||||
"AbstractUserDetailsAuthenticationProvider.badCredentials",
|
||||
"Bad credentials", Locale.KOREA);
|
||||
request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION,
|
||||
new BadCredentialsException(message));
|
||||
|
||||
filter.doFilter(request, new MockHttpServletResponse(), chain);
|
||||
}
|
||||
filter.doFilter(request, new MockHttpServletResponse(), chain);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,42 +20,40 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
@ContextConfiguration(locations = "classpath:org/springframework/security/web/authentication/DelegatingAuthenticationEntryPointTest-context.xml")
|
||||
public class DelegatingAuthenticationEntryPointContextTests {
|
||||
|
||||
@Autowired
|
||||
private DelegatingAuthenticationEntryPoint daep;
|
||||
@Autowired
|
||||
private DelegatingAuthenticationEntryPoint daep;
|
||||
|
||||
@Autowired
|
||||
@Qualifier("firstAEP")
|
||||
private AuthenticationEntryPoint firstAEP;
|
||||
@Autowired
|
||||
@Qualifier("firstAEP")
|
||||
private AuthenticationEntryPoint firstAEP;
|
||||
|
||||
@Autowired
|
||||
@Qualifier("defaultAEP")
|
||||
private AuthenticationEntryPoint defaultAEP;
|
||||
@Autowired
|
||||
@Qualifier("defaultAEP")
|
||||
private AuthenticationEntryPoint defaultAEP;
|
||||
|
||||
@Test
|
||||
@DirtiesContext
|
||||
public void testFirstAEP() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRemoteAddr("192.168.1.10");
|
||||
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));
|
||||
@Test
|
||||
@DirtiesContext
|
||||
public void testFirstAEP() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRemoteAddr("192.168.1.10");
|
||||
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));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DirtiesContext
|
||||
public void testDefaultAEP() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
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));
|
||||
@Test
|
||||
@DirtiesContext
|
||||
public void testDefaultAEP() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
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));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -36,66 +36,66 @@ 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();
|
||||
private DelegatingAuthenticationEntryPoint daep;
|
||||
private LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPoints;
|
||||
private AuthenticationEntryPoint defaultEntryPoint;
|
||||
private HttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
@Before
|
||||
public void before() {
|
||||
defaultEntryPoint = mock(AuthenticationEntryPoint.class);
|
||||
entryPoints = new LinkedHashMap<RequestMatcher, AuthenticationEntryPoint>();
|
||||
daep = new DelegatingAuthenticationEntryPoint(entryPoints);
|
||||
daep.setDefaultEntryPoint(defaultEntryPoint);
|
||||
}
|
||||
@Before
|
||||
public void before() {
|
||||
defaultEntryPoint = mock(AuthenticationEntryPoint.class);
|
||||
entryPoints = new LinkedHashMap<RequestMatcher, AuthenticationEntryPoint>();
|
||||
daep = new DelegatingAuthenticationEntryPoint(entryPoints);
|
||||
daep.setDefaultEntryPoint(defaultEntryPoint);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDefaultEntryPoint() throws Exception {
|
||||
AuthenticationEntryPoint firstAEP = mock(AuthenticationEntryPoint.class);
|
||||
RequestMatcher firstRM = mock(RequestMatcher.class);
|
||||
when(firstRM.matches(request)).thenReturn(false);
|
||||
entryPoints.put(firstRM, firstAEP);
|
||||
@Test
|
||||
public void testDefaultEntryPoint() throws Exception {
|
||||
AuthenticationEntryPoint firstAEP = mock(AuthenticationEntryPoint.class);
|
||||
RequestMatcher firstRM = mock(RequestMatcher.class);
|
||||
when(firstRM.matches(request)).thenReturn(false);
|
||||
entryPoints.put(firstRM, firstAEP);
|
||||
|
||||
daep.commence(request, null, null);
|
||||
daep.commence(request, null, null);
|
||||
|
||||
verify(defaultEntryPoint).commence(request, null, null);
|
||||
verify(firstAEP, never()).commence(request, null, null);
|
||||
}
|
||||
verify(defaultEntryPoint).commence(request, null, null);
|
||||
verify(firstAEP, never()).commence(request, null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFirstEntryPoint() throws Exception {
|
||||
AuthenticationEntryPoint firstAEP = mock(AuthenticationEntryPoint.class);
|
||||
RequestMatcher firstRM = mock(RequestMatcher.class);
|
||||
AuthenticationEntryPoint secondAEP = mock(AuthenticationEntryPoint.class);
|
||||
RequestMatcher secondRM = mock(RequestMatcher.class);
|
||||
when(firstRM.matches(request)).thenReturn(true);
|
||||
entryPoints.put(firstRM, firstAEP);
|
||||
entryPoints.put(secondRM, secondAEP);
|
||||
@Test
|
||||
public void testFirstEntryPoint() throws Exception {
|
||||
AuthenticationEntryPoint firstAEP = mock(AuthenticationEntryPoint.class);
|
||||
RequestMatcher firstRM = mock(RequestMatcher.class);
|
||||
AuthenticationEntryPoint secondAEP = mock(AuthenticationEntryPoint.class);
|
||||
RequestMatcher secondRM = mock(RequestMatcher.class);
|
||||
when(firstRM.matches(request)).thenReturn(true);
|
||||
entryPoints.put(firstRM, firstAEP);
|
||||
entryPoints.put(secondRM, secondAEP);
|
||||
|
||||
daep.commence(request, null, null);
|
||||
daep.commence(request, null, null);
|
||||
|
||||
verify(firstAEP).commence(request, null, null);
|
||||
verify(secondAEP, never()).commence(request, null, null);
|
||||
verify(defaultEntryPoint, never()).commence(request, null, null);
|
||||
verify(secondRM, never()).matches(request);
|
||||
}
|
||||
verify(firstAEP).commence(request, null, null);
|
||||
verify(secondAEP, never()).commence(request, null, null);
|
||||
verify(defaultEntryPoint, never()).commence(request, null, null);
|
||||
verify(secondRM, never()).matches(request);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSecondEntryPoint() throws Exception {
|
||||
AuthenticationEntryPoint firstAEP = mock(AuthenticationEntryPoint.class);
|
||||
RequestMatcher firstRM = mock(RequestMatcher.class);
|
||||
AuthenticationEntryPoint secondAEP = mock(AuthenticationEntryPoint.class);
|
||||
RequestMatcher secondRM = mock(RequestMatcher.class);
|
||||
when(firstRM.matches(request)).thenReturn(false);
|
||||
when(secondRM.matches(request)).thenReturn(true);
|
||||
entryPoints.put(firstRM, firstAEP);
|
||||
entryPoints.put(secondRM, secondAEP);
|
||||
@Test
|
||||
public void testSecondEntryPoint() throws Exception {
|
||||
AuthenticationEntryPoint firstAEP = mock(AuthenticationEntryPoint.class);
|
||||
RequestMatcher firstRM = mock(RequestMatcher.class);
|
||||
AuthenticationEntryPoint secondAEP = mock(AuthenticationEntryPoint.class);
|
||||
RequestMatcher secondRM = mock(RequestMatcher.class);
|
||||
when(firstRM.matches(request)).thenReturn(false);
|
||||
when(secondRM.matches(request)).thenReturn(true);
|
||||
entryPoints.put(firstRM, firstAEP);
|
||||
entryPoints.put(secondRM, secondAEP);
|
||||
|
||||
daep.commence(request, null, null);
|
||||
daep.commence(request, null, null);
|
||||
|
||||
verify(secondAEP).commence(request, null, null);
|
||||
verify(firstAEP, never()).commence(request, null, null);
|
||||
verify(defaultEntryPoint, never()).commence(request, null, null);
|
||||
}
|
||||
verify(secondAEP).commence(request, null, null);
|
||||
verify(firstAEP, never()).commence(request, null, null);
|
||||
verify(defaultEntryPoint, never()).commence(request, null, null);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -36,7 +36,8 @@ import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyZeroInteractions;
|
||||
|
||||
/**
|
||||
* Test class for {@link org.springframework.security.web.authentication.DelegatingAuthenticationFailureHandler}
|
||||
* Test class for
|
||||
* {@link org.springframework.security.web.authentication.DelegatingAuthenticationFailureHandler}
|
||||
*
|
||||
* @author Kazuki shimizu
|
||||
* @since 4.0
|
||||
@@ -44,100 +45,101 @@ import static org.mockito.Mockito.verifyZeroInteractions;
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class DelegatingAuthenticationFailureHandlerTests {
|
||||
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
@Mock
|
||||
private AuthenticationFailureHandler handler1;
|
||||
@Mock
|
||||
private AuthenticationFailureHandler handler1;
|
||||
|
||||
@Mock
|
||||
private AuthenticationFailureHandler handler2;
|
||||
@Mock
|
||||
private AuthenticationFailureHandler handler2;
|
||||
|
||||
@Mock
|
||||
private AuthenticationFailureHandler defaultHandler;
|
||||
@Mock
|
||||
private AuthenticationFailureHandler defaultHandler;
|
||||
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
|
||||
@Mock
|
||||
private HttpServletResponse response;
|
||||
@Mock
|
||||
private HttpServletResponse response;
|
||||
|
||||
private LinkedHashMap<Class<? extends AuthenticationException>, AuthenticationFailureHandler> handlers;
|
||||
private LinkedHashMap<Class<? extends AuthenticationException>, AuthenticationFailureHandler> handlers;
|
||||
|
||||
private DelegatingAuthenticationFailureHandler handler;
|
||||
private DelegatingAuthenticationFailureHandler handler;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
handlers = new LinkedHashMap<Class<? extends AuthenticationException>, AuthenticationFailureHandler>();
|
||||
}
|
||||
@Before
|
||||
public void setup() {
|
||||
handlers = new LinkedHashMap<Class<? extends AuthenticationException>, AuthenticationFailureHandler>();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void handleByDefaultHandler() throws Exception {
|
||||
handlers.put(BadCredentialsException.class, handler1);
|
||||
handler = new DelegatingAuthenticationFailureHandler(handlers, defaultHandler);
|
||||
@Test
|
||||
public void handleByDefaultHandler() throws Exception {
|
||||
handlers.put(BadCredentialsException.class, handler1);
|
||||
handler = new DelegatingAuthenticationFailureHandler(handlers, defaultHandler);
|
||||
|
||||
AuthenticationException exception = new AccountExpiredException("");
|
||||
handler.onAuthenticationFailure(request, response, exception);
|
||||
AuthenticationException exception = new AccountExpiredException("");
|
||||
handler.onAuthenticationFailure(request, response, exception);
|
||||
|
||||
verifyZeroInteractions(handler1, handler2);
|
||||
verify(defaultHandler).onAuthenticationFailure(request, response, exception);
|
||||
}
|
||||
verifyZeroInteractions(handler1, handler2);
|
||||
verify(defaultHandler).onAuthenticationFailure(request, response, exception);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void handleByMappedHandlerWithSameType() throws Exception {
|
||||
handlers.put(BadCredentialsException.class, handler1); // same type
|
||||
handlers.put(AccountStatusException.class, handler2);
|
||||
handler = new DelegatingAuthenticationFailureHandler(handlers, defaultHandler);
|
||||
@Test
|
||||
public void handleByMappedHandlerWithSameType() throws Exception {
|
||||
handlers.put(BadCredentialsException.class, handler1); // same type
|
||||
handlers.put(AccountStatusException.class, handler2);
|
||||
handler = new DelegatingAuthenticationFailureHandler(handlers, defaultHandler);
|
||||
|
||||
AuthenticationException exception = new BadCredentialsException("");
|
||||
handler.onAuthenticationFailure(request, response, exception);
|
||||
AuthenticationException exception = new BadCredentialsException("");
|
||||
handler.onAuthenticationFailure(request, response, exception);
|
||||
|
||||
verifyZeroInteractions(handler2, defaultHandler);
|
||||
verify(handler1).onAuthenticationFailure(request, response, exception);
|
||||
}
|
||||
verifyZeroInteractions(handler2, defaultHandler);
|
||||
verify(handler1).onAuthenticationFailure(request, response, exception);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void handleByMappedHandlerWithSuperType() throws Exception {
|
||||
handlers.put(BadCredentialsException.class, handler1);
|
||||
handlers.put(AccountStatusException.class, handler2); // super type of CredentialsExpiredException
|
||||
handler = new DelegatingAuthenticationFailureHandler(handlers, defaultHandler);
|
||||
@Test
|
||||
public void handleByMappedHandlerWithSuperType() throws Exception {
|
||||
handlers.put(BadCredentialsException.class, handler1);
|
||||
handlers.put(AccountStatusException.class, handler2); // super type of
|
||||
// CredentialsExpiredException
|
||||
handler = new DelegatingAuthenticationFailureHandler(handlers, defaultHandler);
|
||||
|
||||
AuthenticationException exception = new CredentialsExpiredException("");
|
||||
handler.onAuthenticationFailure(request, response, exception);
|
||||
AuthenticationException exception = new CredentialsExpiredException("");
|
||||
handler.onAuthenticationFailure(request, response, exception);
|
||||
|
||||
verifyZeroInteractions(handler1, defaultHandler);
|
||||
verify(handler2).onAuthenticationFailure(request, response, exception);
|
||||
}
|
||||
verifyZeroInteractions(handler1, defaultHandler);
|
||||
verify(handler2).onAuthenticationFailure(request, response, exception);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void handlersIsNull() {
|
||||
@Test
|
||||
public void handlersIsNull() {
|
||||
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
thrown.expectMessage("handlers cannot be null or empty");
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
thrown.expectMessage("handlers cannot be null or empty");
|
||||
|
||||
new DelegatingAuthenticationFailureHandler(null, defaultHandler);
|
||||
new DelegatingAuthenticationFailureHandler(null, defaultHandler);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void handlersIsEmpty() {
|
||||
@Test
|
||||
public void handlersIsEmpty() {
|
||||
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
thrown.expectMessage("handlers cannot be null or empty");
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
thrown.expectMessage("handlers cannot be null or empty");
|
||||
|
||||
new DelegatingAuthenticationFailureHandler(handlers, defaultHandler);
|
||||
new DelegatingAuthenticationFailureHandler(handlers, defaultHandler);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void defaultHandlerIsNull() {
|
||||
@Test
|
||||
public void defaultHandlerIsNull() {
|
||||
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
thrown.expectMessage("defaultHandler cannot be null");
|
||||
thrown.expect(IllegalArgumentException.class);
|
||||
thrown.expectMessage("defaultHandler cannot be null");
|
||||
|
||||
handlers.put(BadCredentialsException.class, handler1);
|
||||
new DelegatingAuthenticationFailureHandler(handlers, null);
|
||||
handlers.put(BadCredentialsException.class, handler1);
|
||||
new DelegatingAuthenticationFailureHandler(handlers, null);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -16,27 +16,31 @@ import java.util.HashMap;
|
||||
*/
|
||||
public class ExceptionMappingAuthenticationFailureHandlerTests {
|
||||
|
||||
@Test
|
||||
public void defaultTargetUrlIsUsedIfNoMappingExists() throws Exception {
|
||||
ExceptionMappingAuthenticationFailureHandler fh = new ExceptionMappingAuthenticationFailureHandler();
|
||||
fh.setDefaultFailureUrl("/failed");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
fh.onAuthenticationFailure(new MockHttpServletRequest(), response, new BadCredentialsException(""));
|
||||
@Test
|
||||
public void defaultTargetUrlIsUsedIfNoMappingExists() throws Exception {
|
||||
ExceptionMappingAuthenticationFailureHandler fh = new ExceptionMappingAuthenticationFailureHandler();
|
||||
fh.setDefaultFailureUrl("/failed");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
fh.onAuthenticationFailure(new MockHttpServletRequest(), response,
|
||||
new BadCredentialsException(""));
|
||||
|
||||
assertEquals("/failed", response.getRedirectedUrl());
|
||||
}
|
||||
assertEquals("/failed", response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void exceptionMapIsUsedIfMappingExists() throws Exception {
|
||||
ExceptionMappingAuthenticationFailureHandler fh = new ExceptionMappingAuthenticationFailureHandler();
|
||||
HashMap<String, String> mapping = new HashMap<String, String>();
|
||||
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(""));
|
||||
@Test
|
||||
public void exceptionMapIsUsedIfMappingExists() throws Exception {
|
||||
ExceptionMappingAuthenticationFailureHandler fh = new ExceptionMappingAuthenticationFailureHandler();
|
||||
HashMap<String, String> mapping = new HashMap<String, String>();
|
||||
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(""));
|
||||
|
||||
assertEquals("/badcreds", response.getRedirectedUrl());
|
||||
}
|
||||
assertEquals("/badcreds", response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -30,31 +30,32 @@ import org.springframework.security.core.AuthenticationException;
|
||||
* @since 4.0
|
||||
*/
|
||||
public class HttpStatusEntryPointTests {
|
||||
MockHttpServletRequest request;
|
||||
MockHttpServletResponse response;
|
||||
AuthenticationException authException;
|
||||
MockHttpServletRequest request;
|
||||
MockHttpServletResponse response;
|
||||
AuthenticationException authException;
|
||||
|
||||
HttpStatusEntryPoint entryPoint;
|
||||
HttpStatusEntryPoint entryPoint;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
@Before
|
||||
public void setup() {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
authException = new AuthenticationException("") {};
|
||||
entryPoint = new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
@SuppressWarnings("serial")
|
||||
@Before
|
||||
public void setup() {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
authException = new AuthenticationException("") {
|
||||
};
|
||||
entryPoint = new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullStatus() {
|
||||
new HttpStatusEntryPoint(null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullStatus() {
|
||||
new HttpStatusEntryPoint(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void unauthorized() throws Exception {
|
||||
entryPoint.commence(request, response, authException);
|
||||
@Test
|
||||
public void unauthorized() throws Exception {
|
||||
entryPoint.commence(request, response, authException);
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
|
||||
}
|
||||
assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -25,7 +25,6 @@ import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.MockPortResolver;
|
||||
import org.springframework.security.web.PortMapperImpl;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link LoginUrlAuthenticationEntryPoint}.
|
||||
*
|
||||
@@ -33,222 +32,246 @@ import org.springframework.security.web.PortMapperImpl;
|
||||
* @author colin sampaleanu
|
||||
*/
|
||||
public class LoginUrlAuthenticationEntryPointTests {
|
||||
//~ Methods ========================================================================================================
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testDetectsMissingLoginFormUrl() throws Exception {
|
||||
new LoginUrlAuthenticationEntryPoint(null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testDetectsMissingLoginFormUrl() throws Exception {
|
||||
new LoginUrlAuthenticationEntryPoint(null);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testDetectsMissingPortMapper() throws Exception {
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/login");
|
||||
ep.setPortMapper(null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testDetectsMissingPortMapper() throws Exception {
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(
|
||||
"/login");
|
||||
ep.setPortMapper(null);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testDetectsMissingPortResolver() throws Exception {
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/login");
|
||||
ep.setPortResolver(null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testDetectsMissingPortResolver() throws Exception {
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(
|
||||
"/login");
|
||||
ep.setPortResolver(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGettersSetters() {
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(8080, 8443));
|
||||
assertEquals("/hello", ep.getLoginFormUrl());
|
||||
assertTrue(ep.getPortMapper() != null);
|
||||
assertTrue(ep.getPortResolver() != null);
|
||||
@Test
|
||||
public void testGettersSetters() {
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(
|
||||
"/hello");
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(8080, 8443));
|
||||
assertEquals("/hello", ep.getLoginFormUrl());
|
||||
assertTrue(ep.getPortMapper() != null);
|
||||
assertTrue(ep.getPortResolver() != null);
|
||||
|
||||
ep.setForceHttps(false);
|
||||
assertFalse(ep.isForceHttps());
|
||||
ep.setForceHttps(true);
|
||||
assertTrue(ep.isForceHttps());
|
||||
assertFalse(ep.isUseForward());
|
||||
ep.setUseForward(true);
|
||||
assertTrue(ep.isUseForward());
|
||||
}
|
||||
ep.setForceHttps(false);
|
||||
assertFalse(ep.isForceHttps());
|
||||
ep.setForceHttps(true);
|
||||
assertTrue(ep.isForceHttps());
|
||||
assertFalse(ep.isUseForward());
|
||||
ep.setUseForward(true);
|
||||
assertTrue(ep.isUseForward());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpsOperationFromOriginalHttpUrl() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/some_path");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setServerPort(80);
|
||||
@Test
|
||||
public void testHttpsOperationFromOriginalHttpUrl() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/some_path");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setServerPort(80);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setForceHttps(true);
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(80, 443));
|
||||
ep.afterPropertiesSet();
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(
|
||||
"/hello");
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setForceHttps(true);
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(80, 443));
|
||||
ep.afterPropertiesSet();
|
||||
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("https://www.example.com/bigWebApp/hello", response.getRedirectedUrl());
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("https://www.example.com/bigWebApp/hello",
|
||||
response.getRedirectedUrl());
|
||||
|
||||
request.setServerPort(8080);
|
||||
response = new MockHttpServletResponse();
|
||||
ep.setPortResolver(new MockPortResolver(8080, 8443));
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("https://www.example.com:8443/bigWebApp/hello", response.getRedirectedUrl());
|
||||
request.setServerPort(8080);
|
||||
response = new MockHttpServletResponse();
|
||||
ep.setPortResolver(new MockPortResolver(8080, 8443));
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("https://www.example.com:8443/bigWebApp/hello",
|
||||
response.getRedirectedUrl());
|
||||
|
||||
// Now test an unusual custom HTTP:HTTPS is handled properly
|
||||
request.setServerPort(8888);
|
||||
response = new MockHttpServletResponse();
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("https://www.example.com:8443/bigWebApp/hello", response.getRedirectedUrl());
|
||||
// Now test an unusual custom HTTP:HTTPS is handled properly
|
||||
request.setServerPort(8888);
|
||||
response = new MockHttpServletResponse();
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("https://www.example.com:8443/bigWebApp/hello",
|
||||
response.getRedirectedUrl());
|
||||
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
Map<String,String> map = new HashMap<String,String>();
|
||||
map.put("8888", "9999");
|
||||
portMapper.setPortMappings(map);
|
||||
response = new MockHttpServletResponse();
|
||||
PortMapperImpl portMapper = new PortMapperImpl();
|
||||
Map<String, String> map = new HashMap<String, String>();
|
||||
map.put("8888", "9999");
|
||||
portMapper.setPortMappings(map);
|
||||
response = new MockHttpServletResponse();
|
||||
|
||||
ep = new LoginUrlAuthenticationEntryPoint("/hello");
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setForceHttps(true);
|
||||
ep.setPortMapper(portMapper);
|
||||
ep.setPortResolver(new MockPortResolver(8888, 9999));
|
||||
ep.afterPropertiesSet();
|
||||
ep = new LoginUrlAuthenticationEntryPoint("/hello");
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setForceHttps(true);
|
||||
ep.setPortMapper(portMapper);
|
||||
ep.setPortResolver(new MockPortResolver(8888, 9999));
|
||||
ep.afterPropertiesSet();
|
||||
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("https://www.example.com:9999/bigWebApp/hello", response.getRedirectedUrl());
|
||||
}
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("https://www.example.com:9999/bigWebApp/hello",
|
||||
response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHttpsOperationFromOriginalHttpsUrl() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/some_path");
|
||||
request.setScheme("https");
|
||||
request.setServerName("www.example.com");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setServerPort(443);
|
||||
@Test
|
||||
public void testHttpsOperationFromOriginalHttpsUrl() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/some_path");
|
||||
request.setScheme("https");
|
||||
request.setServerName("www.example.com");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setServerPort(443);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setForceHttps(true);
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(80, 443));
|
||||
ep.afterPropertiesSet();
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(
|
||||
"/hello");
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setForceHttps(true);
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(80, 443));
|
||||
ep.afterPropertiesSet();
|
||||
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("https://www.example.com/bigWebApp/hello", response.getRedirectedUrl());
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("https://www.example.com/bigWebApp/hello",
|
||||
response.getRedirectedUrl());
|
||||
|
||||
request.setServerPort(8443);
|
||||
response = new MockHttpServletResponse();
|
||||
ep.setPortResolver(new MockPortResolver(8080, 8443));
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("https://www.example.com:8443/bigWebApp/hello", response.getRedirectedUrl());
|
||||
}
|
||||
request.setServerPort(8443);
|
||||
response = new MockHttpServletResponse();
|
||||
ep.setPortResolver(new MockPortResolver(8080, 8443));
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("https://www.example.com:8443/bigWebApp/hello",
|
||||
response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNormalOperation() throws Exception {
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(80, 443));
|
||||
ep.afterPropertiesSet();
|
||||
@Test
|
||||
public void testNormalOperation() throws Exception {
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(
|
||||
"/hello");
|
||||
ep.setPortMapper(new PortMapperImpl());
|
||||
ep.setPortResolver(new MockPortResolver(80, 443));
|
||||
ep.afterPropertiesSet();
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/some_path");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setServerPort(80);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/some_path");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setServerPort(80);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("http://www.example.com/bigWebApp/hello", response.getRedirectedUrl());
|
||||
}
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("http://www.example.com/bigWebApp/hello",
|
||||
response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOperationWhenHttpsRequestsButHttpsPortUnknown() throws Exception {
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
|
||||
ep.setPortResolver(new MockPortResolver(8888, 1234));
|
||||
ep.setForceHttps(true);
|
||||
ep.afterPropertiesSet();
|
||||
@Test
|
||||
public void testOperationWhenHttpsRequestsButHttpsPortUnknown() throws Exception {
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(
|
||||
"/hello");
|
||||
ep.setPortResolver(new MockPortResolver(8888, 1234));
|
||||
ep.setForceHttps(true);
|
||||
ep.afterPropertiesSet();
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/some_path");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setServerPort(8888); // NB: Port we can't resolve
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/some_path");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setServerPort(8888); // NB: Port we can't resolve
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
ep.commence(request, response, null);
|
||||
ep.commence(request, response, null);
|
||||
|
||||
// Response doesn't switch to HTTPS, as we didn't know HTTP port 8888 to HTTP port mapping
|
||||
assertEquals("http://www.example.com:8888/bigWebApp/hello", response.getRedirectedUrl());
|
||||
}
|
||||
// Response doesn't switch to HTTPS, as we didn't know HTTP port 8888 to HTTP port
|
||||
// mapping
|
||||
assertEquals("http://www.example.com:8888/bigWebApp/hello",
|
||||
response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testServerSideRedirectWithoutForceHttpsForwardsToLoginPage() throws Exception {
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
|
||||
ep.setUseForward(true);
|
||||
ep.afterPropertiesSet();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/bigWebApp/some_path");
|
||||
request.setServletPath("/some_path");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setServerPort(80);
|
||||
@Test
|
||||
public void testServerSideRedirectWithoutForceHttpsForwardsToLoginPage()
|
||||
throws Exception {
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(
|
||||
"/hello");
|
||||
ep.setUseForward(true);
|
||||
ep.afterPropertiesSet();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/bigWebApp/some_path");
|
||||
request.setServletPath("/some_path");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setServerPort(80);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("/hello", response.getForwardedUrl());
|
||||
}
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("/hello", response.getForwardedUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testServerSideRedirectWithForceHttpsRedirectsCurrentRequest() throws Exception {
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("/hello");
|
||||
ep.setUseForward(true);
|
||||
ep.setForceHttps(true);
|
||||
ep.afterPropertiesSet();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/bigWebApp/some_path");
|
||||
request.setServletPath("/some_path");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setServerPort(80);
|
||||
@Test
|
||||
public void testServerSideRedirectWithForceHttpsRedirectsCurrentRequest()
|
||||
throws Exception {
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(
|
||||
"/hello");
|
||||
ep.setUseForward(true);
|
||||
ep.setForceHttps(true);
|
||||
ep.afterPropertiesSet();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/bigWebApp/some_path");
|
||||
request.setServletPath("/some_path");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setScheme("http");
|
||||
request.setServerName("www.example.com");
|
||||
request.setContextPath("/bigWebApp");
|
||||
request.setServerPort(80);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("https://www.example.com/bigWebApp/some_path", response.getRedirectedUrl());
|
||||
}
|
||||
ep.commence(request, response, null);
|
||||
assertEquals("https://www.example.com/bigWebApp/some_path",
|
||||
response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
// SEC-1498
|
||||
@Test
|
||||
public void absoluteLoginFormUrlIsSupported() throws Exception {
|
||||
final String loginFormUrl = "http://somesite.com/login";
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(loginFormUrl);
|
||||
ep.afterPropertiesSet();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
ep.commence(new MockHttpServletRequest("GET", "/someUrl"), response, null);
|
||||
assertEquals(loginFormUrl, response.getRedirectedUrl());
|
||||
}
|
||||
// SEC-1498
|
||||
@Test
|
||||
public void absoluteLoginFormUrlIsSupported() throws Exception {
|
||||
final String loginFormUrl = "http://somesite.com/login";
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(
|
||||
loginFormUrl);
|
||||
ep.afterPropertiesSet();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
ep.commence(new MockHttpServletRequest("GET", "/someUrl"), response, null);
|
||||
assertEquals(loginFormUrl, response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void absoluteLoginFormUrlCantBeUsedWithForwarding() throws Exception {
|
||||
final String loginFormUrl = "http://somesite.com/login";
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint("http://somesite.com/login");
|
||||
ep.setUseForward(true);
|
||||
ep.afterPropertiesSet();
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void absoluteLoginFormUrlCantBeUsedWithForwarding() throws Exception {
|
||||
final String loginFormUrl = "http://somesite.com/login";
|
||||
LoginUrlAuthenticationEntryPoint ep = new LoginUrlAuthenticationEntryPoint(
|
||||
"http://somesite.com/login");
|
||||
ep.setUseForward(true);
|
||||
ep.afterPropertiesSet();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,36 +13,38 @@ import org.springframework.security.web.savedrequest.SavedRequest;
|
||||
|
||||
public class SavedRequestAwareAuthenticationSuccessHandlerTests {
|
||||
|
||||
@Test
|
||||
public void defaultUrlMuststartWithSlashOrHttpScheme() {
|
||||
SavedRequestAwareAuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler();
|
||||
@Test
|
||||
public void defaultUrlMuststartWithSlashOrHttpScheme() {
|
||||
SavedRequestAwareAuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler();
|
||||
|
||||
handler.setDefaultTargetUrl("/acceptableRelativeUrl");
|
||||
handler.setDefaultTargetUrl("http://some.site.org/index.html");
|
||||
handler.setDefaultTargetUrl("https://some.site.org/index.html");
|
||||
handler.setDefaultTargetUrl("/acceptableRelativeUrl");
|
||||
handler.setDefaultTargetUrl("http://some.site.org/index.html");
|
||||
handler.setDefaultTargetUrl("https://some.site.org/index.html");
|
||||
|
||||
try {
|
||||
handler.setDefaultTargetUrl("missingSlash");
|
||||
fail("Shouldn't accept default target without leading slash");
|
||||
} catch (IllegalArgumentException expected) {}
|
||||
}
|
||||
try {
|
||||
handler.setDefaultTargetUrl("missingSlash");
|
||||
fail("Shouldn't accept default target without leading slash");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void onAuthenticationSuccessHasSavedRequest() throws Exception {
|
||||
String redirectUrl = "http://localhost/appcontext/page";
|
||||
RedirectStrategy redirectStrategy = mock(RedirectStrategy.class);
|
||||
RequestCache requestCache = mock(RequestCache.class);
|
||||
SavedRequest savedRequest = mock(SavedRequest.class);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
when(savedRequest.getRedirectUrl()).thenReturn(redirectUrl);
|
||||
when(requestCache.getRequest(request, response)).thenReturn(savedRequest);
|
||||
@Test
|
||||
public void onAuthenticationSuccessHasSavedRequest() throws Exception {
|
||||
String redirectUrl = "http://localhost/appcontext/page";
|
||||
RedirectStrategy redirectStrategy = mock(RedirectStrategy.class);
|
||||
RequestCache requestCache = mock(RequestCache.class);
|
||||
SavedRequest savedRequest = mock(SavedRequest.class);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
when(savedRequest.getRedirectUrl()).thenReturn(redirectUrl);
|
||||
when(requestCache.getRequest(request, response)).thenReturn(savedRequest);
|
||||
|
||||
SavedRequestAwareAuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler();
|
||||
handler.setRequestCache(requestCache);
|
||||
handler.setRedirectStrategy(redirectStrategy);
|
||||
handler.onAuthenticationSuccess(request, response, mock(Authentication.class));
|
||||
SavedRequestAwareAuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler();
|
||||
handler.setRequestCache(requestCache);
|
||||
handler.setRedirectStrategy(redirectStrategy);
|
||||
handler.onAuthenticationSuccess(request, response, mock(Authentication.class));
|
||||
|
||||
verify(redirectStrategy).sendRedirect(request, response, redirectUrl);
|
||||
}
|
||||
verify(redirectStrategy).sendRedirect(request, response, redirectUrl);
|
||||
}
|
||||
}
|
||||
@@ -16,62 +16,67 @@ import org.springframework.security.web.WebAttributes;
|
||||
*/
|
||||
public class SimpleUrlAuthenticationFailureHandlerTests {
|
||||
|
||||
@Test
|
||||
public void error401IsReturnedIfNoUrlIsSet() throws Exception {
|
||||
SimpleUrlAuthenticationFailureHandler afh = new SimpleUrlAuthenticationFailureHandler();
|
||||
RedirectStrategy rs = mock(RedirectStrategy.class);
|
||||
afh.setRedirectStrategy(rs);
|
||||
assertSame(rs, afh.getRedirectStrategy());
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
@Test
|
||||
public void error401IsReturnedIfNoUrlIsSet() throws Exception {
|
||||
SimpleUrlAuthenticationFailureHandler afh = new SimpleUrlAuthenticationFailureHandler();
|
||||
RedirectStrategy rs = mock(RedirectStrategy.class);
|
||||
afh.setRedirectStrategy(rs);
|
||||
assertSame(rs, afh.getRedirectStrategy());
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
afh.onAuthenticationFailure(request, response, mock(AuthenticationException.class));
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
afh.onAuthenticationFailure(request, response,
|
||||
mock(AuthenticationException.class));
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void exceptionIsSavedToSessionOnRedirect() throws Exception {
|
||||
SimpleUrlAuthenticationFailureHandler afh = new SimpleUrlAuthenticationFailureHandler();
|
||||
afh.setDefaultFailureUrl("/target");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
@Test
|
||||
public void exceptionIsSavedToSessionOnRedirect() throws Exception {
|
||||
SimpleUrlAuthenticationFailureHandler afh = new SimpleUrlAuthenticationFailureHandler();
|
||||
afh.setDefaultFailureUrl("/target");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
AuthenticationException e = mock(AuthenticationException.class);
|
||||
AuthenticationException e = mock(AuthenticationException.class);
|
||||
|
||||
afh.onAuthenticationFailure(request, response, e);
|
||||
assertSame(e, request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION));
|
||||
assertEquals("/target", response.getRedirectedUrl());
|
||||
}
|
||||
afh.onAuthenticationFailure(request, response, e);
|
||||
assertSame(e,
|
||||
request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION));
|
||||
assertEquals("/target", response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void exceptionIsNotSavedIfAllowSessionCreationIsFalse() throws Exception {
|
||||
SimpleUrlAuthenticationFailureHandler afh = new SimpleUrlAuthenticationFailureHandler("/target");
|
||||
afh.setAllowSessionCreation(false);
|
||||
assertFalse(afh.isAllowSessionCreation());
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
@Test
|
||||
public void exceptionIsNotSavedIfAllowSessionCreationIsFalse() throws Exception {
|
||||
SimpleUrlAuthenticationFailureHandler afh = new SimpleUrlAuthenticationFailureHandler(
|
||||
"/target");
|
||||
afh.setAllowSessionCreation(false);
|
||||
assertFalse(afh.isAllowSessionCreation());
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
afh.onAuthenticationFailure(request, response, mock(AuthenticationException.class));
|
||||
assertNull(request.getSession(false));
|
||||
}
|
||||
afh.onAuthenticationFailure(request, response,
|
||||
mock(AuthenticationException.class));
|
||||
assertNull(request.getSession(false));
|
||||
}
|
||||
|
||||
// SEC-462
|
||||
@Test
|
||||
public void responseIsForwardedIfUseForwardIsTrue() throws Exception {
|
||||
SimpleUrlAuthenticationFailureHandler afh = new SimpleUrlAuthenticationFailureHandler("/target");
|
||||
afh.setUseForward(true);
|
||||
assertTrue(afh.isUseForward());
|
||||
// SEC-462
|
||||
@Test
|
||||
public void responseIsForwardedIfUseForwardIsTrue() throws Exception {
|
||||
SimpleUrlAuthenticationFailureHandler afh = new SimpleUrlAuthenticationFailureHandler(
|
||||
"/target");
|
||||
afh.setUseForward(true);
|
||||
assertTrue(afh.isUseForward());
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
AuthenticationException e = mock(AuthenticationException.class);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
AuthenticationException e = mock(AuthenticationException.class);
|
||||
|
||||
afh.onAuthenticationFailure(request, response, e);
|
||||
assertNull(request.getSession(false));
|
||||
assertNull(response.getRedirectedUrl());
|
||||
assertEquals("/target", response.getForwardedUrl());
|
||||
// Request scope should be used for forward
|
||||
assertSame(e, request.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION));
|
||||
}
|
||||
afh.onAuthenticationFailure(request, response, e);
|
||||
assertNull(request.getSession(false));
|
||||
assertNull(response.getRedirectedUrl());
|
||||
assertEquals("/target", response.getForwardedUrl());
|
||||
// Request scope should be used for forward
|
||||
assertSame(e, request.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -13,97 +13,105 @@ import org.springframework.security.core.Authentication;
|
||||
* @author Luke Taylor
|
||||
*/
|
||||
public class SimpleUrlAuthenticationSuccessHandlerTests {
|
||||
@Test
|
||||
public void defaultTargetUrlIsUsedIfNoOtherInformationSet() throws Exception {
|
||||
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler();
|
||||
@Test
|
||||
public void defaultTargetUrlIsUsedIfNoOtherInformationSet() throws Exception {
|
||||
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler();
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
ash.onAuthenticationSuccess(request, response, mock(Authentication.class));
|
||||
ash.onAuthenticationSuccess(request, response, mock(Authentication.class));
|
||||
|
||||
assertEquals("/", response.getRedirectedUrl());
|
||||
}
|
||||
assertEquals("/", response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
// SEC-1428
|
||||
@Test
|
||||
public void redirectIsNotPerformedIfResponseIsCommitted() throws Exception {
|
||||
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler("/target");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
response.setCommitted(true);
|
||||
// SEC-1428
|
||||
@Test
|
||||
public void redirectIsNotPerformedIfResponseIsCommitted() throws Exception {
|
||||
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler(
|
||||
"/target");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
response.setCommitted(true);
|
||||
|
||||
ash.onAuthenticationSuccess(request, response, mock(Authentication.class));
|
||||
assertNull(response.getRedirectedUrl());
|
||||
}
|
||||
ash.onAuthenticationSuccess(request, response, mock(Authentication.class));
|
||||
assertNull(response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
/**
|
||||
* SEC-213
|
||||
*/
|
||||
@Test
|
||||
public void targetUrlParameterIsUsedIfPresentAndParameterNameIsSet() throws Exception {
|
||||
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler("/defaultTarget");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
request.setParameter("targetUrl", "/target");
|
||||
/**
|
||||
* SEC-213
|
||||
*/
|
||||
@Test
|
||||
public void targetUrlParameterIsUsedIfPresentAndParameterNameIsSet() throws Exception {
|
||||
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler(
|
||||
"/defaultTarget");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
request.setParameter("targetUrl", "/target");
|
||||
|
||||
ash.onAuthenticationSuccess(request, response, mock(Authentication.class));
|
||||
assertEquals("/defaultTarget", response.getRedirectedUrl());
|
||||
ash.onAuthenticationSuccess(request, response, mock(Authentication.class));
|
||||
assertEquals("/defaultTarget", response.getRedirectedUrl());
|
||||
|
||||
// Try with parameter set
|
||||
ash.setTargetUrlParameter("targetUrl");
|
||||
response = new MockHttpServletResponse();
|
||||
ash.onAuthenticationSuccess(request, response, mock(Authentication.class));
|
||||
assertEquals("/target", response.getRedirectedUrl());
|
||||
}
|
||||
// Try with parameter set
|
||||
ash.setTargetUrlParameter("targetUrl");
|
||||
response = new MockHttpServletResponse();
|
||||
ash.onAuthenticationSuccess(request, response, mock(Authentication.class));
|
||||
assertEquals("/target", response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void refererIsUsedIfUseRefererIsSet() throws Exception {
|
||||
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler("/defaultTarget");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
ash.setUseReferer(true);
|
||||
request.addHeader("Referer", "http://www.springsource.com/");
|
||||
@Test
|
||||
public void refererIsUsedIfUseRefererIsSet() throws Exception {
|
||||
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler(
|
||||
"/defaultTarget");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
ash.setUseReferer(true);
|
||||
request.addHeader("Referer", "http://www.springsource.com/");
|
||||
|
||||
ash.onAuthenticationSuccess(request, response, mock(Authentication.class));
|
||||
assertEquals("http://www.springsource.com/", response.getRedirectedUrl());
|
||||
}
|
||||
ash.onAuthenticationSuccess(request, response, mock(Authentication.class));
|
||||
assertEquals("http://www.springsource.com/", response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
/**
|
||||
* SEC-297 fix.
|
||||
*/
|
||||
@Test
|
||||
public void absoluteDefaultTargetUrlDoesNotHaveContextPathPrepended() throws Exception {
|
||||
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler();
|
||||
ash.setDefaultTargetUrl("https://monkeymachine.co.uk/");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
/**
|
||||
* SEC-297 fix.
|
||||
*/
|
||||
@Test
|
||||
public void absoluteDefaultTargetUrlDoesNotHaveContextPathPrepended()
|
||||
throws Exception {
|
||||
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler();
|
||||
ash.setDefaultTargetUrl("https://monkeymachine.co.uk/");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
ash.onAuthenticationSuccess(request, response, mock(Authentication.class));
|
||||
ash.onAuthenticationSuccess(request, response, mock(Authentication.class));
|
||||
|
||||
assertEquals("https://monkeymachine.co.uk/", response.getRedirectedUrl());
|
||||
}
|
||||
assertEquals("https://monkeymachine.co.uk/", response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setTargetUrlParameterNullTargetUrlParameter() {
|
||||
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler();
|
||||
ash.setTargetUrlParameter("targetUrl");
|
||||
ash.setTargetUrlParameter(null);
|
||||
assertEquals(null,ash.getTargetUrlParameter());
|
||||
}
|
||||
@Test
|
||||
public void setTargetUrlParameterNullTargetUrlParameter() {
|
||||
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler();
|
||||
ash.setTargetUrlParameter("targetUrl");
|
||||
ash.setTargetUrlParameter(null);
|
||||
assertEquals(null, ash.getTargetUrlParameter());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setTargetUrlParameterEmptyTargetUrlParameter() {
|
||||
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler();
|
||||
@Test
|
||||
public void setTargetUrlParameterEmptyTargetUrlParameter() {
|
||||
SimpleUrlAuthenticationSuccessHandler ash = new SimpleUrlAuthenticationSuccessHandler();
|
||||
|
||||
try {
|
||||
ash.setTargetUrlParameter("");
|
||||
fail("Expected Exception");
|
||||
}catch(IllegalArgumentException success) {}
|
||||
try {
|
||||
ash.setTargetUrlParameter("");
|
||||
fail("Expected Exception");
|
||||
}
|
||||
catch (IllegalArgumentException success) {
|
||||
}
|
||||
|
||||
try {
|
||||
ash.setTargetUrlParameter(" ");
|
||||
fail("Expected Exception");
|
||||
}catch(IllegalArgumentException success) {}
|
||||
}
|
||||
try {
|
||||
ash.setTargetUrlParameter(" ");
|
||||
fail("Expected Exception");
|
||||
}
|
||||
catch (IllegalArgumentException success) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@
|
||||
|
||||
package org.springframework.security.web.authentication;
|
||||
|
||||
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@@ -33,120 +32,145 @@ import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link UsernamePasswordAuthenticationFilter}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class UsernamePasswordAuthenticationFilterTests extends TestCase {
|
||||
//~ Methods ========================================================================================================
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
@Test
|
||||
public void testNormalOperation() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
|
||||
request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod");
|
||||
request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "koala");
|
||||
@Test
|
||||
public void testNormalOperation() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
|
||||
request.addParameter(
|
||||
UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY,
|
||||
"rod");
|
||||
request.addParameter(
|
||||
UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY,
|
||||
"koala");
|
||||
|
||||
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
// filter.init(null);
|
||||
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
// filter.init(null);
|
||||
|
||||
Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse());
|
||||
assertTrue(result != null);
|
||||
assertEquals("127.0.0.1", ((WebAuthenticationDetails) result.getDetails()).getRemoteAddress());
|
||||
}
|
||||
Authentication result = filter.attemptAuthentication(request,
|
||||
new MockHttpServletResponse());
|
||||
assertTrue(result != null);
|
||||
assertEquals("127.0.0.1",
|
||||
((WebAuthenticationDetails) result.getDetails()).getRemoteAddress());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNullPasswordHandledGracefully() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
|
||||
request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, "rod");
|
||||
@Test
|
||||
public void testNullPasswordHandledGracefully() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
|
||||
request.addParameter(
|
||||
UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY,
|
||||
"rod");
|
||||
|
||||
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
assertNotNull(filter.attemptAuthentication(request, new MockHttpServletResponse()));
|
||||
}
|
||||
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
assertNotNull(filter
|
||||
.attemptAuthentication(request, new MockHttpServletResponse()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNullUsernameHandledGracefully() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
|
||||
request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "koala");
|
||||
@Test
|
||||
public void testNullUsernameHandledGracefully() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
|
||||
request.addParameter(
|
||||
UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY,
|
||||
"koala");
|
||||
|
||||
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
assertNotNull(filter.attemptAuthentication(request, new MockHttpServletResponse()));
|
||||
}
|
||||
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
assertNotNull(filter
|
||||
.attemptAuthentication(request, new MockHttpServletResponse()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUsingDifferentParameterNamesWorksAsExpected() throws ServletException {
|
||||
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
filter.setUsernameParameter("x");
|
||||
filter.setPasswordParameter("y");
|
||||
@Test
|
||||
public void testUsingDifferentParameterNamesWorksAsExpected() throws ServletException {
|
||||
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
filter.setUsernameParameter("x");
|
||||
filter.setPasswordParameter("y");
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
|
||||
request.addParameter("x", "rod");
|
||||
request.addParameter("y", "koala");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
|
||||
request.addParameter("x", "rod");
|
||||
request.addParameter("y", "koala");
|
||||
|
||||
Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse());
|
||||
assertNotNull(result);
|
||||
assertEquals("127.0.0.1", ((WebAuthenticationDetails) result.getDetails()).getRemoteAddress());
|
||||
}
|
||||
Authentication result = filter.attemptAuthentication(request,
|
||||
new MockHttpServletResponse());
|
||||
assertNotNull(result);
|
||||
assertEquals("127.0.0.1",
|
||||
((WebAuthenticationDetails) result.getDetails()).getRemoteAddress());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSpacesAreTrimmedCorrectlyFromUsername() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
|
||||
request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY, " rod ");
|
||||
request.addParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY, "koala");
|
||||
@Test
|
||||
public void testSpacesAreTrimmedCorrectlyFromUsername() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
|
||||
request.addParameter(
|
||||
UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY,
|
||||
" rod ");
|
||||
request.addParameter(
|
||||
UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY,
|
||||
"koala");
|
||||
|
||||
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
|
||||
Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse());
|
||||
assertEquals("rod", result.getName());
|
||||
}
|
||||
Authentication result = filter.attemptAuthentication(request,
|
||||
new MockHttpServletResponse());
|
||||
assertEquals("rod", result.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFailedAuthenticationThrowsException() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
|
||||
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(""));
|
||||
filter.setAuthenticationManager(am);
|
||||
@Test
|
||||
public void testFailedAuthenticationThrowsException() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/");
|
||||
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(""));
|
||||
filter.setAuthenticationManager(am);
|
||||
|
||||
try {
|
||||
filter.attemptAuthentication(request, new MockHttpServletResponse());
|
||||
fail("Expected AuthenticationException");
|
||||
} catch (AuthenticationException e) {
|
||||
}
|
||||
}
|
||||
try {
|
||||
filter.attemptAuthentication(request, new MockHttpServletResponse());
|
||||
fail("Expected AuthenticationException");
|
||||
}
|
||||
catch (AuthenticationException e) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* SEC-571
|
||||
*/
|
||||
@Test
|
||||
public void noSessionIsCreatedIfAllowSessionCreationIsFalse() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
/**
|
||||
* SEC-571
|
||||
*/
|
||||
@Test
|
||||
public void noSessionIsCreatedIfAllowSessionCreationIsFalse() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
|
||||
filter.setAllowSessionCreation(false);
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
|
||||
filter.setAllowSessionCreation(false);
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
|
||||
filter.attemptAuthentication(request, new MockHttpServletResponse());
|
||||
filter.attemptAuthentication(request, new MockHttpServletResponse());
|
||||
|
||||
assertNull(request.getSession(false));
|
||||
}
|
||||
assertNull(request.getSession(false));
|
||||
}
|
||||
|
||||
private AuthenticationManager createAuthenticationManager() {
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
when(am.authenticate(any(Authentication.class))).thenAnswer(new Answer<Authentication>() {
|
||||
public Authentication answer(InvocationOnMock invocation) throws Throwable {
|
||||
return (Authentication) invocation.getArguments()[0];
|
||||
}
|
||||
});
|
||||
private AuthenticationManager createAuthenticationManager() {
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
when(am.authenticate(any(Authentication.class))).thenAnswer(
|
||||
new Answer<Authentication>() {
|
||||
public Authentication answer(InvocationOnMock invocation)
|
||||
throws Throwable {
|
||||
return (Authentication) invocation.getArguments()[0];
|
||||
}
|
||||
});
|
||||
|
||||
return am;
|
||||
}
|
||||
return am;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -15,32 +15,33 @@ import org.springframework.security.core.Authentication;
|
||||
*/
|
||||
public class CookieClearingLogoutHandlerTests {
|
||||
|
||||
// SEC-2036
|
||||
@Test
|
||||
public void emptyContextRootIsConverted() {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setContextPath("");
|
||||
CookieClearingLogoutHandler handler = new CookieClearingLogoutHandler("my_cookie");
|
||||
handler.logout(request, response, mock(Authentication.class));
|
||||
assertEquals(1, response.getCookies().length);
|
||||
for (Cookie c : response.getCookies()) {
|
||||
assertEquals("/", c.getPath());
|
||||
assertEquals(0, c.getMaxAge());
|
||||
}
|
||||
}
|
||||
// SEC-2036
|
||||
@Test
|
||||
public void emptyContextRootIsConverted() {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setContextPath("");
|
||||
CookieClearingLogoutHandler handler = new CookieClearingLogoutHandler("my_cookie");
|
||||
handler.logout(request, response, mock(Authentication.class));
|
||||
assertEquals(1, response.getCookies().length);
|
||||
for (Cookie c : response.getCookies()) {
|
||||
assertEquals("/", c.getPath());
|
||||
assertEquals(0, c.getMaxAge());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configuredCookiesAreCleared() {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setContextPath("/app");
|
||||
CookieClearingLogoutHandler handler = new CookieClearingLogoutHandler("my_cookie", "my_cookie_too");
|
||||
handler.logout(request, response, mock(Authentication.class));
|
||||
assertEquals(2, response.getCookies().length);
|
||||
for (Cookie c : response.getCookies()) {
|
||||
assertEquals("/app", c.getPath());
|
||||
assertEquals(0, c.getMaxAge());
|
||||
}
|
||||
}
|
||||
@Test
|
||||
public void configuredCookiesAreCleared() {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setContextPath("/app");
|
||||
CookieClearingLogoutHandler handler = new CookieClearingLogoutHandler(
|
||||
"my_cookie", "my_cookie_too");
|
||||
handler.logout(request, response, mock(Authentication.class));
|
||||
assertEquals(2, response.getCookies().length);
|
||||
for (Cookie c : response.getCookies()) {
|
||||
assertEquals("/app", c.getPath());
|
||||
assertEquals(0, c.getMaxAge());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,34 +12,34 @@ import org.springframework.security.web.firewall.DefaultHttpFirewall;
|
||||
* @author Luke Taylor
|
||||
*/
|
||||
public class LogoutHandlerTests extends TestCase {
|
||||
LogoutFilter filter;
|
||||
LogoutFilter filter;
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
filter = new LogoutFilter("/success", new SecurityContextLogoutHandler());
|
||||
}
|
||||
protected void setUp() throws Exception {
|
||||
filter = new LogoutFilter("/success", new SecurityContextLogoutHandler());
|
||||
}
|
||||
|
||||
public void testRequiresLogoutUrlWorksWithPathParams() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
public void testRequiresLogoutUrlWorksWithPathParams() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
request.setRequestURI("/context/logout;someparam=blah?param=blah");
|
||||
request.setServletPath("/logout;someparam=blah");
|
||||
request.setQueryString("otherparam=blah");
|
||||
request.setRequestURI("/context/logout;someparam=blah?param=blah");
|
||||
request.setServletPath("/logout;someparam=blah");
|
||||
request.setQueryString("otherparam=blah");
|
||||
|
||||
DefaultHttpFirewall fw = new DefaultHttpFirewall();
|
||||
assertTrue(filter.requiresLogout(fw.getFirewalledRequest(request), response));
|
||||
}
|
||||
DefaultHttpFirewall fw = new DefaultHttpFirewall();
|
||||
assertTrue(filter.requiresLogout(fw.getFirewalledRequest(request), response));
|
||||
}
|
||||
|
||||
public void testRequiresLogoutUrlWorksWithQueryParams() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setContextPath("/context");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
public void testRequiresLogoutUrlWorksWithQueryParams() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setContextPath("/context");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
request.setServletPath("/logout");
|
||||
request.setRequestURI("/context/logout?param=blah");
|
||||
request.setQueryString("otherparam=blah");
|
||||
request.setServletPath("/logout");
|
||||
request.setRequestURI("/context/logout?param=blah");
|
||||
request.setQueryString("otherparam=blah");
|
||||
|
||||
assertTrue(filter.requiresLogout(request, response));
|
||||
}
|
||||
assertTrue(filter.requiresLogout(request, response));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -31,43 +31,46 @@ import org.springframework.security.core.context.SecurityContextHolder;
|
||||
*
|
||||
*/
|
||||
public class SecurityContextLogoutHandlerTests {
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletResponse response;
|
||||
private SecurityContextLogoutHandler handler;
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletResponse response;
|
||||
private SecurityContextLogoutHandler handler;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
@Before
|
||||
public void setUp() {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
|
||||
handler = new SecurityContextLogoutHandler();
|
||||
handler = new SecurityContextLogoutHandler();
|
||||
|
||||
SecurityContext context = SecurityContextHolder.createEmptyContext();
|
||||
context.setAuthentication(new TestingAuthenticationToken("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER")));
|
||||
SecurityContextHolder.setContext(context);
|
||||
}
|
||||
SecurityContext context = SecurityContextHolder.createEmptyContext();
|
||||
context.setAuthentication(new TestingAuthenticationToken("user", "password",
|
||||
AuthorityUtils.createAuthorityList("ROLE_USER")));
|
||||
SecurityContextHolder.setContext(context);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
@After
|
||||
public void tearDown() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
// SEC-2025
|
||||
@Test
|
||||
public void clearsAuthentication() {
|
||||
SecurityContext beforeContext = SecurityContextHolder.getContext();
|
||||
handler.logout(request, response, SecurityContextHolder.getContext().getAuthentication());
|
||||
assertNull(beforeContext.getAuthentication());
|
||||
}
|
||||
// SEC-2025
|
||||
@Test
|
||||
public void clearsAuthentication() {
|
||||
SecurityContext beforeContext = SecurityContextHolder.getContext();
|
||||
handler.logout(request, response, SecurityContextHolder.getContext()
|
||||
.getAuthentication());
|
||||
assertNull(beforeContext.getAuthentication());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void disableClearsAuthentication() {
|
||||
handler.setClearAuthentication(false);
|
||||
SecurityContext beforeContext = SecurityContextHolder.getContext();
|
||||
Authentication beforeAuthentication = beforeContext.getAuthentication();
|
||||
handler.logout(request, response, SecurityContextHolder.getContext().getAuthentication());
|
||||
@Test
|
||||
public void disableClearsAuthentication() {
|
||||
handler.setClearAuthentication(false);
|
||||
SecurityContext beforeContext = SecurityContextHolder.getContext();
|
||||
Authentication beforeAuthentication = beforeContext.getAuthentication();
|
||||
handler.logout(request, response, SecurityContextHolder.getContext()
|
||||
.getAuthentication());
|
||||
|
||||
assertNotNull(beforeContext.getAuthentication());
|
||||
assertSame(beforeAuthentication, beforeContext.getAuthentication());
|
||||
}
|
||||
assertNotNull(beforeContext.getAuthentication());
|
||||
assertSame(beforeAuthentication, beforeContext.getAuthentication());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,27 +14,27 @@ import org.springframework.security.core.Authentication;
|
||||
*/
|
||||
public class SimpleUrlLogoutSuccessHandlerTests {
|
||||
|
||||
@Test
|
||||
public void doesntRedirectIfResponseIsCommitted() throws Exception {
|
||||
SimpleUrlLogoutSuccessHandler lsh = new SimpleUrlLogoutSuccessHandler();
|
||||
lsh.setDefaultTargetUrl("/target");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
response.setCommitted(true);
|
||||
lsh.onLogoutSuccess(request, response, mock(Authentication.class));
|
||||
assertNull(request.getSession(false));
|
||||
assertNull(response.getRedirectedUrl());
|
||||
assertNull(response.getForwardedUrl());
|
||||
}
|
||||
@Test
|
||||
public void doesntRedirectIfResponseIsCommitted() throws Exception {
|
||||
SimpleUrlLogoutSuccessHandler lsh = new SimpleUrlLogoutSuccessHandler();
|
||||
lsh.setDefaultTargetUrl("/target");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
response.setCommitted(true);
|
||||
lsh.onLogoutSuccess(request, response, mock(Authentication.class));
|
||||
assertNull(request.getSession(false));
|
||||
assertNull(response.getRedirectedUrl());
|
||||
assertNull(response.getForwardedUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void absoluteUrlIsSupported() throws Exception {
|
||||
SimpleUrlLogoutSuccessHandler lsh = new SimpleUrlLogoutSuccessHandler();
|
||||
lsh.setDefaultTargetUrl("http://someurl.com/");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
lsh.onLogoutSuccess(request, response, mock(Authentication.class));
|
||||
assertEquals("http://someurl.com/", response.getRedirectedUrl());
|
||||
}
|
||||
@Test
|
||||
public void absoluteUrlIsSupported() throws Exception {
|
||||
SimpleUrlLogoutSuccessHandler lsh = new SimpleUrlLogoutSuccessHandler();
|
||||
lsh.setDefaultTargetUrl("http://someurl.com/");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
lsh.onLogoutSuccess(request, response, mock(Authentication.class));
|
||||
assertEquals("http://someurl.com/", response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -49,251 +49,281 @@ import org.springframework.security.core.userdetails.User;
|
||||
*
|
||||
*/
|
||||
public class AbstractPreAuthenticatedProcessingFilterTests {
|
||||
private AbstractPreAuthenticatedProcessingFilter filter;
|
||||
private AbstractPreAuthenticatedProcessingFilter filter;
|
||||
|
||||
@Before
|
||||
public void createFilter() {
|
||||
filter = new AbstractPreAuthenticatedProcessingFilter() {
|
||||
protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
|
||||
return "n/a";
|
||||
}
|
||||
@Before
|
||||
public void createFilter() {
|
||||
filter = new AbstractPreAuthenticatedProcessingFilter() {
|
||||
protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
|
||||
return "n/a";
|
||||
}
|
||||
|
||||
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
|
||||
return "doesntmatter";
|
||||
}
|
||||
};
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
|
||||
return "doesntmatter";
|
||||
}
|
||||
};
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
@After
|
||||
public void tearDown() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterChainProceedsOnFailedAuthenticationByDefault() throws Exception {
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException(""));
|
||||
filter.setAuthenticationManager(am);
|
||||
filter.afterPropertiesSet();
|
||||
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), mock(FilterChain.class));
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
@Test
|
||||
public void filterChainProceedsOnFailedAuthenticationByDefault() throws Exception {
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
when(am.authenticate(any(Authentication.class))).thenThrow(
|
||||
new BadCredentialsException(""));
|
||||
filter.setAuthenticationManager(am);
|
||||
filter.afterPropertiesSet();
|
||||
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(),
|
||||
mock(FilterChain.class));
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
/* SEC-881 */
|
||||
@Test(expected=BadCredentialsException.class)
|
||||
public void exceptionIsThrownOnFailedAuthenticationIfContinueFilterChainOnUnsuccessfulAuthenticationSetToFalse() throws Exception {
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
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));
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
/* SEC-881 */
|
||||
@Test(expected = BadCredentialsException.class)
|
||||
public void exceptionIsThrownOnFailedAuthenticationIfContinueFilterChainOnUnsuccessfulAuthenticationSetToFalse()
|
||||
throws Exception {
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
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));
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAfterPropertiesSet() {
|
||||
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
|
||||
try {
|
||||
filter.afterPropertiesSet();
|
||||
fail("AfterPropertiesSet didn't throw expected exception");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
} catch (Exception unexpected) {
|
||||
fail("AfterPropertiesSet throws unexpected exception");
|
||||
}
|
||||
}
|
||||
@Test
|
||||
public void testAfterPropertiesSet() {
|
||||
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
|
||||
try {
|
||||
filter.afterPropertiesSet();
|
||||
fail("AfterPropertiesSet didn't throw expected exception");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
catch (Exception unexpected) {
|
||||
fail("AfterPropertiesSet throws unexpected exception");
|
||||
}
|
||||
}
|
||||
|
||||
// SEC-2045
|
||||
@Test
|
||||
public void testAfterPropertiesSetInvokesSuper() throws Exception {
|
||||
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
filter.setAuthenticationManager(am);
|
||||
filter.afterPropertiesSet();
|
||||
assertTrue(filter.initFilterBeanInvoked);
|
||||
}
|
||||
// SEC-2045
|
||||
@Test
|
||||
public void testAfterPropertiesSetInvokesSuper() throws Exception {
|
||||
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
filter.setAuthenticationManager(am);
|
||||
filter.afterPropertiesSet();
|
||||
assertTrue(filter.initFilterBeanInvoked);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDoFilterAuthenticated() throws Exception {
|
||||
testDoFilter(true);
|
||||
}
|
||||
@Test
|
||||
public void testDoFilterAuthenticated() throws Exception {
|
||||
testDoFilter(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDoFilterUnauthenticated() throws Exception {
|
||||
testDoFilter(false);
|
||||
}
|
||||
@Test
|
||||
public void testDoFilterUnauthenticated() throws Exception {
|
||||
testDoFilter(false);
|
||||
}
|
||||
|
||||
// SEC-1968
|
||||
@Test
|
||||
public void nullPreAuthenticationClearsPreviousUser() throws Exception {
|
||||
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("oldUser", "pass","ROLE_USER"));
|
||||
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
|
||||
filter.principal = null;
|
||||
filter.setCheckForPrincipalChanges(true);
|
||||
// SEC-1968
|
||||
@Test
|
||||
public void nullPreAuthenticationClearsPreviousUser() throws Exception {
|
||||
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());
|
||||
|
||||
assertEquals(null, SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
assertEquals(null, SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nullPreAuthenticationPerservesPreviousUserCheckPrincipalChangesFalse() throws Exception {
|
||||
TestingAuthenticationToken authentication = new TestingAuthenticationToken("oldUser", "pass","ROLE_USER");
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
|
||||
filter.principal = null;
|
||||
@Test
|
||||
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());
|
||||
|
||||
assertEquals(authentication, SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
assertEquals(authentication, SecurityContextHolder.getContext()
|
||||
.getAuthentication());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requiresAuthenticationFalsePrincipalString() throws Exception {
|
||||
Object principal = "sameprincipal";
|
||||
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(principal, "something", "ROLE_USER"));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
@Test
|
||||
public void requiresAuthenticationFalsePrincipalString() throws Exception {
|
||||
Object principal = "sameprincipal";
|
||||
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();
|
||||
filter.setCheckForPrincipalChanges(true);
|
||||
filter.principal = principal;
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
filter.setAuthenticationManager(am);
|
||||
filter.afterPropertiesSet();
|
||||
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
|
||||
filter.setCheckForPrincipalChanges(true);
|
||||
filter.principal = principal;
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
filter.setAuthenticationManager(am);
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
verifyZeroInteractions(am);
|
||||
}
|
||||
verifyZeroInteractions(am);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requiresAuthenticationTruePrincipalString() throws Exception {
|
||||
Object currentPrincipal = "currentUser";
|
||||
TestingAuthenticationToken authRequest = new TestingAuthenticationToken(currentPrincipal, "something", "ROLE_USER");
|
||||
SecurityContextHolder.getContext().setAuthentication(authRequest);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
@Test
|
||||
public void requiresAuthenticationTruePrincipalString() throws Exception {
|
||||
Object currentPrincipal = "currentUser";
|
||||
TestingAuthenticationToken authRequest = new TestingAuthenticationToken(
|
||||
currentPrincipal, "something", "ROLE_USER");
|
||||
SecurityContextHolder.getContext().setAuthentication(authRequest);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
|
||||
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
|
||||
filter.setCheckForPrincipalChanges(true);
|
||||
filter.principal = "newUser";
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
filter.setAuthenticationManager(am);
|
||||
filter.afterPropertiesSet();
|
||||
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
|
||||
filter.setCheckForPrincipalChanges(true);
|
||||
filter.principal = "newUser";
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
filter.setAuthenticationManager(am);
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class));
|
||||
}
|
||||
verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class));
|
||||
}
|
||||
|
||||
// SEC-2078
|
||||
@Test
|
||||
public void requiresAuthenticationFalsePrincipalNotString() throws Exception {
|
||||
Object principal = new Object();
|
||||
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(principal, "something", "ROLE_USER"));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
// SEC-2078
|
||||
@Test
|
||||
public void requiresAuthenticationFalsePrincipalNotString() throws Exception {
|
||||
Object principal = new Object();
|
||||
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();
|
||||
filter.setCheckForPrincipalChanges(true);
|
||||
filter.principal = principal;
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
filter.setAuthenticationManager(am);
|
||||
filter.afterPropertiesSet();
|
||||
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
|
||||
filter.setCheckForPrincipalChanges(true);
|
||||
filter.principal = principal;
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
filter.setAuthenticationManager(am);
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
verifyZeroInteractions(am);
|
||||
}
|
||||
verifyZeroInteractions(am);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requiresAuthenticationFalsePrincipalUser() throws Exception {
|
||||
User currentPrincipal = new User("user","password", AuthorityUtils.createAuthorityList("ROLE_USER"));
|
||||
UsernamePasswordAuthenticationToken currentAuthentication = new UsernamePasswordAuthenticationToken(
|
||||
currentPrincipal, currentPrincipal.getPassword(), currentPrincipal.getAuthorities());
|
||||
SecurityContextHolder.getContext().setAuthentication(currentAuthentication);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
@Test
|
||||
public void requiresAuthenticationFalsePrincipalUser() throws Exception {
|
||||
User currentPrincipal = new User("user", "password",
|
||||
AuthorityUtils.createAuthorityList("ROLE_USER"));
|
||||
UsernamePasswordAuthenticationToken currentAuthentication = new UsernamePasswordAuthenticationToken(
|
||||
currentPrincipal, currentPrincipal.getPassword(),
|
||||
currentPrincipal.getAuthorities());
|
||||
SecurityContextHolder.getContext().setAuthentication(currentAuthentication);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
|
||||
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
|
||||
filter.setCheckForPrincipalChanges(true);
|
||||
filter.principal = new User(currentPrincipal.getUsername(), currentPrincipal.getPassword(), AuthorityUtils.NO_AUTHORITIES);
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
filter.setAuthenticationManager(am);
|
||||
filter.afterPropertiesSet();
|
||||
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
|
||||
filter.setCheckForPrincipalChanges(true);
|
||||
filter.principal = new User(currentPrincipal.getUsername(),
|
||||
currentPrincipal.getPassword(), AuthorityUtils.NO_AUTHORITIES);
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
filter.setAuthenticationManager(am);
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
verifyZeroInteractions(am);
|
||||
}
|
||||
verifyZeroInteractions(am);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requiresAuthenticationTruePrincipalNotString() throws Exception {
|
||||
Object currentPrincipal = new Object();
|
||||
TestingAuthenticationToken authRequest = new TestingAuthenticationToken(currentPrincipal, "something", "ROLE_USER");
|
||||
SecurityContextHolder.getContext().setAuthentication(authRequest);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
@Test
|
||||
public void requiresAuthenticationTruePrincipalNotString() throws Exception {
|
||||
Object currentPrincipal = new Object();
|
||||
TestingAuthenticationToken authRequest = new TestingAuthenticationToken(
|
||||
currentPrincipal, "something", "ROLE_USER");
|
||||
SecurityContextHolder.getContext().setAuthentication(authRequest);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
|
||||
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
|
||||
filter.setCheckForPrincipalChanges(true);
|
||||
filter.principal = new Object();
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
filter.setAuthenticationManager(am);
|
||||
filter.afterPropertiesSet();
|
||||
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
|
||||
filter.setCheckForPrincipalChanges(true);
|
||||
filter.principal = new Object();
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
filter.setAuthenticationManager(am);
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class));
|
||||
}
|
||||
verify(am).authenticate(any(PreAuthenticatedAuthenticationToken.class));
|
||||
}
|
||||
|
||||
private void testDoFilter(boolean grantAccess) throws Exception {
|
||||
MockHttpServletRequest req = new MockHttpServletRequest();
|
||||
MockHttpServletResponse res = new MockHttpServletResponse();
|
||||
getFilter(grantAccess).doFilter(req,res,new MockFilterChain());
|
||||
assertEquals(grantAccess, null != SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
private void testDoFilter(boolean grantAccess) throws Exception {
|
||||
MockHttpServletRequest req = new MockHttpServletRequest();
|
||||
MockHttpServletResponse res = new MockHttpServletResponse();
|
||||
getFilter(grantAccess).doFilter(req, res, new MockFilterChain());
|
||||
assertEquals(grantAccess, null != SecurityContextHolder.getContext()
|
||||
.getAuthentication());
|
||||
}
|
||||
|
||||
private static ConcretePreAuthenticatedProcessingFilter getFilter(boolean grantAccess) throws Exception {
|
||||
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
private static ConcretePreAuthenticatedProcessingFilter getFilter(boolean grantAccess)
|
||||
throws Exception {
|
||||
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
|
||||
if (!grantAccess) {
|
||||
when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException(""));
|
||||
} else {
|
||||
when(am.authenticate(any(Authentication.class))).thenAnswer(new Answer<Authentication>() {
|
||||
public Authentication answer(InvocationOnMock invocation) throws Throwable {
|
||||
return (Authentication) invocation.getArguments()[0];
|
||||
}
|
||||
});
|
||||
}
|
||||
if (!grantAccess) {
|
||||
when(am.authenticate(any(Authentication.class))).thenThrow(
|
||||
new BadCredentialsException(""));
|
||||
}
|
||||
else {
|
||||
when(am.authenticate(any(Authentication.class))).thenAnswer(
|
||||
new Answer<Authentication>() {
|
||||
public Authentication answer(InvocationOnMock invocation)
|
||||
throws Throwable {
|
||||
return (Authentication) invocation.getArguments()[0];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
filter.setAuthenticationManager(am);
|
||||
filter.afterPropertiesSet();
|
||||
return filter;
|
||||
}
|
||||
filter.setAuthenticationManager(am);
|
||||
filter.afterPropertiesSet();
|
||||
return filter;
|
||||
}
|
||||
|
||||
private static class ConcretePreAuthenticatedProcessingFilter extends AbstractPreAuthenticatedProcessingFilter {
|
||||
private Object principal = "testPrincipal";
|
||||
private boolean initFilterBeanInvoked;
|
||||
protected Object getPreAuthenticatedPrincipal(HttpServletRequest httpRequest) {
|
||||
return principal;
|
||||
}
|
||||
protected Object getPreAuthenticatedCredentials(HttpServletRequest httpRequest) {
|
||||
return "testCredentials";
|
||||
}
|
||||
@Override
|
||||
protected void initFilterBean() throws ServletException {
|
||||
super.initFilterBean();
|
||||
initFilterBeanInvoked = true;
|
||||
}
|
||||
}
|
||||
private static class ConcretePreAuthenticatedProcessingFilter extends
|
||||
AbstractPreAuthenticatedProcessingFilter {
|
||||
private Object principal = "testPrincipal";
|
||||
private boolean initFilterBeanInvoked;
|
||||
|
||||
protected Object getPreAuthenticatedPrincipal(HttpServletRequest httpRequest) {
|
||||
return principal;
|
||||
}
|
||||
|
||||
protected Object getPreAuthenticatedCredentials(HttpServletRequest httpRequest) {
|
||||
return "testCredentials";
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void initFilterBean() throws ServletException {
|
||||
super.initFilterBean();
|
||||
initFilterBeanInvoked = true;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -15,17 +15,21 @@ import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
public class Http403ForbiddenEntryPointTests extends TestCase {
|
||||
|
||||
public void testCommence() {
|
||||
MockHttpServletRequest req = new MockHttpServletRequest();
|
||||
MockHttpServletResponse resp = new MockHttpServletResponse();
|
||||
Http403ForbiddenEntryPoint fep = new Http403ForbiddenEntryPoint();
|
||||
try {
|
||||
fep.commence(req,resp,new AuthenticationCredentialsNotFoundException("test"));
|
||||
assertEquals("Incorrect status",resp.getStatus(),HttpServletResponse.SC_FORBIDDEN);
|
||||
} catch (IOException e) {
|
||||
fail("Unexpected exception thrown: "+e);
|
||||
} catch (ServletException e) {
|
||||
fail("Unexpected exception thrown: "+e);
|
||||
}
|
||||
}
|
||||
public void testCommence() {
|
||||
MockHttpServletRequest req = new MockHttpServletRequest();
|
||||
MockHttpServletResponse resp = new MockHttpServletResponse();
|
||||
Http403ForbiddenEntryPoint fep = new Http403ForbiddenEntryPoint();
|
||||
try {
|
||||
fep.commence(req, resp,
|
||||
new AuthenticationCredentialsNotFoundException("test"));
|
||||
assertEquals("Incorrect status", resp.getStatus(),
|
||||
HttpServletResponse.SC_FORBIDDEN);
|
||||
}
|
||||
catch (IOException e) {
|
||||
fail("Unexpected exception thrown: " + e);
|
||||
}
|
||||
catch (ServletException e) {
|
||||
fail("Unexpected exception thrown: " + e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,97 +24,108 @@ import org.springframework.security.web.authentication.preauth.PreAuthenticatedA
|
||||
*/
|
||||
public class PreAuthenticatedAuthenticationProviderTests {
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public final void afterPropertiesSet() {
|
||||
PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public final void afterPropertiesSet() {
|
||||
PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
|
||||
|
||||
provider.afterPropertiesSet();
|
||||
}
|
||||
provider.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void authenticateInvalidToken() throws Exception {
|
||||
UserDetails ud = new User("dummyUser", "dummyPwd", true, true, true, true, AuthorityUtils.NO_AUTHORITIES );
|
||||
PreAuthenticatedAuthenticationProvider provider = getProvider(ud);
|
||||
Authentication request = new UsernamePasswordAuthenticationToken("dummyUser", "dummyPwd");
|
||||
Authentication result = provider.authenticate(request);
|
||||
assertNull(result);
|
||||
}
|
||||
@Test
|
||||
public final void authenticateInvalidToken() throws Exception {
|
||||
UserDetails ud = new User("dummyUser", "dummyPwd", true, true, true, true,
|
||||
AuthorityUtils.NO_AUTHORITIES);
|
||||
PreAuthenticatedAuthenticationProvider provider = getProvider(ud);
|
||||
Authentication request = new UsernamePasswordAuthenticationToken("dummyUser",
|
||||
"dummyPwd");
|
||||
Authentication result = provider.authenticate(request);
|
||||
assertNull(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void nullPrincipalReturnsNullAuthentication() throws Exception {
|
||||
PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
|
||||
Authentication request = new PreAuthenticatedAuthenticationToken(null, "dummyPwd");
|
||||
Authentication result = provider.authenticate(request);
|
||||
assertNull(result);
|
||||
}
|
||||
@Test
|
||||
public final void nullPrincipalReturnsNullAuthentication() throws Exception {
|
||||
PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
|
||||
Authentication request = new PreAuthenticatedAuthenticationToken(null, "dummyPwd");
|
||||
Authentication result = provider.authenticate(request);
|
||||
assertNull(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void authenticateKnownUser() throws Exception {
|
||||
UserDetails ud = new User("dummyUser", "dummyPwd", true, true, true, true, AuthorityUtils.NO_AUTHORITIES );
|
||||
PreAuthenticatedAuthenticationProvider provider = getProvider(ud);
|
||||
Authentication request = new PreAuthenticatedAuthenticationToken("dummyUser", "dummyPwd");
|
||||
Authentication result = provider.authenticate(request);
|
||||
assertNotNull(result);
|
||||
assertEquals(result.getPrincipal(), ud);
|
||||
// @TODO: Add more asserts?
|
||||
}
|
||||
@Test
|
||||
public final void authenticateKnownUser() throws Exception {
|
||||
UserDetails ud = new User("dummyUser", "dummyPwd", true, true, true, true,
|
||||
AuthorityUtils.NO_AUTHORITIES);
|
||||
PreAuthenticatedAuthenticationProvider provider = getProvider(ud);
|
||||
Authentication request = new PreAuthenticatedAuthenticationToken("dummyUser",
|
||||
"dummyPwd");
|
||||
Authentication result = provider.authenticate(request);
|
||||
assertNotNull(result);
|
||||
assertEquals(result.getPrincipal(), ud);
|
||||
// @TODO: Add more asserts?
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void authenticateIgnoreCredentials() throws Exception {
|
||||
UserDetails ud = new User("dummyUser1", "dummyPwd1", true, true, true, true, AuthorityUtils.NO_AUTHORITIES );
|
||||
PreAuthenticatedAuthenticationProvider provider = getProvider(ud);
|
||||
Authentication request = new PreAuthenticatedAuthenticationToken("dummyUser1", "dummyPwd2");
|
||||
Authentication result = provider.authenticate(request);
|
||||
assertNotNull(result);
|
||||
assertEquals(result.getPrincipal(), ud);
|
||||
// @TODO: Add more asserts?
|
||||
}
|
||||
@Test
|
||||
public final void authenticateIgnoreCredentials() throws Exception {
|
||||
UserDetails ud = new User("dummyUser1", "dummyPwd1", true, true, true, true,
|
||||
AuthorityUtils.NO_AUTHORITIES);
|
||||
PreAuthenticatedAuthenticationProvider provider = getProvider(ud);
|
||||
Authentication request = new PreAuthenticatedAuthenticationToken("dummyUser1",
|
||||
"dummyPwd2");
|
||||
Authentication result = provider.authenticate(request);
|
||||
assertNotNull(result);
|
||||
assertEquals(result.getPrincipal(), ud);
|
||||
// @TODO: Add more asserts?
|
||||
}
|
||||
|
||||
@Test(expected=UsernameNotFoundException.class)
|
||||
public final void authenticateUnknownUserThrowsException() throws Exception {
|
||||
UserDetails ud = new User("dummyUser1", "dummyPwd", true, true, true, true, AuthorityUtils.NO_AUTHORITIES );
|
||||
PreAuthenticatedAuthenticationProvider provider = getProvider(ud);
|
||||
Authentication request = new PreAuthenticatedAuthenticationToken("dummyUser2", "dummyPwd");
|
||||
provider.authenticate(request);
|
||||
}
|
||||
@Test(expected = UsernameNotFoundException.class)
|
||||
public final void authenticateUnknownUserThrowsException() throws Exception {
|
||||
UserDetails ud = new User("dummyUser1", "dummyPwd", true, true, true, true,
|
||||
AuthorityUtils.NO_AUTHORITIES);
|
||||
PreAuthenticatedAuthenticationProvider provider = getProvider(ud);
|
||||
Authentication request = new PreAuthenticatedAuthenticationToken("dummyUser2",
|
||||
"dummyPwd");
|
||||
provider.authenticate(request);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void supportsArbitraryObject() throws Exception {
|
||||
PreAuthenticatedAuthenticationProvider provider = getProvider(null);
|
||||
assertFalse(provider.supports(Authentication.class));
|
||||
}
|
||||
@Test
|
||||
public final void supportsArbitraryObject() throws Exception {
|
||||
PreAuthenticatedAuthenticationProvider provider = getProvider(null);
|
||||
assertFalse(provider.supports(Authentication.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void supportsPreAuthenticatedAuthenticationToken() throws Exception {
|
||||
PreAuthenticatedAuthenticationProvider provider = getProvider(null);
|
||||
assertTrue(provider.supports(PreAuthenticatedAuthenticationToken.class));
|
||||
}
|
||||
@Test
|
||||
public final void supportsPreAuthenticatedAuthenticationToken() throws Exception {
|
||||
PreAuthenticatedAuthenticationProvider provider = getProvider(null);
|
||||
assertTrue(provider.supports(PreAuthenticatedAuthenticationToken.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getSetOrder() throws Exception {
|
||||
PreAuthenticatedAuthenticationProvider provider = getProvider(null);
|
||||
provider.setOrder(333);
|
||||
assertEquals(provider.getOrder(), 333);
|
||||
}
|
||||
@Test
|
||||
public void getSetOrder() throws Exception {
|
||||
PreAuthenticatedAuthenticationProvider provider = getProvider(null);
|
||||
provider.setOrder(333);
|
||||
assertEquals(provider.getOrder(), 333);
|
||||
}
|
||||
|
||||
private PreAuthenticatedAuthenticationProvider getProvider(UserDetails aUserDetails) throws Exception {
|
||||
PreAuthenticatedAuthenticationProvider result = new PreAuthenticatedAuthenticationProvider();
|
||||
result.setPreAuthenticatedUserDetailsService(getPreAuthenticatedUserDetailsService(aUserDetails));
|
||||
result.afterPropertiesSet();
|
||||
return result;
|
||||
}
|
||||
private PreAuthenticatedAuthenticationProvider getProvider(UserDetails aUserDetails)
|
||||
throws Exception {
|
||||
PreAuthenticatedAuthenticationProvider result = new PreAuthenticatedAuthenticationProvider();
|
||||
result.setPreAuthenticatedUserDetailsService(getPreAuthenticatedUserDetailsService(aUserDetails));
|
||||
result.afterPropertiesSet();
|
||||
return result;
|
||||
}
|
||||
|
||||
private AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken>
|
||||
getPreAuthenticatedUserDetailsService(final UserDetails aUserDetails) {
|
||||
return new AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken>() {
|
||||
public UserDetails loadUserDetails(PreAuthenticatedAuthenticationToken token) throws UsernameNotFoundException {
|
||||
if (aUserDetails != null && aUserDetails.getUsername().equals(token.getName())) {
|
||||
return aUserDetails;
|
||||
}
|
||||
private AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> getPreAuthenticatedUserDetailsService(
|
||||
final UserDetails aUserDetails) {
|
||||
return new AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken>() {
|
||||
public UserDetails loadUserDetails(PreAuthenticatedAuthenticationToken token)
|
||||
throws UsernameNotFoundException {
|
||||
if (aUserDetails != null
|
||||
&& aUserDetails.getUsername().equals(token.getName())) {
|
||||
return aUserDetails;
|
||||
}
|
||||
|
||||
throw new UsernameNotFoundException("notfound");
|
||||
}
|
||||
};
|
||||
}
|
||||
throw new UsernameNotFoundException("notfound");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -16,42 +16,45 @@ import org.springframework.security.web.authentication.preauth.PreAuthenticatedA
|
||||
*/
|
||||
public class PreAuthenticatedAuthenticationTokenTests extends TestCase {
|
||||
|
||||
public void testPreAuthenticatedAuthenticationTokenRequestWithDetails() {
|
||||
Object principal = "dummyUser";
|
||||
Object credentials = "dummyCredentials";
|
||||
Object details = "dummyDetails";
|
||||
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, credentials);
|
||||
token.setDetails(details);
|
||||
assertEquals(principal, token.getPrincipal());
|
||||
assertEquals(credentials, token.getCredentials());
|
||||
assertEquals(details, token.getDetails());
|
||||
assertTrue(token.getAuthorities().isEmpty());
|
||||
}
|
||||
public void testPreAuthenticatedAuthenticationTokenRequestWithDetails() {
|
||||
Object principal = "dummyUser";
|
||||
Object credentials = "dummyCredentials";
|
||||
Object details = "dummyDetails";
|
||||
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
|
||||
principal, credentials);
|
||||
token.setDetails(details);
|
||||
assertEquals(principal, token.getPrincipal());
|
||||
assertEquals(credentials, token.getCredentials());
|
||||
assertEquals(details, token.getDetails());
|
||||
assertTrue(token.getAuthorities().isEmpty());
|
||||
}
|
||||
|
||||
public void testPreAuthenticatedAuthenticationTokenRequestWithoutDetails() {
|
||||
Object principal = "dummyUser";
|
||||
Object credentials = "dummyCredentials";
|
||||
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal, credentials);
|
||||
assertEquals(principal, token.getPrincipal());
|
||||
assertEquals(credentials, token.getCredentials());
|
||||
assertNull(token.getDetails());
|
||||
assertTrue(token.getAuthorities().isEmpty());
|
||||
}
|
||||
public void testPreAuthenticatedAuthenticationTokenRequestWithoutDetails() {
|
||||
Object principal = "dummyUser";
|
||||
Object credentials = "dummyCredentials";
|
||||
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
|
||||
principal, credentials);
|
||||
assertEquals(principal, token.getPrincipal());
|
||||
assertEquals(credentials, token.getCredentials());
|
||||
assertNull(token.getDetails());
|
||||
assertTrue(token.getAuthorities().isEmpty());
|
||||
}
|
||||
|
||||
public void testPreAuthenticatedAuthenticationTokenResponse() {
|
||||
Object principal = "dummyUser";
|
||||
Object credentials = "dummyCredentials";
|
||||
List<GrantedAuthority> gas = AuthorityUtils.createAuthorityList("Role1");
|
||||
PreAuthenticatedAuthenticationToken token =
|
||||
new PreAuthenticatedAuthenticationToken(principal, credentials, gas);
|
||||
assertEquals(principal, token.getPrincipal());
|
||||
assertEquals(credentials, token.getCredentials());
|
||||
assertNull(token.getDetails());
|
||||
assertNotNull(token.getAuthorities());
|
||||
Collection<GrantedAuthority> resultColl = token.getAuthorities();
|
||||
assertTrue("GrantedAuthority collections do not match; result: " + resultColl + ", expected: " + gas,
|
||||
gas.containsAll(resultColl) && resultColl.containsAll(gas));
|
||||
public void testPreAuthenticatedAuthenticationTokenResponse() {
|
||||
Object principal = "dummyUser";
|
||||
Object credentials = "dummyCredentials";
|
||||
List<GrantedAuthority> gas = AuthorityUtils.createAuthorityList("Role1");
|
||||
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
|
||||
principal, credentials, gas);
|
||||
assertEquals(principal, token.getPrincipal());
|
||||
assertEquals(credentials, token.getCredentials());
|
||||
assertNull(token.getDetails());
|
||||
assertNotNull(token.getAuthorities());
|
||||
Collection<GrantedAuthority> resultColl = token.getAuthorities();
|
||||
assertTrue("GrantedAuthority collections do not match; result: " + resultColl
|
||||
+ ", expected: " + gas,
|
||||
gas.containsAll(resultColl) && resultColl.containsAll(gas));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -17,55 +17,62 @@ import org.springframework.security.core.userdetails.UserDetails;
|
||||
*/
|
||||
public class PreAuthenticatedGrantedAuthoritiesUserDetailsServiceTests {
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testGetUserDetailsInvalidType() {
|
||||
PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
|
||||
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken("dummy", "dummy");
|
||||
token.setDetails(new Object());
|
||||
svc.loadUserDetails(token);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testGetUserDetailsInvalidType() {
|
||||
PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
|
||||
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
|
||||
"dummy", "dummy");
|
||||
token.setDetails(new Object());
|
||||
svc.loadUserDetails(token);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testGetUserDetailsNoDetails() {
|
||||
PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
|
||||
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken("dummy", "dummy");
|
||||
token.setDetails(null);
|
||||
svc.loadUserDetails(token);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testGetUserDetailsNoDetails() {
|
||||
PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
|
||||
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
|
||||
"dummy", "dummy");
|
||||
token.setDetails(null);
|
||||
svc.loadUserDetails(token);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetUserDetailsEmptyAuthorities() {
|
||||
final String userName = "dummyUser";
|
||||
testGetUserDetails(userName, AuthorityUtils.NO_AUTHORITIES);
|
||||
}
|
||||
@Test
|
||||
public void testGetUserDetailsEmptyAuthorities() {
|
||||
final String userName = "dummyUser";
|
||||
testGetUserDetails(userName, AuthorityUtils.NO_AUTHORITIES);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetUserDetailsWithAuthorities() {
|
||||
final String userName = "dummyUser";
|
||||
testGetUserDetails(userName, AuthorityUtils.createAuthorityList("Role1", "Role2"));
|
||||
}
|
||||
@Test
|
||||
public void testGetUserDetailsWithAuthorities() {
|
||||
final String userName = "dummyUser";
|
||||
testGetUserDetails(userName, AuthorityUtils.createAuthorityList("Role1", "Role2"));
|
||||
}
|
||||
|
||||
private void testGetUserDetails(final String userName, final List<GrantedAuthority> gas) {
|
||||
PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
|
||||
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(userName, "dummy");
|
||||
token.setDetails(new GrantedAuthoritiesContainer() {
|
||||
public Collection<? extends GrantedAuthority> getGrantedAuthorities() {
|
||||
return gas;
|
||||
}
|
||||
});
|
||||
UserDetails ud = svc.loadUserDetails(token);
|
||||
assertTrue(ud.isAccountNonExpired());
|
||||
assertTrue(ud.isAccountNonLocked());
|
||||
assertTrue(ud.isCredentialsNonExpired());
|
||||
assertTrue(ud.isEnabled());
|
||||
assertEquals(ud.getUsername(), userName);
|
||||
private void testGetUserDetails(final String userName,
|
||||
final List<GrantedAuthority> gas) {
|
||||
PreAuthenticatedGrantedAuthoritiesUserDetailsService svc = new PreAuthenticatedGrantedAuthoritiesUserDetailsService();
|
||||
PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(
|
||||
userName, "dummy");
|
||||
token.setDetails(new GrantedAuthoritiesContainer() {
|
||||
public Collection<? extends GrantedAuthority> getGrantedAuthorities() {
|
||||
return gas;
|
||||
}
|
||||
});
|
||||
UserDetails ud = svc.loadUserDetails(token);
|
||||
assertTrue(ud.isAccountNonExpired());
|
||||
assertTrue(ud.isAccountNonLocked());
|
||||
assertTrue(ud.isCredentialsNonExpired());
|
||||
assertTrue(ud.isEnabled());
|
||||
assertEquals(ud.getUsername(), userName);
|
||||
|
||||
//Password is not saved by
|
||||
// PreAuthenticatedGrantedAuthoritiesUserDetailsService
|
||||
//assertEquals(ud.getPassword(),password);
|
||||
// Password is not saved by
|
||||
// PreAuthenticatedGrantedAuthoritiesUserDetailsService
|
||||
// assertEquals(ud.getPassword(),password);
|
||||
|
||||
assertTrue("GrantedAuthority collections do not match; result: " + ud.getAuthorities() + ", expected: " + gas,
|
||||
gas.containsAll(ud.getAuthorities()) && ud.getAuthorities().containsAll(gas));
|
||||
}
|
||||
assertTrue(
|
||||
"GrantedAuthority collections do not match; result: "
|
||||
+ ud.getAuthorities() + ", expected: " + gas,
|
||||
gas.containsAll(ud.getAuthorities())
|
||||
&& ud.getAuthorities().containsAll(gas));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -17,35 +17,37 @@ import java.util.Set;
|
||||
* @author TSARDD
|
||||
*/
|
||||
public class PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests {
|
||||
List<GrantedAuthority> gas = AuthorityUtils.createAuthorityList("Role1", "Role2");
|
||||
List<GrantedAuthority> gas = AuthorityUtils.createAuthorityList("Role1", "Role2");
|
||||
|
||||
@Test
|
||||
public void testToString() {
|
||||
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(
|
||||
getRequest("testUser", new String[] {}), gas);
|
||||
String toString = details.toString();
|
||||
assertTrue("toString should contain Role1", toString.contains("Role1"));
|
||||
assertTrue("toString should contain Role2", toString.contains("Role2"));
|
||||
}
|
||||
@Test
|
||||
public void testToString() {
|
||||
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(
|
||||
getRequest("testUser", new String[] {}), gas);
|
||||
String toString = details.toString();
|
||||
assertTrue("toString should contain Role1", toString.contains("Role1"));
|
||||
assertTrue("toString should contain Role2", toString.contains("Role2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetSetPreAuthenticatedGrantedAuthorities() {
|
||||
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(
|
||||
getRequest("testUser", new String[] {}), gas);
|
||||
List<GrantedAuthority> returnedGas = details.getGrantedAuthorities();
|
||||
assertTrue("Collections do not contain same elements; expected: " + gas + ", returned: " + returnedGas,
|
||||
gas.containsAll(returnedGas) && returnedGas.containsAll(gas));
|
||||
}
|
||||
@Test
|
||||
public void testGetSetPreAuthenticatedGrantedAuthorities() {
|
||||
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(
|
||||
getRequest("testUser", new String[] {}), gas);
|
||||
List<GrantedAuthority> returnedGas = details.getGrantedAuthorities();
|
||||
assertTrue("Collections do not contain same elements; expected: " + gas
|
||||
+ ", returned: " + returnedGas, gas.containsAll(returnedGas)
|
||||
&& returnedGas.containsAll(gas));
|
||||
}
|
||||
|
||||
private HttpServletRequest getRequest(final String userName,final String[] aRoles) {
|
||||
MockHttpServletRequest req = new MockHttpServletRequest() {
|
||||
private Set<String> roles = new HashSet<String>(Arrays.asList(aRoles));
|
||||
public boolean isUserInRole(String arg0) {
|
||||
return roles.contains(arg0);
|
||||
}
|
||||
};
|
||||
req.setRemoteUser(userName);
|
||||
return req;
|
||||
}
|
||||
private HttpServletRequest getRequest(final String userName, final String[] aRoles) {
|
||||
MockHttpServletRequest req = new MockHttpServletRequest() {
|
||||
private Set<String> roles = new HashSet<String>(Arrays.asList(aRoles));
|
||||
|
||||
public boolean isUserInRole(String arg0) {
|
||||
return roles.contains(arg0);
|
||||
}
|
||||
};
|
||||
req.setRemoteUser(userName);
|
||||
return req;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -24,122 +24,131 @@ import org.springframework.security.web.authentication.preauth.RequestHeaderAuth
|
||||
*/
|
||||
public class RequestHeaderAuthenticationFilterTests {
|
||||
|
||||
@After
|
||||
@Before
|
||||
public void clearContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
@After
|
||||
@Before
|
||||
public void clearContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test(expected = PreAuthenticatedCredentialsNotFoundException.class)
|
||||
public void rejectsMissingHeader() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
|
||||
@Test(expected = PreAuthenticatedCredentialsNotFoundException.class)
|
||||
public void rejectsMissingHeader() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
}
|
||||
filter.doFilter(request, response, chain);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void defaultsToUsingSiteminderHeader() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addHeader("SM_USER", "cat");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
@Test
|
||||
public void defaultsToUsingSiteminderHeader() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addHeader("SM_USER", "cat");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals("cat", SecurityContextHolder.getContext().getAuthentication().getName());
|
||||
assertEquals("N/A", SecurityContextHolder.getContext().getAuthentication().getCredentials());
|
||||
}
|
||||
filter.doFilter(request, response, chain);
|
||||
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals("cat", SecurityContextHolder.getContext().getAuthentication()
|
||||
.getName());
|
||||
assertEquals("N/A", SecurityContextHolder.getContext().getAuthentication()
|
||||
.getCredentials());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void alternativeHeaderNameIsSupported() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addHeader("myUsernameHeader", "wolfman");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
filter.setPrincipalRequestHeader("myUsernameHeader");
|
||||
@Test
|
||||
public void alternativeHeaderNameIsSupported() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addHeader("myUsernameHeader", "wolfman");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
filter.setPrincipalRequestHeader("myUsernameHeader");
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals("wolfman", SecurityContextHolder.getContext().getAuthentication().getName());
|
||||
}
|
||||
filter.doFilter(request, response, chain);
|
||||
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals("wolfman", SecurityContextHolder.getContext().getAuthentication()
|
||||
.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void credentialsAreRetrievedIfHeaderNameIsSet() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
filter.setCredentialsRequestHeader("myCredentialsHeader");
|
||||
request.addHeader("SM_USER", "cat");
|
||||
request.addHeader("myCredentialsHeader", "catspassword");
|
||||
@Test
|
||||
public void credentialsAreRetrievedIfHeaderNameIsSet() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
filter.setCredentialsRequestHeader("myCredentialsHeader");
|
||||
request.addHeader("SM_USER", "cat");
|
||||
request.addHeader("myCredentialsHeader", "catspassword");
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals("catspassword", SecurityContextHolder.getContext().getAuthentication().getCredentials());
|
||||
}
|
||||
filter.doFilter(request, response, chain);
|
||||
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals("catspassword", SecurityContextHolder.getContext()
|
||||
.getAuthentication().getCredentials());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void userIsReauthenticatedIfPrincipalChangesAndCheckForPrincipalChangesIsSet() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
filter.setCheckForPrincipalChanges(true);
|
||||
request.addHeader("SM_USER", "cat");
|
||||
filter.doFilter(request, response, new MockFilterChain());
|
||||
request = new MockHttpServletRequest();
|
||||
request.addHeader("SM_USER", "dog");
|
||||
filter.doFilter(request, response, new MockFilterChain());
|
||||
Authentication dog = SecurityContextHolder.getContext().getAuthentication();
|
||||
assertNotNull(dog);
|
||||
assertEquals("dog", dog.getName());
|
||||
// Make sure authentication doesn't occur every time (i.e. if the header *doesn't change)
|
||||
filter.setAuthenticationManager(mock(AuthenticationManager.class));
|
||||
filter.doFilter(request, response, new MockFilterChain());
|
||||
assertSame(dog, SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
@Test
|
||||
public void userIsReauthenticatedIfPrincipalChangesAndCheckForPrincipalChangesIsSet()
|
||||
throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
filter.setCheckForPrincipalChanges(true);
|
||||
request.addHeader("SM_USER", "cat");
|
||||
filter.doFilter(request, response, new MockFilterChain());
|
||||
request = new MockHttpServletRequest();
|
||||
request.addHeader("SM_USER", "dog");
|
||||
filter.doFilter(request, response, new MockFilterChain());
|
||||
Authentication dog = SecurityContextHolder.getContext().getAuthentication();
|
||||
assertNotNull(dog);
|
||||
assertEquals("dog", dog.getName());
|
||||
// Make sure authentication doesn't occur every time (i.e. if the header *doesn't
|
||||
// change)
|
||||
filter.setAuthenticationManager(mock(AuthenticationManager.class));
|
||||
filter.doFilter(request, response, new MockFilterChain());
|
||||
assertSame(dog, SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
@Test(expected=PreAuthenticatedCredentialsNotFoundException.class)
|
||||
public void missingHeaderCausesException() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
@Test(expected = PreAuthenticatedCredentialsNotFoundException.class)
|
||||
public void missingHeaderCausesException() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
}
|
||||
filter.doFilter(request, response, chain);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void missingHeaderIsIgnoredIfExceptionIfHeaderMissingIsFalse() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
|
||||
filter.setExceptionIfHeaderMissing(false);
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
filter.doFilter(request, response, chain);
|
||||
}
|
||||
@Test
|
||||
public void missingHeaderIsIgnoredIfExceptionIfHeaderMissingIsFalse()
|
||||
throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain chain = new MockFilterChain();
|
||||
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
|
||||
filter.setExceptionIfHeaderMissing(false);
|
||||
filter.setAuthenticationManager(createAuthenticationManager());
|
||||
filter.doFilter(request, response, chain);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an authentication manager which returns the passed in object.
|
||||
*/
|
||||
private AuthenticationManager createAuthenticationManager() {
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
when(am.authenticate(any(Authentication.class))).thenAnswer(new Answer<Authentication>() {
|
||||
public Authentication answer(InvocationOnMock invocation) throws Throwable {
|
||||
return (Authentication) invocation.getArguments()[0];
|
||||
}
|
||||
});
|
||||
/**
|
||||
* Create an authentication manager which returns the passed in object.
|
||||
*/
|
||||
private AuthenticationManager createAuthenticationManager() {
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
when(am.authenticate(any(Authentication.class))).thenAnswer(
|
||||
new Answer<Authentication>() {
|
||||
public Authentication answer(InvocationOnMock invocation)
|
||||
throws Throwable {
|
||||
return (Authentication) invocation.getArguments()[0];
|
||||
}
|
||||
});
|
||||
|
||||
return am;
|
||||
}
|
||||
return am;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,126 +22,135 @@ import org.springframework.security.web.authentication.preauth.PreAuthenticatedG
|
||||
*
|
||||
* @author TSARDD
|
||||
*/
|
||||
public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extends TestCase {
|
||||
public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests extends
|
||||
TestCase {
|
||||
|
||||
public final void testAfterPropertiesSetException() {
|
||||
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource t = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource();
|
||||
try {
|
||||
t.afterPropertiesSet();
|
||||
fail("AfterPropertiesSet didn't throw expected exception");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
} catch (Exception unexpected) {
|
||||
fail("AfterPropertiesSet throws unexpected exception");
|
||||
}
|
||||
}
|
||||
public final void testAfterPropertiesSetException() {
|
||||
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource t = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource();
|
||||
try {
|
||||
t.afterPropertiesSet();
|
||||
fail("AfterPropertiesSet didn't throw expected exception");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
catch (Exception unexpected) {
|
||||
fail("AfterPropertiesSet throws unexpected exception");
|
||||
}
|
||||
}
|
||||
|
||||
public final void testBuildDetailsHttpServletRequestNoMappedNoUserRoles() {
|
||||
String[] mappedRoles = new String[] {};
|
||||
String[] roles = new String[] {};
|
||||
String[] expectedRoles = new String[] {};
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
public final void testBuildDetailsHttpServletRequestNoMappedNoUserRoles() {
|
||||
String[] mappedRoles = new String[] {};
|
||||
String[] roles = new String[] {};
|
||||
String[] expectedRoles = new String[] {};
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
|
||||
public final void testBuildDetailsHttpServletRequestNoMappedUnmappedUserRoles() {
|
||||
String[] mappedRoles = new String[] {};
|
||||
String[] roles = new String[] { "Role1", "Role2" };
|
||||
String[] expectedRoles = new String[] {};
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
public final void testBuildDetailsHttpServletRequestNoMappedUnmappedUserRoles() {
|
||||
String[] mappedRoles = new String[] {};
|
||||
String[] roles = new String[] { "Role1", "Role2" };
|
||||
String[] expectedRoles = new String[] {};
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
|
||||
public final void testBuildDetailsHttpServletRequestNoUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] {};
|
||||
String[] expectedRoles = new String[] {};
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
public final void testBuildDetailsHttpServletRequestNoUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] {};
|
||||
String[] expectedRoles = new String[] {};
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
|
||||
public final void testBuildDetailsHttpServletRequestAllUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] expectedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
public final void testBuildDetailsHttpServletRequestAllUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] expectedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
|
||||
public final void testBuildDetailsHttpServletRequestUnmappedUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] { "Role1", "Role2", "Role3", "Role4", "Role5" };
|
||||
String[] expectedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
public final void testBuildDetailsHttpServletRequestUnmappedUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] { "Role1", "Role2", "Role3", "Role4", "Role5" };
|
||||
String[] expectedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
|
||||
public final void testBuildDetailsHttpServletRequestPartialUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] { "Role2", "Role3" };
|
||||
String[] expectedRoles = new String[] { "Role2", "Role3" };
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
public final void testBuildDetailsHttpServletRequestPartialUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] { "Role2", "Role3" };
|
||||
String[] expectedRoles = new String[] { "Role2", "Role3" };
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
|
||||
public final void testBuildDetailsHttpServletRequestPartialAndUnmappedUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] { "Role2", "Role3", "Role5" };
|
||||
String[] expectedRoles = new String[] { "Role2", "Role3" };
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
public final void testBuildDetailsHttpServletRequestPartialAndUnmappedUserRoles() {
|
||||
String[] mappedRoles = new String[] { "Role1", "Role2", "Role3", "Role4" };
|
||||
String[] roles = new String[] { "Role2", "Role3", "Role5" };
|
||||
String[] expectedRoles = new String[] { "Role2", "Role3" };
|
||||
testDetails(mappedRoles, roles, expectedRoles);
|
||||
}
|
||||
|
||||
private void testDetails(String[] mappedRoles, String[] userRoles, String[] expectedRoles) {
|
||||
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource src = getJ2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(mappedRoles);
|
||||
Object o = src.buildDetails(getRequest("testUser", userRoles));
|
||||
assertNotNull(o);
|
||||
assertTrue("Returned object not of type PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails, actual type: " + o.getClass(),
|
||||
o instanceof PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails);
|
||||
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = (PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails) o;
|
||||
List<GrantedAuthority> gas = details.getGrantedAuthorities();
|
||||
assertNotNull("Granted authorities should not be null", gas);
|
||||
assertEquals(expectedRoles.length, gas.size());
|
||||
private void testDetails(String[] mappedRoles, String[] userRoles,
|
||||
String[] expectedRoles) {
|
||||
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource src = getJ2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(mappedRoles);
|
||||
Object o = src.buildDetails(getRequest("testUser", userRoles));
|
||||
assertNotNull(o);
|
||||
assertTrue(
|
||||
"Returned object not of type PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails, actual type: "
|
||||
+ o.getClass(),
|
||||
o instanceof PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails);
|
||||
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = (PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails) o;
|
||||
List<GrantedAuthority> gas = details.getGrantedAuthorities();
|
||||
assertNotNull("Granted authorities should not be null", gas);
|
||||
assertEquals(expectedRoles.length, gas.size());
|
||||
|
||||
Collection<String> expectedRolesColl = Arrays.asList(expectedRoles);
|
||||
Collection<String> gasRolesSet = new HashSet<String>();
|
||||
for (int i = 0; i < gas.size(); i++) {
|
||||
gasRolesSet.add(gas.get(i).getAuthority());
|
||||
}
|
||||
assertTrue("Granted Authorities do not match expected roles", expectedRolesColl.containsAll(gasRolesSet)
|
||||
&& gasRolesSet.containsAll(expectedRolesColl));
|
||||
}
|
||||
Collection<String> expectedRolesColl = Arrays.asList(expectedRoles);
|
||||
Collection<String> gasRolesSet = new HashSet<String>();
|
||||
for (int i = 0; i < gas.size(); i++) {
|
||||
gasRolesSet.add(gas.get(i).getAuthority());
|
||||
}
|
||||
assertTrue(
|
||||
"Granted Authorities do not match expected roles",
|
||||
expectedRolesColl.containsAll(gasRolesSet)
|
||||
&& gasRolesSet.containsAll(expectedRolesColl));
|
||||
}
|
||||
|
||||
private J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource getJ2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(
|
||||
String[] mappedRoles) {
|
||||
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource result = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource();
|
||||
result.setMappableRolesRetriever(getMappableRolesRetriever(mappedRoles));
|
||||
result.setUserRoles2GrantedAuthoritiesMapper(getJ2eeUserRoles2GrantedAuthoritiesMapper());
|
||||
private J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource getJ2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(
|
||||
String[] mappedRoles) {
|
||||
J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource result = new J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource();
|
||||
result.setMappableRolesRetriever(getMappableRolesRetriever(mappedRoles));
|
||||
result.setUserRoles2GrantedAuthoritiesMapper(getJ2eeUserRoles2GrantedAuthoritiesMapper());
|
||||
|
||||
try {
|
||||
result.afterPropertiesSet();
|
||||
} catch (Exception expected) {
|
||||
fail("AfterPropertiesSet throws unexpected exception");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
try {
|
||||
result.afterPropertiesSet();
|
||||
}
|
||||
catch (Exception expected) {
|
||||
fail("AfterPropertiesSet throws unexpected exception");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private MappableAttributesRetriever getMappableRolesRetriever(String[] mappedRoles) {
|
||||
SimpleMappableAttributesRetriever result = new SimpleMappableAttributesRetriever();
|
||||
result.setMappableAttributes(new HashSet<String>(Arrays.asList(mappedRoles)));
|
||||
return result;
|
||||
}
|
||||
private MappableAttributesRetriever getMappableRolesRetriever(String[] mappedRoles) {
|
||||
SimpleMappableAttributesRetriever result = new SimpleMappableAttributesRetriever();
|
||||
result.setMappableAttributes(new HashSet<String>(Arrays.asList(mappedRoles)));
|
||||
return result;
|
||||
}
|
||||
|
||||
private Attributes2GrantedAuthoritiesMapper getJ2eeUserRoles2GrantedAuthoritiesMapper() {
|
||||
SimpleAttributes2GrantedAuthoritiesMapper result = new SimpleAttributes2GrantedAuthoritiesMapper();
|
||||
result.setAddPrefixIfAlreadyExisting(false);
|
||||
result.setConvertAttributeToLowerCase(false);
|
||||
result.setConvertAttributeToUpperCase(false);
|
||||
result.setAttributePrefix("");
|
||||
return result;
|
||||
}
|
||||
private Attributes2GrantedAuthoritiesMapper getJ2eeUserRoles2GrantedAuthoritiesMapper() {
|
||||
SimpleAttributes2GrantedAuthoritiesMapper result = new SimpleAttributes2GrantedAuthoritiesMapper();
|
||||
result.setAddPrefixIfAlreadyExisting(false);
|
||||
result.setConvertAttributeToLowerCase(false);
|
||||
result.setConvertAttributeToUpperCase(false);
|
||||
result.setAttributePrefix("");
|
||||
return result;
|
||||
}
|
||||
|
||||
private HttpServletRequest getRequest(final String userName,final String[] aRoles)
|
||||
{
|
||||
MockHttpServletRequest req = new MockHttpServletRequest() {
|
||||
private Set<String> roles = new HashSet<String>(Arrays.asList(aRoles));
|
||||
public boolean isUserInRole(String arg0) {
|
||||
return roles.contains(arg0);
|
||||
}
|
||||
};
|
||||
req.setRemoteUser(userName);
|
||||
return req;
|
||||
}
|
||||
private HttpServletRequest getRequest(final String userName, final String[] aRoles) {
|
||||
MockHttpServletRequest req = new MockHttpServletRequest() {
|
||||
private Set<String> roles = new HashSet<String>(Arrays.asList(aRoles));
|
||||
|
||||
public boolean isUserInRole(String arg0) {
|
||||
return roles.contains(arg0);
|
||||
}
|
||||
};
|
||||
req.setRemoteUser(userName);
|
||||
return req;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,32 +19,36 @@ import org.springframework.security.web.authentication.preauth.j2ee.J2eePreAuthe
|
||||
*/
|
||||
public class J2eePreAuthenticatedProcessingFilterTests extends TestCase {
|
||||
|
||||
public final void testGetPreAuthenticatedPrincipal() {
|
||||
String user = "testUser";
|
||||
assertEquals(user, new J2eePreAuthenticatedProcessingFilter().getPreAuthenticatedPrincipal(
|
||||
getRequest(user,new String[] {})));
|
||||
}
|
||||
public final void testGetPreAuthenticatedPrincipal() {
|
||||
String user = "testUser";
|
||||
assertEquals(user,
|
||||
new J2eePreAuthenticatedProcessingFilter()
|
||||
.getPreAuthenticatedPrincipal(getRequest(user, new String[] {})));
|
||||
}
|
||||
|
||||
public final void testGetPreAuthenticatedCredentials() {
|
||||
assertEquals("N/A", new J2eePreAuthenticatedProcessingFilter().getPreAuthenticatedCredentials(
|
||||
getRequest("testUser", new String[] {})));
|
||||
}
|
||||
public final void testGetPreAuthenticatedCredentials() {
|
||||
assertEquals("N/A",
|
||||
new J2eePreAuthenticatedProcessingFilter()
|
||||
.getPreAuthenticatedCredentials(getRequest("testUser",
|
||||
new String[] {})));
|
||||
}
|
||||
|
||||
private final HttpServletRequest getRequest(final String aUserName,final String[] aRoles)
|
||||
{
|
||||
MockHttpServletRequest req = new MockHttpServletRequest() {
|
||||
private Set<String> roles = new HashSet<String>(Arrays.asList(aRoles));
|
||||
public boolean isUserInRole(String arg0) {
|
||||
return roles.contains(arg0);
|
||||
}
|
||||
};
|
||||
req.setRemoteUser(aUserName);
|
||||
req.setUserPrincipal(new Principal() {
|
||||
public String getName() {
|
||||
return aUserName;
|
||||
}
|
||||
});
|
||||
return req;
|
||||
}
|
||||
private final HttpServletRequest getRequest(final String aUserName,
|
||||
final String[] aRoles) {
|
||||
MockHttpServletRequest req = new MockHttpServletRequest() {
|
||||
private Set<String> roles = new HashSet<String>(Arrays.asList(aRoles));
|
||||
|
||||
public boolean isUserInRole(String arg0) {
|
||||
return roles.contains(arg0);
|
||||
}
|
||||
};
|
||||
req.setRemoteUser(aUserName);
|
||||
req.setUserPrincipal(new Principal() {
|
||||
public String getName() {
|
||||
return aUserName;
|
||||
}
|
||||
});
|
||||
return req;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -13,46 +13,50 @@ import org.springframework.core.io.ResourceLoader;
|
||||
|
||||
public class WebXmlJ2eeDefinedRolesRetrieverTests {
|
||||
|
||||
@Test
|
||||
public void testRole1To4Roles() throws Exception {
|
||||
List<String> ROLE1TO4_EXPECTED_ROLES = Arrays.asList(new String[] { "Role1", "Role2", "Role3", "Role4" });
|
||||
final Resource webXml = new ClassPathResource("webxml/Role1-4.web.xml");
|
||||
WebXmlMappableAttributesRetriever rolesRetriever = new WebXmlMappableAttributesRetriever();
|
||||
@Test
|
||||
public void testRole1To4Roles() throws Exception {
|
||||
List<String> ROLE1TO4_EXPECTED_ROLES = Arrays.asList(new String[] { "Role1",
|
||||
"Role2", "Role3", "Role4" });
|
||||
final Resource webXml = new ClassPathResource("webxml/Role1-4.web.xml");
|
||||
WebXmlMappableAttributesRetriever rolesRetriever = new WebXmlMappableAttributesRetriever();
|
||||
|
||||
rolesRetriever.setResourceLoader(new ResourceLoader() {
|
||||
public ClassLoader getClassLoader() {
|
||||
return Thread.currentThread().getContextClassLoader();
|
||||
}
|
||||
rolesRetriever.setResourceLoader(new ResourceLoader() {
|
||||
public ClassLoader getClassLoader() {
|
||||
return Thread.currentThread().getContextClassLoader();
|
||||
}
|
||||
|
||||
public Resource getResource(String location) {
|
||||
return webXml;
|
||||
}
|
||||
});
|
||||
public Resource getResource(String location) {
|
||||
return webXml;
|
||||
}
|
||||
});
|
||||
|
||||
rolesRetriever.afterPropertiesSet();
|
||||
Set<String> j2eeRoles = rolesRetriever.getMappableAttributes();
|
||||
assertNotNull(j2eeRoles);
|
||||
assertTrue("J2eeRoles expected size: " + ROLE1TO4_EXPECTED_ROLES.size() + ", actual size: " + j2eeRoles.size(),
|
||||
j2eeRoles.size() == ROLE1TO4_EXPECTED_ROLES.size());
|
||||
assertTrue("J2eeRoles expected contents (arbitrary order): " + ROLE1TO4_EXPECTED_ROLES + ", actual content: " + j2eeRoles,
|
||||
j2eeRoles.containsAll(ROLE1TO4_EXPECTED_ROLES));
|
||||
}
|
||||
rolesRetriever.afterPropertiesSet();
|
||||
Set<String> j2eeRoles = rolesRetriever.getMappableAttributes();
|
||||
assertNotNull(j2eeRoles);
|
||||
assertTrue("J2eeRoles expected size: " + ROLE1TO4_EXPECTED_ROLES.size()
|
||||
+ ", actual size: " + j2eeRoles.size(),
|
||||
j2eeRoles.size() == ROLE1TO4_EXPECTED_ROLES.size());
|
||||
assertTrue("J2eeRoles expected contents (arbitrary order): "
|
||||
+ ROLE1TO4_EXPECTED_ROLES + ", actual content: " + j2eeRoles,
|
||||
j2eeRoles.containsAll(ROLE1TO4_EXPECTED_ROLES));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetZeroJ2eeRoles() throws Exception {
|
||||
final Resource webXml = new ClassPathResource("webxml/NoRoles.web.xml");
|
||||
WebXmlMappableAttributesRetriever rolesRetriever = new WebXmlMappableAttributesRetriever();
|
||||
rolesRetriever.setResourceLoader(new ResourceLoader() {
|
||||
public ClassLoader getClassLoader() {
|
||||
return Thread.currentThread().getContextClassLoader();
|
||||
}
|
||||
@Test
|
||||
public void testGetZeroJ2eeRoles() throws Exception {
|
||||
final Resource webXml = new ClassPathResource("webxml/NoRoles.web.xml");
|
||||
WebXmlMappableAttributesRetriever rolesRetriever = new WebXmlMappableAttributesRetriever();
|
||||
rolesRetriever.setResourceLoader(new ResourceLoader() {
|
||||
public ClassLoader getClassLoader() {
|
||||
return Thread.currentThread().getContextClassLoader();
|
||||
}
|
||||
|
||||
public Resource getResource(String location) {
|
||||
return webXml;
|
||||
}
|
||||
});
|
||||
rolesRetriever.afterPropertiesSet();
|
||||
Set<String> j2eeRoles = rolesRetriever.getMappableAttributes();
|
||||
assertEquals("J2eeRoles expected size: 0, actual size: " + j2eeRoles.size(), 0, j2eeRoles.size());
|
||||
}
|
||||
public Resource getResource(String location) {
|
||||
return webXml;
|
||||
}
|
||||
});
|
||||
rolesRetriever.afterPropertiesSet();
|
||||
Set<String> j2eeRoles = rolesRetriever.getMappableAttributes();
|
||||
assertEquals("J2eeRoles expected size: 0, actual size: " + j2eeRoles.size(), 0,
|
||||
j2eeRoles.size());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,35 +22,40 @@ import javax.servlet.FilterChain;
|
||||
*/
|
||||
public class WebSpherePreAuthenticatedProcessingFilterTests {
|
||||
|
||||
@After
|
||||
public void clearContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
@After
|
||||
public void clearContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void principalsAndCredentialsAreExtractedCorrectly() throws Exception {
|
||||
new WebSpherePreAuthenticatedProcessingFilter();
|
||||
WASUsernameAndGroupsExtractor helper = mock(WASUsernameAndGroupsExtractor.class);
|
||||
when(helper.getCurrentUserName()).thenReturn("jerry");
|
||||
WebSpherePreAuthenticatedProcessingFilter filter = new WebSpherePreAuthenticatedProcessingFilter(helper);
|
||||
assertEquals("jerry", filter.getPreAuthenticatedPrincipal(new MockHttpServletRequest()));
|
||||
assertEquals("N/A", filter.getPreAuthenticatedCredentials(new MockHttpServletRequest()));
|
||||
@Test
|
||||
public void principalsAndCredentialsAreExtractedCorrectly() throws Exception {
|
||||
new WebSpherePreAuthenticatedProcessingFilter();
|
||||
WASUsernameAndGroupsExtractor helper = mock(WASUsernameAndGroupsExtractor.class);
|
||||
when(helper.getCurrentUserName()).thenReturn("jerry");
|
||||
WebSpherePreAuthenticatedProcessingFilter filter = new WebSpherePreAuthenticatedProcessingFilter(
|
||||
helper);
|
||||
assertEquals("jerry",
|
||||
filter.getPreAuthenticatedPrincipal(new MockHttpServletRequest()));
|
||||
assertEquals("N/A",
|
||||
filter.getPreAuthenticatedCredentials(new MockHttpServletRequest()));
|
||||
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
when(am.authenticate(any(Authentication.class))).thenAnswer(new Answer<Authentication>() {
|
||||
public Authentication answer(InvocationOnMock invocation) throws Throwable {
|
||||
return (Authentication) invocation.getArguments()[0];
|
||||
}
|
||||
});
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
when(am.authenticate(any(Authentication.class))).thenAnswer(
|
||||
new Answer<Authentication>() {
|
||||
public Authentication answer(InvocationOnMock invocation)
|
||||
throws Throwable {
|
||||
return (Authentication) invocation.getArguments()[0];
|
||||
}
|
||||
});
|
||||
|
||||
filter.setAuthenticationManager(am);
|
||||
WebSpherePreAuthenticatedWebAuthenticationDetailsSource ads =
|
||||
new WebSpherePreAuthenticatedWebAuthenticationDetailsSource(helper);
|
||||
ads.setWebSphereGroups2GrantedAuthoritiesMapper(new SimpleAttributes2GrantedAuthoritiesMapper());
|
||||
filter.setAuthenticationDetailsSource(ads);
|
||||
|
||||
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), mock(FilterChain.class));
|
||||
}
|
||||
filter.setAuthenticationManager(am);
|
||||
WebSpherePreAuthenticatedWebAuthenticationDetailsSource ads = new WebSpherePreAuthenticatedWebAuthenticationDetailsSource(
|
||||
helper);
|
||||
ads.setWebSphereGroups2GrantedAuthoritiesMapper(new SimpleAttributes2GrantedAuthoritiesMapper());
|
||||
filter.setAuthenticationDetailsSource(ads);
|
||||
|
||||
filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(),
|
||||
mock(FilterChain.class));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -13,41 +13,44 @@ import static junit.framework.Assert.*;
|
||||
* @author Luke Taylor
|
||||
*/
|
||||
public class SubjectDnX509PrincipalExtractorTests {
|
||||
SubjectDnX509PrincipalExtractor extractor;
|
||||
SubjectDnX509PrincipalExtractor extractor;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
extractor = new SubjectDnX509PrincipalExtractor();
|
||||
extractor.setMessageSource(new SpringSecurityMessageSource());
|
||||
}
|
||||
@Before
|
||||
public void setUp() {
|
||||
extractor = new SubjectDnX509PrincipalExtractor();
|
||||
extractor.setMessageSource(new SpringSecurityMessageSource());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void invalidRegexFails() throws Exception {
|
||||
extractor.setSubjectDnRegex("CN=(.*?,"); // missing closing bracket on group
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void invalidRegexFails() throws Exception {
|
||||
extractor.setSubjectDnRegex("CN=(.*?,"); // missing closing bracket on group
|
||||
}
|
||||
|
||||
@Test
|
||||
public void defaultCNPatternReturnsExcpectedPrincipal() throws Exception {
|
||||
Object principal = extractor.extractPrincipal(X509TestUtils.buildTestCertificate());
|
||||
assertEquals("Luke Taylor", principal);
|
||||
}
|
||||
@Test
|
||||
public void defaultCNPatternReturnsExcpectedPrincipal() throws Exception {
|
||||
Object principal = extractor.extractPrincipal(X509TestUtils
|
||||
.buildTestCertificate());
|
||||
assertEquals("Luke Taylor", principal);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void matchOnEmailReturnsExpectedPrincipal() throws Exception {
|
||||
extractor.setSubjectDnRegex("emailAddress=(.*?),");
|
||||
Object principal = extractor.extractPrincipal(X509TestUtils.buildTestCertificate());
|
||||
assertEquals("luke@monkeymachine", principal);
|
||||
}
|
||||
@Test
|
||||
public void matchOnEmailReturnsExpectedPrincipal() throws Exception {
|
||||
extractor.setSubjectDnRegex("emailAddress=(.*?),");
|
||||
Object principal = extractor.extractPrincipal(X509TestUtils
|
||||
.buildTestCertificate());
|
||||
assertEquals("luke@monkeymachine", principal);
|
||||
}
|
||||
|
||||
@Test(expected = BadCredentialsException.class)
|
||||
public void matchOnShoeSizeThrowsBadCredentials() throws Exception {
|
||||
extractor.setSubjectDnRegex("shoeSize=(.*?),");
|
||||
extractor.extractPrincipal(X509TestUtils.buildTestCertificate());
|
||||
}
|
||||
@Test(expected = BadCredentialsException.class)
|
||||
public void matchOnShoeSizeThrowsBadCredentials() throws Exception {
|
||||
extractor.setSubjectDnRegex("shoeSize=(.*?),");
|
||||
extractor.extractPrincipal(X509TestUtils.buildTestCertificate());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void defaultCNPatternReturnsPrincipalAtEndOfDNString() throws Exception {
|
||||
Object principal = extractor.extractPrincipal(X509TestUtils.buildTestCertificateWithCnAtEnd());
|
||||
assertEquals("Duke", principal);
|
||||
}
|
||||
@Test
|
||||
public void defaultCNPatternReturnsPrincipalAtEndOfDNString() throws Exception {
|
||||
Object principal = extractor.extractPrincipal(X509TestUtils
|
||||
.buildTestCertificateWithCnAtEnd());
|
||||
assertEquals("Duke", principal);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,119 +20,121 @@ import java.io.ByteArrayInputStream;
|
||||
import java.security.cert.CertificateFactory;
|
||||
import java.security.cert.X509Certificate;
|
||||
|
||||
|
||||
/**
|
||||
* Certificate creation utility for use in X.509 tests.
|
||||
*
|
||||
* @author Luke Taylor
|
||||
*/
|
||||
public class X509TestUtils {
|
||||
//~ Methods ========================================================================================================
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
/**
|
||||
* Builds an X.509 certificate. In human-readable form it is:
|
||||
* <pre>
|
||||
* Certificate:
|
||||
* Data:
|
||||
* Version: 3 (0x2)
|
||||
* Serial Number: 1 (0x1)
|
||||
* Signature Algorithm: sha1WithRSAEncryption
|
||||
* Issuer: CN=Monkey Machine CA, C=UK, ST=Scotland, L=Glasgow,
|
||||
* O=monkeymachine.co.uk/emailAddress=ca@monkeymachine
|
||||
* Validity
|
||||
* Not Before: Mar 6 23:28:22 2005 GMT
|
||||
* Not After : Mar 6 23:28:22 2006 GMT
|
||||
* Subject: C=UK, ST=Scotland, L=Glasgow, O=Monkey Machine Ltd,
|
||||
* OU=Open Source Development Lab., CN=Luke Taylor/emailAddress=luke@monkeymachine
|
||||
* Subject Public Key Info:
|
||||
* Public Key Algorithm: rsaEncryption
|
||||
* RSA Public Key: (512 bit)
|
||||
* [omitted]
|
||||
* X509v3 extensions:
|
||||
* X509v3 Basic Constraints:
|
||||
* CA:FALSE
|
||||
* Netscape Cert Type:
|
||||
* SSL Client
|
||||
* X509v3 Key Usage:
|
||||
* Digital Signature, Non Repudiation, Key Encipherment
|
||||
* X509v3 Subject Key Identifier:
|
||||
* 6E:E6:5B:57:33:CF:0E:2F:15:C2:F4:DF:EC:14:BE:FB:CF:54:56:3C
|
||||
* X509v3 Authority Key Identifier:
|
||||
* keyid:AB:78:EC:AF:10:1B:8A:9B:1F:C7:B1:25:8F:16:28:F2:17:9A:AD:36
|
||||
* DirName:/CN=Monkey Machine CA/C=UK/ST=Scotland/L=Glasgow/O=monkeymachine.co.uk/emailAddress=ca@monkeymachine
|
||||
* serial:00
|
||||
* Netscape CA Revocation Url:
|
||||
* https://monkeymachine.co.uk/ca-crl.pem
|
||||
* Signature Algorithm: sha1WithRSAEncryption
|
||||
* [signature omitted]
|
||||
* </pre>
|
||||
*/
|
||||
public static X509Certificate buildTestCertificate() throws Exception {
|
||||
String cert = "-----BEGIN CERTIFICATE-----\n"
|
||||
+ "MIIEQTCCAymgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBkzEaMBgGA1UEAxMRTW9u\n"
|
||||
+ "a2V5IE1hY2hpbmUgQ0ExCzAJBgNVBAYTAlVLMREwDwYDVQQIEwhTY290bGFuZDEQ\n"
|
||||
+ "MA4GA1UEBxMHR2xhc2dvdzEcMBoGA1UEChMTbW9ua2V5bWFjaGluZS5jby51azEl\n"
|
||||
+ "MCMGCSqGSIb3DQEJARYWY2FAbW9ua2V5bWFjaGluZS5jby51azAeFw0wNTAzMDYy\n"
|
||||
+ "MzI4MjJaFw0wNjAzMDYyMzI4MjJaMIGvMQswCQYDVQQGEwJVSzERMA8GA1UECBMI\n"
|
||||
+ "U2NvdGxhbmQxEDAOBgNVBAcTB0dsYXNnb3cxGzAZBgNVBAoTEk1vbmtleSBNYWNo\n"
|
||||
+ "aW5lIEx0ZDElMCMGA1UECxMcT3BlbiBTb3VyY2UgRGV2ZWxvcG1lbnQgTGFiLjEU\n"
|
||||
+ "MBIGA1UEAxMLTHVrZSBUYXlsb3IxITAfBgkqhkiG9w0BCQEWEmx1a2VAbW9ua2V5\n"
|
||||
+ "bWFjaGluZTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDItxZr07mm65ttYH7RMaVo\n"
|
||||
+ "VeMCq4ptfn+GFFEk4+54OkDuh1CHlk87gEc1jx3ZpQPJRTJx31z3YkiAcP+RDzxr\n"
|
||||
+ "AgMBAAGjggFIMIIBRDAJBgNVHRMEAjAAMBEGCWCGSAGG+EIBAQQEAwIHgDALBgNV\n"
|
||||
+ "HQ8EBAMCBeAwHQYDVR0OBBYEFG7mW1czzw4vFcL03+wUvvvPVFY8MIHABgNVHSME\n"
|
||||
+ "gbgwgbWAFKt47K8QG4qbH8exJY8WKPIXmq02oYGZpIGWMIGTMRowGAYDVQQDExFN\n"
|
||||
+ "b25rZXkgTWFjaGluZSBDQTELMAkGA1UEBhMCVUsxETAPBgNVBAgTCFNjb3RsYW5k\n"
|
||||
+ "MRAwDgYDVQQHEwdHbGFzZ293MRwwGgYDVQQKExNtb25rZXltYWNoaW5lLmNvLnVr\n"
|
||||
+ "MSUwIwYJKoZIhvcNAQkBFhZjYUBtb25rZXltYWNoaW5lLmNvLnVrggEAMDUGCWCG\n"
|
||||
+ "SAGG+EIBBAQoFiZodHRwczovL21vbmtleW1hY2hpbmUuY28udWsvY2EtY3JsLnBl\n"
|
||||
+ "bTANBgkqhkiG9w0BAQUFAAOCAQEAZ961bEgm2rOq6QajRLeoljwXDnt0S9BGEWL4\n"
|
||||
+ "PMU2FXDog9aaPwfmZ5fwKaSebwH4HckTp11xwe/D9uBZJQ74Uf80UL9z2eo0GaSR\n"
|
||||
+ "nRB3QPZfRvop0I4oPvwViKt3puLsi9XSSJ1w9yswnIf89iONT7ZyssPg48Bojo8q\n"
|
||||
+ "lcKwXuDRBWciODK/xWhvQbaegGJ1BtXcEHtvNjrUJLwSMDSr+U5oUYdMohG0h1iJ\n"
|
||||
+ "R+JQc49I33o2cTc77wfEWLtVdXAyYY4GSJR6VfgvV40x85ItaNS3HHfT/aXU1x4m\n"
|
||||
+ "W9YQkWlA6t0blGlC+ghTOY1JbgWnEfXMmVgg9a9cWaYQ+NQwqA==\n" + "-----END CERTIFICATE-----";
|
||||
/**
|
||||
* Builds an X.509 certificate. In human-readable form it is:
|
||||
*
|
||||
* <pre>
|
||||
* Certificate:
|
||||
* Data:
|
||||
* Version: 3 (0x2)
|
||||
* Serial Number: 1 (0x1)
|
||||
* Signature Algorithm: sha1WithRSAEncryption
|
||||
* Issuer: CN=Monkey Machine CA, C=UK, ST=Scotland, L=Glasgow,
|
||||
* O=monkeymachine.co.uk/emailAddress=ca@monkeymachine
|
||||
* Validity
|
||||
* Not Before: Mar 6 23:28:22 2005 GMT
|
||||
* Not After : Mar 6 23:28:22 2006 GMT
|
||||
* Subject: C=UK, ST=Scotland, L=Glasgow, O=Monkey Machine Ltd,
|
||||
* OU=Open Source Development Lab., CN=Luke Taylor/emailAddress=luke@monkeymachine
|
||||
* Subject Public Key Info:
|
||||
* Public Key Algorithm: rsaEncryption
|
||||
* RSA Public Key: (512 bit)
|
||||
* [omitted]
|
||||
* X509v3 extensions:
|
||||
* X509v3 Basic Constraints:
|
||||
* CA:FALSE
|
||||
* Netscape Cert Type:
|
||||
* SSL Client
|
||||
* X509v3 Key Usage:
|
||||
* Digital Signature, Non Repudiation, Key Encipherment
|
||||
* X509v3 Subject Key Identifier:
|
||||
* 6E:E6:5B:57:33:CF:0E:2F:15:C2:F4:DF:EC:14:BE:FB:CF:54:56:3C
|
||||
* X509v3 Authority Key Identifier:
|
||||
* keyid:AB:78:EC:AF:10:1B:8A:9B:1F:C7:B1:25:8F:16:28:F2:17:9A:AD:36
|
||||
* DirName:/CN=Monkey Machine CA/C=UK/ST=Scotland/L=Glasgow/O=monkeymachine.co.uk/emailAddress=ca@monkeymachine
|
||||
* serial:00
|
||||
* Netscape CA Revocation Url:
|
||||
* https://monkeymachine.co.uk/ca-crl.pem
|
||||
* Signature Algorithm: sha1WithRSAEncryption
|
||||
* [signature omitted]
|
||||
* </pre>
|
||||
*/
|
||||
public static X509Certificate buildTestCertificate() throws Exception {
|
||||
String cert = "-----BEGIN CERTIFICATE-----\n"
|
||||
+ "MIIEQTCCAymgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBkzEaMBgGA1UEAxMRTW9u\n"
|
||||
+ "a2V5IE1hY2hpbmUgQ0ExCzAJBgNVBAYTAlVLMREwDwYDVQQIEwhTY290bGFuZDEQ\n"
|
||||
+ "MA4GA1UEBxMHR2xhc2dvdzEcMBoGA1UEChMTbW9ua2V5bWFjaGluZS5jby51azEl\n"
|
||||
+ "MCMGCSqGSIb3DQEJARYWY2FAbW9ua2V5bWFjaGluZS5jby51azAeFw0wNTAzMDYy\n"
|
||||
+ "MzI4MjJaFw0wNjAzMDYyMzI4MjJaMIGvMQswCQYDVQQGEwJVSzERMA8GA1UECBMI\n"
|
||||
+ "U2NvdGxhbmQxEDAOBgNVBAcTB0dsYXNnb3cxGzAZBgNVBAoTEk1vbmtleSBNYWNo\n"
|
||||
+ "aW5lIEx0ZDElMCMGA1UECxMcT3BlbiBTb3VyY2UgRGV2ZWxvcG1lbnQgTGFiLjEU\n"
|
||||
+ "MBIGA1UEAxMLTHVrZSBUYXlsb3IxITAfBgkqhkiG9w0BCQEWEmx1a2VAbW9ua2V5\n"
|
||||
+ "bWFjaGluZTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDItxZr07mm65ttYH7RMaVo\n"
|
||||
+ "VeMCq4ptfn+GFFEk4+54OkDuh1CHlk87gEc1jx3ZpQPJRTJx31z3YkiAcP+RDzxr\n"
|
||||
+ "AgMBAAGjggFIMIIBRDAJBgNVHRMEAjAAMBEGCWCGSAGG+EIBAQQEAwIHgDALBgNV\n"
|
||||
+ "HQ8EBAMCBeAwHQYDVR0OBBYEFG7mW1czzw4vFcL03+wUvvvPVFY8MIHABgNVHSME\n"
|
||||
+ "gbgwgbWAFKt47K8QG4qbH8exJY8WKPIXmq02oYGZpIGWMIGTMRowGAYDVQQDExFN\n"
|
||||
+ "b25rZXkgTWFjaGluZSBDQTELMAkGA1UEBhMCVUsxETAPBgNVBAgTCFNjb3RsYW5k\n"
|
||||
+ "MRAwDgYDVQQHEwdHbGFzZ293MRwwGgYDVQQKExNtb25rZXltYWNoaW5lLmNvLnVr\n"
|
||||
+ "MSUwIwYJKoZIhvcNAQkBFhZjYUBtb25rZXltYWNoaW5lLmNvLnVrggEAMDUGCWCG\n"
|
||||
+ "SAGG+EIBBAQoFiZodHRwczovL21vbmtleW1hY2hpbmUuY28udWsvY2EtY3JsLnBl\n"
|
||||
+ "bTANBgkqhkiG9w0BAQUFAAOCAQEAZ961bEgm2rOq6QajRLeoljwXDnt0S9BGEWL4\n"
|
||||
+ "PMU2FXDog9aaPwfmZ5fwKaSebwH4HckTp11xwe/D9uBZJQ74Uf80UL9z2eo0GaSR\n"
|
||||
+ "nRB3QPZfRvop0I4oPvwViKt3puLsi9XSSJ1w9yswnIf89iONT7ZyssPg48Bojo8q\n"
|
||||
+ "lcKwXuDRBWciODK/xWhvQbaegGJ1BtXcEHtvNjrUJLwSMDSr+U5oUYdMohG0h1iJ\n"
|
||||
+ "R+JQc49I33o2cTc77wfEWLtVdXAyYY4GSJR6VfgvV40x85ItaNS3HHfT/aXU1x4m\n"
|
||||
+ "W9YQkWlA6t0blGlC+ghTOY1JbgWnEfXMmVgg9a9cWaYQ+NQwqA==\n"
|
||||
+ "-----END CERTIFICATE-----";
|
||||
|
||||
ByteArrayInputStream in = new ByteArrayInputStream(cert.getBytes());
|
||||
CertificateFactory cf = CertificateFactory.getInstance("X.509");
|
||||
ByteArrayInputStream in = new ByteArrayInputStream(cert.getBytes());
|
||||
CertificateFactory cf = CertificateFactory.getInstance("X.509");
|
||||
|
||||
return (X509Certificate) cf.generateCertificate(in);
|
||||
}
|
||||
return (X509Certificate) cf.generateCertificate(in);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an X.509 certificate with a subject DN where the CN field is at the end of the line.
|
||||
* The actual DN line is:
|
||||
* <pre>
|
||||
* L=Cupertino,C=US,ST=CA,OU=Java Software,O=Sun Microsystems\, Inc,CN=Duke
|
||||
* </pre>
|
||||
*
|
||||
*/
|
||||
public static X509Certificate buildTestCertificateWithCnAtEnd() throws Exception {
|
||||
String cert = "-----BEGIN CERTIFICATE-----\n" +
|
||||
"MIIDjTCCAnWgAwIBAgIBATALBgkqhkiG9w0BAQswdTENMAsGA1UEAwwERHVrZTEe\n" +
|
||||
"MBwGA1UECgwVU3VuIE1pY3Jvc3lzdGVtcywgSW5jMRYwFAYDVQQLDA1KYXZhIFNv\n" +
|
||||
"ZnR3YXJlMQswCQYDVQQIDAJDQTELMAkGA1UEBhMCVVMxEjAQBgNVBAcMCUN1cGVy\n" +
|
||||
"dGlubzAeFw0xMjA1MTgxNDQ4MzBaFw0xMzA1MTgxNDQ4MzBaMHUxDTALBgNVBAMM\n" +
|
||||
"BER1a2UxHjAcBgNVBAoMFVN1biBNaWNyb3N5c3RlbXMsIEluYzEWMBQGA1UECwwN\n" +
|
||||
"SmF2YSBTb2Z0d2FyZTELMAkGA1UECAwCQ0ExCzAJBgNVBAYTAlVTMRIwEAYDVQQH\n" +
|
||||
"DAlDdXBlcnRpbm8wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDGLaCx\n" +
|
||||
"Dy5oRJ/FelcoO/lAEApAhR4wxmUIu0guzN0Tx/cuWfyo4349NOxf5XfRcje37B//\n" +
|
||||
"hyMwK1Q/pRhRYtZlK+O+9tNCAupekmSxEw9wNsRXNJ18QTTvQRPReXhG8gOiGmU2\n" +
|
||||
"kpTVjpZURo/0WGuEyAWYzH99cQfUM92vIaGKq2fApNfwCULtFnAY9WPDZtwSZYhC\n" +
|
||||
"qSAoy6B1I2A3i+G5Ep++eCa9PZKCZIPWJiC5+nMmzwCOnQqcZlorsrQ+M+I4GgE2\n" +
|
||||
"Rryb/AeKoSPsrm4t0aWhFhKcuHpk3jfKhJhi5e+5bnY17pCoY9hx5EK3WqfKL/x1\n" +
|
||||
"3HKsPpf/MieRWiAdAgMBAAGjKjAoMA4GA1UdDwEB/wQEAwIHgDAWBgNVHSUBAf8E\n" +
|
||||
"DDAKBggrBgEFBQcDAjANBgkqhkiG9w0BAQsFAAOCAQEAdAtXZYCdb7JKzfwY7vEO\n" +
|
||||
"9TOMyxxwxhxs+26urL2wQWqtRgHXopoi/GGSuZG5aPQcHWLoqZ1f7nZoWfKzJMKw\n" +
|
||||
"MOvaw6wSSkmEoEvdek3s/bH6Gp0spnykqtb+kunGr/XFxyBhHmfdSroEgzspslFh\n" +
|
||||
"Glqe/XfrQmFgPWd13GH8mqzSU1zc+0Ka7s68jcuNfz9ble5rT0IrdjRm5E64mVGk\n" +
|
||||
"aJTAO5N87ks5JjkDHDJzcyYRcIpqBGotJtyZTjGpIeAG8xLGlkSsUg88iUOchI7s\n" +
|
||||
"dOmse9mpgEjCb4kdZ0PnoxMFjsPR8AoGOz4A5vA19nKqWM8bxK9hqLGKsaiQpQg7\n" +
|
||||
"bA==\n" +
|
||||
"-----END CERTIFICATE-----\n";
|
||||
ByteArrayInputStream in = new ByteArrayInputStream(cert.getBytes());
|
||||
CertificateFactory cf = CertificateFactory.getInstance("X.509");
|
||||
/**
|
||||
* Builds an X.509 certificate with a subject DN where the CN field is at the end of
|
||||
* the line. The actual DN line is:
|
||||
*
|
||||
* <pre>
|
||||
* L=Cupertino,C=US,ST=CA,OU=Java Software,O=Sun Microsystems\, Inc,CN=Duke
|
||||
* </pre>
|
||||
*
|
||||
*/
|
||||
public static X509Certificate buildTestCertificateWithCnAtEnd() throws Exception {
|
||||
String cert = "-----BEGIN CERTIFICATE-----\n"
|
||||
+ "MIIDjTCCAnWgAwIBAgIBATALBgkqhkiG9w0BAQswdTENMAsGA1UEAwwERHVrZTEe\n"
|
||||
+ "MBwGA1UECgwVU3VuIE1pY3Jvc3lzdGVtcywgSW5jMRYwFAYDVQQLDA1KYXZhIFNv\n"
|
||||
+ "ZnR3YXJlMQswCQYDVQQIDAJDQTELMAkGA1UEBhMCVVMxEjAQBgNVBAcMCUN1cGVy\n"
|
||||
+ "dGlubzAeFw0xMjA1MTgxNDQ4MzBaFw0xMzA1MTgxNDQ4MzBaMHUxDTALBgNVBAMM\n"
|
||||
+ "BER1a2UxHjAcBgNVBAoMFVN1biBNaWNyb3N5c3RlbXMsIEluYzEWMBQGA1UECwwN\n"
|
||||
+ "SmF2YSBTb2Z0d2FyZTELMAkGA1UECAwCQ0ExCzAJBgNVBAYTAlVTMRIwEAYDVQQH\n"
|
||||
+ "DAlDdXBlcnRpbm8wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDGLaCx\n"
|
||||
+ "Dy5oRJ/FelcoO/lAEApAhR4wxmUIu0guzN0Tx/cuWfyo4349NOxf5XfRcje37B//\n"
|
||||
+ "hyMwK1Q/pRhRYtZlK+O+9tNCAupekmSxEw9wNsRXNJ18QTTvQRPReXhG8gOiGmU2\n"
|
||||
+ "kpTVjpZURo/0WGuEyAWYzH99cQfUM92vIaGKq2fApNfwCULtFnAY9WPDZtwSZYhC\n"
|
||||
+ "qSAoy6B1I2A3i+G5Ep++eCa9PZKCZIPWJiC5+nMmzwCOnQqcZlorsrQ+M+I4GgE2\n"
|
||||
+ "Rryb/AeKoSPsrm4t0aWhFhKcuHpk3jfKhJhi5e+5bnY17pCoY9hx5EK3WqfKL/x1\n"
|
||||
+ "3HKsPpf/MieRWiAdAgMBAAGjKjAoMA4GA1UdDwEB/wQEAwIHgDAWBgNVHSUBAf8E\n"
|
||||
+ "DDAKBggrBgEFBQcDAjANBgkqhkiG9w0BAQsFAAOCAQEAdAtXZYCdb7JKzfwY7vEO\n"
|
||||
+ "9TOMyxxwxhxs+26urL2wQWqtRgHXopoi/GGSuZG5aPQcHWLoqZ1f7nZoWfKzJMKw\n"
|
||||
+ "MOvaw6wSSkmEoEvdek3s/bH6Gp0spnykqtb+kunGr/XFxyBhHmfdSroEgzspslFh\n"
|
||||
+ "Glqe/XfrQmFgPWd13GH8mqzSU1zc+0Ka7s68jcuNfz9ble5rT0IrdjRm5E64mVGk\n"
|
||||
+ "aJTAO5N87ks5JjkDHDJzcyYRcIpqBGotJtyZTjGpIeAG8xLGlkSsUg88iUOchI7s\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);
|
||||
}
|
||||
return (X509Certificate) cf.generateCertificate(in);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,41 +30,43 @@ import org.springframework.util.ReflectionUtils;
|
||||
* @author Rob Winch
|
||||
*/
|
||||
@RunWith(PowerMockRunner.class)
|
||||
@PrepareForTest({Method.class, ReflectionUtils.class})
|
||||
@PrepareForTest({ Method.class, ReflectionUtils.class })
|
||||
public class AbstractRememberMeServicesServlet3Tests {
|
||||
@Mock
|
||||
private Method method;
|
||||
@Mock
|
||||
private Method method;
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
spy(ReflectionUtils.class);
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
spy(ReflectionUtils.class);
|
||||
|
||||
when(ReflectionUtils.findMethod(Cookie.class, "setHttpOnly", boolean.class)).thenReturn(method);
|
||||
}
|
||||
when(ReflectionUtils.findMethod(Cookie.class, "setHttpOnly", boolean.class))
|
||||
.thenReturn(method);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void httpOnlySetInServlet30DefaultConstructor() throws Exception {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
when(request.getContextPath()).thenReturn("/contextpath");
|
||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
||||
ArgumentCaptor<Cookie> cookie = ArgumentCaptor.forClass(Cookie.class);
|
||||
MockRememberMeServices services = new MockRememberMeServices();
|
||||
services.setCookie(new String[] {"mycookie"}, 1000, request, response);
|
||||
verify(response).addCookie(cookie.capture());
|
||||
verifyStatic();
|
||||
ReflectionUtils.invokeMethod(same(method), eq(cookie.getValue()), eq(true));
|
||||
}
|
||||
@Test
|
||||
public void httpOnlySetInServlet30DefaultConstructor() throws Exception {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
when(request.getContextPath()).thenReturn("/contextpath");
|
||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
||||
ArgumentCaptor<Cookie> cookie = ArgumentCaptor.forClass(Cookie.class);
|
||||
MockRememberMeServices services = new MockRememberMeServices();
|
||||
services.setCookie(new String[] { "mycookie" }, 1000, request, response);
|
||||
verify(response).addCookie(cookie.capture());
|
||||
verifyStatic();
|
||||
ReflectionUtils.invokeMethod(same(method), eq(cookie.getValue()), eq(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void httpOnlySetInServlet30() throws Exception {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
when(request.getContextPath()).thenReturn("/contextpath");
|
||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
||||
ArgumentCaptor<Cookie> cookie = ArgumentCaptor.forClass(Cookie.class);
|
||||
MockRememberMeServices services = new MockRememberMeServices("key",mock(UserDetailsService.class));
|
||||
services.setCookie(new String[] {"mycookie"}, 1000, request, response);
|
||||
verify(response).addCookie(cookie.capture());
|
||||
verifyStatic();
|
||||
ReflectionUtils.invokeMethod(same(method), eq(cookie.getValue()), eq(true));
|
||||
}
|
||||
@Test
|
||||
public void httpOnlySetInServlet30() throws Exception {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
when(request.getContextPath()).thenReturn("/contextpath");
|
||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
||||
ArgumentCaptor<Cookie> cookie = ArgumentCaptor.forClass(Cookie.class);
|
||||
MockRememberMeServices services = new MockRememberMeServices("key",
|
||||
mock(UserDetailsService.class));
|
||||
services.setCookie(new String[] { "mycookie" }, 1000, request, response);
|
||||
verify(response).addCookie(cookie.capture());
|
||||
verifyStatic();
|
||||
ReflectionUtils.invokeMethod(same(method), eq(cookie.getValue()), eq(true));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,425 +43,446 @@ import org.springframework.util.StringUtils;
|
||||
@RunWith(PowerMockRunner.class)
|
||||
@PrepareOnlyThisForTest(ReflectionUtils.class)
|
||||
public class AbstractRememberMeServicesTests {
|
||||
static User joe = new User("joe", "password", true, true,true,true, AuthorityUtils.createAuthorityList("ROLE_A"));
|
||||
|
||||
MockUserDetailsService uds;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
uds = new MockUserDetailsService(joe, false);
|
||||
}
|
||||
|
||||
@Test(expected = InvalidCookieException.class)
|
||||
public void nonBase64CookieShouldBeDetected() {
|
||||
new MockRememberMeServices(uds).decodeCookie("nonBase64CookieValue%");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setAndGetAreConsistent() throws Exception {
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
assertNotNull(services.getCookieName());
|
||||
assertNotNull(services.getParameter());
|
||||
assertEquals("xxxx", services.getKey());
|
||||
services.setParameter("rm");
|
||||
assertEquals("rm", services.getParameter());
|
||||
services.setCookieName("kookie");
|
||||
assertEquals("kookie", services.getCookieName());
|
||||
services.setTokenValiditySeconds(600);
|
||||
assertEquals(600, services.getTokenValiditySeconds());
|
||||
assertSame(uds, services.getUserDetailsService());
|
||||
AuthenticationDetailsSource ads = mock(AuthenticationDetailsSource.class);
|
||||
services.setAuthenticationDetailsSource(ads);
|
||||
assertSame(ads, services.getAuthenticationDetailsSource());
|
||||
services.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void cookieShouldBeCorrectlyEncodedAndDecoded() throws Exception {
|
||||
String[] cookie = new String[] {"name", "cookie", "tokens", "blah"};
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
|
||||
String encoded = services.encodeCookie(cookie);
|
||||
// '=' aren't allowed in version 0 cookies.
|
||||
assertFalse(encoded.endsWith("="));
|
||||
String[] decoded = services.decodeCookie(encoded);
|
||||
|
||||
assertEquals(4, decoded.length);
|
||||
assertEquals("name", decoded[0]);
|
||||
assertEquals("cookie", decoded[1]);
|
||||
assertEquals("tokens", decoded[2]);
|
||||
assertEquals("blah", decoded[3]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void cookieWithOpenIDidentifierAsNameIsEncodedAndDecoded() throws Exception {
|
||||
String[] cookie = new String[] {"http://id.openid.zz", "cookie", "tokens", "blah"};
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
|
||||
String[] decoded = services.decodeCookie(services.encodeCookie(cookie));
|
||||
assertEquals(4, decoded.length);
|
||||
assertEquals("http://id.openid.zz", decoded[0]);
|
||||
|
||||
// Check https (SEC-1410)
|
||||
cookie[0] = "https://id.openid.zz";
|
||||
decoded = services.decodeCookie(services.encodeCookie(cookie));
|
||||
assertEquals(4, decoded.length);
|
||||
assertEquals("https://id.openid.zz", decoded[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void autoLoginShouldReturnNullIfNoLoginCookieIsPresented() {
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
assertNull(services.autoLogin(request, response));
|
||||
|
||||
// shouldn't try to invalidate our cookie
|
||||
assertNull(response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY));
|
||||
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
// set non-login cookie
|
||||
request.setCookies(new Cookie("mycookie", "cookie"));
|
||||
assertNull(services.autoLogin(request, response));
|
||||
assertNull(response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void successfulAutoLoginReturnsExpectedAuthentication() throws Exception {
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
services.afterPropertiesSet();
|
||||
assertNotNull(services.getUserDetailsService());
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
request.setCookies(createLoginCookie("cookie:1:2"));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
Authentication result = services.autoLogin(request, response);
|
||||
|
||||
assertNotNull(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void autoLoginShouldFailIfCookieIsNotBase64() throws Exception {
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
request.setCookies(new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, "ZZZ"));
|
||||
Authentication result = services.autoLogin(request, response);
|
||||
assertNull(result);
|
||||
assertCookieCancelled(response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void autoLoginShouldFailIfCookieIsEmpty() throws Exception {
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
request.setCookies(new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, ""));
|
||||
Authentication result = services.autoLogin(request, response);
|
||||
assertNull(result);
|
||||
assertCookieCancelled(response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void autoLoginShouldFailIfInvalidCookieExceptionIsRaised() {
|
||||
MockRememberMeServices services = new MockRememberMeServices(new MockUserDetailsService(joe, true));
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
// Wrong number of tokens
|
||||
request.setCookies(createLoginCookie("cookie:1"));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
Authentication result = services.autoLogin(request, response);
|
||||
|
||||
assertNull(result);
|
||||
|
||||
assertCookieCancelled(response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void autoLoginShouldFailIfUserNotFound() {
|
||||
uds.setThrowException(true);
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setCookies(createLoginCookie("cookie:1:2"));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
Authentication result = services.autoLogin(request, response);
|
||||
|
||||
assertNull(result);
|
||||
|
||||
assertCookieCancelled(response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void autoLoginShouldFailIfUserAccountIsLocked() {
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
services.setUserDetailsChecker(new AccountStatusUserDetailsChecker());
|
||||
uds.toReturn = new User("joe", "password",false,true,true,true,joe.getAuthorities());
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setCookies(createLoginCookie("cookie:1:2"));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
Authentication result = services.autoLogin(request, response);
|
||||
|
||||
assertNull(result);
|
||||
|
||||
assertCookieCancelled(response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loginFailShouldCancelCookie() {
|
||||
uds.setThrowException(true);
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setContextPath("contextpath");
|
||||
request.setCookies(createLoginCookie("cookie:1:2"));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
services.loginFail(request, response);
|
||||
|
||||
assertCookieCancelled(response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void logoutShouldCancelCookie() throws Exception {
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setContextPath("contextpath");
|
||||
request.setCookies(createLoginCookie("cookie:1:2"));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
services.logout(request, response, mock(Authentication.class));
|
||||
// Try again with null Authentication
|
||||
response = new MockHttpServletResponse();
|
||||
|
||||
services.logout(request, response, null);
|
||||
|
||||
assertCookieCancelled(response);
|
||||
}
|
||||
|
||||
@Test(expected = CookieTheftException.class)
|
||||
public void cookieTheftExceptionShouldBeRethrown() {
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds) {
|
||||
protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) {
|
||||
throw new CookieTheftException("Pretending cookie was stolen");
|
||||
}
|
||||
};
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
request.setCookies(createLoginCookie("cookie:1:2"));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
services.autoLogin(request, response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loginSuccessCallsOnLoginSuccessCorrectly() {
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
Authentication auth = new UsernamePasswordAuthenticationToken("joe","password");
|
||||
|
||||
// No parameter set
|
||||
services.loginSuccess(request, response, auth);
|
||||
assertFalse(services.loginSuccessCalled);
|
||||
|
||||
// Parameter set to true
|
||||
services = new MockRememberMeServices(uds);
|
||||
request.setParameter(MockRememberMeServices.DEFAULT_PARAMETER, "true");
|
||||
services.loginSuccess(request, response, auth);
|
||||
assertTrue(services.loginSuccessCalled);
|
||||
|
||||
// Different parameter name, set to true
|
||||
services = new MockRememberMeServices(uds);
|
||||
services.setParameter("my_parameter");
|
||||
request.setParameter("my_parameter", "true");
|
||||
services.loginSuccess(request, response, auth);
|
||||
assertTrue(services.loginSuccessCalled);
|
||||
|
||||
|
||||
// Parameter set to false
|
||||
services = new MockRememberMeServices(uds);
|
||||
request.setParameter(MockRememberMeServices.DEFAULT_PARAMETER, "false");
|
||||
services.loginSuccess(request, response, auth);
|
||||
assertFalse(services.loginSuccessCalled);
|
||||
|
||||
// alwaysRemember set to true
|
||||
services = new MockRememberMeServices(uds);
|
||||
services.setAlwaysRemember(true);
|
||||
services.loginSuccess(request, response, auth);
|
||||
assertTrue(services.loginSuccessCalled);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setCookieUsesCorrectNamePathAndValue() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
request.setContextPath("contextpath");
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds) {
|
||||
protected String encodeCookie(String[] cookieTokens) {
|
||||
return cookieTokens[0];
|
||||
}
|
||||
};
|
||||
services.setCookieName("mycookiename");
|
||||
services.setCookie(new String[] {"mycookie"}, 1000, request, response);
|
||||
Cookie cookie = response.getCookie("mycookiename");
|
||||
|
||||
assertNotNull(cookie);
|
||||
assertEquals("mycookie", cookie.getValue());
|
||||
assertEquals("mycookiename", cookie.getName());
|
||||
assertEquals("contextpath", cookie.getPath());
|
||||
assertFalse(cookie.getSecure());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setCookieSetsSecureFlagIfConfigured() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
request.setContextPath("contextpath");
|
||||
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds) {
|
||||
protected String encodeCookie(String[] cookieTokens) {
|
||||
return cookieTokens[0];
|
||||
}
|
||||
};
|
||||
services.setUseSecureCookie(true);
|
||||
services.setCookie(new String[] {"mycookie"}, 1000, request, response);
|
||||
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertTrue(cookie.getSecure());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setHttpOnlyIgnoredForServlet25() throws Exception {
|
||||
spy(ReflectionUtils.class);
|
||||
when(ReflectionUtils.findMethod(Cookie.class,"setHttpOnly", boolean.class)).thenReturn(null);
|
||||
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
assertNull(ReflectionTestUtils.getField(services, "setHttpOnlyMethod"));
|
||||
|
||||
services = new MockRememberMeServices("key",new MockUserDetailsService(joe, false));
|
||||
assertNull(ReflectionTestUtils.getField(services, "setHttpOnlyMethod"));
|
||||
}
|
||||
|
||||
// SEC-2791
|
||||
@Test
|
||||
public void setCookieMaxAge0VersionSet() {
|
||||
MockRememberMeServices services = new MockRememberMeServices();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
services.setCookie(new String[] {"value"}, 0, request, response);
|
||||
|
||||
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertThat(cookie.getVersion()).isEqualTo(1);
|
||||
}
|
||||
|
||||
// SEC-2791
|
||||
@Test
|
||||
public void setCookieMaxAgeNegativeVersionSet() {
|
||||
MockRememberMeServices services = new MockRememberMeServices();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
services.setCookie(new String[] {"value"}, -1, request, response);
|
||||
|
||||
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertThat(cookie.getVersion()).isEqualTo(1);
|
||||
}
|
||||
|
||||
// SEC-2791
|
||||
@Test
|
||||
public void setCookieMaxAge1VersionSet() {
|
||||
MockRememberMeServices services = new MockRememberMeServices();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
services.setCookie(new String[] {"value"}, 1, request, response);
|
||||
|
||||
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertThat(cookie.getVersion()).isEqualTo(0);
|
||||
}
|
||||
|
||||
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, ":")));
|
||||
|
||||
return new Cookie[] {cookie};
|
||||
}
|
||||
|
||||
private void assertCookieCancelled(MockHttpServletResponse response) {
|
||||
Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertNotNull(returnedCookie);
|
||||
assertEquals(0, returnedCookie.getMaxAge());
|
||||
}
|
||||
|
||||
//~ Inner Classes ==================================================================================================
|
||||
|
||||
static class MockRememberMeServices extends AbstractRememberMeServices {
|
||||
boolean loginSuccessCalled;
|
||||
|
||||
MockRememberMeServices(String key, UserDetailsService userDetailsService) {
|
||||
super(key, userDetailsService);
|
||||
}
|
||||
|
||||
MockRememberMeServices(UserDetailsService userDetailsService) {
|
||||
super("xxxx", userDetailsService);
|
||||
}
|
||||
|
||||
MockRememberMeServices() {
|
||||
this(new MockUserDetailsService(null,false));
|
||||
}
|
||||
|
||||
protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) {
|
||||
loginSuccessCalled = true;
|
||||
}
|
||||
|
||||
protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) throws RememberMeAuthenticationException {
|
||||
if(cookieTokens.length != 3) {
|
||||
throw new InvalidCookieException("deliberate exception");
|
||||
}
|
||||
|
||||
UserDetails user = getUserDetailsService().loadUserByUsername("joe");
|
||||
|
||||
return user;
|
||||
}
|
||||
}
|
||||
|
||||
public static class MockUserDetailsService implements UserDetailsService {
|
||||
private UserDetails toReturn;
|
||||
private boolean throwException;
|
||||
|
||||
public MockUserDetailsService() {
|
||||
this(null, false);
|
||||
}
|
||||
|
||||
public MockUserDetailsService(UserDetails toReturn, boolean throwException) {
|
||||
this.toReturn = toReturn;
|
||||
this.throwException = throwException;
|
||||
}
|
||||
|
||||
public UserDetails loadUserByUsername(String username) {
|
||||
if (throwException) {
|
||||
throw new UsernameNotFoundException("as requested by mock");
|
||||
}
|
||||
|
||||
return toReturn;
|
||||
}
|
||||
|
||||
public void setThrowException(boolean value) {
|
||||
this.throwException = value;
|
||||
}
|
||||
}
|
||||
static User joe = new User("joe", "password", true, true, true, true,
|
||||
AuthorityUtils.createAuthorityList("ROLE_A"));
|
||||
|
||||
MockUserDetailsService uds;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
uds = new MockUserDetailsService(joe, false);
|
||||
}
|
||||
|
||||
@Test(expected = InvalidCookieException.class)
|
||||
public void nonBase64CookieShouldBeDetected() {
|
||||
new MockRememberMeServices(uds).decodeCookie("nonBase64CookieValue%");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setAndGetAreConsistent() throws Exception {
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
assertNotNull(services.getCookieName());
|
||||
assertNotNull(services.getParameter());
|
||||
assertEquals("xxxx", services.getKey());
|
||||
services.setParameter("rm");
|
||||
assertEquals("rm", services.getParameter());
|
||||
services.setCookieName("kookie");
|
||||
assertEquals("kookie", services.getCookieName());
|
||||
services.setTokenValiditySeconds(600);
|
||||
assertEquals(600, services.getTokenValiditySeconds());
|
||||
assertSame(uds, services.getUserDetailsService());
|
||||
AuthenticationDetailsSource ads = mock(AuthenticationDetailsSource.class);
|
||||
services.setAuthenticationDetailsSource(ads);
|
||||
assertSame(ads, services.getAuthenticationDetailsSource());
|
||||
services.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void cookieShouldBeCorrectlyEncodedAndDecoded() throws Exception {
|
||||
String[] cookie = new String[] { "name", "cookie", "tokens", "blah" };
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
|
||||
String encoded = services.encodeCookie(cookie);
|
||||
// '=' aren't allowed in version 0 cookies.
|
||||
assertFalse(encoded.endsWith("="));
|
||||
String[] decoded = services.decodeCookie(encoded);
|
||||
|
||||
assertEquals(4, decoded.length);
|
||||
assertEquals("name", decoded[0]);
|
||||
assertEquals("cookie", decoded[1]);
|
||||
assertEquals("tokens", decoded[2]);
|
||||
assertEquals("blah", decoded[3]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void cookieWithOpenIDidentifierAsNameIsEncodedAndDecoded() throws Exception {
|
||||
String[] cookie = new String[] { "http://id.openid.zz", "cookie", "tokens",
|
||||
"blah" };
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
|
||||
String[] decoded = services.decodeCookie(services.encodeCookie(cookie));
|
||||
assertEquals(4, decoded.length);
|
||||
assertEquals("http://id.openid.zz", decoded[0]);
|
||||
|
||||
// Check https (SEC-1410)
|
||||
cookie[0] = "https://id.openid.zz";
|
||||
decoded = services.decodeCookie(services.encodeCookie(cookie));
|
||||
assertEquals(4, decoded.length);
|
||||
assertEquals("https://id.openid.zz", decoded[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void autoLoginShouldReturnNullIfNoLoginCookieIsPresented() {
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
assertNull(services.autoLogin(request, response));
|
||||
|
||||
// shouldn't try to invalidate our cookie
|
||||
assertNull(response
|
||||
.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY));
|
||||
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
// set non-login cookie
|
||||
request.setCookies(new Cookie("mycookie", "cookie"));
|
||||
assertNull(services.autoLogin(request, response));
|
||||
assertNull(response
|
||||
.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void successfulAutoLoginReturnsExpectedAuthentication() throws Exception {
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
services.afterPropertiesSet();
|
||||
assertNotNull(services.getUserDetailsService());
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
request.setCookies(createLoginCookie("cookie:1:2"));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
Authentication result = services.autoLogin(request, response);
|
||||
|
||||
assertNotNull(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void autoLoginShouldFailIfCookieIsNotBase64() throws Exception {
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
request.setCookies(new Cookie(
|
||||
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, "ZZZ"));
|
||||
Authentication result = services.autoLogin(request, response);
|
||||
assertNull(result);
|
||||
assertCookieCancelled(response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void autoLoginShouldFailIfCookieIsEmpty() throws Exception {
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
request.setCookies(new Cookie(
|
||||
AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, ""));
|
||||
Authentication result = services.autoLogin(request, response);
|
||||
assertNull(result);
|
||||
assertCookieCancelled(response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void autoLoginShouldFailIfInvalidCookieExceptionIsRaised() {
|
||||
MockRememberMeServices services = new MockRememberMeServices(
|
||||
new MockUserDetailsService(joe, true));
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
// Wrong number of tokens
|
||||
request.setCookies(createLoginCookie("cookie:1"));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
Authentication result = services.autoLogin(request, response);
|
||||
|
||||
assertNull(result);
|
||||
|
||||
assertCookieCancelled(response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void autoLoginShouldFailIfUserNotFound() {
|
||||
uds.setThrowException(true);
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setCookies(createLoginCookie("cookie:1:2"));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
Authentication result = services.autoLogin(request, response);
|
||||
|
||||
assertNull(result);
|
||||
|
||||
assertCookieCancelled(response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void autoLoginShouldFailIfUserAccountIsLocked() {
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
services.setUserDetailsChecker(new AccountStatusUserDetailsChecker());
|
||||
uds.toReturn = new User("joe", "password", false, true, true, true,
|
||||
joe.getAuthorities());
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setCookies(createLoginCookie("cookie:1:2"));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
Authentication result = services.autoLogin(request, response);
|
||||
|
||||
assertNull(result);
|
||||
|
||||
assertCookieCancelled(response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loginFailShouldCancelCookie() {
|
||||
uds.setThrowException(true);
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setContextPath("contextpath");
|
||||
request.setCookies(createLoginCookie("cookie:1:2"));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
services.loginFail(request, response);
|
||||
|
||||
assertCookieCancelled(response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void logoutShouldCancelCookie() throws Exception {
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setContextPath("contextpath");
|
||||
request.setCookies(createLoginCookie("cookie:1:2"));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
services.logout(request, response, mock(Authentication.class));
|
||||
// Try again with null Authentication
|
||||
response = new MockHttpServletResponse();
|
||||
|
||||
services.logout(request, response, null);
|
||||
|
||||
assertCookieCancelled(response);
|
||||
}
|
||||
|
||||
@Test(expected = CookieTheftException.class)
|
||||
public void cookieTheftExceptionShouldBeRethrown() {
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds) {
|
||||
protected UserDetails processAutoLoginCookie(String[] cookieTokens,
|
||||
HttpServletRequest request, HttpServletResponse response) {
|
||||
throw new CookieTheftException("Pretending cookie was stolen");
|
||||
}
|
||||
};
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
request.setCookies(createLoginCookie("cookie:1:2"));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
services.autoLogin(request, response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loginSuccessCallsOnLoginSuccessCorrectly() {
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
Authentication auth = new UsernamePasswordAuthenticationToken("joe", "password");
|
||||
|
||||
// No parameter set
|
||||
services.loginSuccess(request, response, auth);
|
||||
assertFalse(services.loginSuccessCalled);
|
||||
|
||||
// Parameter set to true
|
||||
services = new MockRememberMeServices(uds);
|
||||
request.setParameter(MockRememberMeServices.DEFAULT_PARAMETER, "true");
|
||||
services.loginSuccess(request, response, auth);
|
||||
assertTrue(services.loginSuccessCalled);
|
||||
|
||||
// Different parameter name, set to true
|
||||
services = new MockRememberMeServices(uds);
|
||||
services.setParameter("my_parameter");
|
||||
request.setParameter("my_parameter", "true");
|
||||
services.loginSuccess(request, response, auth);
|
||||
assertTrue(services.loginSuccessCalled);
|
||||
|
||||
// Parameter set to false
|
||||
services = new MockRememberMeServices(uds);
|
||||
request.setParameter(MockRememberMeServices.DEFAULT_PARAMETER, "false");
|
||||
services.loginSuccess(request, response, auth);
|
||||
assertFalse(services.loginSuccessCalled);
|
||||
|
||||
// alwaysRemember set to true
|
||||
services = new MockRememberMeServices(uds);
|
||||
services.setAlwaysRemember(true);
|
||||
services.loginSuccess(request, response, auth);
|
||||
assertTrue(services.loginSuccessCalled);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setCookieUsesCorrectNamePathAndValue() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
request.setContextPath("contextpath");
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds) {
|
||||
protected String encodeCookie(String[] cookieTokens) {
|
||||
return cookieTokens[0];
|
||||
}
|
||||
};
|
||||
services.setCookieName("mycookiename");
|
||||
services.setCookie(new String[] { "mycookie" }, 1000, request, response);
|
||||
Cookie cookie = response.getCookie("mycookiename");
|
||||
|
||||
assertNotNull(cookie);
|
||||
assertEquals("mycookie", cookie.getValue());
|
||||
assertEquals("mycookiename", cookie.getName());
|
||||
assertEquals("contextpath", cookie.getPath());
|
||||
assertFalse(cookie.getSecure());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setCookieSetsSecureFlagIfConfigured() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
request.setContextPath("contextpath");
|
||||
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds) {
|
||||
protected String encodeCookie(String[] cookieTokens) {
|
||||
return cookieTokens[0];
|
||||
}
|
||||
};
|
||||
services.setUseSecureCookie(true);
|
||||
services.setCookie(new String[] { "mycookie" }, 1000, request, response);
|
||||
Cookie cookie = response
|
||||
.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertTrue(cookie.getSecure());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setHttpOnlyIgnoredForServlet25() throws Exception {
|
||||
spy(ReflectionUtils.class);
|
||||
when(ReflectionUtils.findMethod(Cookie.class, "setHttpOnly", boolean.class))
|
||||
.thenReturn(null);
|
||||
|
||||
MockRememberMeServices services = new MockRememberMeServices(uds);
|
||||
assertNull(ReflectionTestUtils.getField(services, "setHttpOnlyMethod"));
|
||||
|
||||
services = new MockRememberMeServices("key", new MockUserDetailsService(joe,
|
||||
false));
|
||||
assertNull(ReflectionTestUtils.getField(services, "setHttpOnlyMethod"));
|
||||
}
|
||||
|
||||
// SEC-2791
|
||||
@Test
|
||||
public void setCookieMaxAge0VersionSet() {
|
||||
MockRememberMeServices services = new MockRememberMeServices();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
services.setCookie(new String[] { "value" }, 0, request, response);
|
||||
|
||||
Cookie cookie = response
|
||||
.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertThat(cookie.getVersion()).isEqualTo(1);
|
||||
}
|
||||
|
||||
// SEC-2791
|
||||
@Test
|
||||
public void setCookieMaxAgeNegativeVersionSet() {
|
||||
MockRememberMeServices services = new MockRememberMeServices();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
services.setCookie(new String[] { "value" }, -1, request, response);
|
||||
|
||||
Cookie cookie = response
|
||||
.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertThat(cookie.getVersion()).isEqualTo(1);
|
||||
}
|
||||
|
||||
// SEC-2791
|
||||
@Test
|
||||
public void setCookieMaxAge1VersionSet() {
|
||||
MockRememberMeServices services = new MockRememberMeServices();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
services.setCookie(new String[] { "value" }, 1, request, response);
|
||||
|
||||
Cookie cookie = response
|
||||
.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertThat(cookie.getVersion()).isEqualTo(0);
|
||||
}
|
||||
|
||||
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,
|
||||
":")));
|
||||
|
||||
return new Cookie[] { cookie };
|
||||
}
|
||||
|
||||
private void assertCookieCancelled(MockHttpServletResponse response) {
|
||||
Cookie returnedCookie = response
|
||||
.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertNotNull(returnedCookie);
|
||||
assertEquals(0, returnedCookie.getMaxAge());
|
||||
}
|
||||
|
||||
// ~ Inner Classes
|
||||
// ==================================================================================================
|
||||
|
||||
static class MockRememberMeServices extends AbstractRememberMeServices {
|
||||
boolean loginSuccessCalled;
|
||||
|
||||
MockRememberMeServices(String key, UserDetailsService userDetailsService) {
|
||||
super(key, userDetailsService);
|
||||
}
|
||||
|
||||
MockRememberMeServices(UserDetailsService userDetailsService) {
|
||||
super("xxxx", userDetailsService);
|
||||
}
|
||||
|
||||
MockRememberMeServices() {
|
||||
this(new MockUserDetailsService(null, false));
|
||||
}
|
||||
|
||||
protected void onLoginSuccess(HttpServletRequest request,
|
||||
HttpServletResponse response, Authentication successfulAuthentication) {
|
||||
loginSuccessCalled = true;
|
||||
}
|
||||
|
||||
protected UserDetails processAutoLoginCookie(String[] cookieTokens,
|
||||
HttpServletRequest request, HttpServletResponse response)
|
||||
throws RememberMeAuthenticationException {
|
||||
if (cookieTokens.length != 3) {
|
||||
throw new InvalidCookieException("deliberate exception");
|
||||
}
|
||||
|
||||
UserDetails user = getUserDetailsService().loadUserByUsername("joe");
|
||||
|
||||
return user;
|
||||
}
|
||||
}
|
||||
|
||||
public static class MockUserDetailsService implements UserDetailsService {
|
||||
private UserDetails toReturn;
|
||||
private boolean throwException;
|
||||
|
||||
public MockUserDetailsService() {
|
||||
this(null, false);
|
||||
}
|
||||
|
||||
public MockUserDetailsService(UserDetails toReturn, boolean throwException) {
|
||||
this.toReturn = toReturn;
|
||||
this.throwException = throwException;
|
||||
}
|
||||
|
||||
public UserDetails loadUserByUsername(String username) {
|
||||
if (throwException) {
|
||||
throw new UsernameNotFoundException("as requested by mock");
|
||||
}
|
||||
|
||||
return toReturn;
|
||||
}
|
||||
|
||||
public void setThrowException(boolean value) {
|
||||
this.throwException = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,148 +44,155 @@ import org.springframework.test.util.ReflectionTestUtils;
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class JdbcTokenRepositoryImplTests {
|
||||
@Mock
|
||||
private Log logger;
|
||||
@Mock
|
||||
private Log logger;
|
||||
|
||||
private static SingleConnectionDataSource dataSource;
|
||||
private JdbcTokenRepositoryImpl repo;
|
||||
private JdbcTemplate template;
|
||||
private static SingleConnectionDataSource dataSource;
|
||||
private JdbcTokenRepositoryImpl repo;
|
||||
private JdbcTemplate template;
|
||||
|
||||
@BeforeClass
|
||||
public static void createDataSource() {
|
||||
dataSource = new SingleConnectionDataSource("jdbc:hsqldb:mem:tokenrepotest", "sa", "", true);
|
||||
dataSource.setDriverClassName("org.hsqldb.jdbc.JDBCDriver");
|
||||
}
|
||||
@BeforeClass
|
||||
public static void createDataSource() {
|
||||
dataSource = new SingleConnectionDataSource("jdbc:hsqldb:mem:tokenrepotest",
|
||||
"sa", "", true);
|
||||
dataSource.setDriverClassName("org.hsqldb.jdbc.JDBCDriver");
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void clearDataSource() throws Exception {
|
||||
dataSource.destroy();
|
||||
dataSource = null;
|
||||
}
|
||||
@AfterClass
|
||||
public static void clearDataSource() throws Exception {
|
||||
dataSource.destroy();
|
||||
dataSource = null;
|
||||
}
|
||||
|
||||
@Before
|
||||
public void populateDatabase() {
|
||||
repo = new JdbcTokenRepositoryImpl();
|
||||
ReflectionTestUtils.setField(repo, "logger", logger);
|
||||
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)");
|
||||
}
|
||||
@Before
|
||||
public void populateDatabase() {
|
||||
repo = new JdbcTokenRepositoryImpl();
|
||||
ReflectionTestUtils.setField(repo, "logger", logger);
|
||||
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)");
|
||||
}
|
||||
|
||||
@After
|
||||
public void clearData() {
|
||||
template.execute("drop table persistent_logins");
|
||||
}
|
||||
@After
|
||||
public void clearData() {
|
||||
template.execute("drop table persistent_logins");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createNewTokenInsertsCorrectData() {
|
||||
Date currentDate = new Date();
|
||||
PersistentRememberMeToken token = new PersistentRememberMeToken("joeuser", "joesseries", "atoken", currentDate);
|
||||
repo.createNewToken(token);
|
||||
@Test
|
||||
public void createNewTokenInsertsCorrectData() {
|
||||
Date currentDate = new Date();
|
||||
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");
|
||||
|
||||
assertEquals(currentDate, results.get("last_used"));
|
||||
assertEquals("joeuser", results.get("username"));
|
||||
assertEquals("joesseries", results.get("series"));
|
||||
assertEquals("atoken", results.get("token"));
|
||||
}
|
||||
assertEquals(currentDate, results.get("last_used"));
|
||||
assertEquals("joeuser", results.get("username"));
|
||||
assertEquals("joesseries", results.get("series"));
|
||||
assertEquals("atoken", results.get("token"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void retrievingTokenReturnsCorrectData() {
|
||||
@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')");
|
||||
PersistentRememberMeToken token = repo.getTokenForSeries("joesseries");
|
||||
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");
|
||||
|
||||
assertEquals("joeuser", token.getUsername());
|
||||
assertEquals("joesseries", token.getSeries());
|
||||
assertEquals("atoken", token.getTokenValue());
|
||||
assertEquals(Timestamp.valueOf("2007-10-09 18:19:25.000000000"), token.getDate());
|
||||
}
|
||||
assertEquals("joeuser", token.getUsername());
|
||||
assertEquals("joesseries", token.getSeries());
|
||||
assertEquals("atoken", token.getTokenValue());
|
||||
assertEquals(Timestamp.valueOf("2007-10-09 18:19:25.000000000"), token.getDate());
|
||||
}
|
||||
|
||||
@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')");
|
||||
@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')");
|
||||
|
||||
// List results = template.queryForList("select * from persistent_logins where series = 'joesseries'");
|
||||
// List results =
|
||||
// template.queryForList("select * from persistent_logins where series = 'joesseries'");
|
||||
|
||||
assertNull(repo.getTokenForSeries("joesseries"));
|
||||
}
|
||||
assertNull(repo.getTokenForSeries("joesseries"));
|
||||
}
|
||||
|
||||
// SEC-1964
|
||||
@Test
|
||||
public void retrievingTokenWithNoSeriesReturnsNull() {
|
||||
when(logger.isDebugEnabled()).thenReturn(true);
|
||||
// SEC-1964
|
||||
@Test
|
||||
public void retrievingTokenWithNoSeriesReturnsNull() {
|
||||
when(logger.isDebugEnabled()).thenReturn(true);
|
||||
|
||||
assertNull(repo.getTokenForSeries("missingSeries"));
|
||||
assertNull(repo.getTokenForSeries("missingSeries"));
|
||||
|
||||
verify(logger).isDebugEnabled();
|
||||
verify(logger).debug(eq("Querying token for series 'missingSeries' returned no results."),
|
||||
any(EmptyResultDataAccessException.class));
|
||||
verifyNoMoreInteractions(logger);
|
||||
}
|
||||
verify(logger).isDebugEnabled();
|
||||
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')");
|
||||
@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')");
|
||||
|
||||
// List results = template.queryForList("select * from persistent_logins where series = 'joesseries'");
|
||||
// List results =
|
||||
// template.queryForList("select * from persistent_logins where series = 'joesseries'");
|
||||
|
||||
repo.removeUserTokens("joeuser");
|
||||
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'");
|
||||
|
||||
assertEquals(0, results.size());
|
||||
}
|
||||
assertEquals(0, results.size());
|
||||
}
|
||||
|
||||
@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() + "')");
|
||||
repo.updateToken("joesseries", "newtoken", new Date());
|
||||
@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() + "')");
|
||||
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'");
|
||||
|
||||
assertEquals("joeuser", results.get("username"));
|
||||
assertEquals("joesseries", results.get("series"));
|
||||
assertEquals("newtoken", results.get("token"));
|
||||
Date lastUsed = (Date) results.get("last_used");
|
||||
assertTrue(lastUsed.getTime() > ts.getTime());
|
||||
}
|
||||
assertEquals("joeuser", results.get("username"));
|
||||
assertEquals("joesseries", results.get("series"));
|
||||
assertEquals("newtoken", results.get("token"));
|
||||
Date lastUsed = (Date) results.get("last_used");
|
||||
assertTrue(lastUsed.getTime() > ts.getTime());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createTableOnStartupCreatesCorrectTable() {
|
||||
template.execute("drop table persistent_logins");
|
||||
repo = new JdbcTokenRepositoryImpl();
|
||||
repo.setDataSource(dataSource);
|
||||
repo.setCreateTableOnStartup(true);
|
||||
repo.initDao();
|
||||
@Test
|
||||
public void createTableOnStartupCreatesCorrectTable() {
|
||||
template.execute("drop table persistent_logins");
|
||||
repo = new JdbcTokenRepositoryImpl();
|
||||
repo.setDataSource(dataSource);
|
||||
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
|
||||
@Test
|
||||
public void updateUsesLastUsed() {
|
||||
JdbcTemplate template = mock(JdbcTemplate.class);
|
||||
Date lastUsed = new Date(1424841314059L);
|
||||
JdbcTokenRepositoryImpl repository = new JdbcTokenRepositoryImpl();
|
||||
repository.setJdbcTemplate(template);
|
||||
|
||||
// SEC-2879
|
||||
@Test
|
||||
public void updateUsesLastUsed() {
|
||||
JdbcTemplate template = mock(JdbcTemplate.class);
|
||||
Date lastUsed = new Date(1424841314059L);
|
||||
JdbcTokenRepositoryImpl repository = new JdbcTokenRepositoryImpl();
|
||||
repository.setJdbcTemplate(template);
|
||||
repository.updateToken("series", "token", lastUsed);
|
||||
|
||||
repository.updateToken("series", "token", lastUsed);
|
||||
|
||||
verify(template).update(anyString(), anyString(), eq(lastUsed), anyString());
|
||||
}
|
||||
verify(template).update(anyString(), anyString(), eq(lastUsed), anyString());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -19,20 +19,20 @@ import org.springframework.security.web.authentication.NullRememberMeServices;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link org.springframework.security.web.authentication.NullRememberMeServices}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class NullRememberMeServicesTests extends TestCase {
|
||||
//~ Methods ========================================================================================================
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
public void testAlwaysReturnsNull() {
|
||||
NullRememberMeServices services = new NullRememberMeServices();
|
||||
assertNull(services.autoLogin(null, null));
|
||||
services.loginFail(null, null);
|
||||
services.loginSuccess(null, null, null);
|
||||
assertTrue(true);
|
||||
}
|
||||
public void testAlwaysReturnsNull() {
|
||||
NullRememberMeServices services = new NullRememberMeServices();
|
||||
assertNull(services.autoLogin(null, null));
|
||||
services.loginFail(null, null);
|
||||
services.loginSuccess(null, null, null);
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,133 +25,142 @@ import org.springframework.security.web.authentication.rememberme.AbstractRememb
|
||||
* @author Luke Taylor
|
||||
*/
|
||||
public class PersistentTokenBasedRememberMeServicesTests {
|
||||
private PersistentTokenBasedRememberMeServices services;
|
||||
private PersistentTokenBasedRememberMeServices services;
|
||||
|
||||
private MockTokenRepository repo;
|
||||
private MockTokenRepository repo;
|
||||
|
||||
@Before
|
||||
public void setUpData() throws Exception {
|
||||
services = new PersistentTokenBasedRememberMeServices("key",
|
||||
new AbstractRememberMeServicesTests.MockUserDetailsService(AbstractRememberMeServicesTests.joe, false),
|
||||
new InMemoryTokenRepositoryImpl());
|
||||
services.setCookieName("mycookiename");
|
||||
// Default to 100 days (see SEC-1081).
|
||||
services.setTokenValiditySeconds(100 * 24 * 60 * 60);
|
||||
services.afterPropertiesSet();
|
||||
}
|
||||
@Before
|
||||
public void setUpData() throws Exception {
|
||||
services = new PersistentTokenBasedRememberMeServices("key",
|
||||
new AbstractRememberMeServicesTests.MockUserDetailsService(
|
||||
AbstractRememberMeServicesTests.joe, false),
|
||||
new InMemoryTokenRepositoryImpl());
|
||||
services.setCookieName("mycookiename");
|
||||
// Default to 100 days (see SEC-1081).
|
||||
services.setTokenValiditySeconds(100 * 24 * 60 * 60);
|
||||
services.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test(expected = InvalidCookieException.class)
|
||||
public void loginIsRejectedWithWrongNumberOfCookieTokens() {
|
||||
services.processAutoLoginCookie(new String[] {"series", "token", "extra"}, new MockHttpServletRequest(),
|
||||
new MockHttpServletResponse());
|
||||
}
|
||||
@Test(expected = InvalidCookieException.class)
|
||||
public void loginIsRejectedWithWrongNumberOfCookieTokens() {
|
||||
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());
|
||||
}
|
||||
@Test(expected = RememberMeAuthenticationException.class)
|
||||
public void loginIsRejectedWhenNoTokenMatchingSeriesIsFound() {
|
||||
services = create(null);
|
||||
services.processAutoLoginCookie(new String[] { "series", "token" },
|
||||
new MockHttpServletRequest(), new MockHttpServletResponse());
|
||||
}
|
||||
|
||||
@Test(expected = RememberMeAuthenticationException.class)
|
||||
public void loginIsRejectedWhenTokenIsExpired() {
|
||||
services = create(new PersistentRememberMeToken("joe", "series","token", new Date(System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(1) - 100)));
|
||||
services.setTokenValiditySeconds(1);
|
||||
@Test(expected = RememberMeAuthenticationException.class)
|
||||
public void loginIsRejectedWhenTokenIsExpired() {
|
||||
services = create(new PersistentRememberMeToken("joe", "series", "token",
|
||||
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());
|
||||
}
|
||||
@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());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void successfulAutoLoginCreatesNewTokenAndCookieWithSameSeries() {
|
||||
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);
|
||||
assertEquals("series",repo.getStoredToken().getSeries());
|
||||
assertEquals(16, repo.getStoredToken().getTokenValue().length());
|
||||
String[] cookie = services.decodeCookie(response.getCookie("mycookiename").getValue());
|
||||
assertEquals("series", cookie[0]);
|
||||
assertEquals(repo.getStoredToken().getTokenValue(), cookie[1]);
|
||||
}
|
||||
@Test
|
||||
public void successfulAutoLoginCreatesNewTokenAndCookieWithSameSeries() {
|
||||
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);
|
||||
assertEquals("series", repo.getStoredToken().getSeries());
|
||||
assertEquals(16, repo.getStoredToken().getTokenValue().length());
|
||||
String[] cookie = services.decodeCookie(response.getCookie("mycookiename")
|
||||
.getValue());
|
||||
assertEquals("series", cookie[0]);
|
||||
assertEquals(repo.getStoredToken().getTokenValue(), cookie[1]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loginSuccessCreatesNewTokenAndCookieWithNewSeries() {
|
||||
services = create(null);
|
||||
services.setAlwaysRemember(true);
|
||||
services.setTokenLength(12);
|
||||
services.setSeriesLength(12);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
services.loginSuccess(new MockHttpServletRequest(),
|
||||
response, new UsernamePasswordAuthenticationToken("joe","password"));
|
||||
assertEquals(16, repo.getStoredToken().getSeries().length());
|
||||
assertEquals(16, repo.getStoredToken().getTokenValue().length());
|
||||
@Test
|
||||
public void loginSuccessCreatesNewTokenAndCookieWithNewSeries() {
|
||||
services = create(null);
|
||||
services.setAlwaysRemember(true);
|
||||
services.setTokenLength(12);
|
||||
services.setSeriesLength(12);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
services.loginSuccess(new MockHttpServletRequest(), response,
|
||||
new UsernamePasswordAuthenticationToken("joe", "password"));
|
||||
assertEquals(16, repo.getStoredToken().getSeries().length());
|
||||
assertEquals(16, repo.getStoredToken().getTokenValue().length());
|
||||
|
||||
String[] cookie = services.decodeCookie(response.getCookie("mycookiename").getValue());
|
||||
String[] cookie = services.decodeCookie(response.getCookie("mycookiename")
|
||||
.getValue());
|
||||
|
||||
assertEquals(repo.getStoredToken().getSeries(), cookie[0]);
|
||||
assertEquals(repo.getStoredToken().getTokenValue(), cookie[1]);
|
||||
}
|
||||
assertEquals(repo.getStoredToken().getSeries(), cookie[0]);
|
||||
assertEquals(repo.getStoredToken().getTokenValue(), cookie[1]);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void logoutClearsUsersTokenAndCookie() throws Exception {
|
||||
Cookie cookie = new Cookie("mycookiename", "somevalue");
|
||||
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"));
|
||||
Cookie returnedCookie = response.getCookie("mycookiename");
|
||||
assertNotNull(returnedCookie);
|
||||
assertEquals(0, returnedCookie.getMaxAge());
|
||||
@Test
|
||||
public void logoutClearsUsersTokenAndCookie() throws Exception {
|
||||
Cookie cookie = new Cookie("mycookiename", "somevalue");
|
||||
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"));
|
||||
Cookie returnedCookie = response.getCookie("mycookiename");
|
||||
assertNotNull(returnedCookie);
|
||||
assertEquals(0, returnedCookie.getMaxAge());
|
||||
|
||||
// SEC-1280
|
||||
services.logout(request, response, null);
|
||||
}
|
||||
// SEC-1280
|
||||
services.logout(request, response, null);
|
||||
}
|
||||
|
||||
private PersistentTokenBasedRememberMeServices create(PersistentRememberMeToken token) {
|
||||
repo = new MockTokenRepository(token);
|
||||
PersistentTokenBasedRememberMeServices services = new PersistentTokenBasedRememberMeServices("key",
|
||||
new AbstractRememberMeServicesTests.MockUserDetailsService(AbstractRememberMeServicesTests.joe, false),
|
||||
repo);
|
||||
private PersistentTokenBasedRememberMeServices create(PersistentRememberMeToken token) {
|
||||
repo = new MockTokenRepository(token);
|
||||
PersistentTokenBasedRememberMeServices services = new PersistentTokenBasedRememberMeServices(
|
||||
"key", new AbstractRememberMeServicesTests.MockUserDetailsService(
|
||||
AbstractRememberMeServicesTests.joe, false), repo);
|
||||
|
||||
services.setCookieName("mycookiename");
|
||||
return services;
|
||||
}
|
||||
services.setCookieName("mycookiename");
|
||||
return services;
|
||||
}
|
||||
|
||||
private class MockTokenRepository implements PersistentTokenRepository {
|
||||
private PersistentRememberMeToken storedToken;
|
||||
private class MockTokenRepository implements PersistentTokenRepository {
|
||||
private PersistentRememberMeToken storedToken;
|
||||
|
||||
private MockTokenRepository(PersistentRememberMeToken token) {
|
||||
storedToken = token;
|
||||
}
|
||||
private MockTokenRepository(PersistentRememberMeToken token) {
|
||||
storedToken = token;
|
||||
}
|
||||
|
||||
public void createNewToken(PersistentRememberMeToken token) {
|
||||
storedToken = token;
|
||||
}
|
||||
public void createNewToken(PersistentRememberMeToken token) {
|
||||
storedToken = token;
|
||||
}
|
||||
|
||||
public void updateToken(String series, String tokenValue, Date lastUsed) {
|
||||
storedToken = new PersistentRememberMeToken(storedToken.getUsername(), storedToken.getSeries(),
|
||||
tokenValue, lastUsed);
|
||||
}
|
||||
public void updateToken(String series, String tokenValue, Date lastUsed) {
|
||||
storedToken = new PersistentRememberMeToken(storedToken.getUsername(),
|
||||
storedToken.getSeries(), tokenValue, lastUsed);
|
||||
}
|
||||
|
||||
public PersistentRememberMeToken getTokenForSeries(String seriesId) {
|
||||
return storedToken;
|
||||
}
|
||||
public PersistentRememberMeToken getTokenForSeries(String seriesId) {
|
||||
return storedToken;
|
||||
}
|
||||
|
||||
public void removeUserTokens(String username) {
|
||||
}
|
||||
public void removeUserTokens(String username) {
|
||||
}
|
||||
|
||||
PersistentRememberMeToken getStoredToken() {
|
||||
return storedToken;
|
||||
}
|
||||
}
|
||||
PersistentRememberMeToken getStoredToken() {
|
||||
return storedToken;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,135 +37,151 @@ import javax.servlet.FilterChain;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link RememberMeAuthenticationFilter}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class RememberMeAuthenticationFilterTests {
|
||||
Authentication remembered = new TestingAuthenticationToken("remembered", "password","ROLE_REMEMBERED");
|
||||
Authentication remembered = new TestingAuthenticationToken("remembered", "password",
|
||||
"ROLE_REMEMBERED");
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
@Before
|
||||
public void setUp() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
@After
|
||||
public void tearDown() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testDetectsAuthenticationManagerProperty() {
|
||||
new RememberMeAuthenticationFilter(null, new NullRememberMeServices());
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testDetectsAuthenticationManagerProperty() {
|
||||
new RememberMeAuthenticationFilter(null, new NullRememberMeServices());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testDetectsRememberMeServicesProperty() {
|
||||
new RememberMeAuthenticationFilter(mock(AuthenticationManager.class), null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testDetectsRememberMeServicesProperty() {
|
||||
new RememberMeAuthenticationFilter(mock(AuthenticationManager.class), null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOperationWhenAuthenticationExistsInContextHolder() throws Exception {
|
||||
// Put an Authentication object into the SecurityContextHolder
|
||||
Authentication originalAuth = new TestingAuthenticationToken("user", "password","ROLE_A");
|
||||
SecurityContextHolder.getContext().setAuthentication(originalAuth);
|
||||
@Test
|
||||
public void testOperationWhenAuthenticationExistsInContextHolder() throws Exception {
|
||||
// Put an Authentication object into the SecurityContextHolder
|
||||
Authentication originalAuth = new TestingAuthenticationToken("user", "password",
|
||||
"ROLE_A");
|
||||
SecurityContextHolder.getContext().setAuthentication(originalAuth);
|
||||
|
||||
// Setup our filter correctly
|
||||
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(mock(AuthenticationManager.class), new MockRememberMeServices(remembered));
|
||||
filter.afterPropertiesSet();
|
||||
// Setup our filter correctly
|
||||
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(
|
||||
mock(AuthenticationManager.class), new MockRememberMeServices(remembered));
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
// Test
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
FilterChain fc = mock(FilterChain.class);
|
||||
request.setRequestURI("x");
|
||||
filter.doFilter(request, new MockHttpServletResponse(), fc);
|
||||
// Test
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
FilterChain fc = mock(FilterChain.class);
|
||||
request.setRequestURI("x");
|
||||
filter.doFilter(request, new MockHttpServletResponse(), fc);
|
||||
|
||||
// Ensure filter didn't change our original object
|
||||
assertSame(originalAuth, SecurityContextHolder.getContext().getAuthentication());
|
||||
verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
}
|
||||
// Ensure filter didn't change our original object
|
||||
assertSame(originalAuth, SecurityContextHolder.getContext().getAuthentication());
|
||||
verify(fc)
|
||||
.doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOperationWhenNoAuthenticationInContextHolder() throws Exception {
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
when(am.authenticate(remembered)).thenReturn(remembered);
|
||||
@Test
|
||||
public void testOperationWhenNoAuthenticationInContextHolder() throws Exception {
|
||||
AuthenticationManager am = mock(AuthenticationManager.class);
|
||||
when(am.authenticate(remembered)).thenReturn(remembered);
|
||||
|
||||
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(remembered));
|
||||
filter.afterPropertiesSet();
|
||||
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am,
|
||||
new MockRememberMeServices(remembered));
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
FilterChain fc = mock(FilterChain.class);
|
||||
request.setRequestURI("x");
|
||||
filter.doFilter(request, new MockHttpServletResponse(), fc);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
FilterChain fc = mock(FilterChain.class);
|
||||
request.setRequestURI("x");
|
||||
filter.doFilter(request, new MockHttpServletResponse(), fc);
|
||||
|
||||
// Ensure filter setup with our remembered authentication object
|
||||
assertSame(remembered, SecurityContextHolder.getContext().getAuthentication());
|
||||
verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
}
|
||||
// Ensure filter setup with our remembered authentication object
|
||||
assertSame(remembered, SecurityContextHolder.getContext().getAuthentication());
|
||||
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(""));
|
||||
@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(""));
|
||||
|
||||
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am,
|
||||
new MockRememberMeServices(remembered)) {
|
||||
protected void onUnsuccessfulAuthentication(HttpServletRequest request,
|
||||
HttpServletResponse response, AuthenticationException failed) {
|
||||
super.onUnsuccessfulAuthentication(request, response, failed);
|
||||
SecurityContextHolder.getContext().setAuthentication(failedAuth);
|
||||
}
|
||||
};
|
||||
filter.setApplicationEventPublisher(mock(ApplicationEventPublisher.class));
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am, new MockRememberMeServices(remembered)) {
|
||||
protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) {
|
||||
super.onUnsuccessfulAuthentication(request, response, failed);
|
||||
SecurityContextHolder.getContext().setAuthentication(failedAuth);
|
||||
}
|
||||
};
|
||||
filter.setApplicationEventPublisher(mock(ApplicationEventPublisher.class));
|
||||
filter.afterPropertiesSet();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
FilterChain fc = mock(FilterChain.class);
|
||||
request.setRequestURI("x");
|
||||
filter.doFilter(request, new MockHttpServletResponse(), fc);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
FilterChain fc = mock(FilterChain.class);
|
||||
request.setRequestURI("x");
|
||||
filter.doFilter(request, new MockHttpServletResponse(), fc);
|
||||
assertSame(failedAuth, SecurityContextHolder.getContext().getAuthentication());
|
||||
verify(fc)
|
||||
.doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
}
|
||||
|
||||
assertSame(failedAuth, SecurityContextHolder.getContext().getAuthentication());
|
||||
verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
}
|
||||
@Test
|
||||
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"));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterChain fc = mock(FilterChain.class);
|
||||
request.setRequestURI("x");
|
||||
filter.doFilter(request, response, fc);
|
||||
|
||||
@Test
|
||||
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"));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterChain fc = mock(FilterChain.class);
|
||||
request.setRequestURI("x");
|
||||
filter.doFilter(request, response, fc);
|
||||
assertEquals("/target", response.getRedirectedUrl());
|
||||
|
||||
assertEquals("/target", response.getRedirectedUrl());
|
||||
// Should return after success handler is invoked, so chain should not proceed
|
||||
verifyZeroInteractions(fc);
|
||||
}
|
||||
|
||||
// Should return after success handler is invoked, so chain should not proceed
|
||||
verifyZeroInteractions(fc);
|
||||
}
|
||||
// ~ Inner Classes
|
||||
// ==================================================================================================
|
||||
|
||||
//~ Inner Classes ==================================================================================================
|
||||
private class MockRememberMeServices implements RememberMeServices {
|
||||
private Authentication authToReturn;
|
||||
|
||||
private class MockRememberMeServices implements RememberMeServices {
|
||||
private Authentication authToReturn;
|
||||
public MockRememberMeServices(Authentication authToReturn) {
|
||||
this.authToReturn = authToReturn;
|
||||
}
|
||||
|
||||
public MockRememberMeServices(Authentication authToReturn) {
|
||||
this.authToReturn = authToReturn;
|
||||
}
|
||||
public Authentication autoLogin(HttpServletRequest request,
|
||||
HttpServletResponse response) {
|
||||
return authToReturn;
|
||||
}
|
||||
|
||||
public Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) {
|
||||
return authToReturn;
|
||||
}
|
||||
public void loginFail(HttpServletRequest request, HttpServletResponse response) {
|
||||
}
|
||||
|
||||
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) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,285 +39,321 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* Tests {@link org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices}.
|
||||
* Tests
|
||||
* {@link org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices}
|
||||
* .
|
||||
*
|
||||
* @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;
|
||||
private UserDetailsService uds;
|
||||
private UserDetails user = new User("someone", "password", true, true, true, true,
|
||||
AuthorityUtils.createAuthorityList("ROLE_ABC"));
|
||||
private TokenBasedRememberMeServices services;
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
@Before
|
||||
public void createTokenBasedRememberMeServices() {
|
||||
uds = mock(UserDetailsService.class);
|
||||
services = new TokenBasedRememberMeServices("key",uds);
|
||||
}
|
||||
@Before
|
||||
public void createTokenBasedRememberMeServices() {
|
||||
uds = mock(UserDetailsService.class);
|
||||
services = new TokenBasedRememberMeServices("key", uds);
|
||||
}
|
||||
|
||||
void udsWillReturnUser() {
|
||||
when(uds.loadUserByUsername(any(String.class))).thenReturn(user);
|
||||
}
|
||||
void udsWillReturnUser() {
|
||||
when(uds.loadUserByUsername(any(String.class))).thenReturn(user);
|
||||
}
|
||||
|
||||
void udsWillThrowNotFound() {
|
||||
when(uds.loadUserByUsername(any(String.class))).thenThrow(new UsernameNotFoundException(""));
|
||||
}
|
||||
void udsWillThrowNotFound() {
|
||||
when(uds.loadUserByUsername(any(String.class))).thenThrow(
|
||||
new UsernameNotFoundException(""));
|
||||
}
|
||||
|
||||
private long determineExpiryTimeFromBased64EncodedToken(String validToken) {
|
||||
String cookieAsPlainText = new String(Base64.decodeBase64(validToken.getBytes()));
|
||||
String[] cookieTokens = StringUtils.delimitedListToStringArray(cookieAsPlainText, ":");
|
||||
private long determineExpiryTimeFromBased64EncodedToken(String validToken) {
|
||||
String cookieAsPlainText = new String(Base64.decodeBase64(validToken.getBytes()));
|
||||
String[] cookieTokens = StringUtils.delimitedListToStringArray(cookieAsPlainText,
|
||||
":");
|
||||
|
||||
if (cookieTokens.length == 3) {
|
||||
try {
|
||||
return Long.parseLong(cookieTokens[1]);
|
||||
} catch (NumberFormatException ignored) {}
|
||||
}
|
||||
if (cookieTokens.length == 3) {
|
||||
try {
|
||||
return Long.parseLong(cookieTokens[1]);
|
||||
}
|
||||
catch (NumberFormatException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
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 tokenValue = username + ":" + expiryTime + ":" + signatureValue;
|
||||
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 tokenValue = username + ":" + expiryTime + ":" + signatureValue;
|
||||
|
||||
return new String(Base64.encodeBase64(tokenValue.getBytes()));
|
||||
}
|
||||
return new String(Base64.encodeBase64(tokenValue.getBytes()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void autoLoginReturnsNullIfNoCookiePresented() throws Exception {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
@Test
|
||||
public void autoLoginReturnsNullIfNoCookiePresented() throws Exception {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
Authentication result = services.autoLogin(new MockHttpServletRequest(), response);
|
||||
assertNull(result);
|
||||
// No cookie set
|
||||
assertNull(response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY));
|
||||
}
|
||||
Authentication result = services
|
||||
.autoLogin(new MockHttpServletRequest(), response);
|
||||
assertNull(result);
|
||||
// No cookie set
|
||||
assertNull(response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void autoLoginIgnoresUnrelatedCookie() throws Exception {
|
||||
Cookie cookie = new Cookie("unrelated_cookie", "foobar");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setCookies(cookie);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
@Test
|
||||
public void autoLoginIgnoresUnrelatedCookie() throws Exception {
|
||||
Cookie cookie = new Cookie("unrelated_cookie", "foobar");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setCookies(cookie);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
Authentication result = services.autoLogin(request, response);
|
||||
Authentication result = services.autoLogin(request, response);
|
||||
|
||||
assertNull(result);
|
||||
assertNull(response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY));
|
||||
}
|
||||
assertNull(result);
|
||||
assertNull(response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void autoLoginReturnsNullForExpiredCookieAndClearsCookie() throws Exception {
|
||||
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
|
||||
generateCorrectCookieContentForToken(System.currentTimeMillis() - 1000000, "someone", "password", "key"));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setCookies(cookie);
|
||||
@Test
|
||||
public void autoLoginReturnsNullForExpiredCookieAndClearsCookie() throws Exception {
|
||||
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();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
assertNull(services.autoLogin(request, response));
|
||||
Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertNotNull(returnedCookie);
|
||||
assertEquals(0, returnedCookie.getMaxAge());
|
||||
}
|
||||
assertNull(services.autoLogin(request, response));
|
||||
Cookie returnedCookie = response
|
||||
.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertNotNull(returnedCookie);
|
||||
assertEquals(0, returnedCookie.getMaxAge());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void autoLoginReturnsNullAndClearsCookieIfMissingThreeTokensInCookieValue() throws Exception {
|
||||
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
|
||||
new String(Base64.encodeBase64("x".getBytes())));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setCookies(cookie);
|
||||
@Test
|
||||
public void autoLoginReturnsNullAndClearsCookieIfMissingThreeTokensInCookieValue()
|
||||
throws Exception {
|
||||
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();
|
||||
assertNull(services.autoLogin(request, response));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
assertNull(services.autoLogin(request, response));
|
||||
|
||||
Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertNotNull(returnedCookie);
|
||||
assertEquals(0, returnedCookie.getMaxAge());
|
||||
}
|
||||
Cookie returnedCookie = response
|
||||
.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertNotNull(returnedCookie);
|
||||
assertEquals(0, returnedCookie.getMaxAge());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void autoLoginClearsNonBase64EncodedCookie() throws Exception {
|
||||
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
|
||||
"NOT_BASE_64_ENCODED");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setCookies(cookie);
|
||||
@Test
|
||||
public void autoLoginClearsNonBase64EncodedCookie() throws Exception {
|
||||
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();
|
||||
assertNull(services.autoLogin(request, response));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
assertNull(services.autoLogin(request, response));
|
||||
|
||||
Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertNotNull(returnedCookie);
|
||||
assertEquals(0, returnedCookie.getMaxAge());
|
||||
}
|
||||
Cookie returnedCookie = response
|
||||
.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertNotNull(returnedCookie);
|
||||
assertEquals(0, returnedCookie.getMaxAge());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void autoLoginClearsCookieIfSignatureBlocksDoesNotMatchExpectedValue() throws Exception {
|
||||
udsWillReturnUser();
|
||||
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);
|
||||
@Test
|
||||
public void autoLoginClearsCookieIfSignatureBlocksDoesNotMatchExpectedValue()
|
||||
throws Exception {
|
||||
udsWillReturnUser();
|
||||
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);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
assertNull(services.autoLogin(request, response));
|
||||
assertNull(services.autoLogin(request, response));
|
||||
|
||||
Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertNotNull(returnedCookie);
|
||||
assertEquals(0, returnedCookie.getMaxAge());
|
||||
}
|
||||
Cookie returnedCookie = response
|
||||
.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertNotNull(returnedCookie);
|
||||
assertEquals(0, returnedCookie.getMaxAge());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void autoLoginClearsCookieIfTokenDoesNotContainANumberInCookieValue() throws Exception {
|
||||
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);
|
||||
@Test
|
||||
public void autoLoginClearsCookieIfTokenDoesNotContainANumberInCookieValue()
|
||||
throws Exception {
|
||||
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();
|
||||
assertNull(services.autoLogin(request, response));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
assertNull(services.autoLogin(request, response));
|
||||
|
||||
Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertNotNull(returnedCookie);
|
||||
assertEquals(0, returnedCookie.getMaxAge());
|
||||
}
|
||||
Cookie returnedCookie = response
|
||||
.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertNotNull(returnedCookie);
|
||||
assertEquals(0, returnedCookie.getMaxAge());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void autoLoginClearsCookieIfUserNotFound() throws Exception {
|
||||
udsWillThrowNotFound();
|
||||
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
|
||||
generateCorrectCookieContentForToken(System.currentTimeMillis() + 1000000, "someone", "password", "key"));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setCookies(cookie);
|
||||
@Test
|
||||
public void autoLoginClearsCookieIfUserNotFound() throws Exception {
|
||||
udsWillThrowNotFound();
|
||||
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();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
assertNull(services.autoLogin(request, response));
|
||||
assertNull(services.autoLogin(request, response));
|
||||
|
||||
Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertNotNull(returnedCookie);
|
||||
assertEquals(0, returnedCookie.getMaxAge());
|
||||
}
|
||||
Cookie returnedCookie = response
|
||||
.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertNotNull(returnedCookie);
|
||||
assertEquals(0, returnedCookie.getMaxAge());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void autoLoginWithValidTokenAndUserSucceeds() throws Exception {
|
||||
udsWillReturnUser();
|
||||
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
|
||||
generateCorrectCookieContentForToken(System.currentTimeMillis() + 1000000, "someone", "password", "key"));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setCookies(cookie);
|
||||
@Test
|
||||
public void autoLoginWithValidTokenAndUserSucceeds() throws Exception {
|
||||
udsWillReturnUser();
|
||||
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();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
Authentication result = services.autoLogin(request, response);
|
||||
Authentication result = services.autoLogin(request, response);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(user, result.getPrincipal());
|
||||
}
|
||||
assertNotNull(result);
|
||||
assertEquals(user, result.getPrincipal());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGettersSetters() {
|
||||
assertEquals(uds, services.getUserDetailsService());
|
||||
@Test
|
||||
public void testGettersSetters() {
|
||||
assertEquals(uds, services.getUserDetailsService());
|
||||
|
||||
assertEquals("key", services.getKey());
|
||||
assertEquals("key", services.getKey());
|
||||
|
||||
assertEquals(DEFAULT_PARAMETER, services.getParameter());
|
||||
services.setParameter("some_param");
|
||||
assertEquals("some_param", services.getParameter());
|
||||
assertEquals(DEFAULT_PARAMETER, services.getParameter());
|
||||
services.setParameter("some_param");
|
||||
assertEquals("some_param", services.getParameter());
|
||||
|
||||
services.setTokenValiditySeconds(12);
|
||||
assertEquals(12, services.getTokenValiditySeconds());
|
||||
}
|
||||
services.setTokenValiditySeconds(12);
|
||||
assertEquals(12, services.getTokenValiditySeconds());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loginFailClearsCookie() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
services.loginFail(request, response);
|
||||
@Test
|
||||
public void loginFailClearsCookie() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
services.loginFail(request, response);
|
||||
|
||||
Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertNotNull(cookie);
|
||||
assertEquals(0, cookie.getMaxAge());
|
||||
}
|
||||
Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertNotNull(cookie);
|
||||
assertEquals(0, cookie.getMaxAge());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loginSuccessIgnoredIfParameterNotSetOrFalse() {
|
||||
TokenBasedRememberMeServices services = new TokenBasedRememberMeServices("key",new AbstractRememberMeServicesTests.MockUserDetailsService(null, false));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addParameter(DEFAULT_PARAMETER, "false");
|
||||
@Test
|
||||
public void loginSuccessIgnoredIfParameterNotSetOrFalse() {
|
||||
TokenBasedRememberMeServices services = new TokenBasedRememberMeServices("key",
|
||||
new AbstractRememberMeServicesTests.MockUserDetailsService(null, false));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addParameter(DEFAULT_PARAMETER, "false");
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password","ROLE_ABC"));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
services.loginSuccess(request, response, new TestingAuthenticationToken(
|
||||
"someone", "password", "ROLE_ABC"));
|
||||
|
||||
Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertNull(cookie);
|
||||
}
|
||||
Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertNull(cookie);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loginSuccessNormalWithNonUserDetailsBasedPrincipalSetsExpectedCookie() {
|
||||
// SEC-822
|
||||
services.setTokenValiditySeconds(500000000);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addParameter(TokenBasedRememberMeServices.DEFAULT_PARAMETER, "true");
|
||||
@Test
|
||||
public void loginSuccessNormalWithNonUserDetailsBasedPrincipalSetsExpectedCookie() {
|
||||
// SEC-822
|
||||
services.setTokenValiditySeconds(500000000);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addParameter(TokenBasedRememberMeServices.DEFAULT_PARAMETER, "true");
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password","ROLE_ABC"));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
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];
|
||||
long expectedExpiryTime = 1000L * 500000000;
|
||||
expectedExpiryTime += System.currentTimeMillis();
|
||||
assertTrue(Long.parseLong(expiryTime) > expectedExpiryTime - 10000);
|
||||
assertNotNull(cookie);
|
||||
assertEquals(services.getTokenValiditySeconds(), cookie.getMaxAge());
|
||||
assertTrue(Base64.isArrayByteBase64(cookie.getValue().getBytes()));
|
||||
assertTrue(new Date().before(new Date(determineExpiryTimeFromBased64EncodedToken(cookie.getValue()))));
|
||||
}
|
||||
Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
String expiryTime = services.decodeCookie(cookie.getValue())[1];
|
||||
long expectedExpiryTime = 1000L * 500000000;
|
||||
expectedExpiryTime += System.currentTimeMillis();
|
||||
assertTrue(Long.parseLong(expiryTime) > expectedExpiryTime - 10000);
|
||||
assertNotNull(cookie);
|
||||
assertEquals(services.getTokenValiditySeconds(), cookie.getMaxAge());
|
||||
assertTrue(Base64.isArrayByteBase64(cookie.getValue().getBytes()));
|
||||
assertTrue(new Date().before(new Date(
|
||||
determineExpiryTimeFromBased64EncodedToken(cookie.getValue()))));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loginSuccessNormalWithUserDetailsBasedPrincipalSetsExpectedCookie() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addParameter(TokenBasedRememberMeServices.DEFAULT_PARAMETER, "true");
|
||||
@Test
|
||||
public void loginSuccessNormalWithUserDetailsBasedPrincipalSetsExpectedCookie() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addParameter(TokenBasedRememberMeServices.DEFAULT_PARAMETER, "true");
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password","ROLE_ABC"));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
services.loginSuccess(request, response, new TestingAuthenticationToken(
|
||||
"someone", "password", "ROLE_ABC"));
|
||||
|
||||
Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertNotNull(cookie);
|
||||
assertEquals(services.getTokenValiditySeconds(), cookie.getMaxAge());
|
||||
assertTrue(Base64.isArrayByteBase64(cookie.getValue().getBytes()));
|
||||
assertTrue(new Date().before(new Date(determineExpiryTimeFromBased64EncodedToken(cookie.getValue()))));
|
||||
}
|
||||
Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertNotNull(cookie);
|
||||
assertEquals(services.getTokenValiditySeconds(), cookie.getMaxAge());
|
||||
assertTrue(Base64.isArrayByteBase64(cookie.getValue().getBytes()));
|
||||
assertTrue(new Date().before(new Date(
|
||||
determineExpiryTimeFromBased64EncodedToken(cookie.getValue()))));
|
||||
}
|
||||
|
||||
// SEC-933
|
||||
@Test
|
||||
public void obtainPasswordReturnsNullForTokenWithNullCredentials() throws Exception {
|
||||
TestingAuthenticationToken token = new TestingAuthenticationToken("username", null);
|
||||
assertNull(services.retrievePassword(token));
|
||||
}
|
||||
// SEC-933
|
||||
@Test
|
||||
public void obtainPasswordReturnsNullForTokenWithNullCredentials() throws Exception {
|
||||
TestingAuthenticationToken token = new TestingAuthenticationToken("username",
|
||||
null);
|
||||
assertNull(services.retrievePassword(token));
|
||||
}
|
||||
|
||||
// SEC-949
|
||||
@Test
|
||||
public void negativeValidityPeriodIsSetOnCookieButExpiryTimeRemainsAtTwoWeeks() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addParameter(DEFAULT_PARAMETER, "true");
|
||||
// SEC-949
|
||||
@Test
|
||||
public void negativeValidityPeriodIsSetOnCookieButExpiryTimeRemainsAtTwoWeeks()
|
||||
throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addParameter(DEFAULT_PARAMETER, "true");
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
services.setTokenValiditySeconds(-1);
|
||||
services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password","ROLE_ABC"));
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
services.setTokenValiditySeconds(-1);
|
||||
services.loginSuccess(request, response, new TestingAuthenticationToken(
|
||||
"someone", "password", "ROLE_ABC"));
|
||||
|
||||
Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertNotNull(cookie);
|
||||
// Check the expiry time is within 50ms of two weeks from current time
|
||||
assertTrue(determineExpiryTimeFromBased64EncodedToken(cookie.getValue()) - System.currentTimeMillis() >
|
||||
TWO_WEEKS_S - 50);
|
||||
assertEquals(-1, cookie.getMaxAge());
|
||||
assertTrue(Base64.isArrayByteBase64(cookie.getValue().getBytes()));
|
||||
}
|
||||
Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
|
||||
assertNotNull(cookie);
|
||||
// Check the expiry time is within 50ms of two weeks from current time
|
||||
assertTrue(determineExpiryTimeFromBased64EncodedToken(cookie.getValue())
|
||||
- System.currentTimeMillis() > TWO_WEEKS_S - 50);
|
||||
assertEquals(-1, cookie.getMaxAge());
|
||||
assertTrue(Base64.isArrayByteBase64(cookie.getValue().getBytes()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,28 +35,29 @@ import org.springframework.util.ReflectionUtils;
|
||||
*
|
||||
*/
|
||||
@RunWith(PowerMockRunner.class)
|
||||
@PrepareForTest({ReflectionUtils.class, Method.class})
|
||||
@PrepareForTest({ ReflectionUtils.class, Method.class })
|
||||
public class ChangeSessionIdAuthenticationStrategyTests {
|
||||
@Mock
|
||||
private Method method;
|
||||
@Mock
|
||||
private Method method;
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void constructChangeIdMethodNotFound() {
|
||||
new ChangeSessionIdAuthenticationStrategy();
|
||||
}
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void constructChangeIdMethodNotFound() {
|
||||
new ChangeSessionIdAuthenticationStrategy();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void applySessionFixation() throws Exception {
|
||||
spy(ReflectionUtils.class);
|
||||
Method method = mock(Method.class);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.getSession();
|
||||
when(ReflectionUtils.findMethod(HttpServletRequest.class, "changeSessionId")).thenReturn(method);
|
||||
@Test
|
||||
public void applySessionFixation() throws Exception {
|
||||
spy(ReflectionUtils.class);
|
||||
Method method = mock(Method.class);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.getSession();
|
||||
when(ReflectionUtils.findMethod(HttpServletRequest.class, "changeSessionId"))
|
||||
.thenReturn(method);
|
||||
|
||||
new ChangeSessionIdAuthenticationStrategy().applySessionFixation(request);
|
||||
new ChangeSessionIdAuthenticationStrategy().applySessionFixation(request);
|
||||
|
||||
verifyStatic();
|
||||
ReflectionUtils.invokeMethod(same(method), eq(request));
|
||||
}
|
||||
verifyStatic();
|
||||
ReflectionUtils.invokeMethod(same(method), eq(request));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -38,55 +38,60 @@ import org.springframework.security.core.Authentication;
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class CompositeSessionAuthenticationStrategyTests {
|
||||
@Mock
|
||||
private SessionAuthenticationStrategy strategy1;
|
||||
@Mock
|
||||
private SessionAuthenticationStrategy strategy2;
|
||||
@Mock
|
||||
private Authentication authentication;
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
@Mock
|
||||
private HttpServletResponse response;
|
||||
@Mock
|
||||
private SessionAuthenticationStrategy strategy1;
|
||||
@Mock
|
||||
private SessionAuthenticationStrategy strategy2;
|
||||
@Mock
|
||||
private Authentication authentication;
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
@Mock
|
||||
private HttpServletResponse response;
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullDelegates() {
|
||||
new CompositeSessionAuthenticationStrategy(null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullDelegates() {
|
||||
new CompositeSessionAuthenticationStrategy(null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorEmptyDelegates() {
|
||||
new CompositeSessionAuthenticationStrategy(
|
||||
Collections.<SessionAuthenticationStrategy> emptyList());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorEmptyDelegates() {
|
||||
new CompositeSessionAuthenticationStrategy(Collections.<SessionAuthenticationStrategy>emptyList());
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorDelegatesContainNull() {
|
||||
new CompositeSessionAuthenticationStrategy(
|
||||
Collections.<SessionAuthenticationStrategy> singletonList(null));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorDelegatesContainNull() {
|
||||
new CompositeSessionAuthenticationStrategy(Collections.<SessionAuthenticationStrategy>singletonList(null));
|
||||
}
|
||||
@Test
|
||||
public void delegatesToAll() {
|
||||
CompositeSessionAuthenticationStrategy strategy = new CompositeSessionAuthenticationStrategy(
|
||||
Arrays.asList(strategy1, strategy2));
|
||||
strategy.onAuthentication(authentication, request, response);
|
||||
|
||||
@Test
|
||||
public void delegatesToAll() {
|
||||
CompositeSessionAuthenticationStrategy strategy = new CompositeSessionAuthenticationStrategy(Arrays.asList(strategy1,strategy2));
|
||||
strategy.onAuthentication(authentication, request, response);
|
||||
verify(strategy1).onAuthentication(authentication, request, response);
|
||||
verify(strategy2).onAuthentication(authentication, request, response);
|
||||
}
|
||||
|
||||
verify(strategy1).onAuthentication(authentication, request, response);
|
||||
verify(strategy2).onAuthentication(authentication, request, response);
|
||||
}
|
||||
@Test
|
||||
public void delegateShortCircuits() {
|
||||
doThrow(new SessionAuthenticationException("oops")).when(strategy1)
|
||||
.onAuthentication(authentication, request, response);
|
||||
|
||||
CompositeSessionAuthenticationStrategy strategy = new CompositeSessionAuthenticationStrategy(
|
||||
Arrays.asList(strategy1, strategy2));
|
||||
|
||||
@Test
|
||||
public void delegateShortCircuits() {
|
||||
doThrow(new SessionAuthenticationException("oops")).when(strategy1).onAuthentication(authentication, request, response);
|
||||
try {
|
||||
strategy.onAuthentication(authentication, request, response);
|
||||
fail("Expected Exception");
|
||||
}
|
||||
catch (SessionAuthenticationException success) {
|
||||
}
|
||||
|
||||
CompositeSessionAuthenticationStrategy strategy = new CompositeSessionAuthenticationStrategy(Arrays.asList(strategy1,strategy2));
|
||||
|
||||
try {
|
||||
strategy.onAuthentication(authentication, request, response);
|
||||
fail("Expected Exception");
|
||||
} catch (SessionAuthenticationException success) {}
|
||||
|
||||
verify(strategy1).onAuthentication(authentication, request, response);
|
||||
verify(strategy2,times(0)).onAuthentication(authentication, request, response);
|
||||
}
|
||||
verify(strategy1).onAuthentication(authentication, request, response);
|
||||
verify(strategy2, times(0)).onAuthentication(authentication, request, response);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,87 +46,96 @@ import org.springframework.security.core.session.SessionRegistry;
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class ConcurrentSessionControlAuthenticationStrategyTests {
|
||||
@Mock
|
||||
private SessionRegistry sessionRegistry;
|
||||
@Mock
|
||||
private SessionRegistry sessionRegistry;
|
||||
|
||||
private Authentication authentication;
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletResponse response;
|
||||
private SessionInformation sessionInformation;
|
||||
private Authentication authentication;
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletResponse response;
|
||||
private SessionInformation sessionInformation;
|
||||
|
||||
private ConcurrentSessionControlAuthenticationStrategy strategy;
|
||||
private ConcurrentSessionControlAuthenticationStrategy strategy;
|
||||
|
||||
@Before
|
||||
public void setup() throws Exception {
|
||||
authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
sessionInformation = new SessionInformation(authentication.getPrincipal(), "unique", new Date(1374766134216L));
|
||||
@Before
|
||||
public void setup() throws Exception {
|
||||
authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
sessionInformation = new SessionInformation(authentication.getPrincipal(),
|
||||
"unique", new Date(1374766134216L));
|
||||
|
||||
strategy = new ConcurrentSessionControlAuthenticationStrategy(sessionRegistry);
|
||||
}
|
||||
strategy = new ConcurrentSessionControlAuthenticationStrategy(sessionRegistry);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullRegistry() {
|
||||
new ConcurrentSessionControlAuthenticationStrategy(null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullRegistry() {
|
||||
new ConcurrentSessionControlAuthenticationStrategy(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noRegisteredSession() {
|
||||
when(sessionRegistry.getAllSessions(any(), anyBoolean())).thenReturn(Collections.<SessionInformation>emptyList());
|
||||
strategy.setMaximumSessions(1);
|
||||
strategy.setExceptionIfMaximumExceeded(true);
|
||||
@Test
|
||||
public void noRegisteredSession() {
|
||||
when(sessionRegistry.getAllSessions(any(), anyBoolean())).thenReturn(
|
||||
Collections.<SessionInformation> emptyList());
|
||||
strategy.setMaximumSessions(1);
|
||||
strategy.setExceptionIfMaximumExceeded(true);
|
||||
|
||||
strategy.onAuthentication(authentication, request, response);
|
||||
strategy.onAuthentication(authentication, request, response);
|
||||
|
||||
// no exception
|
||||
}
|
||||
// no exception
|
||||
}
|
||||
|
||||
@Test
|
||||
public void maxSessionsSameSessionId() {
|
||||
MockHttpSession session = new MockHttpSession(new MockServletContext(), sessionInformation.getSessionId());
|
||||
request.setSession(session);
|
||||
when(sessionRegistry.getAllSessions(any(), anyBoolean())).thenReturn(Collections.<SessionInformation>singletonList(sessionInformation));
|
||||
strategy.setMaximumSessions(1);
|
||||
strategy.setExceptionIfMaximumExceeded(true);
|
||||
@Test
|
||||
public void maxSessionsSameSessionId() {
|
||||
MockHttpSession session = new MockHttpSession(new MockServletContext(),
|
||||
sessionInformation.getSessionId());
|
||||
request.setSession(session);
|
||||
when(sessionRegistry.getAllSessions(any(), anyBoolean())).thenReturn(
|
||||
Collections.<SessionInformation> singletonList(sessionInformation));
|
||||
strategy.setMaximumSessions(1);
|
||||
strategy.setExceptionIfMaximumExceeded(true);
|
||||
|
||||
strategy.onAuthentication(authentication, request, response);
|
||||
strategy.onAuthentication(authentication, request, response);
|
||||
|
||||
// no exception
|
||||
}
|
||||
// no exception
|
||||
}
|
||||
|
||||
@Test(expected = SessionAuthenticationException.class)
|
||||
public void maxSessionsWithException() {
|
||||
when(sessionRegistry.getAllSessions(any(), anyBoolean())).thenReturn(Collections.<SessionInformation>singletonList(sessionInformation));
|
||||
strategy.setMaximumSessions(1);
|
||||
strategy.setExceptionIfMaximumExceeded(true);
|
||||
@Test(expected = SessionAuthenticationException.class)
|
||||
public void maxSessionsWithException() {
|
||||
when(sessionRegistry.getAllSessions(any(), anyBoolean())).thenReturn(
|
||||
Collections.<SessionInformation> singletonList(sessionInformation));
|
||||
strategy.setMaximumSessions(1);
|
||||
strategy.setExceptionIfMaximumExceeded(true);
|
||||
|
||||
strategy.onAuthentication(authentication, request, response);
|
||||
}
|
||||
strategy.onAuthentication(authentication, request, response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void maxSessionsExpireExistingUser() {
|
||||
when(sessionRegistry.getAllSessions(any(), anyBoolean())).thenReturn(Collections.<SessionInformation>singletonList(sessionInformation));
|
||||
strategy.setMaximumSessions(1);
|
||||
@Test
|
||||
public void maxSessionsExpireExistingUser() {
|
||||
when(sessionRegistry.getAllSessions(any(), anyBoolean())).thenReturn(
|
||||
Collections.<SessionInformation> singletonList(sessionInformation));
|
||||
strategy.setMaximumSessions(1);
|
||||
|
||||
strategy.onAuthentication(authentication, request, response);
|
||||
strategy.onAuthentication(authentication, request, response);
|
||||
|
||||
assertThat(sessionInformation.isExpired()).isTrue();
|
||||
}
|
||||
assertThat(sessionInformation.isExpired()).isTrue();
|
||||
}
|
||||
|
||||
@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));
|
||||
strategy.setMaximumSessions(2);
|
||||
@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));
|
||||
strategy.setMaximumSessions(2);
|
||||
|
||||
strategy.onAuthentication(authentication, request, response);
|
||||
strategy.onAuthentication(authentication, request, response);
|
||||
|
||||
assertThat(sessionInformation.isExpired()).isTrue();
|
||||
}
|
||||
assertThat(sessionInformation.isExpired()).isTrue();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setMessageSourceNull() {
|
||||
strategy.setMessageSource(null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setMessageSourceNull() {
|
||||
strategy.setMessageSource(null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,33 +35,34 @@ import org.springframework.security.core.session.SessionRegistry;
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class RegisterSessionAuthenticationStrategyTests {
|
||||
|
||||
@Mock
|
||||
private SessionRegistry registry;
|
||||
@Mock
|
||||
private SessionRegistry registry;
|
||||
|
||||
private RegisterSessionAuthenticationStrategy authenticationStrategy;
|
||||
private RegisterSessionAuthenticationStrategy authenticationStrategy;
|
||||
|
||||
private Authentication authentication;
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletResponse response;
|
||||
private Authentication authentication;
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletResponse response;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
authenticationStrategy = new RegisterSessionAuthenticationStrategy(registry);
|
||||
authentication = new TestingAuthenticationToken("user", "password","ROLE_USER");
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
}
|
||||
@Before
|
||||
public void setup() {
|
||||
authenticationStrategy = new RegisterSessionAuthenticationStrategy(registry);
|
||||
authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullRegistry() {
|
||||
new RegisterSessionAuthenticationStrategy(null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullRegistry() {
|
||||
new RegisterSessionAuthenticationStrategy(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void onAuthenticationRegistersSession() {
|
||||
authenticationStrategy.onAuthentication(authentication, request, response);
|
||||
@Test
|
||||
public void onAuthenticationRegistersSession() {
|
||||
authenticationStrategy.onAuthentication(authentication, request, response);
|
||||
|
||||
verify(registry).registerNewSession(request.getSession().getId(), authentication.getPrincipal());
|
||||
}
|
||||
verify(registry).registerNewSession(request.getSession().getId(),
|
||||
authentication.getPrincipal());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -42,380 +42,406 @@ import org.springframework.security.web.authentication.SimpleUrlAuthenticationSu
|
||||
import javax.servlet.FilterChain;
|
||||
import java.util.*;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link org.springframework.security.web.authentication.switchuser.SwitchUserFilter}.
|
||||
* Tests
|
||||
* {@link org.springframework.security.web.authentication.switchuser.SwitchUserFilter}.
|
||||
*
|
||||
* @author Mark St.Godard
|
||||
* @author Luke Taylor
|
||||
*/
|
||||
public class SwitchUserFilterTests {
|
||||
private final static List<GrantedAuthority> ROLES_12 = AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO");
|
||||
|
||||
@Before
|
||||
public void authenticateCurrentUser() {
|
||||
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("dano", "hawaii50");
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
}
|
||||
|
||||
@After
|
||||
public void clearContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
private MockHttpServletRequest createMockSwitchRequest() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setScheme("http");
|
||||
request.setServerName("localhost");
|
||||
request.setRequestURI("/login/impersonate");
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
private Authentication switchToUser(String name) {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addParameter("myUsernameParameter", name);
|
||||
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setUsernameParameter("myUsernameParameter");
|
||||
filter.setUserDetailsService(new MockUserDetailsService());
|
||||
|
||||
return filter.attemptSwitchUser(request);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requiresExitUserMatchesCorrectly() {
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setExitUserUrl("/j_spring_security_my_exit_user");
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/j_spring_security_my_exit_user");
|
||||
|
||||
assertTrue(filter.requiresExitUser(request));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requiresSwitchMatchesCorrectly() {
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setSwitchUserUrl("/j_spring_security_my_switch_user");
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/j_spring_security_my_switch_user");
|
||||
|
||||
assertTrue(filter.requiresSwitchUser(request));
|
||||
}
|
||||
|
||||
@Test(expected=UsernameNotFoundException.class)
|
||||
public void attemptSwitchToUnknownUserFails() throws Exception {
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "user-that-doesnt-exist");
|
||||
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setUserDetailsService(new MockUserDetailsService());
|
||||
filter.attemptSwitchUser(request);
|
||||
}
|
||||
|
||||
@Test(expected=DisabledException.class)
|
||||
public void attemptSwitchToUserThatIsDisabledFails() throws Exception {
|
||||
switchToUser("mcgarrett");
|
||||
}
|
||||
|
||||
@Test(expected=AccountExpiredException.class)
|
||||
public void attemptSwitchToUserWithAccountExpiredFails() throws Exception {
|
||||
switchToUser("wofat");
|
||||
}
|
||||
|
||||
@Test(expected=CredentialsExpiredException.class)
|
||||
public void attemptSwitchToUserWithExpiredCredentialsFails() throws Exception {
|
||||
switchToUser("steve");
|
||||
}
|
||||
|
||||
@Test(expected=UsernameNotFoundException.class)
|
||||
public void switchUserWithNullUsernameThrowsException() throws Exception {
|
||||
switchToUser(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void attemptSwitchUserIsSuccessfulWithValidUser() throws Exception {
|
||||
assertNotNull(switchToUser("jacklord"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void switchToLockedAccountCausesRedirectToSwitchFailureUrl() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/login/impersonate");
|
||||
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "mcgarrett");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setTargetUrl("/target");
|
||||
filter.setUserDetailsService(new MockUserDetailsService());
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
// Check it with no url set (should get a text response)
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
filter.doFilter(request, response, chain);
|
||||
verify(chain, never()).doFilter(request, response);
|
||||
|
||||
assertNotNull(response.getErrorMessage());
|
||||
|
||||
// Now check for the redirect
|
||||
request.setContextPath("/mywebapp");
|
||||
request.setRequestURI("/mywebapp/login/impersonate");
|
||||
filter = new SwitchUserFilter();
|
||||
filter.setTargetUrl("/target");
|
||||
filter.setUserDetailsService(new MockUserDetailsService());
|
||||
filter.setSwitchFailureUrl("/switchfailed");
|
||||
filter.afterPropertiesSet();
|
||||
response = new MockHttpServletResponse();
|
||||
|
||||
chain = mock(FilterChain.class);
|
||||
filter.doFilter(request, response, chain);
|
||||
verify(chain, never()).doFilter(request, response);
|
||||
|
||||
assertEquals("/mywebapp/switchfailed", response.getRedirectedUrl());
|
||||
assertEquals("/switchfailed", FieldUtils.getFieldValue(filter, "switchFailureUrl"));
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void configMissingUserDetailsServiceFails() throws Exception {
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setSwitchUserUrl("/login/impersonate");
|
||||
filter.setExitUserUrl("/logout/impersonate");
|
||||
filter.setTargetUrl("/main.jsp");
|
||||
filter.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testBadConfigMissingTargetUrl() throws Exception {
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setUserDetailsService(new MockUserDetailsService());
|
||||
filter.setSwitchUserUrl("/login/impersonate");
|
||||
filter.setExitUserUrl("/logout/impersonate");
|
||||
filter.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void defaultProcessesFilterUrlMatchesUrlWithPathParameter() {
|
||||
MockHttpServletRequest request = createMockSwitchRequest();
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setSwitchUserUrl("/login/impersonate");
|
||||
|
||||
request.setRequestURI("/webapp/login/impersonate;jsessionid=8JHDUD723J8");
|
||||
assertTrue(filter.requiresSwitchUser(request));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void exitUserJackLordToDanoSucceeds() throws Exception {
|
||||
// original user
|
||||
UsernamePasswordAuthenticationToken source = new UsernamePasswordAuthenticationToken("dano", "hawaii50", ROLES_12);
|
||||
|
||||
// set current user (Admin)
|
||||
List<GrantedAuthority> adminAuths = new ArrayList<GrantedAuthority>();
|
||||
adminAuths.addAll(ROLES_12);
|
||||
adminAuths.add(new SwitchUserGrantedAuthority("PREVIOUS_ADMINISTRATOR", source));
|
||||
UsernamePasswordAuthenticationToken admin =
|
||||
new UsernamePasswordAuthenticationToken("jacklord", "hawaii50", adminAuths);
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(admin);
|
||||
|
||||
MockHttpServletRequest request = createMockSwitchRequest();
|
||||
request.setRequestURI("/logout/impersonate");
|
||||
|
||||
// setup filter
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setUserDetailsService(new MockUserDetailsService());
|
||||
filter.setExitUserUrl("/logout/impersonate");
|
||||
filter.setSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/webapp/someOtherUrl"));
|
||||
|
||||
// run 'exit'
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
verify(chain, never()).doFilter(request, response);
|
||||
|
||||
// check current user, should be back to original user (dano)
|
||||
Authentication targetAuth = SecurityContextHolder.getContext().getAuthentication();
|
||||
assertNotNull(targetAuth);
|
||||
assertEquals("dano", targetAuth.getPrincipal());
|
||||
}
|
||||
|
||||
@Test(expected=AuthenticationException.class)
|
||||
public void exitUserWithNoCurrentUserFails() throws Exception {
|
||||
// no current user in secure context
|
||||
SecurityContextHolder.clearContext();
|
||||
|
||||
MockHttpServletRequest request = createMockSwitchRequest();
|
||||
request.setRequestURI("/logout/impersonate");
|
||||
|
||||
// setup filter
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setUserDetailsService(new MockUserDetailsService());
|
||||
filter.setExitUserUrl("/logout/impersonate");
|
||||
|
||||
// run 'exit', expect fail due to no current user
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
verify(chain, never()).doFilter(request, response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void redirectToTargetUrlIsCorrect() throws Exception {
|
||||
MockHttpServletRequest request = createMockSwitchRequest();
|
||||
request.setContextPath("/webapp");
|
||||
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "jacklord");
|
||||
request.setRequestURI("/webapp/login/impersonate");
|
||||
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setSwitchUserUrl("/login/impersonate");
|
||||
filter.setSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/someOtherUrl"));
|
||||
filter.setUserDetailsService(new MockUserDetailsService());
|
||||
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
verify(chain, never()).doFilter(request, response);
|
||||
|
||||
|
||||
assertEquals("/webapp/someOtherUrl", response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void redirectOmitsContextPathIfUseRelativeContextSet() throws Exception {
|
||||
// set current user
|
||||
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("dano", "hawaii50");
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
MockHttpServletRequest request = createMockSwitchRequest();
|
||||
request.setContextPath("/webapp");
|
||||
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "jacklord");
|
||||
request.setRequestURI("/webapp/login/impersonate");
|
||||
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setSwitchUserUrl("/login/impersonate");
|
||||
SimpleUrlAuthenticationSuccessHandler switchSuccessHandler =
|
||||
new SimpleUrlAuthenticationSuccessHandler("/someOtherUrl");
|
||||
DefaultRedirectStrategy contextRelativeRedirector = new DefaultRedirectStrategy();
|
||||
contextRelativeRedirector.setContextRelative(true);
|
||||
switchSuccessHandler.setRedirectStrategy(contextRelativeRedirector);
|
||||
filter.setSuccessHandler(switchSuccessHandler);
|
||||
filter.setUserDetailsService(new MockUserDetailsService());
|
||||
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
verify(chain, never()).doFilter(request, response);
|
||||
|
||||
|
||||
assertEquals("/someOtherUrl", response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSwitchRequestFromDanoToJackLord() throws Exception {
|
||||
// set current user
|
||||
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("dano", "hawaii50");
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
// http request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/webapp/login/impersonate");
|
||||
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "jacklord");
|
||||
|
||||
// http response
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
// setup filter
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setUserDetailsService(new MockUserDetailsService());
|
||||
filter.setSwitchUserUrl("/login/impersonate");
|
||||
filter.setSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/webapp/someOtherUrl"));
|
||||
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
|
||||
// test updates user token and context
|
||||
filter.doFilter(request, response, chain);
|
||||
verify(chain, never()).doFilter(request, response);
|
||||
|
||||
// check current user
|
||||
Authentication targetAuth = SecurityContextHolder.getContext().getAuthentication();
|
||||
assertNotNull(targetAuth);
|
||||
assertTrue(targetAuth.getPrincipal() instanceof UserDetails);
|
||||
assertEquals("jacklord", ((User) targetAuth.getPrincipal()).getUsername());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void modificationOfAuthoritiesWorks() {
|
||||
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken("dano", "hawaii50");
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY, "jacklord");
|
||||
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setUserDetailsService(new MockUserDetailsService());
|
||||
filter.setSwitchUserAuthorityChanger(new SwitchUserAuthorityChanger() {
|
||||
public Collection<GrantedAuthority> modifyGrantedAuthorities(UserDetails targetUser, Authentication currentAuthentication, Collection<? extends GrantedAuthority> authoritiesToBeGranted) {
|
||||
List <GrantedAuthority>auths = new ArrayList<GrantedAuthority>();
|
||||
auths.add(new SimpleGrantedAuthority("ROLE_NEW"));
|
||||
return auths;
|
||||
}
|
||||
});
|
||||
|
||||
Authentication result = filter.attemptSwitchUser(request);
|
||||
assertTrue(result != null);
|
||||
assertEquals(2, result.getAuthorities().size());
|
||||
assertTrue(AuthorityUtils.authorityListToSet(result.getAuthorities()).contains("ROLE_NEW"));
|
||||
}
|
||||
|
||||
// SEC-1763
|
||||
@Test
|
||||
public void nestedSwitchesAreNotAllowed() throws Exception {
|
||||
// original user
|
||||
UsernamePasswordAuthenticationToken source = new UsernamePasswordAuthenticationToken("orig", "hawaii50", ROLES_12);
|
||||
SecurityContextHolder.getContext().setAuthentication(source);
|
||||
SecurityContextHolder.getContext().setAuthentication(switchToUser("jacklord"));
|
||||
Authentication switched = switchToUser("dano");
|
||||
|
||||
SwitchUserGrantedAuthority switchedFrom = null;
|
||||
|
||||
for (GrantedAuthority ga: switched.getAuthorities()) {
|
||||
if (ga instanceof SwitchUserGrantedAuthority) {
|
||||
switchedFrom = (SwitchUserGrantedAuthority)ga;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
assertSame(source, switchedFrom.getSource());
|
||||
}
|
||||
|
||||
//~ Inner Classes ==================================================================================================
|
||||
|
||||
private class MockUserDetailsService implements UserDetailsService {
|
||||
private String password = "hawaii50";
|
||||
|
||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
// jacklord, dano (active)
|
||||
// mcgarrett (disabled)
|
||||
// wofat (account expired)
|
||||
// steve (credentials expired)
|
||||
if ("jacklord".equals(username) || "dano".equals(username)) {
|
||||
return new User(username, password, true, true, true, true, ROLES_12);
|
||||
} else if ("mcgarrett".equals(username)) {
|
||||
return new User(username, password, false, true, true, true, ROLES_12);
|
||||
} else if ("wofat".equals(username)) {
|
||||
return new User(username, password, true, false, true, true, ROLES_12);
|
||||
} else if ("steve".equals(username)) {
|
||||
return new User(username, password, true, true, false, true, ROLES_12);
|
||||
} else {
|
||||
throw new UsernameNotFoundException("Could not find: " + username);
|
||||
}
|
||||
}
|
||||
}
|
||||
private final static List<GrantedAuthority> ROLES_12 = AuthorityUtils
|
||||
.createAuthorityList("ROLE_ONE", "ROLE_TWO");
|
||||
|
||||
@Before
|
||||
public void authenticateCurrentUser() {
|
||||
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
|
||||
"dano", "hawaii50");
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
}
|
||||
|
||||
@After
|
||||
public void clearContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
private MockHttpServletRequest createMockSwitchRequest() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setScheme("http");
|
||||
request.setServerName("localhost");
|
||||
request.setRequestURI("/login/impersonate");
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
private Authentication switchToUser(String name) {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addParameter("myUsernameParameter", name);
|
||||
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setUsernameParameter("myUsernameParameter");
|
||||
filter.setUserDetailsService(new MockUserDetailsService());
|
||||
|
||||
return filter.attemptSwitchUser(request);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requiresExitUserMatchesCorrectly() {
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setExitUserUrl("/j_spring_security_my_exit_user");
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/j_spring_security_my_exit_user");
|
||||
|
||||
assertTrue(filter.requiresExitUser(request));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requiresSwitchMatchesCorrectly() {
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setSwitchUserUrl("/j_spring_security_my_switch_user");
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/j_spring_security_my_switch_user");
|
||||
|
||||
assertTrue(filter.requiresSwitchUser(request));
|
||||
}
|
||||
|
||||
@Test(expected = UsernameNotFoundException.class)
|
||||
public void attemptSwitchToUnknownUserFails() throws Exception {
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY,
|
||||
"user-that-doesnt-exist");
|
||||
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setUserDetailsService(new MockUserDetailsService());
|
||||
filter.attemptSwitchUser(request);
|
||||
}
|
||||
|
||||
@Test(expected = DisabledException.class)
|
||||
public void attemptSwitchToUserThatIsDisabledFails() throws Exception {
|
||||
switchToUser("mcgarrett");
|
||||
}
|
||||
|
||||
@Test(expected = AccountExpiredException.class)
|
||||
public void attemptSwitchToUserWithAccountExpiredFails() throws Exception {
|
||||
switchToUser("wofat");
|
||||
}
|
||||
|
||||
@Test(expected = CredentialsExpiredException.class)
|
||||
public void attemptSwitchToUserWithExpiredCredentialsFails() throws Exception {
|
||||
switchToUser("steve");
|
||||
}
|
||||
|
||||
@Test(expected = UsernameNotFoundException.class)
|
||||
public void switchUserWithNullUsernameThrowsException() throws Exception {
|
||||
switchToUser(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void attemptSwitchUserIsSuccessfulWithValidUser() throws Exception {
|
||||
assertNotNull(switchToUser("jacklord"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void switchToLockedAccountCausesRedirectToSwitchFailureUrl() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/login/impersonate");
|
||||
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY,
|
||||
"mcgarrett");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setTargetUrl("/target");
|
||||
filter.setUserDetailsService(new MockUserDetailsService());
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
// Check it with no url set (should get a text response)
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
filter.doFilter(request, response, chain);
|
||||
verify(chain, never()).doFilter(request, response);
|
||||
|
||||
assertNotNull(response.getErrorMessage());
|
||||
|
||||
// Now check for the redirect
|
||||
request.setContextPath("/mywebapp");
|
||||
request.setRequestURI("/mywebapp/login/impersonate");
|
||||
filter = new SwitchUserFilter();
|
||||
filter.setTargetUrl("/target");
|
||||
filter.setUserDetailsService(new MockUserDetailsService());
|
||||
filter.setSwitchFailureUrl("/switchfailed");
|
||||
filter.afterPropertiesSet();
|
||||
response = new MockHttpServletResponse();
|
||||
|
||||
chain = mock(FilterChain.class);
|
||||
filter.doFilter(request, response, chain);
|
||||
verify(chain, never()).doFilter(request, response);
|
||||
|
||||
assertEquals("/mywebapp/switchfailed", response.getRedirectedUrl());
|
||||
assertEquals("/switchfailed",
|
||||
FieldUtils.getFieldValue(filter, "switchFailureUrl"));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void configMissingUserDetailsServiceFails() throws Exception {
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setSwitchUserUrl("/login/impersonate");
|
||||
filter.setExitUserUrl("/logout/impersonate");
|
||||
filter.setTargetUrl("/main.jsp");
|
||||
filter.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testBadConfigMissingTargetUrl() throws Exception {
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setUserDetailsService(new MockUserDetailsService());
|
||||
filter.setSwitchUserUrl("/login/impersonate");
|
||||
filter.setExitUserUrl("/logout/impersonate");
|
||||
filter.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void defaultProcessesFilterUrlMatchesUrlWithPathParameter() {
|
||||
MockHttpServletRequest request = createMockSwitchRequest();
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setSwitchUserUrl("/login/impersonate");
|
||||
|
||||
request.setRequestURI("/webapp/login/impersonate;jsessionid=8JHDUD723J8");
|
||||
assertTrue(filter.requiresSwitchUser(request));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void exitUserJackLordToDanoSucceeds() throws Exception {
|
||||
// original user
|
||||
UsernamePasswordAuthenticationToken source = new UsernamePasswordAuthenticationToken(
|
||||
"dano", "hawaii50", ROLES_12);
|
||||
|
||||
// set current user (Admin)
|
||||
List<GrantedAuthority> adminAuths = new ArrayList<GrantedAuthority>();
|
||||
adminAuths.addAll(ROLES_12);
|
||||
adminAuths.add(new SwitchUserGrantedAuthority("PREVIOUS_ADMINISTRATOR", source));
|
||||
UsernamePasswordAuthenticationToken admin = new UsernamePasswordAuthenticationToken(
|
||||
"jacklord", "hawaii50", adminAuths);
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(admin);
|
||||
|
||||
MockHttpServletRequest request = createMockSwitchRequest();
|
||||
request.setRequestURI("/logout/impersonate");
|
||||
|
||||
// setup filter
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setUserDetailsService(new MockUserDetailsService());
|
||||
filter.setExitUserUrl("/logout/impersonate");
|
||||
filter.setSuccessHandler(new SimpleUrlAuthenticationSuccessHandler(
|
||||
"/webapp/someOtherUrl"));
|
||||
|
||||
// run 'exit'
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
verify(chain, never()).doFilter(request, response);
|
||||
|
||||
// check current user, should be back to original user (dano)
|
||||
Authentication targetAuth = SecurityContextHolder.getContext()
|
||||
.getAuthentication();
|
||||
assertNotNull(targetAuth);
|
||||
assertEquals("dano", targetAuth.getPrincipal());
|
||||
}
|
||||
|
||||
@Test(expected = AuthenticationException.class)
|
||||
public void exitUserWithNoCurrentUserFails() throws Exception {
|
||||
// no current user in secure context
|
||||
SecurityContextHolder.clearContext();
|
||||
|
||||
MockHttpServletRequest request = createMockSwitchRequest();
|
||||
request.setRequestURI("/logout/impersonate");
|
||||
|
||||
// setup filter
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setUserDetailsService(new MockUserDetailsService());
|
||||
filter.setExitUserUrl("/logout/impersonate");
|
||||
|
||||
// run 'exit', expect fail due to no current user
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
verify(chain, never()).doFilter(request, response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void redirectToTargetUrlIsCorrect() throws Exception {
|
||||
MockHttpServletRequest request = createMockSwitchRequest();
|
||||
request.setContextPath("/webapp");
|
||||
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY,
|
||||
"jacklord");
|
||||
request.setRequestURI("/webapp/login/impersonate");
|
||||
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setSwitchUserUrl("/login/impersonate");
|
||||
filter.setSuccessHandler(new SimpleUrlAuthenticationSuccessHandler(
|
||||
"/someOtherUrl"));
|
||||
filter.setUserDetailsService(new MockUserDetailsService());
|
||||
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
verify(chain, never()).doFilter(request, response);
|
||||
|
||||
assertEquals("/webapp/someOtherUrl", response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void redirectOmitsContextPathIfUseRelativeContextSet() throws Exception {
|
||||
// set current user
|
||||
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
|
||||
"dano", "hawaii50");
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
MockHttpServletRequest request = createMockSwitchRequest();
|
||||
request.setContextPath("/webapp");
|
||||
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY,
|
||||
"jacklord");
|
||||
request.setRequestURI("/webapp/login/impersonate");
|
||||
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setSwitchUserUrl("/login/impersonate");
|
||||
SimpleUrlAuthenticationSuccessHandler switchSuccessHandler = new SimpleUrlAuthenticationSuccessHandler(
|
||||
"/someOtherUrl");
|
||||
DefaultRedirectStrategy contextRelativeRedirector = new DefaultRedirectStrategy();
|
||||
contextRelativeRedirector.setContextRelative(true);
|
||||
switchSuccessHandler.setRedirectStrategy(contextRelativeRedirector);
|
||||
filter.setSuccessHandler(switchSuccessHandler);
|
||||
filter.setUserDetailsService(new MockUserDetailsService());
|
||||
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
verify(chain, never()).doFilter(request, response);
|
||||
|
||||
assertEquals("/someOtherUrl", response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSwitchRequestFromDanoToJackLord() throws Exception {
|
||||
// set current user
|
||||
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
|
||||
"dano", "hawaii50");
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
// http request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/webapp/login/impersonate");
|
||||
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY,
|
||||
"jacklord");
|
||||
|
||||
// http response
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
// setup filter
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setUserDetailsService(new MockUserDetailsService());
|
||||
filter.setSwitchUserUrl("/login/impersonate");
|
||||
filter.setSuccessHandler(new SimpleUrlAuthenticationSuccessHandler(
|
||||
"/webapp/someOtherUrl"));
|
||||
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
|
||||
// test updates user token and context
|
||||
filter.doFilter(request, response, chain);
|
||||
verify(chain, never()).doFilter(request, response);
|
||||
|
||||
// check current user
|
||||
Authentication targetAuth = SecurityContextHolder.getContext()
|
||||
.getAuthentication();
|
||||
assertNotNull(targetAuth);
|
||||
assertTrue(targetAuth.getPrincipal() instanceof UserDetails);
|
||||
assertEquals("jacklord", ((User) targetAuth.getPrincipal()).getUsername());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void modificationOfAuthoritiesWorks() {
|
||||
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
|
||||
"dano", "hawaii50");
|
||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addParameter(SwitchUserFilter.SPRING_SECURITY_SWITCH_USERNAME_KEY,
|
||||
"jacklord");
|
||||
|
||||
SwitchUserFilter filter = new SwitchUserFilter();
|
||||
filter.setUserDetailsService(new MockUserDetailsService());
|
||||
filter.setSwitchUserAuthorityChanger(new SwitchUserAuthorityChanger() {
|
||||
public Collection<GrantedAuthority> modifyGrantedAuthorities(
|
||||
UserDetails targetUser, Authentication currentAuthentication,
|
||||
Collection<? extends GrantedAuthority> authoritiesToBeGranted) {
|
||||
List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
|
||||
auths.add(new SimpleGrantedAuthority("ROLE_NEW"));
|
||||
return auths;
|
||||
}
|
||||
});
|
||||
|
||||
Authentication result = filter.attemptSwitchUser(request);
|
||||
assertTrue(result != null);
|
||||
assertEquals(2, result.getAuthorities().size());
|
||||
assertTrue(AuthorityUtils.authorityListToSet(result.getAuthorities()).contains(
|
||||
"ROLE_NEW"));
|
||||
}
|
||||
|
||||
// SEC-1763
|
||||
@Test
|
||||
public void nestedSwitchesAreNotAllowed() throws Exception {
|
||||
// original user
|
||||
UsernamePasswordAuthenticationToken source = new UsernamePasswordAuthenticationToken(
|
||||
"orig", "hawaii50", ROLES_12);
|
||||
SecurityContextHolder.getContext().setAuthentication(source);
|
||||
SecurityContextHolder.getContext().setAuthentication(switchToUser("jacklord"));
|
||||
Authentication switched = switchToUser("dano");
|
||||
|
||||
SwitchUserGrantedAuthority switchedFrom = null;
|
||||
|
||||
for (GrantedAuthority ga : switched.getAuthorities()) {
|
||||
if (ga instanceof SwitchUserGrantedAuthority) {
|
||||
switchedFrom = (SwitchUserGrantedAuthority) ga;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
assertSame(source, switchedFrom.getSource());
|
||||
}
|
||||
|
||||
// ~ Inner Classes
|
||||
// ==================================================================================================
|
||||
|
||||
private class MockUserDetailsService implements UserDetailsService {
|
||||
private String password = "hawaii50";
|
||||
|
||||
public UserDetails loadUserByUsername(String username)
|
||||
throws UsernameNotFoundException {
|
||||
// jacklord, dano (active)
|
||||
// mcgarrett (disabled)
|
||||
// wofat (account expired)
|
||||
// steve (credentials expired)
|
||||
if ("jacklord".equals(username) || "dano".equals(username)) {
|
||||
return new User(username, password, true, true, true, true, ROLES_12);
|
||||
}
|
||||
else if ("mcgarrett".equals(username)) {
|
||||
return new User(username, password, false, true, true, true, ROLES_12);
|
||||
}
|
||||
else if ("wofat".equals(username)) {
|
||||
return new User(username, password, true, false, true, true, ROLES_12);
|
||||
}
|
||||
else if ("steve".equals(username)) {
|
||||
return new User(username, password, true, true, false, true, ROLES_12);
|
||||
}
|
||||
else {
|
||||
throw new UsernameNotFoundException("Could not find: " + username);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,68 +22,70 @@ import org.springframework.security.web.authentication.www.BasicAuthenticationEn
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link BasicAuthenticationEntryPoint}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class BasicAuthenticationEntryPointTests extends TestCase {
|
||||
//~ Constructors ===================================================================================================
|
||||
// ~ Constructors
|
||||
// ===================================================================================================
|
||||
|
||||
public BasicAuthenticationEntryPointTests() {
|
||||
super();
|
||||
}
|
||||
public BasicAuthenticationEntryPointTests() {
|
||||
super();
|
||||
}
|
||||
|
||||
public BasicAuthenticationEntryPointTests(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
public BasicAuthenticationEntryPointTests(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
public static void main(String[] args) {
|
||||
junit.textui.TestRunner.run(BasicAuthenticationEntryPointTests.class);
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
junit.textui.TestRunner.run(BasicAuthenticationEntryPointTests.class);
|
||||
}
|
||||
|
||||
public final void setUp() throws Exception {
|
||||
super.setUp();
|
||||
}
|
||||
public final void setUp() throws Exception {
|
||||
super.setUp();
|
||||
}
|
||||
|
||||
public void testDetectsMissingRealmName() throws Exception {
|
||||
BasicAuthenticationEntryPoint ep = new BasicAuthenticationEntryPoint();
|
||||
public void testDetectsMissingRealmName() throws Exception {
|
||||
BasicAuthenticationEntryPoint ep = new BasicAuthenticationEntryPoint();
|
||||
|
||||
try {
|
||||
ep.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("realmName must be specified", expected.getMessage());
|
||||
}
|
||||
}
|
||||
try {
|
||||
ep.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertEquals("realmName must be specified", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testGettersSetters() {
|
||||
BasicAuthenticationEntryPoint ep = new BasicAuthenticationEntryPoint();
|
||||
ep.setRealmName("realm");
|
||||
assertEquals("realm", ep.getRealmName());
|
||||
}
|
||||
public void testGettersSetters() {
|
||||
BasicAuthenticationEntryPoint ep = new BasicAuthenticationEntryPoint();
|
||||
ep.setRealmName("realm");
|
||||
assertEquals("realm", ep.getRealmName());
|
||||
}
|
||||
|
||||
public void testNormalOperation() throws Exception {
|
||||
BasicAuthenticationEntryPoint ep = new BasicAuthenticationEntryPoint();
|
||||
public void testNormalOperation() throws Exception {
|
||||
BasicAuthenticationEntryPoint ep = new BasicAuthenticationEntryPoint();
|
||||
|
||||
ep.setRealmName("hello");
|
||||
ep.setRealmName("hello");
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/some_path");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/some_path");
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
//ep.afterPropertiesSet();
|
||||
// ep.afterPropertiesSet();
|
||||
|
||||
String msg = "These are the jokes kid";
|
||||
ep.commence(request, response, new DisabledException(msg));
|
||||
String msg = "These are the jokes kid";
|
||||
ep.commence(request, response, new DisabledException(msg));
|
||||
|
||||
assertEquals(401, response.getStatus());
|
||||
assertEquals(msg, response.getErrorMessage());
|
||||
assertEquals(401, response.getStatus());
|
||||
assertEquals(msg, response.getErrorMessage());
|
||||
|
||||
assertEquals("Basic realm=\"hello\"", response.getHeader("WWW-Authenticate"));
|
||||
}
|
||||
assertEquals("Basic realm=\"hello\"", response.getHeader("WWW-Authenticate"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,225 +41,246 @@ import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetails;
|
||||
import org.springframework.web.util.WebUtils;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link BasicAuthenticationFilter}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class BasicAuthenticationFilterTests {
|
||||
//~ Instance fields ================================================================================================
|
||||
// ~ Instance fields
|
||||
// ================================================================================================
|
||||
|
||||
private BasicAuthenticationFilter filter;
|
||||
private AuthenticationManager manager;
|
||||
private BasicAuthenticationFilter filter;
|
||||
private AuthenticationManager manager;
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
SecurityContextHolder.clearContext();
|
||||
UsernamePasswordAuthenticationToken rodRequest = new UsernamePasswordAuthenticationToken("rod", "koala");
|
||||
rodRequest.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
|
||||
Authentication rod =
|
||||
new UsernamePasswordAuthenticationToken("rod", "koala", AuthorityUtils.createAuthorityList("ROLE_1"));
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
SecurityContextHolder.clearContext();
|
||||
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(""));
|
||||
manager = mock(AuthenticationManager.class);
|
||||
when(manager.authenticate(rodRequest)).thenReturn(rod);
|
||||
when(manager.authenticate(not(eq(rodRequest)))).thenThrow(
|
||||
new BadCredentialsException(""));
|
||||
|
||||
filter = new BasicAuthenticationFilter(manager,new BasicAuthenticationEntryPoint());
|
||||
}
|
||||
filter = new BasicAuthenticationFilter(manager,
|
||||
new BasicAuthenticationEntryPoint());
|
||||
}
|
||||
|
||||
@After
|
||||
public void clearContext() throws Exception {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
@After
|
||||
public void clearContext() throws Exception {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFilterIgnoresRequestsContainingNoAuthorizationHeader() throws Exception {
|
||||
@Test
|
||||
public void testFilterIgnoresRequestsContainingNoAuthorizationHeader()
|
||||
throws Exception {
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setServletPath("/some_file.html");
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setServletPath("/some_file.html");
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
filter.doFilter(request, response, chain);
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
|
||||
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
|
||||
|
||||
// Test
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
|
||||
}
|
||||
// Test
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGettersSetters() {
|
||||
assertThat(filter.getAuthenticationManager()).isNotNull();
|
||||
assertThat(filter.getAuthenticationEntryPoint()).isNotNull();
|
||||
}
|
||||
@Test
|
||||
public void testGettersSetters() {
|
||||
assertThat(filter.getAuthenticationManager()).isNotNull();
|
||||
assertThat(filter.getAuthenticationEntryPoint()).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
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.setServletPath("/some_file.html");
|
||||
request.setSession(new MockHttpSession());
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
@Test
|
||||
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.setServletPath("/some_file.html");
|
||||
request.setSession(new MockHttpSession());
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
filter.doFilter(request, response, chain);
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
|
||||
assertThat(response.getStatus()).isEqualTo(401);
|
||||
}
|
||||
verify(chain, never()).doFilter(any(ServletRequest.class),
|
||||
any(ServletResponse.class));
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
|
||||
assertThat(response.getStatus()).isEqualTo(401);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invalidBase64IsIgnored() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addHeader("Authorization", "Basic NOT_VALID_BASE64");
|
||||
request.setServletPath("/some_file.html");
|
||||
request.setSession(new MockHttpSession());
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
@Test
|
||||
public void invalidBase64IsIgnored() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addHeader("Authorization", "Basic NOT_VALID_BASE64");
|
||||
request.setServletPath("/some_file.html");
|
||||
request.setSession(new MockHttpSession());
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
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));
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
|
||||
assertThat(response.getStatus()).isEqualTo(401);
|
||||
}
|
||||
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));
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
|
||||
assertThat(response.getStatus()).isEqualTo(401);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNormalOperation() throws Exception {
|
||||
String token = "rod:koala";
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
|
||||
request.setServletPath("/some_file.html");
|
||||
@Test
|
||||
public void testNormalOperation() throws Exception {
|
||||
String token = "rod:koala";
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addHeader("Authorization",
|
||||
"Basic " + new String(Base64.encodeBase64(token.getBytes())));
|
||||
request.setServletPath("/some_file.html");
|
||||
|
||||
// Test
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
filter.doFilter(request, new MockHttpServletResponse(), chain);
|
||||
// Test
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
filter.doFilter(request, new MockHttpServletResponse(), chain);
|
||||
|
||||
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
|
||||
}
|
||||
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication().getName())
|
||||
.isEqualTo("rod");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testOtherAuthorizationSchemeIsIgnored() throws Exception {
|
||||
@Test
|
||||
public void testOtherAuthorizationSchemeIsIgnored() throws Exception {
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addHeader("Authorization", "SOME_OTHER_AUTHENTICATION_SCHEME");
|
||||
request.setServletPath("/some_file.html");
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
filter.doFilter(request, new MockHttpServletResponse(), chain);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addHeader("Authorization", "SOME_OTHER_AUTHENTICATION_SCHEME");
|
||||
request.setServletPath("/some_file.html");
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
filter.doFilter(request, new MockHttpServletResponse(), chain);
|
||||
|
||||
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
|
||||
}
|
||||
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testStartupDetectsMissingAuthenticationEntryPoint() throws Exception {
|
||||
new BasicAuthenticationFilter(manager, null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testStartupDetectsMissingAuthenticationEntryPoint() throws Exception {
|
||||
new BasicAuthenticationFilter(manager, null);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void testStartupDetectsMissingAuthenticationManager() throws Exception {
|
||||
BasicAuthenticationFilter filter = new BasicAuthenticationFilter(null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void testStartupDetectsMissingAuthenticationManager() throws Exception {
|
||||
BasicAuthenticationFilter filter = new BasicAuthenticationFilter(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSuccessLoginThenFailureLoginResultsInSessionLosingToken() throws Exception {
|
||||
String token = "rod:koala";
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
|
||||
request.setServletPath("/some_file.html");
|
||||
final MockHttpServletResponse response1 = new MockHttpServletResponse();
|
||||
@Test
|
||||
public void testSuccessLoginThenFailureLoginResultsInSessionLosingToken()
|
||||
throws Exception {
|
||||
String token = "rod:koala";
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addHeader("Authorization",
|
||||
"Basic " + new String(Base64.encodeBase64(token.getBytes())));
|
||||
request.setServletPath("/some_file.html");
|
||||
final MockHttpServletResponse response1 = new MockHttpServletResponse();
|
||||
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
filter.doFilter(request, response1, chain);
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
filter.doFilter(request, response1, chain);
|
||||
|
||||
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
|
||||
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
|
||||
|
||||
// Test
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
|
||||
// Test
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication().getName())
|
||||
.isEqualTo("rod");
|
||||
|
||||
// NOW PERFORM FAILED AUTHENTICATION
|
||||
// NOW PERFORM FAILED AUTHENTICATION
|
||||
|
||||
token = "otherUser:WRONG_PASSWORD";
|
||||
request = new MockHttpServletRequest();
|
||||
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
|
||||
final MockHttpServletResponse response2 = new MockHttpServletResponse();
|
||||
token = "otherUser:WRONG_PASSWORD";
|
||||
request = new MockHttpServletRequest();
|
||||
request.addHeader("Authorization",
|
||||
"Basic " + new String(Base64.encodeBase64(token.getBytes())));
|
||||
final MockHttpServletResponse response2 = new MockHttpServletResponse();
|
||||
|
||||
chain = mock(FilterChain.class);
|
||||
filter.doFilter(request, response2, chain);
|
||||
chain = mock(FilterChain.class);
|
||||
filter.doFilter(request, response2, chain);
|
||||
|
||||
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
|
||||
request.setServletPath("/some_file.html");
|
||||
verify(chain, never()).doFilter(any(ServletRequest.class),
|
||||
any(ServletResponse.class));
|
||||
request.setServletPath("/some_file.html");
|
||||
|
||||
// Test - the filter chain will not be invoked, as we get a 401 forbidden response
|
||||
MockHttpServletResponse response = response2;
|
||||
// Test - the filter chain will not be invoked, as we get a 401 forbidden response
|
||||
MockHttpServletResponse response = response2;
|
||||
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
|
||||
assertThat(response.getStatus()).isEqualTo(401);
|
||||
}
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
|
||||
assertThat(response.getStatus()).isEqualTo(401);
|
||||
}
|
||||
|
||||
@Test
|
||||
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.setServletPath("/some_file.html");
|
||||
request.setSession(new MockHttpSession());
|
||||
@Test
|
||||
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.setServletPath("/some_file.html");
|
||||
request.setSession(new MockHttpSession());
|
||||
|
||||
filter = new BasicAuthenticationFilter(manager);
|
||||
assertThat(filter.isIgnoreFailure()).isTrue();
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
filter.doFilter(request, new MockHttpServletResponse(), chain);
|
||||
filter = new BasicAuthenticationFilter(manager);
|
||||
assertThat(filter.isIgnoreFailure()).isTrue();
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
filter.doFilter(request, new MockHttpServletResponse(), chain);
|
||||
|
||||
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
|
||||
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
|
||||
|
||||
// Test - the filter chain will be invoked, as we've set ignoreFailure = true
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
|
||||
}
|
||||
// Test - the filter chain will be invoked, as we've set ignoreFailure = true
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
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.setServletPath("/some_file.html");
|
||||
request.setSession(new MockHttpSession());
|
||||
assertThat(filter.isIgnoreFailure()).isFalse();
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
@Test
|
||||
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.setServletPath("/some_file.html");
|
||||
request.setSession(new MockHttpSession());
|
||||
assertThat(filter.isIgnoreFailure()).isFalse();
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
filter.doFilter(request, response, chain);
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
// Test - the filter chain will not be invoked, as we get a 401 forbidden response
|
||||
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
|
||||
assertThat(response.getStatus()).isEqualTo(401);
|
||||
}
|
||||
// Test - the filter chain will not be invoked, as we get a 401 forbidden response
|
||||
verify(chain, never()).doFilter(any(ServletRequest.class),
|
||||
any(ServletResponse.class));
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
|
||||
assertThat(response.getStatus()).isEqualTo(401);
|
||||
}
|
||||
|
||||
// SEC-2054
|
||||
@Test
|
||||
public void skippedOnErrorDispatch() throws Exception {
|
||||
// SEC-2054
|
||||
@Test
|
||||
public void skippedOnErrorDispatch() throws Exception {
|
||||
|
||||
String token = "bad:credentials";
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
|
||||
request.setServletPath("/some_file.html");
|
||||
request.setAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE, "/error");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
String token = "bad:credentials";
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.addHeader("Authorization",
|
||||
"Basic " + new String(Base64.encodeBase64(token.getBytes())));
|
||||
request.setServletPath("/some_file.html");
|
||||
request.setAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE, "/error");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
FilterChain chain = mock(FilterChain.class);
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
}
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,115 +21,132 @@ import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link org.springframework.security.util.StringSplitUtils}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class DigestAuthUtilsTests extends TestCase {
|
||||
//~ Constructors ===================================================================================================
|
||||
// ~ Constructors
|
||||
// ===================================================================================================
|
||||
|
||||
//~ Methods ========================================================================================================
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
public void testSplitEachArrayElementAndCreateMapNormalOperation() {
|
||||
// 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, "=", "\"");
|
||||
public void testSplitEachArrayElementAndCreateMapNormalOperation() {
|
||||
// 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, "=", "\"");
|
||||
|
||||
assertEquals("rod", headerMap.get("username"));
|
||||
assertEquals("Contacts Realm", headerMap.get("realm"));
|
||||
assertEquals("MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==", headerMap.get("nonce"));
|
||||
assertEquals("/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4",
|
||||
headerMap.get("uri"));
|
||||
assertEquals("38644211cf9ac3da63ab639807e2baff", headerMap.get("response"));
|
||||
assertEquals("auth", headerMap.get("qop"));
|
||||
assertEquals("00000004", headerMap.get("nc"));
|
||||
assertEquals("2b8d329a8571b99a", headerMap.get("cnonce"));
|
||||
assertEquals(8, headerMap.size());
|
||||
}
|
||||
assertEquals("rod", headerMap.get("username"));
|
||||
assertEquals("Contacts Realm", headerMap.get("realm"));
|
||||
assertEquals("MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==",
|
||||
headerMap.get("nonce"));
|
||||
assertEquals(
|
||||
"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4",
|
||||
headerMap.get("uri"));
|
||||
assertEquals("38644211cf9ac3da63ab639807e2baff", headerMap.get("response"));
|
||||
assertEquals("auth", headerMap.get("qop"));
|
||||
assertEquals("00000004", headerMap.get("nc"));
|
||||
assertEquals("2b8d329a8571b99a", headerMap.get("cnonce"));
|
||||
assertEquals(8, headerMap.size());
|
||||
}
|
||||
|
||||
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);
|
||||
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);
|
||||
|
||||
assertEquals("\"rod\"", headerMap.get("username"));
|
||||
assertEquals("\"Contacts Realm\"", headerMap.get("realm"));
|
||||
assertEquals("\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\"", headerMap.get("nonce"));
|
||||
assertEquals("\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\"",
|
||||
headerMap.get("uri"));
|
||||
assertEquals("\"38644211cf9ac3da63ab639807e2baff\"", headerMap.get("response"));
|
||||
assertEquals("auth", headerMap.get("qop"));
|
||||
assertEquals("00000004", headerMap.get("nc"));
|
||||
assertEquals("\"2b8d329a8571b99a\"", headerMap.get("cnonce"));
|
||||
assertEquals(8, headerMap.size());
|
||||
}
|
||||
assertEquals("\"rod\"", headerMap.get("username"));
|
||||
assertEquals("\"Contacts Realm\"", headerMap.get("realm"));
|
||||
assertEquals(
|
||||
"\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\"",
|
||||
headerMap.get("nonce"));
|
||||
assertEquals(
|
||||
"\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\"",
|
||||
headerMap.get("uri"));
|
||||
assertEquals("\"38644211cf9ac3da63ab639807e2baff\"", headerMap.get("response"));
|
||||
assertEquals("auth", headerMap.get("qop"));
|
||||
assertEquals("00000004", headerMap.get("nc"));
|
||||
assertEquals("\"2b8d329a8571b99a\"", headerMap.get("cnonce"));
|
||||
assertEquals(8, headerMap.size());
|
||||
}
|
||||
|
||||
public void testSplitEachArrayElementAndCreateMapReturnsNullIfArrayEmptyOrNull() {
|
||||
assertNull(DigestAuthUtils.splitEachArrayElementAndCreateMap(null, "=", "\""));
|
||||
assertNull(DigestAuthUtils.splitEachArrayElementAndCreateMap(new String[]{}, "=", "\""));
|
||||
}
|
||||
public void testSplitEachArrayElementAndCreateMapReturnsNullIfArrayEmptyOrNull() {
|
||||
assertNull(DigestAuthUtils.splitEachArrayElementAndCreateMap(null, "=", "\""));
|
||||
assertNull(DigestAuthUtils.splitEachArrayElementAndCreateMap(new String[] {},
|
||||
"=", "\""));
|
||||
}
|
||||
|
||||
public void testSplitNormalOperation() {
|
||||
String unsplit = "username=\"rod==\"";
|
||||
assertEquals("username", DigestAuthUtils.split(unsplit, "=")[0]);
|
||||
assertEquals("\"rod==\"", DigestAuthUtils.split(unsplit, "=")[1]); // should not remove quotes or extra equals
|
||||
}
|
||||
public void testSplitNormalOperation() {
|
||||
String unsplit = "username=\"rod==\"";
|
||||
assertEquals("username", DigestAuthUtils.split(unsplit, "=")[0]);
|
||||
assertEquals("\"rod==\"", DigestAuthUtils.split(unsplit, "=")[1]); // should not
|
||||
// remove
|
||||
// quotes or
|
||||
// extra
|
||||
// equals
|
||||
}
|
||||
|
||||
public void testSplitRejectsNullsAndIncorrectLengthStrings() {
|
||||
try {
|
||||
DigestAuthUtils.split(null, "="); // null
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
public void testSplitRejectsNullsAndIncorrectLengthStrings() {
|
||||
try {
|
||||
DigestAuthUtils.split(null, "="); // null
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
DigestAuthUtils.split("", "="); // empty string
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
try {
|
||||
DigestAuthUtils.split("", "="); // empty string
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
DigestAuthUtils.split("sdch=dfgf", null); // null
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
try {
|
||||
DigestAuthUtils.split("sdch=dfgf", null); // null
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
DigestAuthUtils.split("fvfv=dcdc", ""); // empty string
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
try {
|
||||
DigestAuthUtils.split("fvfv=dcdc", ""); // empty string
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
DigestAuthUtils.split("dfdc=dcdc", "BIGGER_THAN_ONE_CHARACTER");
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
try {
|
||||
DigestAuthUtils.split("dfdc=dcdc", "BIGGER_THAN_ONE_CHARACTER");
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void testSplitWorksWithDifferentDelimiters() {
|
||||
assertEquals(2, DigestAuthUtils.split("18/rod", "/").length);
|
||||
assertNull(DigestAuthUtils.split("18/rod", "!"));
|
||||
public void testSplitWorksWithDifferentDelimiters() {
|
||||
assertEquals(2, DigestAuthUtils.split("18/rod", "/").length);
|
||||
assertNull(DigestAuthUtils.split("18/rod", "!"));
|
||||
|
||||
// only guarantees to split at FIRST delimiter, not EACH delimiter
|
||||
assertEquals(2, DigestAuthUtils.split("18|rod|foo|bar", "|").length);
|
||||
}
|
||||
// only guarantees to split at FIRST delimiter, not EACH delimiter
|
||||
assertEquals(2, DigestAuthUtils.split("18|rod|foo|bar", "|").length);
|
||||
}
|
||||
|
||||
public void testAuthorizationHeaderWithCommasIsSplitCorrectly() {
|
||||
String header = "Digest username=\"hamilton,bob\", realm=\"bobs,ok,realm\", nonce=\"the,nonce\", "
|
||||
+ "uri=\"the,Uri\", response=\"the,response,Digest\", qop=theqop, nc=thenc, cnonce=\"the,cnonce\"";
|
||||
|
||||
public void testAuthorizationHeaderWithCommasIsSplitCorrectly() {
|
||||
String header = "Digest username=\"hamilton,bob\", realm=\"bobs,ok,realm\", nonce=\"the,nonce\", " +
|
||||
"uri=\"the,Uri\", response=\"the,response,Digest\", qop=theqop, nc=thenc, cnonce=\"the,cnonce\"";
|
||||
String[] parts = DigestAuthUtils.splitIgnoringQuotes(header, ',');
|
||||
|
||||
String[] parts = DigestAuthUtils.splitIgnoringQuotes(header, ',');
|
||||
|
||||
assertEquals(8, parts.length);
|
||||
}
|
||||
assertEquals(8, parts.length);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,122 +26,128 @@ import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.authentication.DisabledException;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link DigestAuthenticationEntryPoint}.
|
||||
*
|
||||
* @author Ben Alex
|
||||
*/
|
||||
public class DigestAuthenticationEntryPointTests extends TestCase {
|
||||
//~ Methods ========================================================================================================
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
private void checkNonceValid(String nonce) {
|
||||
// Check the nonce seems to be generated correctly
|
||||
// format of nonce is:
|
||||
// base64(expirationTime + ":" + md5Hex(expirationTime + ":" + key))
|
||||
assertTrue(Base64.isArrayByteBase64(nonce.getBytes()));
|
||||
private void checkNonceValid(String nonce) {
|
||||
// Check the nonce seems to be generated correctly
|
||||
// format of nonce is:
|
||||
// base64(expirationTime + ":" + md5Hex(expirationTime + ":" + key))
|
||||
assertTrue(Base64.isArrayByteBase64(nonce.getBytes()));
|
||||
|
||||
String decodedNonce = new String(Base64.decodeBase64(nonce.getBytes()));
|
||||
String[] nonceTokens = StringUtils.delimitedListToStringArray(decodedNonce, ":");
|
||||
assertEquals(2, nonceTokens.length);
|
||||
String decodedNonce = new String(Base64.decodeBase64(nonce.getBytes()));
|
||||
String[] nonceTokens = StringUtils.delimitedListToStringArray(decodedNonce, ":");
|
||||
assertEquals(2, nonceTokens.length);
|
||||
|
||||
String expectedNonceSignature = DigestUtils.md5Hex(nonceTokens[0] + ":" + "key");
|
||||
assertEquals(expectedNonceSignature, nonceTokens[1]);
|
||||
}
|
||||
String expectedNonceSignature = DigestUtils.md5Hex(nonceTokens[0] + ":" + "key");
|
||||
assertEquals(expectedNonceSignature, nonceTokens[1]);
|
||||
}
|
||||
|
||||
public void testDetectsMissingKey() throws Exception {
|
||||
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
|
||||
ep.setRealmName("realm");
|
||||
public void testDetectsMissingKey() throws Exception {
|
||||
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
|
||||
ep.setRealmName("realm");
|
||||
|
||||
try {
|
||||
ep.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("key must be specified", expected.getMessage());
|
||||
}
|
||||
}
|
||||
try {
|
||||
ep.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertEquals("key must be specified", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testDetectsMissingRealmName() throws Exception {
|
||||
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
|
||||
ep.setKey("dcdc");
|
||||
ep.setNonceValiditySeconds(12);
|
||||
public void testDetectsMissingRealmName() throws Exception {
|
||||
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
|
||||
ep.setKey("dcdc");
|
||||
ep.setNonceValiditySeconds(12);
|
||||
|
||||
try {
|
||||
ep.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("realmName must be specified", expected.getMessage());
|
||||
}
|
||||
}
|
||||
try {
|
||||
ep.afterPropertiesSet();
|
||||
fail("Should have thrown IllegalArgumentException");
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
assertEquals("realmName must be specified", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public void testGettersSetters() {
|
||||
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
|
||||
assertEquals(300, ep.getNonceValiditySeconds()); // 5 mins default
|
||||
ep.setRealmName("realm");
|
||||
assertEquals("realm", ep.getRealmName());
|
||||
ep.setKey("dcdc");
|
||||
assertEquals("dcdc", ep.getKey());
|
||||
ep.setNonceValiditySeconds(12);
|
||||
assertEquals(12, ep.getNonceValiditySeconds());
|
||||
}
|
||||
public void testGettersSetters() {
|
||||
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
|
||||
assertEquals(300, ep.getNonceValiditySeconds()); // 5 mins default
|
||||
ep.setRealmName("realm");
|
||||
assertEquals("realm", ep.getRealmName());
|
||||
ep.setKey("dcdc");
|
||||
assertEquals("dcdc", ep.getKey());
|
||||
ep.setNonceValiditySeconds(12);
|
||||
assertEquals(12, ep.getNonceValiditySeconds());
|
||||
}
|
||||
|
||||
public void testNormalOperation() throws Exception {
|
||||
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
|
||||
ep.setRealmName("hello");
|
||||
ep.setKey("key");
|
||||
public void testNormalOperation() throws Exception {
|
||||
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
|
||||
ep.setRealmName("hello");
|
||||
ep.setKey("key");
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/some_path");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/some_path");
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
ep.afterPropertiesSet();
|
||||
ep.afterPropertiesSet();
|
||||
|
||||
ep.commence(request, response, new DisabledException("foobar"));
|
||||
ep.commence(request, response, new DisabledException("foobar"));
|
||||
|
||||
// Check response is properly formed
|
||||
assertEquals(401, response.getStatus());
|
||||
assertEquals(true, response.getHeader("WWW-Authenticate").toString().startsWith("Digest "));
|
||||
// Check response is properly formed
|
||||
assertEquals(401, response.getStatus());
|
||||
assertEquals(true,
|
||||
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, "=", "\"");
|
||||
// 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, "=", "\"");
|
||||
|
||||
assertEquals("hello", headerMap.get("realm"));
|
||||
assertEquals("auth", headerMap.get("qop"));
|
||||
assertNull(headerMap.get("stale"));
|
||||
assertEquals("hello", headerMap.get("realm"));
|
||||
assertEquals("auth", headerMap.get("qop"));
|
||||
assertNull(headerMap.get("stale"));
|
||||
|
||||
checkNonceValid((String) headerMap.get("nonce"));
|
||||
}
|
||||
checkNonceValid((String) headerMap.get("nonce"));
|
||||
}
|
||||
|
||||
public void testOperationIfDueToStaleNonce() throws Exception {
|
||||
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
|
||||
ep.setRealmName("hello");
|
||||
ep.setKey("key");
|
||||
public void testOperationIfDueToStaleNonce() throws Exception {
|
||||
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
|
||||
ep.setRealmName("hello");
|
||||
ep.setKey("key");
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/some_path");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRequestURI("/some_path");
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
ep.afterPropertiesSet();
|
||||
ep.afterPropertiesSet();
|
||||
|
||||
ep.commence(request, response, new NonceExpiredException("expired nonce"));
|
||||
ep.commence(request, response, new NonceExpiredException("expired nonce"));
|
||||
|
||||
// Check response is properly formed
|
||||
assertEquals(401, response.getStatus());
|
||||
assertTrue(response.getHeader("WWW-Authenticate").toString().startsWith("Digest "));
|
||||
// Check response is properly formed
|
||||
assertEquals(401, response.getStatus());
|
||||
assertTrue(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, "=", "\"");
|
||||
// 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, "=", "\"");
|
||||
|
||||
assertEquals("hello", headerMap.get("realm"));
|
||||
assertEquals("auth", headerMap.get("qop"));
|
||||
assertEquals("true", headerMap.get("stale"));
|
||||
assertEquals("hello", headerMap.get("realm"));
|
||||
assertEquals("auth", headerMap.get("qop"));
|
||||
assertEquals("true", headerMap.get("stale"));
|
||||
|
||||
checkNonceValid((String) headerMap.get("nonce"));
|
||||
}
|
||||
checkNonceValid((String) headerMap.get("nonce"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,7 +41,6 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.security.core.userdetails.cache.NullUserCache;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link DigestAuthenticationFilter}.
|
||||
*
|
||||
@@ -49,374 +48,429 @@ import org.springframework.util.StringUtils;
|
||||
* @author Luke Taylor
|
||||
*/
|
||||
public class DigestAuthenticationFilterTests {
|
||||
//~ Static fields/initializers =====================================================================================
|
||||
|
||||
private static final String NC = "00000002";
|
||||
private static final String CNONCE = "c822c727a648aba7";
|
||||
private static final String REALM = "The Actual, Correct Realm Name";
|
||||
private static final String KEY = "springsecurity";
|
||||
private static final String QOP = "auth";
|
||||
private static final String USERNAME = "rod,ok";
|
||||
private static final String PASSWORD = "koala";
|
||||
private static final String REQUEST_URI = "/some_file.html";
|
||||
|
||||
/**
|
||||
* A standard valid nonce with a validity period of 60 seconds
|
||||
*/
|
||||
private static final String NONCE = generateNonce(60);
|
||||
|
||||
//~ Instance fields ================================================================================================
|
||||
|
||||
// private ApplicationContext ctx;
|
||||
private DigestAuthenticationFilter filter;
|
||||
private MockHttpServletRequest request;
|
||||
|
||||
|
||||
//~ 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 MockHttpServletResponse executeFilterInContainerSimulator(Filter filter, final ServletRequest request,
|
||||
final boolean expectChainToProceed) throws ServletException, IOException {
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
final FilterChain chain = mock(FilterChain.class);
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
verify(chain, times(expectChainToProceed ? 1 : 0)).doFilter(request, response);
|
||||
return response;
|
||||
}
|
||||
|
||||
private static String generateNonce(int validitySeconds) {
|
||||
long expiryTime = System.currentTimeMillis() + (validitySeconds * 1000);
|
||||
String signatureValue = DigestUtils.md5Hex(expiryTime + ":" + KEY);
|
||||
String nonceValue = expiryTime + ":" + signatureValue;
|
||||
|
||||
return new String(Base64.encodeBase64(nonceValue.getBytes()));
|
||||
}
|
||||
|
||||
@After
|
||||
public void clearContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
SecurityContextHolder.clearContext();
|
||||
|
||||
// Create User Details Service
|
||||
UserDetailsService uds = new UserDetailsService() {
|
||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
return new User("rod,ok", "koala", AuthorityUtils.createAuthorityList("ROLE_ONE","ROLE_TWO"));
|
||||
}
|
||||
};
|
||||
|
||||
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
|
||||
ep.setRealmName(REALM);
|
||||
ep.setKey(KEY);
|
||||
|
||||
filter = new DigestAuthenticationFilter();
|
||||
filter.setUserDetailsService(uds);
|
||||
filter.setAuthenticationEntryPoint(ep);
|
||||
|
||||
request = new MockHttpServletRequest("GET", REQUEST_URI);
|
||||
request.setServletPath(REQUEST_URI);
|
||||
}
|
||||
|
||||
@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);
|
||||
|
||||
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);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(401, response.getStatus());
|
||||
|
||||
String header = response.getHeader("WWW-Authenticate").toString().substring(7);
|
||||
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header);
|
||||
Map<String,String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
|
||||
assertEquals("true", headerMap.get("stale"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFilterIgnoresRequestsContainingNoAuthorizationHeader()
|
||||
throws Exception {
|
||||
executeFilterInContainerSimulator(filter, request, true);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGettersSetters() {
|
||||
DigestAuthenticationFilter filter = new DigestAuthenticationFilter();
|
||||
filter.setUserDetailsService(mock(UserDetailsService.class));
|
||||
assertTrue(filter.getUserDetailsService() != null);
|
||||
|
||||
filter.setAuthenticationEntryPoint(new DigestAuthenticationEntryPoint());
|
||||
assertTrue(filter.getAuthenticationEntryPoint() != null);
|
||||
|
||||
filter.setUserCache(null);
|
||||
assertNull(filter.getUserCache());
|
||||
filter.setUserCache(new NullUserCache());
|
||||
assertNotNull(filter.getUserCache());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInvalidDigestAuthorizationTokenGeneratesError()
|
||||
throws Exception {
|
||||
String token = "NOT_A_VALID_TOKEN_AS_MISSING_COLON";
|
||||
|
||||
request.addHeader("Authorization", "Digest " + new String(Base64.encodeBase64(token.getBytes())));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
|
||||
|
||||
assertEquals(401, response.getStatus());
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMalformedHeaderReturnsForbidden() throws Exception {
|
||||
request.addHeader("Authorization", "Digest scsdcsdc");
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNonBase64EncodedNonceReturnsForbidden() throws Exception {
|
||||
String nonce = "NOT_BASE_64_ENCODED";
|
||||
|
||||
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET",
|
||||
REQUEST_URI, QOP, nonce, NC, CNONCE);
|
||||
|
||||
request.addHeader("Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
|
||||
@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);
|
||||
|
||||
request.addHeader("Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
|
||||
@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);
|
||||
|
||||
request.addHeader("Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
|
||||
@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);
|
||||
|
||||
request.addHeader("Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
|
||||
@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);
|
||||
|
||||
request.addHeader("Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
executeFilterInContainerSimulator(filter, request, true);
|
||||
|
||||
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(USERNAME,
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNormalOperationWhenPasswordNotAlreadyEncoded() 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));
|
||||
|
||||
executeFilterInContainerSimulator(filter, request, true);
|
||||
|
||||
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(USERNAME,
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
|
||||
assertFalse(SecurityContextHolder.getContext().getAuthentication().isAuthenticated());
|
||||
}
|
||||
|
||||
@Test
|
||||
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));
|
||||
|
||||
filter.setCreateAuthenticatedToken(true);
|
||||
executeFilterInContainerSimulator(filter, request, true);
|
||||
|
||||
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(USERNAME,
|
||||
((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
|
||||
assertTrue(SecurityContextHolder.getContext().getAuthentication().isAuthenticated());
|
||||
assertEquals(AuthorityUtils.createAuthorityList("ROLE_ONE","ROLE_TWO"),
|
||||
SecurityContextHolder.getContext().getAuthentication().getAuthorities());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void otherAuthorizationSchemeIsIgnored()
|
||||
throws Exception {
|
||||
request.addHeader("Authorization", "SOME_OTHER_AUTHENTICATION_SCHEME");
|
||||
|
||||
executeFilterInContainerSimulator(filter, request, true);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void startupDetectsMissingAuthenticationEntryPoint() throws Exception {
|
||||
DigestAuthenticationFilter filter = new DigestAuthenticationFilter();
|
||||
filter.setUserDetailsService(mock(UserDetailsService.class));
|
||||
filter.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void startupDetectsMissingUserDetailsService() throws Exception {
|
||||
DigestAuthenticationFilter filter = new DigestAuthenticationFilter();
|
||||
filter.setAuthenticationEntryPoint(new DigestAuthenticationEntryPoint());
|
||||
filter.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test
|
||||
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));
|
||||
|
||||
executeFilterInContainerSimulator(filter, request, true);
|
||||
|
||||
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
|
||||
// Now retry, giving an invalid nonce
|
||||
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));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
|
||||
|
||||
// Check we lost our previous authentication
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void wrongCnonceBasedOnDigestReturnsForbidden() throws Exception {
|
||||
String cnonce = "NOT_SAME_AS_USED_FOR_DIGEST_COMPUTATION";
|
||||
|
||||
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET",
|
||||
REQUEST_URI, QOP, NONCE, NC, "DIFFERENT_CNONCE");
|
||||
|
||||
request.addHeader("Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, cnonce));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
|
||||
@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);
|
||||
|
||||
request.addHeader("Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
|
||||
@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);
|
||||
|
||||
request.addHeader("Authorization",
|
||||
createAuthorizationHeader(USERNAME, realm, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void wrongUsernameReturnsForbidden() throws Exception {
|
||||
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));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
// ~ Static fields/initializers
|
||||
// =====================================================================================
|
||||
|
||||
private static final String NC = "00000002";
|
||||
private static final String CNONCE = "c822c727a648aba7";
|
||||
private static final String REALM = "The Actual, Correct Realm Name";
|
||||
private static final String KEY = "springsecurity";
|
||||
private static final String QOP = "auth";
|
||||
private static final String USERNAME = "rod,ok";
|
||||
private static final String PASSWORD = "koala";
|
||||
private static final String REQUEST_URI = "/some_file.html";
|
||||
|
||||
/**
|
||||
* A standard valid nonce with a validity period of 60 seconds
|
||||
*/
|
||||
private static final String NONCE = generateNonce(60);
|
||||
|
||||
// ~ Instance fields
|
||||
// ================================================================================================
|
||||
|
||||
// private ApplicationContext ctx;
|
||||
private DigestAuthenticationFilter filter;
|
||||
private MockHttpServletRequest request;
|
||||
|
||||
// ~ 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 MockHttpServletResponse executeFilterInContainerSimulator(Filter filter,
|
||||
final ServletRequest request, final boolean expectChainToProceed)
|
||||
throws ServletException, IOException {
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
final FilterChain chain = mock(FilterChain.class);
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
verify(chain, times(expectChainToProceed ? 1 : 0)).doFilter(request, response);
|
||||
return response;
|
||||
}
|
||||
|
||||
private static String generateNonce(int validitySeconds) {
|
||||
long expiryTime = System.currentTimeMillis() + (validitySeconds * 1000);
|
||||
String signatureValue = DigestUtils.md5Hex(expiryTime + ":" + KEY);
|
||||
String nonceValue = expiryTime + ":" + signatureValue;
|
||||
|
||||
return new String(Base64.encodeBase64(nonceValue.getBytes()));
|
||||
}
|
||||
|
||||
@After
|
||||
public void clearContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
SecurityContextHolder.clearContext();
|
||||
|
||||
// Create User Details Service
|
||||
UserDetailsService uds = new UserDetailsService() {
|
||||
public UserDetails loadUserByUsername(String username)
|
||||
throws UsernameNotFoundException {
|
||||
return new User("rod,ok", "koala", AuthorityUtils.createAuthorityList(
|
||||
"ROLE_ONE", "ROLE_TWO"));
|
||||
}
|
||||
};
|
||||
|
||||
DigestAuthenticationEntryPoint ep = new DigestAuthenticationEntryPoint();
|
||||
ep.setRealmName(REALM);
|
||||
ep.setKey(KEY);
|
||||
|
||||
filter = new DigestAuthenticationFilter();
|
||||
filter.setUserDetailsService(uds);
|
||||
filter.setAuthenticationEntryPoint(ep);
|
||||
|
||||
request = new MockHttpServletRequest("GET", REQUEST_URI);
|
||||
request.setServletPath(REQUEST_URI);
|
||||
}
|
||||
|
||||
@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);
|
||||
|
||||
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);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(401, response.getStatus());
|
||||
|
||||
String header = response.getHeader("WWW-Authenticate").toString().substring(7);
|
||||
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header);
|
||||
Map<String, String> headerMap = DigestAuthUtils
|
||||
.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
|
||||
assertEquals("true", headerMap.get("stale"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFilterIgnoresRequestsContainingNoAuthorizationHeader()
|
||||
throws Exception {
|
||||
executeFilterInContainerSimulator(filter, request, true);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGettersSetters() {
|
||||
DigestAuthenticationFilter filter = new DigestAuthenticationFilter();
|
||||
filter.setUserDetailsService(mock(UserDetailsService.class));
|
||||
assertTrue(filter.getUserDetailsService() != null);
|
||||
|
||||
filter.setAuthenticationEntryPoint(new DigestAuthenticationEntryPoint());
|
||||
assertTrue(filter.getAuthenticationEntryPoint() != null);
|
||||
|
||||
filter.setUserCache(null);
|
||||
assertNull(filter.getUserCache());
|
||||
filter.setUserCache(new NullUserCache());
|
||||
assertNotNull(filter.getUserCache());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInvalidDigestAuthorizationTokenGeneratesError() throws Exception {
|
||||
String token = "NOT_A_VALID_TOKEN_AS_MISSING_COLON";
|
||||
|
||||
request.addHeader("Authorization",
|
||||
"Digest " + new String(Base64.encodeBase64(token.getBytes())));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
|
||||
request, false);
|
||||
|
||||
assertEquals(401, response.getStatus());
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMalformedHeaderReturnsForbidden() throws Exception {
|
||||
request.addHeader("Authorization", "Digest scsdcsdc");
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
|
||||
request, false);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNonBase64EncodedNonceReturnsForbidden() throws Exception {
|
||||
String nonce = "NOT_BASE_64_ENCODED";
|
||||
|
||||
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM,
|
||||
PASSWORD, "GET", REQUEST_URI, QOP, nonce, NC, CNONCE);
|
||||
|
||||
request.addHeader(
|
||||
"Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI,
|
||||
responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
|
||||
request, false);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
|
||||
@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);
|
||||
|
||||
request.addHeader(
|
||||
"Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI,
|
||||
responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
|
||||
request, false);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
|
||||
@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);
|
||||
|
||||
request.addHeader(
|
||||
"Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI,
|
||||
responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
|
||||
request, false);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
|
||||
@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);
|
||||
|
||||
request.addHeader(
|
||||
"Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI,
|
||||
responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
|
||||
request, false);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
|
||||
@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);
|
||||
|
||||
request.addHeader(
|
||||
"Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI,
|
||||
responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
executeFilterInContainerSimulator(filter, request, true);
|
||||
|
||||
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(USERNAME, ((UserDetails) SecurityContextHolder.getContext()
|
||||
.getAuthentication().getPrincipal()).getUsername());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNormalOperationWhenPasswordNotAlreadyEncoded() 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));
|
||||
|
||||
executeFilterInContainerSimulator(filter, request, true);
|
||||
|
||||
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(USERNAME, ((UserDetails) SecurityContextHolder.getContext()
|
||||
.getAuthentication().getPrincipal()).getUsername());
|
||||
assertFalse(SecurityContextHolder.getContext().getAuthentication()
|
||||
.isAuthenticated());
|
||||
}
|
||||
|
||||
@Test
|
||||
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));
|
||||
|
||||
filter.setCreateAuthenticatedToken(true);
|
||||
executeFilterInContainerSimulator(filter, request, true);
|
||||
|
||||
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(USERNAME, ((UserDetails) SecurityContextHolder.getContext()
|
||||
.getAuthentication().getPrincipal()).getUsername());
|
||||
assertTrue(SecurityContextHolder.getContext().getAuthentication()
|
||||
.isAuthenticated());
|
||||
assertEquals(AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"),
|
||||
SecurityContextHolder.getContext().getAuthentication().getAuthorities());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void otherAuthorizationSchemeIsIgnored() throws Exception {
|
||||
request.addHeader("Authorization", "SOME_OTHER_AUTHENTICATION_SCHEME");
|
||||
|
||||
executeFilterInContainerSimulator(filter, request, true);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void startupDetectsMissingAuthenticationEntryPoint() throws Exception {
|
||||
DigestAuthenticationFilter filter = new DigestAuthenticationFilter();
|
||||
filter.setUserDetailsService(mock(UserDetailsService.class));
|
||||
filter.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void startupDetectsMissingUserDetailsService() throws Exception {
|
||||
DigestAuthenticationFilter filter = new DigestAuthenticationFilter();
|
||||
filter.setAuthenticationEntryPoint(new DigestAuthenticationEntryPoint());
|
||||
filter.afterPropertiesSet();
|
||||
}
|
||||
|
||||
@Test
|
||||
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));
|
||||
|
||||
executeFilterInContainerSimulator(filter, request, true);
|
||||
|
||||
assertNotNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
|
||||
// Now retry, giving an invalid nonce
|
||||
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));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
|
||||
request, false);
|
||||
|
||||
// Check we lost our previous authentication
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void wrongCnonceBasedOnDigestReturnsForbidden() throws Exception {
|
||||
String cnonce = "NOT_SAME_AS_USED_FOR_DIGEST_COMPUTATION";
|
||||
|
||||
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM,
|
||||
PASSWORD, "GET", REQUEST_URI, QOP, NONCE, NC, "DIFFERENT_CNONCE");
|
||||
|
||||
request.addHeader(
|
||||
"Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI,
|
||||
responseDigest, QOP, NC, cnonce));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
|
||||
request, false);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
|
||||
@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);
|
||||
|
||||
request.addHeader(
|
||||
"Authorization",
|
||||
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI,
|
||||
responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
|
||||
request, false);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
|
||||
@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);
|
||||
|
||||
request.addHeader(
|
||||
"Authorization",
|
||||
createAuthorizationHeader(USERNAME, realm, NONCE, REQUEST_URI,
|
||||
responseDigest, QOP, NC, CNONCE));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
|
||||
request, false);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void wrongUsernameReturnsForbidden() throws Exception {
|
||||
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));
|
||||
|
||||
MockHttpServletResponse response = executeFilterInContainerSimulator(filter,
|
||||
request, false);
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
assertEquals(401, response.getStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@
|
||||
*/
|
||||
package org.springframework.security.web.bind.support;
|
||||
|
||||
|
||||
import static org.fest.assertions.Assertions.assertThat;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
@@ -42,162 +41,199 @@ import org.springframework.util.ReflectionUtils;
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
public class AuthenticationPrincipalArgumentResolverTests {
|
||||
private Object expectedPrincipal;
|
||||
private AuthenticationPrincipalArgumentResolver resolver;
|
||||
private Object expectedPrincipal;
|
||||
private AuthenticationPrincipalArgumentResolver resolver;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
resolver = new AuthenticationPrincipalArgumentResolver();
|
||||
}
|
||||
@Before
|
||||
public void setup() {
|
||||
resolver = new AuthenticationPrincipalArgumentResolver();
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
@After
|
||||
public void cleanup() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void supportsParameterNoAnnotation() throws Exception {
|
||||
assertThat(resolver.supportsParameter(showUserNoAnnotation())).isFalse();
|
||||
}
|
||||
@Test
|
||||
public void supportsParameterNoAnnotation() throws Exception {
|
||||
assertThat(resolver.supportsParameter(showUserNoAnnotation())).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void supportsParameterAnnotation() throws Exception {
|
||||
assertThat(resolver.supportsParameter(showUserAnnotationObject())).isTrue();
|
||||
}
|
||||
@Test
|
||||
public void supportsParameterAnnotation() throws Exception {
|
||||
assertThat(resolver.supportsParameter(showUserAnnotationObject())).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void supportsParameterCustomAnnotation() throws Exception {
|
||||
assertThat(resolver.supportsParameter(showUserCustomAnnotation())).isTrue();
|
||||
}
|
||||
@Test
|
||||
public void supportsParameterCustomAnnotation() throws Exception {
|
||||
assertThat(resolver.supportsParameter(showUserCustomAnnotation())).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resolveArgumentNullAuthentication() throws Exception {
|
||||
assertThat(resolver.resolveArgument(showUserAnnotationString(), null, null, null)).isNull();
|
||||
}
|
||||
@Test
|
||||
public void resolveArgumentNullAuthentication() throws Exception {
|
||||
assertThat(resolver.resolveArgument(showUserAnnotationString(), null, null, null))
|
||||
.isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resolveArgumentNullPrincipal() throws Exception {
|
||||
setAuthenticationPrincipal(null);
|
||||
assertThat(resolver.resolveArgument(showUserAnnotationString(), null, null, null)).isNull();
|
||||
}
|
||||
@Test
|
||||
public void resolveArgumentNullPrincipal() throws Exception {
|
||||
setAuthenticationPrincipal(null);
|
||||
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);
|
||||
}
|
||||
@Test
|
||||
public void resolveArgumentString() throws Exception {
|
||||
setAuthenticationPrincipal("john");
|
||||
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);
|
||||
}
|
||||
@Test
|
||||
public void resolveArgumentPrincipalStringOnObject() throws Exception {
|
||||
setAuthenticationPrincipal("john");
|
||||
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);
|
||||
}
|
||||
@Test
|
||||
public void resolveArgumentUserDetails() throws Exception {
|
||||
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);
|
||||
}
|
||||
@Test
|
||||
public void resolveArgumentCustomUserPrincipal() throws Exception {
|
||||
setAuthenticationPrincipal(new CustomUserPrincipal());
|
||||
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);
|
||||
}
|
||||
@Test
|
||||
public void resolveArgumentCustomAnnotation() throws Exception {
|
||||
setAuthenticationPrincipal(new CustomUserPrincipal());
|
||||
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();
|
||||
}
|
||||
@Test
|
||||
public void resolveArgumentNullOnInvalidType() throws Exception {
|
||||
setAuthenticationPrincipal(new CustomUserPrincipal());
|
||||
assertThat(resolver.resolveArgument(showUserAnnotationString(), null, null, null))
|
||||
.isNull();
|
||||
}
|
||||
|
||||
@Test(expected = ClassCastException.class)
|
||||
public void resolveArgumentErrorOnInvalidType() throws Exception {
|
||||
setAuthenticationPrincipal(new CustomUserPrincipal());
|
||||
resolver.resolveArgument(showUserAnnotationErrorOnInvalidType(), null, null, null);
|
||||
}
|
||||
@Test(expected = ClassCastException.class)
|
||||
public void resolveArgumentErrorOnInvalidType() throws Exception {
|
||||
setAuthenticationPrincipal(new CustomUserPrincipal());
|
||||
resolver.resolveArgument(showUserAnnotationErrorOnInvalidType(), null, null, null);
|
||||
}
|
||||
|
||||
@Test(expected = ClassCastException.class)
|
||||
public void resolveArgumentCustomserErrorOnInvalidType() throws Exception {
|
||||
setAuthenticationPrincipal(new CustomUserPrincipal());
|
||||
resolver.resolveArgument(showUserAnnotationCurrentUserErrorOnInvalidType(), null,
|
||||
null, null);
|
||||
}
|
||||
|
||||
@Test(expected = ClassCastException.class)
|
||||
public void resolveArgumentCustomserErrorOnInvalidType() throws Exception {
|
||||
setAuthenticationPrincipal(new CustomUserPrincipal());
|
||||
resolver.resolveArgument(showUserAnnotationCurrentUserErrorOnInvalidType(), null, null, null);
|
||||
}
|
||||
@Test
|
||||
public void resolveArgumentObject() throws Exception {
|
||||
setAuthenticationPrincipal(new Object());
|
||||
assertThat(resolver.resolveArgument(showUserAnnotationObject(), null, null, null))
|
||||
.isEqualTo(expectedPrincipal);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resolveArgumentObject() throws Exception {
|
||||
setAuthenticationPrincipal(new Object());
|
||||
assertThat(resolver.resolveArgument(showUserAnnotationObject(), null, null, null)).isEqualTo(expectedPrincipal);
|
||||
}
|
||||
private MethodParameter showUserNoAnnotation() {
|
||||
return getMethodParameter("showUserNoAnnotation", String.class);
|
||||
}
|
||||
|
||||
private MethodParameter showUserNoAnnotation() {
|
||||
return getMethodParameter("showUserNoAnnotation", String.class);
|
||||
}
|
||||
private MethodParameter showUserAnnotationString() {
|
||||
return getMethodParameter("showUserAnnotation", String.class);
|
||||
}
|
||||
|
||||
private MethodParameter showUserAnnotationString() {
|
||||
return getMethodParameter("showUserAnnotation", String.class);
|
||||
}
|
||||
private MethodParameter showUserAnnotationErrorOnInvalidType() {
|
||||
return getMethodParameter("showUserAnnotationErrorOnInvalidType", String.class);
|
||||
}
|
||||
|
||||
private MethodParameter showUserAnnotationErrorOnInvalidType() {
|
||||
return getMethodParameter("showUserAnnotationErrorOnInvalidType", String.class);
|
||||
}
|
||||
private MethodParameter showUserAnnotationCurrentUserErrorOnInvalidType() {
|
||||
return getMethodParameter("showUserAnnotationCurrentUserErrorOnInvalidType",
|
||||
String.class);
|
||||
}
|
||||
|
||||
private MethodParameter showUserAnnotationCurrentUserErrorOnInvalidType() {
|
||||
return getMethodParameter("showUserAnnotationCurrentUserErrorOnInvalidType", String.class);
|
||||
}
|
||||
private MethodParameter showUserAnnotationUserDetails() {
|
||||
return getMethodParameter("showUserAnnotation", UserDetails.class);
|
||||
}
|
||||
|
||||
private MethodParameter showUserAnnotationUserDetails() {
|
||||
return getMethodParameter("showUserAnnotation", UserDetails.class);
|
||||
}
|
||||
private MethodParameter showUserAnnotationCustomUserPrincipal() {
|
||||
return getMethodParameter("showUserAnnotation", CustomUserPrincipal.class);
|
||||
}
|
||||
|
||||
private MethodParameter showUserAnnotationCustomUserPrincipal() {
|
||||
return getMethodParameter("showUserAnnotation", CustomUserPrincipal.class);
|
||||
}
|
||||
private MethodParameter showUserCustomAnnotation() {
|
||||
return getMethodParameter("showUserCustomAnnotation", CustomUserPrincipal.class);
|
||||
}
|
||||
|
||||
private MethodParameter showUserCustomAnnotation() {
|
||||
return getMethodParameter("showUserCustomAnnotation", CustomUserPrincipal.class);
|
||||
}
|
||||
private MethodParameter showUserAnnotationObject() {
|
||||
return getMethodParameter("showUserAnnotation", Object.class);
|
||||
}
|
||||
|
||||
private MethodParameter showUserAnnotationObject() {
|
||||
return getMethodParameter("showUserAnnotation", Object.class);
|
||||
}
|
||||
private MethodParameter getMethodParameter(String methodName, Class<?>... paramTypes) {
|
||||
Method method = ReflectionUtils.findMethod(TestController.class, methodName,
|
||||
paramTypes);
|
||||
return new MethodParameter(method, 0);
|
||||
}
|
||||
|
||||
private MethodParameter getMethodParameter(String methodName, Class<?>... paramTypes) {
|
||||
Method method = ReflectionUtils.findMethod(TestController.class, methodName,paramTypes);
|
||||
return new MethodParameter(method,0);
|
||||
}
|
||||
@Target({ ElementType.PARAMETER })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@AuthenticationPrincipal
|
||||
static @interface CurrentUser {
|
||||
}
|
||||
|
||||
@Target({ ElementType.PARAMETER})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@AuthenticationPrincipal
|
||||
static @interface CurrentUser { }
|
||||
@Target({ ElementType.PARAMETER })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@AuthenticationPrincipal(errorOnInvalidType = true)
|
||||
static @interface CurrentUserErrorOnInvalidType {
|
||||
}
|
||||
|
||||
@Target({ ElementType.PARAMETER})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@AuthenticationPrincipal(errorOnInvalidType = true)
|
||||
static @interface CurrentUserErrorOnInvalidType { }
|
||||
public static class TestController {
|
||||
public void showUserNoAnnotation(String user) {
|
||||
}
|
||||
|
||||
public static class TestController {
|
||||
public void showUserNoAnnotation(String user) {}
|
||||
public void showUserAnnotation(@AuthenticationPrincipal String user) {}
|
||||
public void showUserAnnotationErrorOnInvalidType(@AuthenticationPrincipal(errorOnInvalidType=true) String user) {}
|
||||
public void showUserAnnotationCurrentUserErrorOnInvalidType(@CurrentUserErrorOnInvalidType String user) {}
|
||||
public void showUserAnnotation(@AuthenticationPrincipal UserDetails user) {}
|
||||
public void showUserAnnotation(@AuthenticationPrincipal CustomUserPrincipal user) {}
|
||||
public void showUserCustomAnnotation(@CurrentUser CustomUserPrincipal user) {}
|
||||
public void showUserAnnotation(@AuthenticationPrincipal Object user) {}
|
||||
}
|
||||
public void showUserAnnotation(@AuthenticationPrincipal String user) {
|
||||
}
|
||||
|
||||
private static class CustomUserPrincipal {}
|
||||
public void showUserAnnotationErrorOnInvalidType(
|
||||
@AuthenticationPrincipal(errorOnInvalidType = true) String user) {
|
||||
}
|
||||
|
||||
private void setAuthenticationPrincipal(Object principal) {
|
||||
this.expectedPrincipal = principal;
|
||||
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(expectedPrincipal, "password", "ROLE_USER"));
|
||||
}
|
||||
public void showUserAnnotationCurrentUserErrorOnInvalidType(
|
||||
@CurrentUserErrorOnInvalidType String user) {
|
||||
}
|
||||
|
||||
public void showUserAnnotation(@AuthenticationPrincipal UserDetails user) {
|
||||
}
|
||||
|
||||
public void showUserAnnotation(@AuthenticationPrincipal CustomUserPrincipal user) {
|
||||
}
|
||||
|
||||
public void showUserCustomAnnotation(@CurrentUser CustomUserPrincipal user) {
|
||||
}
|
||||
|
||||
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"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,7 +33,6 @@ import org.springframework.security.web.authentication.logout.LogoutHandler;
|
||||
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
|
||||
import org.springframework.security.web.session.ConcurrentSessionFilter;
|
||||
|
||||
|
||||
/**
|
||||
* Tests {@link ConcurrentSessionFilter}.
|
||||
*
|
||||
@@ -42,87 +41,92 @@ import org.springframework.security.web.session.ConcurrentSessionFilter;
|
||||
*/
|
||||
public class ConcurrentSessionFilterTests {
|
||||
|
||||
@Test
|
||||
public void detectsExpiredSessions() throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpSession session = new MockHttpSession();
|
||||
request.setSession(session);
|
||||
@Test
|
||||
public void detectsExpiredSessions() throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpSession session = new MockHttpSession();
|
||||
request.setSession(session);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
SessionRegistry registry = new SessionRegistryImpl();
|
||||
registry.registerNewSession(session.getId(), "principal");
|
||||
registry.getSessionInformation(session.getId()).expireNow();
|
||||
SessionRegistry registry = new SessionRegistryImpl();
|
||||
registry.registerNewSession(session.getId(), "principal");
|
||||
registry.getSessionInformation(session.getId()).expireNow();
|
||||
|
||||
// Setup our test fixture and registry to want this session to be expired
|
||||
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry,"/expired.jsp");
|
||||
filter.setRedirectStrategy(new DefaultRedirectStrategy());
|
||||
filter.setLogoutHandlers(new LogoutHandler[]{new SecurityContextLogoutHandler()});
|
||||
filter.afterPropertiesSet();
|
||||
// Setup our test fixture and registry to want this session to be expired
|
||||
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry,
|
||||
"/expired.jsp");
|
||||
filter.setRedirectStrategy(new DefaultRedirectStrategy());
|
||||
filter.setLogoutHandlers(new LogoutHandler[] { new SecurityContextLogoutHandler() });
|
||||
filter.afterPropertiesSet();
|
||||
|
||||
FilterChain fc = mock(FilterChain.class);
|
||||
filter.doFilter(request, response, fc);
|
||||
// Expect that the filter chain will not be invoked, as we redirect to expiredUrl
|
||||
verifyZeroInteractions(fc);
|
||||
FilterChain fc = mock(FilterChain.class);
|
||||
filter.doFilter(request, response, fc);
|
||||
// Expect that the filter chain will not be invoked, as we redirect to expiredUrl
|
||||
verifyZeroInteractions(fc);
|
||||
|
||||
assertEquals("/expired.jsp", response.getRedirectedUrl());
|
||||
}
|
||||
assertEquals("/expired.jsp", response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
// As above, but with no expiredUrl set.
|
||||
@Test
|
||||
public void returnsExpectedMessageWhenNoExpiredUrlSet() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpSession session = new MockHttpSession();
|
||||
request.setSession(session);
|
||||
// As above, but with no expiredUrl set.
|
||||
@Test
|
||||
public void returnsExpectedMessageWhenNoExpiredUrlSet() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpSession session = new MockHttpSession();
|
||||
request.setSession(session);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
SessionRegistry registry = new SessionRegistryImpl();
|
||||
registry.registerNewSession(session.getId(), "principal");
|
||||
registry.getSessionInformation(session.getId()).expireNow();
|
||||
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry);
|
||||
SessionRegistry registry = new SessionRegistryImpl();
|
||||
registry.registerNewSession(session.getId(), "principal");
|
||||
registry.getSessionInformation(session.getId()).expireNow();
|
||||
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry);
|
||||
|
||||
FilterChain fc = mock(FilterChain.class);
|
||||
filter.doFilter(request, response, fc);
|
||||
verifyZeroInteractions(fc);
|
||||
FilterChain fc = mock(FilterChain.class);
|
||||
filter.doFilter(request, response, fc);
|
||||
verifyZeroInteractions(fc);
|
||||
|
||||
assertEquals("This session has been expired (possibly due to multiple concurrent logins being " +
|
||||
"attempted as the same user).", response.getContentAsString());
|
||||
}
|
||||
assertEquals(
|
||||
"This session has been expired (possibly due to multiple concurrent logins being "
|
||||
+ "attempted as the same user).", response.getContentAsString());
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void detectsMissingSessionRegistry() throws Exception {
|
||||
new ConcurrentSessionFilter(null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void detectsMissingSessionRegistry() throws Exception {
|
||||
new ConcurrentSessionFilter(null);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void detectsInvalidUrl() throws Exception {
|
||||
new ConcurrentSessionFilter(new SessionRegistryImpl(), "ImNotValid");
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void detectsInvalidUrl() throws Exception {
|
||||
new ConcurrentSessionFilter(new SessionRegistryImpl(), "ImNotValid");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void lastRequestTimeUpdatesCorrectly() throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpSession session = new MockHttpSession();
|
||||
request.setSession(session);
|
||||
@Test
|
||||
public void lastRequestTimeUpdatesCorrectly() throws Exception {
|
||||
// Setup our HTTP request
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpSession session = new MockHttpSession();
|
||||
request.setSession(session);
|
||||
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterChain fc = mock(FilterChain.class);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FilterChain fc = mock(FilterChain.class);
|
||||
|
||||
// Setup our test fixture
|
||||
SessionRegistry registry = new SessionRegistryImpl();
|
||||
registry.registerNewSession(session.getId(), "principal");
|
||||
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry, "/expired.jsp");
|
||||
// Setup our test fixture
|
||||
SessionRegistry registry = new SessionRegistryImpl();
|
||||
registry.registerNewSession(session.getId(), "principal");
|
||||
ConcurrentSessionFilter filter = new ConcurrentSessionFilter(registry,
|
||||
"/expired.jsp");
|
||||
|
||||
Date lastRequest = registry.getSessionInformation(session.getId()).getLastRequest();
|
||||
Date lastRequest = registry.getSessionInformation(session.getId())
|
||||
.getLastRequest();
|
||||
|
||||
Thread.sleep(1000);
|
||||
Thread.sleep(1000);
|
||||
|
||||
filter.doFilter(request, response, fc);
|
||||
filter.doFilter(request, response, fc);
|
||||
|
||||
verify(fc).doFilter(request, response);
|
||||
assertTrue(registry.getSessionInformation(session.getId()).getLastRequest().after(lastRequest));
|
||||
}
|
||||
verify(fc).doFilter(request, response);
|
||||
assertTrue(registry.getSessionInformation(session.getId()).getLastRequest()
|
||||
.after(lastRequest));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,475 +51,553 @@ import org.springframework.util.ClassUtils;
|
||||
* @author Rob Winch
|
||||
*/
|
||||
@RunWith(PowerMockRunner.class)
|
||||
@PrepareForTest({ClassUtils.class})
|
||||
@PrepareForTest({ ClassUtils.class })
|
||||
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() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
@After
|
||||
public void tearDown() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void servlet25Compatability() throws Exception {
|
||||
spy(ClassUtils.class);
|
||||
when(ClassUtils.class,"hasMethod", ServletRequest.class, "startAsync", new Class[] {}).thenReturn(false);
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
|
||||
repo.loadContext(holder);
|
||||
assertThat(holder.getRequest()).isSameAs(request);
|
||||
}
|
||||
@Test
|
||||
public void servlet25Compatability() throws Exception {
|
||||
spy(ClassUtils.class);
|
||||
when(ClassUtils.class, "hasMethod", ServletRequest.class, "startAsync",
|
||||
new Class[] {}).thenReturn(false);
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
|
||||
response);
|
||||
repo.loadContext(holder);
|
||||
assertThat(holder.getRequest()).isSameAs(request);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void startAsyncDisablesSaveOnCommit() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
|
||||
repo.loadContext(holder);
|
||||
@Test
|
||||
public void startAsyncDisablesSaveOnCommit() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
|
||||
response);
|
||||
repo.loadContext(holder);
|
||||
|
||||
reset(request);
|
||||
holder.getRequest().startAsync();
|
||||
holder.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST);
|
||||
reset(request);
|
||||
holder.getRequest().startAsync();
|
||||
holder.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST);
|
||||
|
||||
// ensure that sendError did cause interaction with the HttpSession
|
||||
verify(request, never()).getSession(anyBoolean());
|
||||
verify(request, never()).getSession();
|
||||
}
|
||||
// ensure that sendError did cause interaction with the HttpSession
|
||||
verify(request, never()).getSession(anyBoolean());
|
||||
verify(request, never()).getSession();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void startAsyncRequestResponseDisablesSaveOnCommit() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
|
||||
response);
|
||||
repo.loadContext(holder);
|
||||
|
||||
@Test
|
||||
public void startAsyncRequestResponseDisablesSaveOnCommit() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
|
||||
repo.loadContext(holder);
|
||||
reset(request);
|
||||
holder.getRequest().startAsync(request, response);
|
||||
holder.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST);
|
||||
|
||||
reset(request);
|
||||
holder.getRequest().startAsync(request,response);
|
||||
holder.getResponse().sendError(HttpServletResponse.SC_BAD_REQUEST);
|
||||
// ensure that sendError did cause interaction with the HttpSession
|
||||
verify(request, never()).getSession(anyBoolean());
|
||||
verify(request, never()).getSession();
|
||||
}
|
||||
|
||||
// ensure that sendError did cause interaction with the HttpSession
|
||||
verify(request, never()).getSession(anyBoolean());
|
||||
verify(request, never()).getSession();
|
||||
}
|
||||
@Test
|
||||
public void sessionIsntCreatedIfContextDoesntChange() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
|
||||
response);
|
||||
SecurityContext context = repo.loadContext(holder);
|
||||
assertNull(request.getSession(false));
|
||||
repo.saveContext(context, holder.getRequest(), holder.getResponse());
|
||||
assertNull(request.getSession(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sessionIsntCreatedIfContextDoesntChange() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
|
||||
SecurityContext context = repo.loadContext(holder);
|
||||
assertNull(request.getSession(false));
|
||||
repo.saveContext(context, holder.getRequest(), holder.getResponse());
|
||||
assertNull(request.getSession(false));
|
||||
}
|
||||
@Test
|
||||
public void sessionIsntCreatedIfAllowSessionCreationIsFalse() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setAllowSessionCreation(false);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
|
||||
response);
|
||||
SecurityContext context = repo.loadContext(holder);
|
||||
// Change context
|
||||
context.setAuthentication(testToken);
|
||||
repo.saveContext(context, holder.getRequest(), holder.getResponse());
|
||||
assertNull(request.getSession(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sessionIsntCreatedIfAllowSessionCreationIsFalse() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setAllowSessionCreation(false);
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
|
||||
SecurityContext context = repo.loadContext(holder);
|
||||
// Change context
|
||||
context.setAuthentication(testToken);
|
||||
repo.saveContext(context, holder.getRequest(), holder.getResponse());
|
||||
assertNull(request.getSession(false));
|
||||
}
|
||||
@Test
|
||||
public void existingContextIsSuccessFullyLoadedFromSessionAndSavedBack()
|
||||
throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setSpringSecurityContextKey("imTheContext");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
request.getSession().setAttribute("imTheContext",
|
||||
SecurityContextHolder.getContext());
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
|
||||
response);
|
||||
SecurityContext context = repo.loadContext(holder);
|
||||
assertNotNull(context);
|
||||
assertEquals(testToken, context.getAuthentication());
|
||||
// Won't actually be saved as it hasn't changed, but go through the use case
|
||||
// anyway
|
||||
repo.saveContext(context, holder.getRequest(), holder.getResponse());
|
||||
assertEquals(context, request.getSession().getAttribute("imTheContext"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void existingContextIsSuccessFullyLoadedFromSessionAndSavedBack() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setSpringSecurityContextKey("imTheContext");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
request.getSession().setAttribute("imTheContext", SecurityContextHolder.getContext());
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
|
||||
SecurityContext context = repo.loadContext(holder);
|
||||
assertNotNull(context);
|
||||
assertEquals(testToken, context.getAuthentication());
|
||||
// Won't actually be saved as it hasn't changed, but go through the use case anyway
|
||||
repo.saveContext(context, holder.getRequest(), holder.getResponse());
|
||||
assertEquals(context, request.getSession().getAttribute("imTheContext"));
|
||||
}
|
||||
// SEC-1528
|
||||
@Test
|
||||
public void saveContextCallsSetAttributeIfContextIsModifiedDirectlyDuringRequest()
|
||||
throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
// Set up an existing authenticated context, mocking that it is in the session
|
||||
// already
|
||||
SecurityContext ctx = SecurityContextHolder.getContext();
|
||||
ctx.setAuthentication(testToken);
|
||||
HttpSession session = mock(HttpSession.class);
|
||||
when(session.getAttribute(SPRING_SECURITY_CONTEXT_KEY)).thenReturn(ctx);
|
||||
request.setSession(session);
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
|
||||
new MockHttpServletResponse());
|
||||
assertSame(ctx, repo.loadContext(holder));
|
||||
|
||||
// SEC-1528
|
||||
@Test
|
||||
public void saveContextCallsSetAttributeIfContextIsModifiedDirectlyDuringRequest() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
// Set up an existing authenticated context, mocking that it is in the session already
|
||||
SecurityContext ctx = SecurityContextHolder.getContext();
|
||||
ctx.setAuthentication(testToken);
|
||||
HttpSession session = mock(HttpSession.class);
|
||||
when(session.getAttribute(SPRING_SECURITY_CONTEXT_KEY)).thenReturn(ctx);
|
||||
request.setSession(session);
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse());
|
||||
assertSame(ctx, repo.loadContext(holder));
|
||||
// Modify context contents. Same user, different role
|
||||
SecurityContextHolder.getContext().setAuthentication(
|
||||
new TestingAuthenticationToken("someone", "passwd", "ROLE_B"));
|
||||
repo.saveContext(ctx, holder.getRequest(), holder.getResponse());
|
||||
|
||||
// Modify context contents. Same user, different role
|
||||
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("someone", "passwd", "ROLE_B"));
|
||||
repo.saveContext(ctx, holder.getRequest(), holder.getResponse());
|
||||
// Must be called even though the value in the local VM is already the same
|
||||
verify(session).setAttribute(SPRING_SECURITY_CONTEXT_KEY, ctx);
|
||||
}
|
||||
|
||||
// Must be called even though the value in the local VM is already the same
|
||||
verify(session).setAttribute(SPRING_SECURITY_CONTEXT_KEY, ctx);
|
||||
}
|
||||
@Test
|
||||
public void nonSecurityContextInSessionIsIgnored() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
request.getSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY,
|
||||
"NotASecurityContextInstance");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
|
||||
response);
|
||||
SecurityContext context = repo.loadContext(holder);
|
||||
assertNotNull(context);
|
||||
assertNull(context.getAuthentication());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nonSecurityContextInSessionIsIgnored() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
request.getSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY, "NotASecurityContextInstance");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
|
||||
SecurityContext context = repo.loadContext(holder);
|
||||
assertNotNull(context);
|
||||
assertNull(context.getAuthentication());
|
||||
}
|
||||
@Test
|
||||
public void sessionIsCreatedAndContextStoredWhenContextChanges() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
|
||||
response);
|
||||
SecurityContext context = repo.loadContext(holder);
|
||||
assertNull(request.getSession(false));
|
||||
// Simulate authentication during the request
|
||||
context.setAuthentication(testToken);
|
||||
repo.saveContext(context, holder.getRequest(), holder.getResponse());
|
||||
assertNotNull(request.getSession(false));
|
||||
assertEquals(context,
|
||||
request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sessionIsCreatedAndContextStoredWhenContextChanges() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
|
||||
SecurityContext context = repo.loadContext(holder);
|
||||
assertNull(request.getSession(false));
|
||||
// Simulate authentication during the request
|
||||
context.setAuthentication(testToken);
|
||||
repo.saveContext(context, holder.getRequest(), holder.getResponse());
|
||||
assertNotNull(request.getSession(false));
|
||||
assertEquals(context, request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY));
|
||||
}
|
||||
@Test
|
||||
public void redirectCausesEarlySaveOfContext() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setSpringSecurityContextKey("imTheContext");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
|
||||
response);
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().sendRedirect("/doesntmatter");
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession()
|
||||
.getAttribute("imTheContext"));
|
||||
assertTrue(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse())
|
||||
.isContextSaved());
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
|
||||
holder.getResponse());
|
||||
// Check it's still the same
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession()
|
||||
.getAttribute("imTheContext"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void redirectCausesEarlySaveOfContext() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setSpringSecurityContextKey("imTheContext");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().sendRedirect("/doesntmatter");
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession().getAttribute("imTheContext"));
|
||||
assertTrue(((SaveContextOnUpdateOrErrorResponseWrapper)holder.getResponse()).isContextSaved());
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
|
||||
// Check it's still the same
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession().getAttribute("imTheContext"));
|
||||
}
|
||||
@Test
|
||||
public void sendErrorCausesEarlySaveOfContext() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setSpringSecurityContextKey("imTheContext");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
|
||||
response);
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().sendError(404);
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession()
|
||||
.getAttribute("imTheContext"));
|
||||
assertTrue(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse())
|
||||
.isContextSaved());
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
|
||||
holder.getResponse());
|
||||
// Check it's still the same
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession()
|
||||
.getAttribute("imTheContext"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sendErrorCausesEarlySaveOfContext() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setSpringSecurityContextKey("imTheContext");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().sendError(404);
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession().getAttribute("imTheContext"));
|
||||
assertTrue(((SaveContextOnUpdateOrErrorResponseWrapper)holder.getResponse()).isContextSaved());
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
|
||||
// Check it's still the same
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession().getAttribute("imTheContext"));
|
||||
}
|
||||
// SEC-2005
|
||||
@Test
|
||||
public void flushBufferCausesEarlySaveOfContext() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setSpringSecurityContextKey("imTheContext");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
|
||||
response);
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().flushBuffer();
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession()
|
||||
.getAttribute("imTheContext"));
|
||||
assertTrue(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse())
|
||||
.isContextSaved());
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
|
||||
holder.getResponse());
|
||||
// Check it's still the same
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession()
|
||||
.getAttribute("imTheContext"));
|
||||
}
|
||||
|
||||
// SEC-2005
|
||||
@Test
|
||||
public void flushBufferCausesEarlySaveOfContext() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setSpringSecurityContextKey("imTheContext");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().flushBuffer();
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession().getAttribute("imTheContext"));
|
||||
assertTrue(((SaveContextOnUpdateOrErrorResponseWrapper)holder.getResponse()).isContextSaved());
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
|
||||
// Check it's still the same
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession().getAttribute("imTheContext"));
|
||||
}
|
||||
// SEC-2005
|
||||
@Test
|
||||
public void writerFlushCausesEarlySaveOfContext() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setSpringSecurityContextKey("imTheContext");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
|
||||
response);
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().getWriter().flush();
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession()
|
||||
.getAttribute("imTheContext"));
|
||||
assertTrue(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse())
|
||||
.isContextSaved());
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
|
||||
holder.getResponse());
|
||||
// Check it's still the same
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession()
|
||||
.getAttribute("imTheContext"));
|
||||
}
|
||||
|
||||
// SEC-2005
|
||||
@Test
|
||||
public void writerFlushCausesEarlySaveOfContext() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setSpringSecurityContextKey("imTheContext");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().getWriter().flush();
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession().getAttribute("imTheContext"));
|
||||
assertTrue(((SaveContextOnUpdateOrErrorResponseWrapper)holder.getResponse()).isContextSaved());
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
|
||||
// Check it's still the same
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession().getAttribute("imTheContext"));
|
||||
}
|
||||
// SEC-2005
|
||||
@Test
|
||||
public void writerCloseCausesEarlySaveOfContext() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setSpringSecurityContextKey("imTheContext");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
|
||||
response);
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().getWriter().close();
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession()
|
||||
.getAttribute("imTheContext"));
|
||||
assertTrue(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse())
|
||||
.isContextSaved());
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
|
||||
holder.getResponse());
|
||||
// Check it's still the same
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession()
|
||||
.getAttribute("imTheContext"));
|
||||
}
|
||||
|
||||
// SEC-2005
|
||||
@Test
|
||||
public void writerCloseCausesEarlySaveOfContext() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setSpringSecurityContextKey("imTheContext");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().getWriter().close();
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession().getAttribute("imTheContext"));
|
||||
assertTrue(((SaveContextOnUpdateOrErrorResponseWrapper)holder.getResponse()).isContextSaved());
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
|
||||
// Check it's still the same
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession().getAttribute("imTheContext"));
|
||||
}
|
||||
// SEC-2005
|
||||
@Test
|
||||
public void outputStreamFlushCausesEarlySaveOfContext() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setSpringSecurityContextKey("imTheContext");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
|
||||
response);
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().getOutputStream().flush();
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession()
|
||||
.getAttribute("imTheContext"));
|
||||
assertTrue(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse())
|
||||
.isContextSaved());
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
|
||||
holder.getResponse());
|
||||
// Check it's still the same
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession()
|
||||
.getAttribute("imTheContext"));
|
||||
}
|
||||
|
||||
// SEC-2005
|
||||
@Test
|
||||
public void outputStreamFlushCausesEarlySaveOfContext() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setSpringSecurityContextKey("imTheContext");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().getOutputStream().flush();
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession().getAttribute("imTheContext"));
|
||||
assertTrue(((SaveContextOnUpdateOrErrorResponseWrapper)holder.getResponse()).isContextSaved());
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
|
||||
// Check it's still the same
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession().getAttribute("imTheContext"));
|
||||
}
|
||||
// SEC-2005
|
||||
@Test
|
||||
public void outputStreamCloseCausesEarlySaveOfContext() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setSpringSecurityContextKey("imTheContext");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
|
||||
response);
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().getOutputStream().close();
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession()
|
||||
.getAttribute("imTheContext"));
|
||||
assertTrue(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse())
|
||||
.isContextSaved());
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
|
||||
holder.getResponse());
|
||||
// Check it's still the same
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession()
|
||||
.getAttribute("imTheContext"));
|
||||
}
|
||||
|
||||
// SEC-2005
|
||||
@Test
|
||||
public void outputStreamCloseCausesEarlySaveOfContext() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setSpringSecurityContextKey("imTheContext");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().getOutputStream().close();
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession().getAttribute("imTheContext"));
|
||||
assertTrue(((SaveContextOnUpdateOrErrorResponseWrapper)holder.getResponse()).isContextSaved());
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
|
||||
// Check it's still the same
|
||||
assertEquals(SecurityContextHolder.getContext(), request.getSession().getAttribute("imTheContext"));
|
||||
}
|
||||
// SEC-SEC-2055
|
||||
@Test
|
||||
public void outputStreamCloseDelegate() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setSpringSecurityContextKey("imTheContext");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
||||
ServletOutputStream outputstream = mock(ServletOutputStream.class);
|
||||
when(response.getOutputStream()).thenReturn(outputstream);
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
|
||||
response);
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().getOutputStream().close();
|
||||
verify(outputstream).close();
|
||||
}
|
||||
|
||||
// SEC-SEC-2055
|
||||
@Test
|
||||
public void outputStreamCloseDelegate() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setSpringSecurityContextKey("imTheContext");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
||||
ServletOutputStream outputstream = mock(ServletOutputStream.class);
|
||||
when(response.getOutputStream()).thenReturn(outputstream);
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().getOutputStream().close();
|
||||
verify(outputstream).close();
|
||||
}
|
||||
// SEC-SEC-2055
|
||||
@Test
|
||||
public void outputStreamFlushesDelegate() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setSpringSecurityContextKey("imTheContext");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
||||
ServletOutputStream outputstream = mock(ServletOutputStream.class);
|
||||
when(response.getOutputStream()).thenReturn(outputstream);
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
|
||||
response);
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().getOutputStream().flush();
|
||||
verify(outputstream).flush();
|
||||
}
|
||||
|
||||
// SEC-SEC-2055
|
||||
@Test
|
||||
public void outputStreamFlushesDelegate() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setSpringSecurityContextKey("imTheContext");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
HttpServletResponse response = mock(HttpServletResponse.class);
|
||||
ServletOutputStream outputstream = mock(ServletOutputStream.class);
|
||||
when(response.getOutputStream()).thenReturn(outputstream);
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
|
||||
SecurityContextHolder.setContext(repo.loadContext(holder));
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
holder.getResponse().getOutputStream().flush();
|
||||
verify(outputstream).flush();
|
||||
}
|
||||
@Test
|
||||
public void noSessionIsCreatedIfSessionWasInvalidatedDuringTheRequest()
|
||||
throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.getSession();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
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());
|
||||
assertNull(request.getSession(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noSessionIsCreatedIfSessionWasInvalidatedDuringTheRequest() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.getSession();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
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());
|
||||
assertNull(request.getSession(false));
|
||||
}
|
||||
// SEC-1315
|
||||
@Test
|
||||
public void noSessionIsCreatedIfAnonymousTokenIsUsed() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
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());
|
||||
assertNull(request.getSession(false));
|
||||
}
|
||||
|
||||
// SEC-1315
|
||||
@Test
|
||||
public void noSessionIsCreatedIfAnonymousTokenIsUsed() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
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());
|
||||
assertNull(request.getSession(false));
|
||||
}
|
||||
// SEC-1587
|
||||
@Test
|
||||
public void contextIsRemovedFromSessionIfCurrentContextIsAnonymous() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext();
|
||||
ctxInSession.setAuthentication(testToken);
|
||||
request.getSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY, ctxInSession);
|
||||
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());
|
||||
assertNull(request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY));
|
||||
}
|
||||
|
||||
// SEC-1587
|
||||
@Test
|
||||
public void contextIsRemovedFromSessionIfCurrentContextIsAnonymous() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext();
|
||||
ctxInSession.setAuthentication(testToken);
|
||||
request.getSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY, ctxInSession);
|
||||
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());
|
||||
assertNull(request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY));
|
||||
}
|
||||
@Test
|
||||
public void contextIsRemovedFromSessionIfCurrentContextIsEmpty() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setSpringSecurityContextKey("imTheContext");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext();
|
||||
ctxInSession.setAuthentication(testToken);
|
||||
request.getSession().setAttribute("imTheContext", ctxInSession);
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
|
||||
new MockHttpServletResponse());
|
||||
repo.loadContext(holder);
|
||||
// Save an empty context
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(),
|
||||
holder.getResponse());
|
||||
assertNull(request.getSession().getAttribute("imTheContext"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void contextIsRemovedFromSessionIfCurrentContextIsEmpty() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setSpringSecurityContextKey("imTheContext");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext();
|
||||
ctxInSession.setAuthentication(testToken);
|
||||
request.getSession().setAttribute("imTheContext", ctxInSession);
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse());
|
||||
repo.loadContext(holder);
|
||||
// Save an empty context
|
||||
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
|
||||
assertNull(request.getSession().getAttribute("imTheContext"));
|
||||
}
|
||||
// SEC-1735
|
||||
@Test
|
||||
public void contextIsNotRemovedFromSessionIfContextBeforeExecutionDefault()
|
||||
throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
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());
|
||||
assertSame(ctxInSession,
|
||||
request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY));
|
||||
}
|
||||
|
||||
// SEC-1735
|
||||
@Test
|
||||
public void contextIsNotRemovedFromSessionIfContextBeforeExecutionDefault() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
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());
|
||||
assertSame(ctxInSession,request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY));
|
||||
}
|
||||
@Test
|
||||
@SuppressWarnings("deprecation")
|
||||
public void sessionDisableUrlRewritingPreventsSessionIdBeingWrittenToUrl()
|
||||
throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
final String sessionId = ";jsessionid=id";
|
||||
MockHttpServletResponse response = new MockHttpServletResponse() {
|
||||
@Override
|
||||
public String encodeRedirectUrl(String url) {
|
||||
return url + sessionId;
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("deprecation")
|
||||
public void sessionDisableUrlRewritingPreventsSessionIdBeingWrittenToUrl() throws Exception {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
final String sessionId = ";jsessionid=id";
|
||||
MockHttpServletResponse response = new MockHttpServletResponse() {
|
||||
@Override
|
||||
public String encodeRedirectUrl(String url) {
|
||||
return url + sessionId;
|
||||
}
|
||||
@Override
|
||||
public String encodeRedirectURL(String url) {
|
||||
return url + sessionId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String encodeRedirectURL(String url) {
|
||||
return url + sessionId;
|
||||
}
|
||||
@Override
|
||||
public String encodeUrl(String url) {
|
||||
return url + sessionId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String encodeUrl(String url) {
|
||||
return url + sessionId;
|
||||
}
|
||||
@Override
|
||||
public String encodeURL(String url) {
|
||||
return url + sessionId;
|
||||
}
|
||||
};
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
|
||||
response);
|
||||
repo.loadContext(holder);
|
||||
String url = "/aUrl";
|
||||
assertEquals(url + sessionId, holder.getResponse().encodeRedirectUrl(url));
|
||||
assertEquals(url + sessionId, holder.getResponse().encodeRedirectURL(url));
|
||||
assertEquals(url + sessionId, holder.getResponse().encodeUrl(url));
|
||||
assertEquals(url + sessionId, holder.getResponse().encodeURL(url));
|
||||
repo.setDisableUrlRewriting(true);
|
||||
holder = new HttpRequestResponseHolder(request, response);
|
||||
repo.loadContext(holder);
|
||||
assertEquals(url, holder.getResponse().encodeRedirectUrl(url));
|
||||
assertEquals(url, holder.getResponse().encodeRedirectURL(url));
|
||||
assertEquals(url, holder.getResponse().encodeUrl(url));
|
||||
assertEquals(url, holder.getResponse().encodeURL(url));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String encodeURL(String url) {
|
||||
return url + sessionId;
|
||||
}
|
||||
};
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
|
||||
repo.loadContext(holder);
|
||||
String url = "/aUrl";
|
||||
assertEquals(url + sessionId, holder.getResponse().encodeRedirectUrl(url));
|
||||
assertEquals(url + sessionId, holder.getResponse().encodeRedirectURL(url));
|
||||
assertEquals(url + sessionId, holder.getResponse().encodeUrl(url));
|
||||
assertEquals(url + sessionId, holder.getResponse().encodeURL(url));
|
||||
repo.setDisableUrlRewriting(true);
|
||||
holder = new HttpRequestResponseHolder(request, response);
|
||||
repo.loadContext(holder);
|
||||
assertEquals(url, holder.getResponse().encodeRedirectUrl(url));
|
||||
assertEquals(url, holder.getResponse().encodeRedirectURL(url));
|
||||
assertEquals(url, holder.getResponse().encodeUrl(url));
|
||||
assertEquals(url, holder.getResponse().encodeURL(url));
|
||||
}
|
||||
@Test
|
||||
public void saveContextCustomTrustResolver() {
|
||||
SecurityContext contextToSave = SecurityContextHolder.createEmptyContext();
|
||||
contextToSave.setAuthentication(testToken);
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
|
||||
new MockHttpServletResponse());
|
||||
repo.loadContext(holder);
|
||||
AuthenticationTrustResolver trustResolver = mock(AuthenticationTrustResolver.class);
|
||||
repo.setTrustResolver(trustResolver);
|
||||
|
||||
@Test
|
||||
public void saveContextCustomTrustResolver() {
|
||||
SecurityContext contextToSave = SecurityContextHolder.createEmptyContext();
|
||||
contextToSave.setAuthentication(testToken);
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse());
|
||||
repo.loadContext(holder);
|
||||
AuthenticationTrustResolver trustResolver = mock(AuthenticationTrustResolver.class);
|
||||
repo.setTrustResolver(trustResolver);
|
||||
repo.saveContext(contextToSave, holder.getRequest(), holder.getResponse());
|
||||
|
||||
repo.saveContext(contextToSave, holder.getRequest(), holder.getResponse());
|
||||
verify(trustResolver).isAnonymous(contextToSave.getAuthentication());
|
||||
}
|
||||
|
||||
verify(trustResolver).isAnonymous(contextToSave.getAuthentication());
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setTrustResolverNull() {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setTrustResolver(null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setTrustResolverNull() {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
repo.setTrustResolver(null);
|
||||
}
|
||||
// SEC-2578
|
||||
@Test
|
||||
public void traverseWrappedRequests() {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,
|
||||
response);
|
||||
SecurityContext context = repo.loadContext(holder);
|
||||
assertNull(request.getSession(false));
|
||||
// Simulate authentication during the request
|
||||
context.setAuthentication(testToken);
|
||||
|
||||
// SEC-2578
|
||||
@Test
|
||||
public void traverseWrappedRequests() {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
|
||||
SecurityContext context = repo.loadContext(holder);
|
||||
assertNull(request.getSession(false));
|
||||
// Simulate authentication during the request
|
||||
context.setAuthentication(testToken);
|
||||
repo.saveContext(context, new HttpServletRequestWrapper(holder.getRequest()),
|
||||
new HttpServletResponseWrapper(holder.getResponse()));
|
||||
|
||||
repo.saveContext(context, new HttpServletRequestWrapper(holder.getRequest()), new HttpServletResponseWrapper(holder.getResponse()));
|
||||
assertNotNull(request.getSession(false));
|
||||
assertEquals(context,
|
||||
request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY));
|
||||
}
|
||||
|
||||
assertNotNull(request.getSession(false));
|
||||
assertEquals(context, request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY));
|
||||
}
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void failsWithStandardResponse() {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
SecurityContext context = SecurityContextHolder.createEmptyContext();
|
||||
context.setAuthentication(testToken);
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void failsWithStandardResponse() {
|
||||
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
SecurityContext context = SecurityContextHolder.createEmptyContext();
|
||||
context.setAuthentication(testToken);
|
||||
|
||||
repo.saveContext(context,request,response);
|
||||
}
|
||||
repo.saveContext(context, request, response);
|
||||
}
|
||||
}
|
||||
@@ -34,154 +34,157 @@ import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class SaveContextOnUpdateOrErrorResponseWrapperTests {
|
||||
@Mock
|
||||
private SecurityContext securityContext;
|
||||
@Mock
|
||||
private SecurityContext securityContext;
|
||||
|
||||
private MockHttpServletResponse response;
|
||||
private SaveContextOnUpdateOrErrorResponseWrapperStub wrappedResponse;
|
||||
private MockHttpServletResponse response;
|
||||
private SaveContextOnUpdateOrErrorResponseWrapperStub wrappedResponse;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
response = new MockHttpServletResponse();
|
||||
wrappedResponse = new SaveContextOnUpdateOrErrorResponseWrapperStub(response, true);
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
}
|
||||
@Before
|
||||
public void setUp() {
|
||||
response = new MockHttpServletResponse();
|
||||
wrappedResponse = new SaveContextOnUpdateOrErrorResponseWrapperStub(response,
|
||||
true);
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
}
|
||||
|
||||
@After
|
||||
public void clearContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
@After
|
||||
public void clearContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sendErrorSavesSecurityContext() throws Exception {
|
||||
int error = HttpServletResponse.SC_FORBIDDEN;
|
||||
wrappedResponse.sendError(error);
|
||||
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
|
||||
assertThat(response.getStatus()).isEqualTo(error);
|
||||
}
|
||||
@Test
|
||||
public void sendErrorSavesSecurityContext() throws Exception {
|
||||
int error = HttpServletResponse.SC_FORBIDDEN;
|
||||
wrappedResponse.sendError(error);
|
||||
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
|
||||
assertThat(response.getStatus()).isEqualTo(error);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sendErrorSkipsSaveSecurityContextDisables() throws Exception {
|
||||
final int error = HttpServletResponse.SC_FORBIDDEN;
|
||||
wrappedResponse.disableSaveOnResponseCommitted();
|
||||
wrappedResponse.sendError(error);
|
||||
assertThat(wrappedResponse.securityContext).isNull();
|
||||
assertThat(response.getStatus()).isEqualTo(error);
|
||||
}
|
||||
@Test
|
||||
public void sendErrorSkipsSaveSecurityContextDisables() throws Exception {
|
||||
final int error = HttpServletResponse.SC_FORBIDDEN;
|
||||
wrappedResponse.disableSaveOnResponseCommitted();
|
||||
wrappedResponse.sendError(error);
|
||||
assertThat(wrappedResponse.securityContext).isNull();
|
||||
assertThat(response.getStatus()).isEqualTo(error);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sendErrorWithMessageSavesSecurityContext() throws Exception {
|
||||
int error = HttpServletResponse.SC_FORBIDDEN;
|
||||
String message = "Forbidden";
|
||||
wrappedResponse.sendError(error, message);
|
||||
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
|
||||
assertThat(response.getStatus()).isEqualTo(error);
|
||||
assertThat(response.getErrorMessage()).isEqualTo(message);
|
||||
}
|
||||
@Test
|
||||
public void sendErrorWithMessageSavesSecurityContext() throws Exception {
|
||||
int error = HttpServletResponse.SC_FORBIDDEN;
|
||||
String message = "Forbidden";
|
||||
wrappedResponse.sendError(error, message);
|
||||
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
|
||||
assertThat(response.getStatus()).isEqualTo(error);
|
||||
assertThat(response.getErrorMessage()).isEqualTo(message);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sendErrorWithMessageSkipsSaveSecurityContextDisables() throws Exception {
|
||||
final int error = HttpServletResponse.SC_FORBIDDEN;
|
||||
final String message = "Forbidden";
|
||||
wrappedResponse.disableSaveOnResponseCommitted();
|
||||
wrappedResponse.sendError(error, message);
|
||||
assertThat(wrappedResponse.securityContext).isNull();
|
||||
assertThat(response.getStatus()).isEqualTo(error);
|
||||
assertThat(response.getErrorMessage()).isEqualTo(message);
|
||||
}
|
||||
@Test
|
||||
public void sendErrorWithMessageSkipsSaveSecurityContextDisables() throws Exception {
|
||||
final int error = HttpServletResponse.SC_FORBIDDEN;
|
||||
final String message = "Forbidden";
|
||||
wrappedResponse.disableSaveOnResponseCommitted();
|
||||
wrappedResponse.sendError(error, message);
|
||||
assertThat(wrappedResponse.securityContext).isNull();
|
||||
assertThat(response.getStatus()).isEqualTo(error);
|
||||
assertThat(response.getErrorMessage()).isEqualTo(message);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sendRedirectSavesSecurityContext() throws Exception {
|
||||
String url = "/location";
|
||||
wrappedResponse.sendRedirect(url);
|
||||
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo(url);
|
||||
}
|
||||
@Test
|
||||
public void sendRedirectSavesSecurityContext() throws Exception {
|
||||
String url = "/location";
|
||||
wrappedResponse.sendRedirect(url);
|
||||
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo(url);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sendRedirectSkipsSaveSecurityContextDisables() throws Exception {
|
||||
final String url = "/location";
|
||||
wrappedResponse.disableSaveOnResponseCommitted();
|
||||
wrappedResponse.sendRedirect(url);
|
||||
assertThat(wrappedResponse.securityContext).isNull();
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo(url);
|
||||
}
|
||||
@Test
|
||||
public void sendRedirectSkipsSaveSecurityContextDisables() throws Exception {
|
||||
final String url = "/location";
|
||||
wrappedResponse.disableSaveOnResponseCommitted();
|
||||
wrappedResponse.sendRedirect(url);
|
||||
assertThat(wrappedResponse.securityContext).isNull();
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo(url);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void outputFlushSavesSecurityContext() throws Exception {
|
||||
wrappedResponse.getOutputStream().flush();
|
||||
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
|
||||
}
|
||||
@Test
|
||||
public void outputFlushSavesSecurityContext() throws Exception {
|
||||
wrappedResponse.getOutputStream().flush();
|
||||
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void outputFlushSkipsSaveSecurityContextDisables() throws Exception {
|
||||
wrappedResponse.disableSaveOnResponseCommitted();
|
||||
wrappedResponse.getOutputStream().flush();
|
||||
assertThat(wrappedResponse.securityContext).isNull();
|
||||
}
|
||||
@Test
|
||||
public void outputFlushSkipsSaveSecurityContextDisables() throws Exception {
|
||||
wrappedResponse.disableSaveOnResponseCommitted();
|
||||
wrappedResponse.getOutputStream().flush();
|
||||
assertThat(wrappedResponse.securityContext).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void outputCloseSavesSecurityContext() throws Exception {
|
||||
wrappedResponse.getOutputStream().close();
|
||||
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
|
||||
}
|
||||
@Test
|
||||
public void outputCloseSavesSecurityContext() throws Exception {
|
||||
wrappedResponse.getOutputStream().close();
|
||||
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void outputCloseSkipsSaveSecurityContextDisables() throws Exception {
|
||||
wrappedResponse.disableSaveOnResponseCommitted();
|
||||
wrappedResponse.getOutputStream().close();
|
||||
assertThat(wrappedResponse.securityContext).isNull();
|
||||
}
|
||||
@Test
|
||||
public void outputCloseSkipsSaveSecurityContextDisables() throws Exception {
|
||||
wrappedResponse.disableSaveOnResponseCommitted();
|
||||
wrappedResponse.getOutputStream().close();
|
||||
assertThat(wrappedResponse.securityContext).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writerFlushSavesSecurityContext() throws Exception {
|
||||
wrappedResponse.getWriter().flush();
|
||||
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
|
||||
}
|
||||
@Test
|
||||
public void writerFlushSavesSecurityContext() throws Exception {
|
||||
wrappedResponse.getWriter().flush();
|
||||
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writerFlushSkipsSaveSecurityContextDisables() throws Exception {
|
||||
wrappedResponse.disableSaveOnResponseCommitted();
|
||||
wrappedResponse.getWriter().flush();
|
||||
assertThat(wrappedResponse.securityContext).isNull();
|
||||
}
|
||||
@Test
|
||||
public void writerFlushSkipsSaveSecurityContextDisables() throws Exception {
|
||||
wrappedResponse.disableSaveOnResponseCommitted();
|
||||
wrappedResponse.getWriter().flush();
|
||||
assertThat(wrappedResponse.securityContext).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writerCloseSavesSecurityContext() throws Exception {
|
||||
wrappedResponse.getWriter().close();
|
||||
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
|
||||
}
|
||||
@Test
|
||||
public void writerCloseSavesSecurityContext() throws Exception {
|
||||
wrappedResponse.getWriter().close();
|
||||
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writerCloseSkipsSaveSecurityContextDisables() throws Exception {
|
||||
wrappedResponse.disableSaveOnResponseCommitted();
|
||||
wrappedResponse.getWriter().close();
|
||||
assertThat(wrappedResponse.securityContext).isNull();
|
||||
}
|
||||
@Test
|
||||
public void writerCloseSkipsSaveSecurityContextDisables() throws Exception {
|
||||
wrappedResponse.disableSaveOnResponseCommitted();
|
||||
wrappedResponse.getWriter().close();
|
||||
assertThat(wrappedResponse.securityContext).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void flushBufferSavesSecurityContext() throws Exception {
|
||||
wrappedResponse.flushBuffer();
|
||||
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
|
||||
}
|
||||
@Test
|
||||
public void flushBufferSavesSecurityContext() throws Exception {
|
||||
wrappedResponse.flushBuffer();
|
||||
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void flushBufferSkipsSaveSecurityContextDisables() throws Exception {
|
||||
wrappedResponse.disableSaveOnResponseCommitted();
|
||||
wrappedResponse.flushBuffer();
|
||||
assertThat(wrappedResponse.securityContext).isNull();
|
||||
}
|
||||
@Test
|
||||
public void flushBufferSkipsSaveSecurityContextDisables() throws Exception {
|
||||
wrappedResponse.disableSaveOnResponseCommitted();
|
||||
wrappedResponse.flushBuffer();
|
||||
assertThat(wrappedResponse.securityContext).isNull();
|
||||
}
|
||||
|
||||
private static class SaveContextOnUpdateOrErrorResponseWrapperStub extends SaveContextOnUpdateOrErrorResponseWrapper {
|
||||
private SecurityContext securityContext;
|
||||
private static class SaveContextOnUpdateOrErrorResponseWrapperStub extends
|
||||
SaveContextOnUpdateOrErrorResponseWrapper {
|
||||
private SecurityContext securityContext;
|
||||
|
||||
public SaveContextOnUpdateOrErrorResponseWrapperStub(HttpServletResponse response, boolean disableUrlRewriting) {
|
||||
super(response, disableUrlRewriting);
|
||||
}
|
||||
public SaveContextOnUpdateOrErrorResponseWrapperStub(
|
||||
HttpServletResponse response, boolean disableUrlRewriting) {
|
||||
super(response, disableUrlRewriting);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void saveContext(SecurityContext context) {
|
||||
securityContext = context;
|
||||
}
|
||||
}
|
||||
@Override
|
||||
protected void saveContext(SecurityContext context) {
|
||||
securityContext = context;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,102 +20,114 @@ 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() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
@After
|
||||
public void clearContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void contextIsClearedAfterChainProceeds() throws Exception {
|
||||
final FilterChain chain = mock(FilterChain.class);
|
||||
final MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
@Test
|
||||
public void contextIsClearedAfterChainProceeds() throws Exception {
|
||||
final FilterChain chain = mock(FilterChain.class);
|
||||
final MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
|
||||
SecurityContextHolder.getContext().setAuthentication(testToken);
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
filter.doFilter(request, response, chain);
|
||||
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void contextIsStillClearedIfExceptionIsThrowByFilterChain() throws Exception {
|
||||
final FilterChain chain = mock(FilterChain.class);
|
||||
final MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
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));
|
||||
try {
|
||||
filter.doFilter(request, response, chain);
|
||||
fail();
|
||||
} catch(IOException expected) {
|
||||
}
|
||||
@Test
|
||||
public void contextIsStillClearedIfExceptionIsThrowByFilterChain() throws Exception {
|
||||
final FilterChain chain = mock(FilterChain.class);
|
||||
final MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
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));
|
||||
try {
|
||||
filter.doFilter(request, response, chain);
|
||||
fail();
|
||||
}
|
||||
catch (IOException expected) {
|
||||
}
|
||||
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
assertNull(SecurityContextHolder.getContext().getAuthentication());
|
||||
}
|
||||
|
||||
@Test
|
||||
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 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);
|
||||
@Test
|
||||
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 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);
|
||||
|
||||
when(repo.loadContext(any(HttpRequestResponseHolder.class))).thenReturn(scBefore);
|
||||
when(repo.loadContext(any(HttpRequestResponseHolder.class))).thenReturn(scBefore);
|
||||
|
||||
final FilterChain chain = new FilterChain() {
|
||||
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
|
||||
assertEquals(beforeAuth, SecurityContextHolder.getContext().getAuthentication());
|
||||
// Change the context here
|
||||
SecurityContextHolder.setContext(scExpectedAfter);
|
||||
}
|
||||
};
|
||||
final FilterChain chain = new FilterChain() {
|
||||
public void doFilter(ServletRequest request, ServletResponse response)
|
||||
throws IOException, ServletException {
|
||||
assertEquals(beforeAuth, SecurityContextHolder.getContext()
|
||||
.getAuthentication());
|
||||
// Change the context here
|
||||
SecurityContextHolder.setContext(scExpectedAfter);
|
||||
}
|
||||
};
|
||||
|
||||
filter.doFilter(request, response, chain);
|
||||
filter.doFilter(request, response, chain);
|
||||
|
||||
verify(repo).saveContext(scExpectedAfter, request, response);
|
||||
}
|
||||
verify(repo).saveContext(scExpectedAfter, request, response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterIsNotAppliedAgainIfFilterAppliedAttributeIsSet() throws Exception {
|
||||
final FilterChain chain = mock(FilterChain.class);
|
||||
final MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(mock(SecurityContextRepository.class));
|
||||
@Test
|
||||
public void filterIsNotAppliedAgainIfFilterAppliedAttributeIsSet() throws Exception {
|
||||
final FilterChain chain = mock(FilterChain.class);
|
||||
final MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(
|
||||
mock(SecurityContextRepository.class));
|
||||
|
||||
request.setAttribute(SecurityContextPersistenceFilter.FILTER_APPLIED, Boolean.TRUE);
|
||||
filter.doFilter(request, response, chain);
|
||||
verify(chain).doFilter(request, response);
|
||||
}
|
||||
request.setAttribute(SecurityContextPersistenceFilter.FILTER_APPLIED,
|
||||
Boolean.TRUE);
|
||||
filter.doFilter(request, response, chain);
|
||||
verify(chain).doFilter(request, response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sessionIsEagerlyCreatedWhenConfigured() throws Exception {
|
||||
final FilterChain chain = mock(FilterChain.class);
|
||||
final MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
|
||||
filter.setForceEagerSessionCreation(true);
|
||||
filter.doFilter(request, response, chain);
|
||||
assertNotNull(request.getSession(false));
|
||||
}
|
||||
@Test
|
||||
public void sessionIsEagerlyCreatedWhenConfigured() throws Exception {
|
||||
final FilterChain chain = mock(FilterChain.class);
|
||||
final MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
final MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
|
||||
filter.setForceEagerSessionCreation(true);
|
||||
filter.doFilter(request, response, chain);
|
||||
assertNotNull(request.getSession(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
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);
|
||||
filter.doFilter(request, response, chain);
|
||||
assertFalse(repo.containsContext(request));
|
||||
assertNull(request.getSession(false));
|
||||
}
|
||||
@Test
|
||||
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);
|
||||
filter.doFilter(request, response, chain);
|
||||
assertFalse(repo.containsContext(request));
|
||||
assertNull(request.getSession(false));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,46 +32,46 @@ import org.springframework.web.context.request.NativeWebRequest;
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class SecurityContextCallableProcessingInterceptorTests {
|
||||
@Mock
|
||||
private SecurityContext securityContext;
|
||||
@Mock
|
||||
private Callable<?> callable;
|
||||
@Mock
|
||||
private NativeWebRequest webRequest;
|
||||
@Mock
|
||||
private SecurityContext securityContext;
|
||||
@Mock
|
||||
private Callable<?> callable;
|
||||
@Mock
|
||||
private NativeWebRequest webRequest;
|
||||
|
||||
@After
|
||||
public void clearSecurityContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
@After
|
||||
public void clearSecurityContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNull() {
|
||||
new SecurityContextCallableProcessingInterceptor(null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNull() {
|
||||
new SecurityContextCallableProcessingInterceptor(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void currentSecurityContext() throws Exception {
|
||||
SecurityContextCallableProcessingInterceptor interceptor = new SecurityContextCallableProcessingInterceptor();
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
interceptor.beforeConcurrentHandling(webRequest, callable);
|
||||
SecurityContextHolder.clearContext();
|
||||
@Test
|
||||
public void currentSecurityContext() throws Exception {
|
||||
SecurityContextCallableProcessingInterceptor interceptor = new SecurityContextCallableProcessingInterceptor();
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
interceptor.beforeConcurrentHandling(webRequest, callable);
|
||||
SecurityContextHolder.clearContext();
|
||||
|
||||
interceptor.preProcess(webRequest, callable);
|
||||
assertThat(SecurityContextHolder.getContext()).isSameAs(securityContext);
|
||||
interceptor.preProcess(webRequest, callable);
|
||||
assertThat(SecurityContextHolder.getContext()).isSameAs(securityContext);
|
||||
|
||||
interceptor.postProcess(webRequest, callable, null);
|
||||
assertThat(SecurityContextHolder.getContext()).isNotSameAs(securityContext);
|
||||
}
|
||||
interceptor.postProcess(webRequest, callable, null);
|
||||
assertThat(SecurityContextHolder.getContext()).isNotSameAs(securityContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void specificSecurityContext() throws Exception {
|
||||
SecurityContextCallableProcessingInterceptor interceptor = new SecurityContextCallableProcessingInterceptor(
|
||||
securityContext);
|
||||
@Test
|
||||
public void specificSecurityContext() throws Exception {
|
||||
SecurityContextCallableProcessingInterceptor interceptor = new SecurityContextCallableProcessingInterceptor(
|
||||
securityContext);
|
||||
|
||||
interceptor.preProcess(webRequest, callable);
|
||||
assertThat(SecurityContextHolder.getContext()).isSameAs(securityContext);
|
||||
interceptor.preProcess(webRequest, callable);
|
||||
assertThat(SecurityContextHolder.getContext()).isSameAs(securityContext);
|
||||
|
||||
interceptor.postProcess(webRequest, callable, null);
|
||||
assertThat(SecurityContextHolder.getContext()).isNotSameAs(securityContext);
|
||||
}
|
||||
interceptor.postProcess(webRequest, callable, null);
|
||||
assertThat(SecurityContextHolder.getContext()).isNotSameAs(securityContext);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,7 +37,6 @@ import org.springframework.web.context.request.async.CallableProcessingIntercept
|
||||
import org.springframework.web.context.request.async.WebAsyncManager;
|
||||
import org.springframework.web.context.request.async.WebAsyncUtils;
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
@@ -45,99 +44,107 @@ import org.springframework.web.context.request.async.WebAsyncUtils;
|
||||
*/
|
||||
@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;
|
||||
@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;
|
||||
private MockFilterChain filterChain;
|
||||
|
||||
private WebAsyncManagerIntegrationFilter filter;
|
||||
private WebAsyncManagerIntegrationFilter filter;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
when(asyncWebRequest.getNativeRequest(HttpServletRequest.class)).thenReturn(request);
|
||||
when(request.getRequestURI()).thenReturn("/");
|
||||
filterChain = new MockFilterChain();
|
||||
@Before
|
||||
public void setUp() {
|
||||
when(asyncWebRequest.getNativeRequest(HttpServletRequest.class)).thenReturn(
|
||||
request);
|
||||
when(request.getRequestURI()).thenReturn("/");
|
||||
filterChain = new MockFilterChain();
|
||||
|
||||
threadFactory = new JoinableThreadFactory();
|
||||
SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor();
|
||||
executor.setThreadFactory(threadFactory);
|
||||
threadFactory = new JoinableThreadFactory();
|
||||
SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor();
|
||||
executor.setThreadFactory(threadFactory);
|
||||
|
||||
asyncManager = WebAsyncUtils.getAsyncManager(request);
|
||||
asyncManager.setAsyncWebRequest(asyncWebRequest);
|
||||
asyncManager.setTaskExecutor(executor);
|
||||
when(request.getAttribute(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE)).thenReturn(asyncManager);
|
||||
asyncManager = WebAsyncUtils.getAsyncManager(request);
|
||||
asyncManager.setAsyncWebRequest(asyncWebRequest);
|
||||
asyncManager.setTaskExecutor(executor);
|
||||
when(request.getAttribute(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE)).thenReturn(
|
||||
asyncManager);
|
||||
|
||||
filter = new WebAsyncManagerIntegrationFilter();
|
||||
}
|
||||
filter = new WebAsyncManagerIntegrationFilter();
|
||||
}
|
||||
|
||||
@After
|
||||
public void clearSecurityContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
@After
|
||||
public void clearSecurityContext() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterInternalRegistersSecurityContextCallableProcessor() throws Exception {
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
asyncManager.registerCallableInterceptors(new CallableProcessingInterceptorAdapter() {
|
||||
@Override
|
||||
public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult)
|
||||
throws Exception {
|
||||
assertThat(SecurityContextHolder.getContext()).isNotSameAs(securityContext);
|
||||
}
|
||||
});
|
||||
filter.doFilterInternal(request, response, filterChain);
|
||||
@Test
|
||||
public void doFilterInternalRegistersSecurityContextCallableProcessor()
|
||||
throws Exception {
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
asyncManager
|
||||
.registerCallableInterceptors(new CallableProcessingInterceptorAdapter() {
|
||||
@Override
|
||||
public <T> void postProcess(NativeWebRequest request,
|
||||
Callable<T> task, Object concurrentResult) throws Exception {
|
||||
assertThat(SecurityContextHolder.getContext()).isNotSameAs(
|
||||
securityContext);
|
||||
}
|
||||
});
|
||||
filter.doFilterInternal(request, response, filterChain);
|
||||
|
||||
VerifyingCallable verifyingCallable = new VerifyingCallable();
|
||||
asyncManager.startCallableProcessing(verifyingCallable);
|
||||
threadFactory.join();
|
||||
assertThat(asyncManager.getConcurrentResult()).isSameAs(securityContext);
|
||||
}
|
||||
VerifyingCallable verifyingCallable = new VerifyingCallable();
|
||||
asyncManager.startCallableProcessing(verifyingCallable);
|
||||
threadFactory.join();
|
||||
assertThat(asyncManager.getConcurrentResult()).isSameAs(securityContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
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)
|
||||
throws Exception {
|
||||
assertThat(SecurityContextHolder.getContext()).isNotSameAs(securityContext);
|
||||
}
|
||||
});
|
||||
filter.doFilterInternal(request, response, filterChain);
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
@Test
|
||||
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) throws Exception {
|
||||
assertThat(SecurityContextHolder.getContext()).isNotSameAs(
|
||||
securityContext);
|
||||
}
|
||||
});
|
||||
filter.doFilterInternal(request, response, filterChain);
|
||||
SecurityContextHolder.setContext(securityContext);
|
||||
|
||||
VerifyingCallable verifyingCallable = new VerifyingCallable();
|
||||
asyncManager.startCallableProcessing(verifyingCallable);
|
||||
threadFactory.join();
|
||||
assertThat(asyncManager.getConcurrentResult()).isSameAs(securityContext);
|
||||
}
|
||||
VerifyingCallable verifyingCallable = new VerifyingCallable();
|
||||
asyncManager.startCallableProcessing(verifyingCallable);
|
||||
threadFactory.join();
|
||||
assertThat(asyncManager.getConcurrentResult()).isSameAs(securityContext);
|
||||
}
|
||||
|
||||
private static final class JoinableThreadFactory implements ThreadFactory {
|
||||
private Thread t;
|
||||
private static final class JoinableThreadFactory implements ThreadFactory {
|
||||
private Thread t;
|
||||
|
||||
public Thread newThread(Runnable r) {
|
||||
t = new Thread(r);
|
||||
return t;
|
||||
}
|
||||
public Thread newThread(Runnable r) {
|
||||
t = new Thread(r);
|
||||
return t;
|
||||
}
|
||||
|
||||
public void join() throws InterruptedException {
|
||||
t.join();
|
||||
}
|
||||
}
|
||||
public void join() throws InterruptedException {
|
||||
t.join();
|
||||
}
|
||||
}
|
||||
|
||||
private class VerifyingCallable implements Callable<SecurityContext> {
|
||||
private class VerifyingCallable implements Callable<SecurityContext> {
|
||||
|
||||
public SecurityContext call() throws Exception {
|
||||
return SecurityContextHolder.getContext();
|
||||
}
|
||||
public SecurityContext call() throws Exception {
|
||||
return SecurityContextHolder.getContext();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,69 +40,80 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class CsrfAuthenticationStrategyTests {
|
||||
@Mock
|
||||
private CsrfTokenRepository csrfTokenRepository;
|
||||
@Mock
|
||||
private CsrfTokenRepository csrfTokenRepository;
|
||||
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletRequest request;
|
||||
|
||||
private MockHttpServletResponse response;
|
||||
private MockHttpServletResponse response;
|
||||
|
||||
private CsrfAuthenticationStrategy strategy;
|
||||
private CsrfAuthenticationStrategy strategy;
|
||||
|
||||
private CsrfToken existingToken;
|
||||
private CsrfToken existingToken;
|
||||
|
||||
private CsrfToken generatedToken;
|
||||
private CsrfToken generatedToken;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
strategy = new CsrfAuthenticationStrategy(csrfTokenRepository);
|
||||
existingToken = new DefaultCsrfToken("_csrf", "_csrf", "1");
|
||||
generatedToken = new DefaultCsrfToken("_csrf", "_csrf", "2");
|
||||
}
|
||||
@Before
|
||||
public void setup() {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
strategy = new CsrfAuthenticationStrategy(csrfTokenRepository);
|
||||
existingToken = new DefaultCsrfToken("_csrf", "_csrf", "1");
|
||||
generatedToken = new DefaultCsrfToken("_csrf", "_csrf", "2");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullCsrfTokenRepository() {
|
||||
new CsrfAuthenticationStrategy(null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullCsrfTokenRepository() {
|
||||
new CsrfAuthenticationStrategy(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void logoutRemovesCsrfTokenAndSavesNew() {
|
||||
when(csrfTokenRepository.loadToken(request)).thenReturn(existingToken);
|
||||
when(csrfTokenRepository.generateToken(request)).thenReturn(generatedToken);
|
||||
strategy.onAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"), request, response);
|
||||
@Test
|
||||
public void logoutRemovesCsrfTokenAndSavesNew() {
|
||||
when(csrfTokenRepository.loadToken(request)).thenReturn(existingToken);
|
||||
when(csrfTokenRepository.generateToken(request)).thenReturn(generatedToken);
|
||||
strategy.onAuthentication(new TestingAuthenticationToken("user", "password",
|
||||
"ROLE_USER"), request, response);
|
||||
|
||||
verify(csrfTokenRepository).saveToken(null, request, response);
|
||||
verify(csrfTokenRepository,never()).saveToken(eq(generatedToken), any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
// SEC-2404, SEC-2832
|
||||
CsrfToken tokenInRequest = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
|
||||
assertThat(tokenInRequest.getToken()).isSameAs(generatedToken.getToken());
|
||||
assertThat(tokenInRequest.getHeaderName()).isSameAs(generatedToken.getHeaderName());
|
||||
assertThat(tokenInRequest.getParameterName()).isSameAs(generatedToken.getParameterName());
|
||||
assertThat(request.getAttribute(generatedToken.getParameterName())).isSameAs(tokenInRequest);
|
||||
}
|
||||
verify(csrfTokenRepository).saveToken(null, request, response);
|
||||
verify(csrfTokenRepository, never()).saveToken(eq(generatedToken),
|
||||
any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
// SEC-2404, SEC-2832
|
||||
CsrfToken tokenInRequest = (CsrfToken) request.getAttribute(CsrfToken.class
|
||||
.getName());
|
||||
assertThat(tokenInRequest.getToken()).isSameAs(generatedToken.getToken());
|
||||
assertThat(tokenInRequest.getHeaderName()).isSameAs(
|
||||
generatedToken.getHeaderName());
|
||||
assertThat(tokenInRequest.getParameterName()).isSameAs(
|
||||
generatedToken.getParameterName());
|
||||
assertThat(request.getAttribute(generatedToken.getParameterName())).isSameAs(
|
||||
tokenInRequest);
|
||||
}
|
||||
|
||||
// SEC-2872
|
||||
@Test
|
||||
public void delaySavingCsrf() {
|
||||
when(csrfTokenRepository.loadToken(request)).thenReturn(existingToken);
|
||||
when(csrfTokenRepository.generateToken(request)).thenReturn(generatedToken);
|
||||
strategy.onAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"), request, response);
|
||||
// SEC-2872
|
||||
@Test
|
||||
public void delaySavingCsrf() {
|
||||
when(csrfTokenRepository.loadToken(request)).thenReturn(existingToken);
|
||||
when(csrfTokenRepository.generateToken(request)).thenReturn(generatedToken);
|
||||
strategy.onAuthentication(new TestingAuthenticationToken("user", "password",
|
||||
"ROLE_USER"), request, response);
|
||||
|
||||
verify(csrfTokenRepository).saveToken(null, request, response);
|
||||
verify(csrfTokenRepository,never()).saveToken(eq(generatedToken), any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
verify(csrfTokenRepository).saveToken(null, request, response);
|
||||
verify(csrfTokenRepository, never()).saveToken(eq(generatedToken),
|
||||
any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
|
||||
CsrfToken tokenInRequest = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
|
||||
tokenInRequest.getToken();
|
||||
verify(csrfTokenRepository).saveToken(eq(generatedToken), any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
}
|
||||
CsrfToken tokenInRequest = (CsrfToken) request.getAttribute(CsrfToken.class
|
||||
.getName());
|
||||
tokenInRequest.getToken();
|
||||
verify(csrfTokenRepository).saveToken(eq(generatedToken),
|
||||
any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void logoutRemovesNoActionIfNullToken() {
|
||||
strategy.onAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"), request, response);
|
||||
@Test
|
||||
public void logoutRemovesNoActionIfNullToken() {
|
||||
strategy.onAuthentication(new TestingAuthenticationToken("user", "password",
|
||||
"ROLE_USER"), request, response);
|
||||
|
||||
verify(csrfTokenRepository,never()).saveToken(any(CsrfToken.class), any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
}
|
||||
verify(csrfTokenRepository, never()).saveToken(any(CsrfToken.class),
|
||||
any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -50,366 +50,333 @@ import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
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;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
token = new DefaultCsrfToken("headerName", "paramName",
|
||||
"csrfTokenValue");
|
||||
resetRequestResponse();
|
||||
filter = new CsrfFilter(tokenRepository);
|
||||
filter.setRequireCsrfProtectionMatcher(requestMatcher);
|
||||
filter.setAccessDeniedHandler(deniedHandler);
|
||||
}
|
||||
|
||||
private void resetRequestResponse() {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullRepository() {
|
||||
new CsrfFilter(null);
|
||||
}
|
||||
|
||||
// SEC-2276
|
||||
@Test
|
||||
public void doFilterDoesNotSaveCsrfTokenUntilAccessed() throws ServletException,
|
||||
IOException {
|
||||
when(requestMatcher.matches(request)).thenReturn(false);
|
||||
when(tokenRepository.generateToken(request)).thenReturn(token);
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
CsrfToken attrToken = (CsrfToken) request.getAttribute(token.getParameterName());
|
||||
|
||||
// no CsrfToken should have been saved yet
|
||||
verify(tokenRepository,times(0)).saveToken(any(CsrfToken.class), any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
verify(filterChain).doFilter(request, response);
|
||||
|
||||
// access the token
|
||||
attrToken.getToken();
|
||||
|
||||
// now the CsrfToken should have been saved
|
||||
verify(tokenRepository).saveToken(eq(token), any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterAccessDeniedNoTokenPresent() throws ServletException,
|
||||
IOException {
|
||||
when(requestMatcher.matches(request)).thenReturn(true);
|
||||
when(tokenRepository.loadToken(request)).thenReturn(token);
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(
|
||||
token);
|
||||
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(
|
||||
token);
|
||||
|
||||
verify(deniedHandler).handle(eq(request), eq(response),
|
||||
any(InvalidCsrfTokenException.class));
|
||||
verifyZeroInteractions(filterChain);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterAccessDeniedIncorrectTokenPresent()
|
||||
throws ServletException, IOException {
|
||||
when(requestMatcher.matches(request)).thenReturn(true);
|
||||
when(tokenRepository.loadToken(request)).thenReturn(token);
|
||||
request.setParameter(token.getParameterName(), token.getToken()
|
||||
+ " INVALID");
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(
|
||||
token);
|
||||
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(
|
||||
token);
|
||||
|
||||
verify(deniedHandler).handle(eq(request), eq(response),
|
||||
any(InvalidCsrfTokenException.class));
|
||||
verifyZeroInteractions(filterChain);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterAccessDeniedIncorrectTokenPresentHeader()
|
||||
throws ServletException, IOException {
|
||||
when(requestMatcher.matches(request)).thenReturn(true);
|
||||
when(tokenRepository.loadToken(request)).thenReturn(token);
|
||||
request.addHeader(token.getHeaderName(), token.getToken() + " INVALID");
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(
|
||||
token);
|
||||
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(
|
||||
token);
|
||||
|
||||
verify(deniedHandler).handle(eq(request), eq(response),
|
||||
any(InvalidCsrfTokenException.class));
|
||||
verifyZeroInteractions(filterChain);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterAccessDeniedIncorrectTokenPresentHeaderPreferredOverParameter()
|
||||
throws ServletException, IOException {
|
||||
when(requestMatcher.matches(request)).thenReturn(true);
|
||||
when(tokenRepository.loadToken(request)).thenReturn(token);
|
||||
request.setParameter(token.getParameterName(), token.getToken());
|
||||
request.addHeader(token.getHeaderName(), token.getToken() + " INVALID");
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(
|
||||
token);
|
||||
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(
|
||||
token);
|
||||
|
||||
verify(deniedHandler).handle(eq(request), eq(response),
|
||||
any(InvalidCsrfTokenException.class));
|
||||
verifyZeroInteractions(filterChain);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterNotCsrfRequestExistingToken() throws ServletException,
|
||||
IOException {
|
||||
when(requestMatcher.matches(request)).thenReturn(false);
|
||||
when(tokenRepository.loadToken(request)).thenReturn(token);
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(
|
||||
token);
|
||||
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(
|
||||
token);
|
||||
|
||||
verify(filterChain).doFilter(request, response);
|
||||
verifyZeroInteractions(deniedHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterNotCsrfRequestGenerateToken() throws ServletException,
|
||||
IOException {
|
||||
when(requestMatcher.matches(request)).thenReturn(false);
|
||||
when(tokenRepository.generateToken(request))
|
||||
.thenReturn(token);
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
assertToken(request.getAttribute(token.getParameterName())).isEqualTo(
|
||||
token);
|
||||
assertToken(request.getAttribute(CsrfToken.class.getName())).isEqualTo(
|
||||
token);
|
||||
|
||||
verify(filterChain).doFilter(request, response);
|
||||
verifyZeroInteractions(deniedHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterIsCsrfRequestExistingTokenHeader()
|
||||
throws ServletException, IOException {
|
||||
when(requestMatcher.matches(request)).thenReturn(true);
|
||||
when(tokenRepository.loadToken(request)).thenReturn(token);
|
||||
request.addHeader(token.getHeaderName(), token.getToken());
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(
|
||||
token);
|
||||
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(
|
||||
token);
|
||||
|
||||
verify(filterChain).doFilter(request, response);
|
||||
verifyZeroInteractions(deniedHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterIsCsrfRequestExistingTokenHeaderPreferredOverInvalidParam()
|
||||
throws ServletException, IOException {
|
||||
when(requestMatcher.matches(request)).thenReturn(true);
|
||||
when(tokenRepository.loadToken(request)).thenReturn(token);
|
||||
request.setParameter(token.getParameterName(), token.getToken()
|
||||
+ " INVALID");
|
||||
request.addHeader(token.getHeaderName(), token.getToken());
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(
|
||||
token);
|
||||
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(
|
||||
token);
|
||||
|
||||
verify(filterChain).doFilter(request, response);
|
||||
verifyZeroInteractions(deniedHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterIsCsrfRequestExistingToken() throws ServletException,
|
||||
IOException {
|
||||
when(requestMatcher.matches(request)).thenReturn(true);
|
||||
when(tokenRepository.loadToken(request)).thenReturn(token);
|
||||
request.setParameter(token.getParameterName(), token.getToken());
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(
|
||||
token);
|
||||
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(
|
||||
token);
|
||||
|
||||
verify(filterChain).doFilter(request, response);
|
||||
verifyZeroInteractions(deniedHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterIsCsrfRequestGenerateToken() throws ServletException,
|
||||
IOException {
|
||||
when(requestMatcher.matches(request)).thenReturn(true);
|
||||
when(tokenRepository.generateToken(request))
|
||||
.thenReturn(token);
|
||||
request.setParameter(token.getParameterName(), token.getToken());
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
assertToken(request.getAttribute(token.getParameterName())).isEqualTo(
|
||||
token);
|
||||
assertToken(request.getAttribute(CsrfToken.class.getName())).isEqualTo(
|
||||
token);
|
||||
|
||||
verify(filterChain).doFilter(request, response);
|
||||
verifyZeroInteractions(deniedHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterDefaultRequireCsrfProtectionMatcherAllowedMethods()
|
||||
throws ServletException, IOException {
|
||||
filter = new CsrfFilter(tokenRepository);
|
||||
filter.setAccessDeniedHandler(deniedHandler);
|
||||
|
||||
for (String method : Arrays.asList("GET", "TRACE", "OPTIONS", "HEAD")) {
|
||||
resetRequestResponse();
|
||||
when(tokenRepository.loadToken(request)).thenReturn(token);
|
||||
request.setMethod(method);
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
verify(filterChain).doFilter(request, response);
|
||||
verifyZeroInteractions(deniedHandler);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* SEC-2292 Should not allow other cases through since spec states HTTP
|
||||
* method is case sensitive
|
||||
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.1
|
||||
*
|
||||
* @throws ServletException
|
||||
* @throws IOException
|
||||
*/
|
||||
@Test
|
||||
public void doFilterDefaultRequireCsrfProtectionMatcherAllowedMethodsCaseSensitive()
|
||||
throws ServletException, IOException {
|
||||
filter = new CsrfFilter(tokenRepository);
|
||||
filter.setAccessDeniedHandler(deniedHandler);
|
||||
|
||||
for (String method : Arrays.asList("get", "TrAcE", "oPTIOnS", "hEaD")) {
|
||||
resetRequestResponse();
|
||||
when(tokenRepository.loadToken(request)).thenReturn(token);
|
||||
request.setMethod(method);
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
verify(deniedHandler).handle(eq(request), eq(response),
|
||||
any(InvalidCsrfTokenException.class));
|
||||
verifyZeroInteractions(filterChain);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterDefaultRequireCsrfProtectionMatcherDeniedMethods()
|
||||
throws ServletException, IOException {
|
||||
filter = new CsrfFilter(tokenRepository);
|
||||
filter.setAccessDeniedHandler(deniedHandler);
|
||||
|
||||
for (String method : Arrays.asList("POST", "PUT", "PATCH", "DELETE",
|
||||
"INVALID")) {
|
||||
resetRequestResponse();
|
||||
when(tokenRepository.loadToken(request)).thenReturn(token);
|
||||
request.setMethod(method);
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
verify(deniedHandler).handle(eq(request), eq(response),
|
||||
any(InvalidCsrfTokenException.class));
|
||||
verifyZeroInteractions(filterChain);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterDefaultAccessDenied() throws ServletException,
|
||||
IOException {
|
||||
filter = new CsrfFilter(tokenRepository);
|
||||
filter.setRequireCsrfProtectionMatcher(requestMatcher);
|
||||
when(requestMatcher.matches(request)).thenReturn(true);
|
||||
when(tokenRepository.loadToken(request)).thenReturn(token);
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(
|
||||
token);
|
||||
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(
|
||||
token);
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(
|
||||
HttpServletResponse.SC_FORBIDDEN);
|
||||
verifyZeroInteractions(filterChain);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setRequireCsrfProtectionMatcherNull() {
|
||||
filter.setRequireCsrfProtectionMatcher(null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setAccessDeniedHandlerNull() {
|
||||
filter.setAccessDeniedHandler(null);
|
||||
}
|
||||
|
||||
private static final CsrfTokenAssert assertToken(Object token) {
|
||||
return new CsrfTokenAssert((CsrfToken)token);
|
||||
}
|
||||
|
||||
private static class CsrfTokenAssert extends
|
||||
GenericAssert<CsrfTokenAssert, CsrfToken> {
|
||||
|
||||
/**
|
||||
* Creates a new </code>{@link ObjectAssert}</code>.
|
||||
*
|
||||
* @param actual
|
||||
* the target to verify.
|
||||
*/
|
||||
protected CsrfTokenAssert(CsrfToken actual) {
|
||||
super(CsrfTokenAssert.class, actual);
|
||||
}
|
||||
|
||||
public CsrfTokenAssert isEqualTo(CsrfToken expected) {
|
||||
assertThat(actual.getHeaderName()).isEqualTo(expected.getHeaderName());
|
||||
assertThat(actual.getParameterName()).isEqualTo(expected.getParameterName());
|
||||
assertThat(actual.getToken()).isEqualTo(expected.getToken());
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@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;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
token = new DefaultCsrfToken("headerName", "paramName", "csrfTokenValue");
|
||||
resetRequestResponse();
|
||||
filter = new CsrfFilter(tokenRepository);
|
||||
filter.setRequireCsrfProtectionMatcher(requestMatcher);
|
||||
filter.setAccessDeniedHandler(deniedHandler);
|
||||
}
|
||||
|
||||
private void resetRequestResponse() {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullRepository() {
|
||||
new CsrfFilter(null);
|
||||
}
|
||||
|
||||
// SEC-2276
|
||||
@Test
|
||||
public void doFilterDoesNotSaveCsrfTokenUntilAccessed() throws ServletException,
|
||||
IOException {
|
||||
when(requestMatcher.matches(request)).thenReturn(false);
|
||||
when(tokenRepository.generateToken(request)).thenReturn(token);
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
CsrfToken attrToken = (CsrfToken) request.getAttribute(token.getParameterName());
|
||||
|
||||
// no CsrfToken should have been saved yet
|
||||
verify(tokenRepository, times(0)).saveToken(any(CsrfToken.class),
|
||||
any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
verify(filterChain).doFilter(request, response);
|
||||
|
||||
// access the token
|
||||
attrToken.getToken();
|
||||
|
||||
// now the CsrfToken should have been saved
|
||||
verify(tokenRepository).saveToken(eq(token), any(HttpServletRequest.class),
|
||||
any(HttpServletResponse.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterAccessDeniedNoTokenPresent() throws ServletException, IOException {
|
||||
when(requestMatcher.matches(request)).thenReturn(true);
|
||||
when(tokenRepository.loadToken(request)).thenReturn(token);
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(token);
|
||||
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(token);
|
||||
|
||||
verify(deniedHandler).handle(eq(request), eq(response),
|
||||
any(InvalidCsrfTokenException.class));
|
||||
verifyZeroInteractions(filterChain);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterAccessDeniedIncorrectTokenPresent() throws ServletException,
|
||||
IOException {
|
||||
when(requestMatcher.matches(request)).thenReturn(true);
|
||||
when(tokenRepository.loadToken(request)).thenReturn(token);
|
||||
request.setParameter(token.getParameterName(), token.getToken() + " INVALID");
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(token);
|
||||
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(token);
|
||||
|
||||
verify(deniedHandler).handle(eq(request), eq(response),
|
||||
any(InvalidCsrfTokenException.class));
|
||||
verifyZeroInteractions(filterChain);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterAccessDeniedIncorrectTokenPresentHeader()
|
||||
throws ServletException, IOException {
|
||||
when(requestMatcher.matches(request)).thenReturn(true);
|
||||
when(tokenRepository.loadToken(request)).thenReturn(token);
|
||||
request.addHeader(token.getHeaderName(), token.getToken() + " INVALID");
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(token);
|
||||
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(token);
|
||||
|
||||
verify(deniedHandler).handle(eq(request), eq(response),
|
||||
any(InvalidCsrfTokenException.class));
|
||||
verifyZeroInteractions(filterChain);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterAccessDeniedIncorrectTokenPresentHeaderPreferredOverParameter()
|
||||
throws ServletException, IOException {
|
||||
when(requestMatcher.matches(request)).thenReturn(true);
|
||||
when(tokenRepository.loadToken(request)).thenReturn(token);
|
||||
request.setParameter(token.getParameterName(), token.getToken());
|
||||
request.addHeader(token.getHeaderName(), token.getToken() + " INVALID");
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(token);
|
||||
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(token);
|
||||
|
||||
verify(deniedHandler).handle(eq(request), eq(response),
|
||||
any(InvalidCsrfTokenException.class));
|
||||
verifyZeroInteractions(filterChain);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterNotCsrfRequestExistingToken() throws ServletException,
|
||||
IOException {
|
||||
when(requestMatcher.matches(request)).thenReturn(false);
|
||||
when(tokenRepository.loadToken(request)).thenReturn(token);
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(token);
|
||||
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(token);
|
||||
|
||||
verify(filterChain).doFilter(request, response);
|
||||
verifyZeroInteractions(deniedHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterNotCsrfRequestGenerateToken() throws ServletException,
|
||||
IOException {
|
||||
when(requestMatcher.matches(request)).thenReturn(false);
|
||||
when(tokenRepository.generateToken(request)).thenReturn(token);
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
assertToken(request.getAttribute(token.getParameterName())).isEqualTo(token);
|
||||
assertToken(request.getAttribute(CsrfToken.class.getName())).isEqualTo(token);
|
||||
|
||||
verify(filterChain).doFilter(request, response);
|
||||
verifyZeroInteractions(deniedHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterIsCsrfRequestExistingTokenHeader() throws ServletException,
|
||||
IOException {
|
||||
when(requestMatcher.matches(request)).thenReturn(true);
|
||||
when(tokenRepository.loadToken(request)).thenReturn(token);
|
||||
request.addHeader(token.getHeaderName(), token.getToken());
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(token);
|
||||
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(token);
|
||||
|
||||
verify(filterChain).doFilter(request, response);
|
||||
verifyZeroInteractions(deniedHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterIsCsrfRequestExistingTokenHeaderPreferredOverInvalidParam()
|
||||
throws ServletException, IOException {
|
||||
when(requestMatcher.matches(request)).thenReturn(true);
|
||||
when(tokenRepository.loadToken(request)).thenReturn(token);
|
||||
request.setParameter(token.getParameterName(), token.getToken() + " INVALID");
|
||||
request.addHeader(token.getHeaderName(), token.getToken());
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(token);
|
||||
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(token);
|
||||
|
||||
verify(filterChain).doFilter(request, response);
|
||||
verifyZeroInteractions(deniedHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterIsCsrfRequestExistingToken() throws ServletException, IOException {
|
||||
when(requestMatcher.matches(request)).thenReturn(true);
|
||||
when(tokenRepository.loadToken(request)).thenReturn(token);
|
||||
request.setParameter(token.getParameterName(), token.getToken());
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(token);
|
||||
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(token);
|
||||
|
||||
verify(filterChain).doFilter(request, response);
|
||||
verifyZeroInteractions(deniedHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterIsCsrfRequestGenerateToken() throws ServletException, IOException {
|
||||
when(requestMatcher.matches(request)).thenReturn(true);
|
||||
when(tokenRepository.generateToken(request)).thenReturn(token);
|
||||
request.setParameter(token.getParameterName(), token.getToken());
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
assertToken(request.getAttribute(token.getParameterName())).isEqualTo(token);
|
||||
assertToken(request.getAttribute(CsrfToken.class.getName())).isEqualTo(token);
|
||||
|
||||
verify(filterChain).doFilter(request, response);
|
||||
verifyZeroInteractions(deniedHandler);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterDefaultRequireCsrfProtectionMatcherAllowedMethods()
|
||||
throws ServletException, IOException {
|
||||
filter = new CsrfFilter(tokenRepository);
|
||||
filter.setAccessDeniedHandler(deniedHandler);
|
||||
|
||||
for (String method : Arrays.asList("GET", "TRACE", "OPTIONS", "HEAD")) {
|
||||
resetRequestResponse();
|
||||
when(tokenRepository.loadToken(request)).thenReturn(token);
|
||||
request.setMethod(method);
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
verify(filterChain).doFilter(request, response);
|
||||
verifyZeroInteractions(deniedHandler);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* SEC-2292 Should not allow other cases through since spec states HTTP method is case
|
||||
* sensitive http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.1
|
||||
*
|
||||
* @throws ServletException
|
||||
* @throws IOException
|
||||
*/
|
||||
@Test
|
||||
public void doFilterDefaultRequireCsrfProtectionMatcherAllowedMethodsCaseSensitive()
|
||||
throws ServletException, IOException {
|
||||
filter = new CsrfFilter(tokenRepository);
|
||||
filter.setAccessDeniedHandler(deniedHandler);
|
||||
|
||||
for (String method : Arrays.asList("get", "TrAcE", "oPTIOnS", "hEaD")) {
|
||||
resetRequestResponse();
|
||||
when(tokenRepository.loadToken(request)).thenReturn(token);
|
||||
request.setMethod(method);
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
verify(deniedHandler).handle(eq(request), eq(response),
|
||||
any(InvalidCsrfTokenException.class));
|
||||
verifyZeroInteractions(filterChain);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterDefaultRequireCsrfProtectionMatcherDeniedMethods()
|
||||
throws ServletException, IOException {
|
||||
filter = new CsrfFilter(tokenRepository);
|
||||
filter.setAccessDeniedHandler(deniedHandler);
|
||||
|
||||
for (String method : Arrays.asList("POST", "PUT", "PATCH", "DELETE", "INVALID")) {
|
||||
resetRequestResponse();
|
||||
when(tokenRepository.loadToken(request)).thenReturn(token);
|
||||
request.setMethod(method);
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
verify(deniedHandler).handle(eq(request), eq(response),
|
||||
any(InvalidCsrfTokenException.class));
|
||||
verifyZeroInteractions(filterChain);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterDefaultAccessDenied() throws ServletException, IOException {
|
||||
filter = new CsrfFilter(tokenRepository);
|
||||
filter.setRequireCsrfProtectionMatcher(requestMatcher);
|
||||
when(requestMatcher.matches(request)).thenReturn(true);
|
||||
when(tokenRepository.loadToken(request)).thenReturn(token);
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
assertThat(request.getAttribute(token.getParameterName())).isEqualTo(token);
|
||||
assertThat(request.getAttribute(CsrfToken.class.getName())).isEqualTo(token);
|
||||
|
||||
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
|
||||
verifyZeroInteractions(filterChain);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setRequireCsrfProtectionMatcherNull() {
|
||||
filter.setRequireCsrfProtectionMatcher(null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setAccessDeniedHandlerNull() {
|
||||
filter.setAccessDeniedHandler(null);
|
||||
}
|
||||
|
||||
private static final CsrfTokenAssert assertToken(Object token) {
|
||||
return new CsrfTokenAssert((CsrfToken) token);
|
||||
}
|
||||
|
||||
private static class CsrfTokenAssert extends
|
||||
GenericAssert<CsrfTokenAssert, CsrfToken> {
|
||||
|
||||
/**
|
||||
* Creates a new </code>{@link ObjectAssert}</code>.
|
||||
*
|
||||
* @param actual the target to verify.
|
||||
*/
|
||||
protected CsrfTokenAssert(CsrfToken actual) {
|
||||
super(CsrfTokenAssert.class, actual);
|
||||
}
|
||||
|
||||
public CsrfTokenAssert isEqualTo(CsrfToken expected) {
|
||||
assertThat(actual.getHeaderName()).isEqualTo(expected.getHeaderName());
|
||||
assertThat(actual.getParameterName()).isEqualTo(expected.getParameterName());
|
||||
assertThat(actual.getToken()).isEqualTo(expected.getToken());
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,32 +32,33 @@ import org.springframework.security.authentication.TestingAuthenticationToken;
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class CsrfLogoutHandlerTests {
|
||||
@Mock
|
||||
private CsrfTokenRepository csrfTokenRepository;
|
||||
@Mock
|
||||
private CsrfTokenRepository csrfTokenRepository;
|
||||
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletRequest request;
|
||||
|
||||
private MockHttpServletResponse response;
|
||||
private MockHttpServletResponse response;
|
||||
|
||||
private CsrfLogoutHandler handler;
|
||||
private CsrfLogoutHandler handler;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
handler = new CsrfLogoutHandler(csrfTokenRepository);
|
||||
}
|
||||
@Before
|
||||
public void setup() {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
handler = new CsrfLogoutHandler(csrfTokenRepository);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullCsrfTokenRepository() {
|
||||
new CsrfLogoutHandler(null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullCsrfTokenRepository() {
|
||||
new CsrfLogoutHandler(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void logoutRemovesCsrfToken() {
|
||||
handler.logout(request, response, new TestingAuthenticationToken("user", "password", "ROLE_USER"));
|
||||
@Test
|
||||
public void logoutRemovesCsrfToken() {
|
||||
handler.logout(request, response, new TestingAuthenticationToken("user",
|
||||
"password", "ROLE_USER"));
|
||||
|
||||
verify(csrfTokenRepository).saveToken(null, request, response);
|
||||
}
|
||||
verify(csrfTokenRepository).saveToken(null, request, response);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -22,37 +22,37 @@ import org.junit.Test;
|
||||
*
|
||||
*/
|
||||
public class DefaultCsrfTokenTests {
|
||||
private final String headerName = "headerName";
|
||||
private final String parameterName = "parameterName";
|
||||
private final String tokenValue = "tokenValue";
|
||||
private final String headerName = "headerName";
|
||||
private final String parameterName = "parameterName";
|
||||
private final String tokenValue = "tokenValue";
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullHeaderName() {
|
||||
new DefaultCsrfToken(null,parameterName, tokenValue);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullHeaderName() {
|
||||
new DefaultCsrfToken(null, parameterName, tokenValue);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorEmptyHeaderName() {
|
||||
new DefaultCsrfToken("",parameterName, tokenValue);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorEmptyHeaderName() {
|
||||
new DefaultCsrfToken("", parameterName, tokenValue);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullParameterName() {
|
||||
new DefaultCsrfToken(headerName,null, tokenValue);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullParameterName() {
|
||||
new DefaultCsrfToken(headerName, null, tokenValue);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorEmptyParameterName() {
|
||||
new DefaultCsrfToken(headerName,"", tokenValue);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorEmptyParameterName() {
|
||||
new DefaultCsrfToken(headerName, "", tokenValue);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullTokenValue() {
|
||||
new DefaultCsrfToken(headerName,parameterName, null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullTokenValue() {
|
||||
new DefaultCsrfToken(headerName, parameterName, null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorEmptyTokenValue() {
|
||||
new DefaultCsrfToken(headerName,parameterName, "");
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorEmptyTokenValue() {
|
||||
new DefaultCsrfToken(headerName, parameterName, "");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,127 +27,124 @@ import org.springframework.mock.web.MockHttpServletResponse;
|
||||
*
|
||||
*/
|
||||
public class HttpSessionCsrfTokenRepositoryTests {
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletRequest request;
|
||||
|
||||
private MockHttpServletResponse response;
|
||||
private MockHttpServletResponse response;
|
||||
|
||||
private CsrfToken token;
|
||||
private HttpSessionCsrfTokenRepository repo;
|
||||
private CsrfToken token;
|
||||
private HttpSessionCsrfTokenRepository repo;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
repo = new HttpSessionCsrfTokenRepository();
|
||||
}
|
||||
@Before
|
||||
public void setup() {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
repo = new HttpSessionCsrfTokenRepository();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void generateToken() {
|
||||
token = repo.generateToken(request);
|
||||
@Test
|
||||
public void generateToken() {
|
||||
token = repo.generateToken(request);
|
||||
|
||||
assertThat(token.getParameterName()).isEqualTo("_csrf");
|
||||
assertThat(token.getToken()).isNotEmpty();
|
||||
assertThat(token.getParameterName()).isEqualTo("_csrf");
|
||||
assertThat(token.getToken()).isNotEmpty();
|
||||
|
||||
CsrfToken loadedToken = repo.loadToken(request);
|
||||
CsrfToken loadedToken = repo.loadToken(request);
|
||||
|
||||
assertThat(loadedToken).isNull();
|
||||
}
|
||||
assertThat(loadedToken).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void generateCustomParameter() {
|
||||
String paramName = "_csrf";
|
||||
repo.setParameterName(paramName);
|
||||
@Test
|
||||
public void generateCustomParameter() {
|
||||
String paramName = "_csrf";
|
||||
repo.setParameterName(paramName);
|
||||
|
||||
token = repo.generateToken(request);
|
||||
token = repo.generateToken(request);
|
||||
|
||||
assertThat(token.getParameterName()).isEqualTo(paramName);
|
||||
assertThat(token.getToken()).isNotEmpty();
|
||||
}
|
||||
assertThat(token.getParameterName()).isEqualTo(paramName);
|
||||
assertThat(token.getToken()).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void generateCustomHeader() {
|
||||
String headerName = "CSRF";
|
||||
repo.setHeaderName(headerName);
|
||||
@Test
|
||||
public void generateCustomHeader() {
|
||||
String headerName = "CSRF";
|
||||
repo.setHeaderName(headerName);
|
||||
|
||||
token = repo.generateToken(request);
|
||||
token = repo.generateToken(request);
|
||||
|
||||
assertThat(token.getHeaderName()).isEqualTo(headerName);
|
||||
assertThat(token.getToken()).isNotEmpty();
|
||||
}
|
||||
assertThat(token.getHeaderName()).isEqualTo(headerName);
|
||||
assertThat(token.getToken()).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadTokenNull() {
|
||||
assertThat(repo.loadToken(request)).isNull();
|
||||
assertThat(request.getSession(false)).isNull();
|
||||
}
|
||||
@Test
|
||||
public void loadTokenNull() {
|
||||
assertThat(repo.loadToken(request)).isNull();
|
||||
assertThat(request.getSession(false)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadTokenNullWhenSessionExists() {
|
||||
request.getSession();
|
||||
assertThat(repo.loadToken(request)).isNull();
|
||||
}
|
||||
@Test
|
||||
public void loadTokenNullWhenSessionExists() {
|
||||
request.getSession();
|
||||
assertThat(repo.loadToken(request)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void saveToken() {
|
||||
CsrfToken tokenToSave = new DefaultCsrfToken("123", "abc", "def");
|
||||
repo.saveToken(tokenToSave, request, response);
|
||||
@Test
|
||||
public void saveToken() {
|
||||
CsrfToken tokenToSave = new DefaultCsrfToken("123", "abc", "def");
|
||||
repo.saveToken(tokenToSave, request, response);
|
||||
|
||||
String attrName = request.getSession().getAttributeNames()
|
||||
.nextElement();
|
||||
CsrfToken loadedToken = (CsrfToken) request.getSession().getAttribute(
|
||||
attrName);
|
||||
String attrName = request.getSession().getAttributeNames().nextElement();
|
||||
CsrfToken loadedToken = (CsrfToken) request.getSession().getAttribute(attrName);
|
||||
|
||||
assertThat(loadedToken).isEqualTo(tokenToSave);
|
||||
}
|
||||
assertThat(loadedToken).isEqualTo(tokenToSave);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void saveTokenCustomSessionAttribute() {
|
||||
CsrfToken tokenToSave = new DefaultCsrfToken("123", "abc", "def");
|
||||
String sessionAttributeName = "custom";
|
||||
repo.setSessionAttributeName(sessionAttributeName);
|
||||
repo.saveToken(tokenToSave, request, response);
|
||||
@Test
|
||||
public void saveTokenCustomSessionAttribute() {
|
||||
CsrfToken tokenToSave = new DefaultCsrfToken("123", "abc", "def");
|
||||
String sessionAttributeName = "custom";
|
||||
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);
|
||||
}
|
||||
assertThat(loadedToken).isEqualTo(tokenToSave);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void saveTokenNullToken() {
|
||||
saveToken();
|
||||
@Test
|
||||
public void saveTokenNullToken() {
|
||||
saveToken();
|
||||
|
||||
repo.saveToken(null, request, response);
|
||||
repo.saveToken(null, request, response);
|
||||
|
||||
assertThat(request.getSession().getAttributeNames().hasMoreElements())
|
||||
.isFalse();
|
||||
}
|
||||
assertThat(request.getSession().getAttributeNames().hasMoreElements()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void saveTokenNullTokenWhenSessionNotExists() {
|
||||
@Test
|
||||
public void saveTokenNullTokenWhenSessionNotExists() {
|
||||
|
||||
repo.saveToken(null, request, response);
|
||||
repo.saveToken(null, request, response);
|
||||
|
||||
assertThat(request.getSession(false)).isNull();
|
||||
}
|
||||
assertThat(request.getSession(false)).isNull();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setSessionAttributeNameEmpty() {
|
||||
repo.setSessionAttributeName("");
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setSessionAttributeNameEmpty() {
|
||||
repo.setSessionAttributeName("");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setSessionAttributeNameNull() {
|
||||
repo.setSessionAttributeName(null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setSessionAttributeNameNull() {
|
||||
repo.setSessionAttributeName(null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setParameterNameEmpty() {
|
||||
repo.setParameterName("");
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setParameterNameEmpty() {
|
||||
repo.setParameterName("");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setParameterNameNull() {
|
||||
repo.setParameterName(null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setParameterNameNull() {
|
||||
repo.setParameterName(null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,10 +24,10 @@ import org.junit.Test;
|
||||
*/
|
||||
public class MissingCsrfTokenExceptionTests {
|
||||
|
||||
// CsrfChannelInterceptor requires this to work
|
||||
@Test
|
||||
public void nullExpectedTokenDoesNotFail() {
|
||||
new MissingCsrfTokenException(null);
|
||||
}
|
||||
// CsrfChannelInterceptor requires this to work
|
||||
@Test
|
||||
public void nullExpectedTokenDoesNotFail() {
|
||||
new MissingCsrfTokenException(null);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -35,94 +35,90 @@ import org.springframework.security.web.FilterChainProxy;
|
||||
@RunWith(PowerMockRunner.class)
|
||||
@PrepareOnlyThisForTest(Logger.class)
|
||||
public class DebugFilterTest {
|
||||
@Captor
|
||||
private ArgumentCaptor<HttpServletRequest> requestCaptor;
|
||||
@Captor
|
||||
private ArgumentCaptor<String> logCaptor;
|
||||
@Captor
|
||||
private ArgumentCaptor<HttpServletRequest> requestCaptor;
|
||||
@Captor
|
||||
private ArgumentCaptor<String> logCaptor;
|
||||
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
@Mock
|
||||
private HttpServletResponse response;
|
||||
@Mock
|
||||
private FilterChain filterChain;
|
||||
@Mock
|
||||
private FilterChainProxy fcp;
|
||||
@Mock
|
||||
private Logger logger;
|
||||
@Mock
|
||||
private HttpServletRequest request;
|
||||
@Mock
|
||||
private HttpServletResponse response;
|
||||
@Mock
|
||||
private FilterChain filterChain;
|
||||
@Mock
|
||||
private FilterChainProxy fcp;
|
||||
@Mock
|
||||
private Logger logger;
|
||||
|
||||
private String requestAttr;
|
||||
private String requestAttr;
|
||||
|
||||
private DebugFilter filter;
|
||||
private DebugFilter filter;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
when(request.getHeaderNames()).thenReturn(Collections.enumeration(Collections.<String>emptyList()));
|
||||
when(request.getServletPath()).thenReturn("/login");
|
||||
filter = new DebugFilter(fcp);
|
||||
WhiteboxImpl.setInternalState(filter, Logger.class, logger);
|
||||
requestAttr = WhiteboxImpl.getInternalState(filter, "ALREADY_FILTERED_ATTR_NAME", filter.getClass());
|
||||
}
|
||||
@Before
|
||||
public void setUp() {
|
||||
when(request.getHeaderNames()).thenReturn(
|
||||
Collections.enumeration(Collections.<String> emptyList()));
|
||||
when(request.getServletPath()).thenReturn("/login");
|
||||
filter = new DebugFilter(fcp);
|
||||
WhiteboxImpl.setInternalState(filter, Logger.class, logger);
|
||||
requestAttr = WhiteboxImpl.getInternalState(filter, "ALREADY_FILTERED_ATTR_NAME",
|
||||
filter.getClass());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterProcessesRequests() throws Exception {
|
||||
filter.doFilter(request, response, filterChain);
|
||||
@Test
|
||||
public void doFilterProcessesRequests() throws Exception {
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
verify(logger).info(anyString());
|
||||
verify(request).setAttribute(requestAttr, Boolean.TRUE);
|
||||
verify(fcp).doFilter(requestCaptor.capture(), eq(response), eq(filterChain));
|
||||
assertEquals(DebugRequestWrapper.class,requestCaptor.getValue().getClass());
|
||||
verify(request).removeAttribute(requestAttr);
|
||||
}
|
||||
verify(logger).info(anyString());
|
||||
verify(request).setAttribute(requestAttr, Boolean.TRUE);
|
||||
verify(fcp).doFilter(requestCaptor.capture(), eq(response), eq(filterChain));
|
||||
assertEquals(DebugRequestWrapper.class, requestCaptor.getValue().getClass());
|
||||
verify(request).removeAttribute(requestAttr);
|
||||
}
|
||||
|
||||
// SEC-1901
|
||||
@Test
|
||||
public void doFilterProcessesForwardedRequests() throws Exception {
|
||||
when(request.getAttribute(requestAttr)).thenReturn(Boolean.TRUE);
|
||||
HttpServletRequest request = new DebugRequestWrapper(this.request);
|
||||
// SEC-1901
|
||||
@Test
|
||||
public void doFilterProcessesForwardedRequests() throws Exception {
|
||||
when(request.getAttribute(requestAttr)).thenReturn(Boolean.TRUE);
|
||||
HttpServletRequest request = new DebugRequestWrapper(this.request);
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
verify(logger).info(anyString());
|
||||
verify(fcp).doFilter(request, response, filterChain);
|
||||
verify(this.request,never()).removeAttribute(requestAttr);
|
||||
}
|
||||
verify(logger).info(anyString());
|
||||
verify(fcp).doFilter(request, response, filterChain);
|
||||
verify(this.request, never()).removeAttribute(requestAttr);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterDoesNotWrapWithDebugRequestWrapperAgain() throws Exception {
|
||||
when(request.getAttribute(requestAttr)).thenReturn(Boolean.TRUE);
|
||||
HttpServletRequest fireWalledRequest = new HttpServletRequestWrapper(new DebugRequestWrapper(this.request));
|
||||
@Test
|
||||
public void doFilterDoesNotWrapWithDebugRequestWrapperAgain() throws Exception {
|
||||
when(request.getAttribute(requestAttr)).thenReturn(Boolean.TRUE);
|
||||
HttpServletRequest fireWalledRequest = new HttpServletRequestWrapper(
|
||||
new DebugRequestWrapper(this.request));
|
||||
|
||||
filter.doFilter(fireWalledRequest, response, filterChain);
|
||||
filter.doFilter(fireWalledRequest, response, filterChain);
|
||||
|
||||
verify(fcp).doFilter(fireWalledRequest, response, filterChain);
|
||||
}
|
||||
verify(fcp).doFilter(fireWalledRequest, response, filterChain);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterLogsProperly() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setMethod("GET");
|
||||
request.setServletPath("/path");
|
||||
request.setPathInfo("/");
|
||||
request.addHeader("A", "A Value");
|
||||
request.addHeader("A", "Another Value");
|
||||
request.addHeader("B", "B Value");
|
||||
@Test
|
||||
public void doFilterLogsProperly() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setMethod("GET");
|
||||
request.setServletPath("/path");
|
||||
request.setPathInfo("/");
|
||||
request.addHeader("A", "A Value");
|
||||
request.addHeader("A", "Another Value");
|
||||
request.addHeader("B", "B Value");
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
verify(logger).info(logCaptor.capture());
|
||||
verify(logger).info(logCaptor.capture());
|
||||
|
||||
assertThat(logCaptor.getValue()).isEqualTo("Request received for GET '/path/':\n" +
|
||||
"\n" +
|
||||
request + "\n" +
|
||||
"\n" +
|
||||
"servletPath:/path\n" +
|
||||
"pathInfo:/\n" +
|
||||
"headers: \n" +
|
||||
"A: A Value, Another Value\n" +
|
||||
"B: B Value\n" +
|
||||
"\n" +
|
||||
"\n" +
|
||||
"Security filter chain: no match");
|
||||
}
|
||||
assertThat(logCaptor.getValue()).isEqualTo(
|
||||
"Request received for GET '/path/':\n" + "\n" + request + "\n" + "\n"
|
||||
+ "servletPath:/path\n" + "pathInfo:/\n" + "headers: \n"
|
||||
+ "A: A Value, Another Value\n" + "B: B Value\n" + "\n" + "\n"
|
||||
+ "Security filter chain: no match");
|
||||
}
|
||||
}
|
||||
@@ -9,36 +9,30 @@ import org.springframework.mock.web.MockHttpServletRequest;
|
||||
* @author Luke Taylor
|
||||
*/
|
||||
public class DefaultHttpFirewallTests {
|
||||
public String[] unnormalizedPaths = {
|
||||
"/..",
|
||||
"/./path/",
|
||||
"/path/path/.",
|
||||
"/path/path//.",
|
||||
"./path/../path//.",
|
||||
"./path",
|
||||
".//path",
|
||||
"."
|
||||
};
|
||||
public String[] unnormalizedPaths = { "/..", "/./path/", "/path/path/.",
|
||||
"/path/path//.", "./path/../path//.", "./path", ".//path", "." };
|
||||
|
||||
@Test
|
||||
public void unnormalizedPathsAreRejected() throws Exception {
|
||||
DefaultHttpFirewall fw = new DefaultHttpFirewall();
|
||||
@Test
|
||||
public void unnormalizedPathsAreRejected() throws Exception {
|
||||
DefaultHttpFirewall fw = new DefaultHttpFirewall();
|
||||
|
||||
MockHttpServletRequest request;
|
||||
for (String path : unnormalizedPaths) {
|
||||
request = new MockHttpServletRequest();
|
||||
request.setServletPath(path);
|
||||
try {
|
||||
fw.getFirewalledRequest(request);
|
||||
fail(path + " is un-normalized");
|
||||
} catch (RequestRejectedException expected) {
|
||||
}
|
||||
request.setPathInfo(path);
|
||||
try {
|
||||
fw.getFirewalledRequest(request);
|
||||
fail(path + " is un-normalized");
|
||||
} catch (RequestRejectedException expected) {
|
||||
}
|
||||
}
|
||||
}
|
||||
MockHttpServletRequest request;
|
||||
for (String path : unnormalizedPaths) {
|
||||
request = new MockHttpServletRequest();
|
||||
request.setServletPath(path);
|
||||
try {
|
||||
fw.getFirewalledRequest(request);
|
||||
fail(path + " is un-normalized");
|
||||
}
|
||||
catch (RequestRejectedException expected) {
|
||||
}
|
||||
request.setPathInfo(path);
|
||||
try {
|
||||
fw.getFirewalledRequest(request);
|
||||
fail(path + " is un-normalized");
|
||||
}
|
||||
catch (RequestRejectedException expected) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,29 +11,32 @@ import org.springframework.mock.web.MockHttpServletResponse;
|
||||
*/
|
||||
public class FirewalledResponseTests {
|
||||
|
||||
@Test
|
||||
public void rejectsRedirectLocationContaingCRLF() throws Exception {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FirewalledResponse fwResponse = new FirewalledResponse(response);
|
||||
@Test
|
||||
public void rejectsRedirectLocationContaingCRLF() throws Exception {
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
FirewalledResponse fwResponse = new FirewalledResponse(response);
|
||||
|
||||
fwResponse.sendRedirect("/theURL");
|
||||
assertEquals("/theURL", response.getRedirectedUrl());
|
||||
fwResponse.sendRedirect("/theURL");
|
||||
assertEquals("/theURL", response.getRedirectedUrl());
|
||||
|
||||
try {
|
||||
fwResponse.sendRedirect("/theURL\r\nsomething");
|
||||
fail();
|
||||
} catch (IllegalArgumentException expected) {
|
||||
}
|
||||
try {
|
||||
fwResponse.sendRedirect("/theURL\rsomething");
|
||||
fail();
|
||||
} catch (IllegalArgumentException expected) {
|
||||
}
|
||||
try {
|
||||
fwResponse.sendRedirect("/theURL\r\nsomething");
|
||||
fail();
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
try {
|
||||
fwResponse.sendRedirect("/theURL\rsomething");
|
||||
fail();
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
|
||||
try {
|
||||
fwResponse.sendRedirect("/theURL\nsomething");
|
||||
fail();
|
||||
} catch (IllegalArgumentException expected) {
|
||||
}
|
||||
}
|
||||
try {
|
||||
fwResponse.sendRedirect("/theURL\nsomething");
|
||||
fail();
|
||||
}
|
||||
catch (IllegalArgumentException expected) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,86 +18,86 @@ import org.springframework.mock.web.MockHttpServletRequest;
|
||||
* @author Luke Taylor
|
||||
*/
|
||||
public class RequestWrapperTests {
|
||||
private static Map<String, String> testPaths = new LinkedHashMap<String,String>();
|
||||
private static Map<String, String> testPaths = new LinkedHashMap<String, String>();
|
||||
|
||||
@BeforeClass
|
||||
// Some of these may be unrealistic values, but we can't be sure because of the
|
||||
// inconsistency in the spec.
|
||||
public static void createTestMap() {
|
||||
testPaths.put("/path1;x=y;z=w/path2;x=y/path3;x=y", "/path1/path2/path3");
|
||||
testPaths.put("/path1;x=y/path2;x=y/", "/path1/path2/");
|
||||
testPaths.put("/path1//path2/", "/path1/path2/");
|
||||
testPaths.put("//path1/path2//", "/path1/path2/");
|
||||
testPaths.put(";x=y;z=w", "");
|
||||
}
|
||||
@BeforeClass
|
||||
// Some of these may be unrealistic values, but we can't be sure because of the
|
||||
// inconsistency in the spec.
|
||||
public static void createTestMap() {
|
||||
testPaths.put("/path1;x=y;z=w/path2;x=y/path3;x=y", "/path1/path2/path3");
|
||||
testPaths.put("/path1;x=y/path2;x=y/", "/path1/path2/");
|
||||
testPaths.put("/path1//path2/", "/path1/path2/");
|
||||
testPaths.put("//path1/path2//", "/path1/path2/");
|
||||
testPaths.put(";x=y;z=w", "");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void pathParametersAreRemovedFromServletPath() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
@Test
|
||||
public void pathParametersAreRemovedFromServletPath() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
for (Map.Entry<String,String> entry : testPaths.entrySet()) {
|
||||
String path = entry.getKey();
|
||||
String expectedResult = entry.getValue();
|
||||
request.setServletPath(path);
|
||||
RequestWrapper wrapper = new RequestWrapper(request);
|
||||
assertEquals(expectedResult, wrapper.getServletPath());
|
||||
wrapper.reset();
|
||||
assertEquals(path, wrapper.getServletPath());
|
||||
}
|
||||
}
|
||||
for (Map.Entry<String, String> entry : testPaths.entrySet()) {
|
||||
String path = entry.getKey();
|
||||
String expectedResult = entry.getValue();
|
||||
request.setServletPath(path);
|
||||
RequestWrapper wrapper = new RequestWrapper(request);
|
||||
assertEquals(expectedResult, wrapper.getServletPath());
|
||||
wrapper.reset();
|
||||
assertEquals(path, wrapper.getServletPath());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void pathParametersAreRemovedFromPathInfo() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
@Test
|
||||
public void pathParametersAreRemovedFromPathInfo() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
for (Map.Entry<String,String> entry : testPaths.entrySet()) {
|
||||
String path = entry.getKey();
|
||||
String expectedResult = entry.getValue();
|
||||
// Should be null when stripped value is empty
|
||||
if (expectedResult.length() == 0) {
|
||||
expectedResult = null;
|
||||
}
|
||||
request.setPathInfo(path);
|
||||
RequestWrapper wrapper = new RequestWrapper(request);
|
||||
assertEquals(expectedResult, wrapper.getPathInfo());
|
||||
wrapper.reset();
|
||||
assertEquals(path, wrapper.getPathInfo());
|
||||
}
|
||||
}
|
||||
for (Map.Entry<String, String> entry : testPaths.entrySet()) {
|
||||
String path = entry.getKey();
|
||||
String expectedResult = entry.getValue();
|
||||
// Should be null when stripped value is empty
|
||||
if (expectedResult.length() == 0) {
|
||||
expectedResult = null;
|
||||
}
|
||||
request.setPathInfo(path);
|
||||
RequestWrapper wrapper = new RequestWrapper(request);
|
||||
assertEquals(expectedResult, wrapper.getPathInfo());
|
||||
wrapper.reset();
|
||||
assertEquals(path, wrapper.getPathInfo());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resetWhenForward() throws Exception {
|
||||
String denormalizedPath = testPaths.keySet().iterator().next();
|
||||
String forwardPath = "/forward/path";
|
||||
HttpServletRequest mockRequest = mock(HttpServletRequest.class);
|
||||
HttpServletResponse mockResponse = mock(HttpServletResponse.class);
|
||||
RequestDispatcher mockDispatcher = mock(RequestDispatcher.class);
|
||||
when(mockRequest.getServletPath()).thenReturn("");
|
||||
when(mockRequest.getPathInfo()).thenReturn(denormalizedPath);
|
||||
when(mockRequest.getRequestDispatcher(forwardPath)).thenReturn(mockDispatcher);
|
||||
@Test
|
||||
public void resetWhenForward() throws Exception {
|
||||
String denormalizedPath = testPaths.keySet().iterator().next();
|
||||
String forwardPath = "/forward/path";
|
||||
HttpServletRequest mockRequest = mock(HttpServletRequest.class);
|
||||
HttpServletResponse mockResponse = mock(HttpServletResponse.class);
|
||||
RequestDispatcher mockDispatcher = mock(RequestDispatcher.class);
|
||||
when(mockRequest.getServletPath()).thenReturn("");
|
||||
when(mockRequest.getPathInfo()).thenReturn(denormalizedPath);
|
||||
when(mockRequest.getRequestDispatcher(forwardPath)).thenReturn(mockDispatcher);
|
||||
|
||||
RequestWrapper wrapper = new RequestWrapper(mockRequest);
|
||||
RequestDispatcher dispatcher = wrapper.getRequestDispatcher(forwardPath);
|
||||
dispatcher.forward(mockRequest, mockResponse);
|
||||
RequestWrapper wrapper = new RequestWrapper(mockRequest);
|
||||
RequestDispatcher dispatcher = wrapper.getRequestDispatcher(forwardPath);
|
||||
dispatcher.forward(mockRequest, mockResponse);
|
||||
|
||||
verify(mockRequest).getRequestDispatcher(forwardPath);
|
||||
verify(mockDispatcher).forward(mockRequest, mockResponse);
|
||||
assertEquals(denormalizedPath,wrapper.getPathInfo());
|
||||
verify(mockRequest,times(2)).getPathInfo();
|
||||
// validate wrapper.getServletPath() delegates to the mock
|
||||
wrapper.getServletPath();
|
||||
verify(mockRequest,times(2)).getServletPath();
|
||||
verifyNoMoreInteractions(mockRequest,mockResponse,mockDispatcher);
|
||||
}
|
||||
verify(mockRequest).getRequestDispatcher(forwardPath);
|
||||
verify(mockDispatcher).forward(mockRequest, mockResponse);
|
||||
assertEquals(denormalizedPath, wrapper.getPathInfo());
|
||||
verify(mockRequest, times(2)).getPathInfo();
|
||||
// validate wrapper.getServletPath() delegates to the mock
|
||||
wrapper.getServletPath();
|
||||
verify(mockRequest, times(2)).getServletPath();
|
||||
verifyNoMoreInteractions(mockRequest, mockResponse, mockDispatcher);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestDispatcherNotWrappedAfterReset() {
|
||||
String path = "/forward/path";
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
RequestDispatcher dispatcher = mock(RequestDispatcher.class);
|
||||
when(request.getRequestDispatcher(path)).thenReturn(dispatcher);
|
||||
RequestWrapper wrapper = new RequestWrapper(request);
|
||||
wrapper.reset();
|
||||
assertSame(dispatcher, wrapper.getRequestDispatcher(path));
|
||||
}
|
||||
@Test
|
||||
public void requestDispatcherNotWrappedAfterReset() {
|
||||
String path = "/forward/path";
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
RequestDispatcher dispatcher = mock(RequestDispatcher.class);
|
||||
when(request.getRequestDispatcher(path)).thenReturn(dispatcher);
|
||||
RequestWrapper wrapper = new RequestWrapper(request);
|
||||
wrapper.reset();
|
||||
assertSame(dispatcher, wrapper.getRequestDispatcher(path));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,39 +40,40 @@ import org.springframework.security.web.header.HeaderWriterFilter;
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class HeaderWriterFilterTests {
|
||||
@Mock
|
||||
private HeaderWriter writer1;
|
||||
@Mock
|
||||
private HeaderWriter writer1;
|
||||
|
||||
@Mock
|
||||
private HeaderWriter writer2;
|
||||
@Mock
|
||||
private HeaderWriter writer2;
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void noHeadersConfigured() throws Exception {
|
||||
List<HeaderWriter> headerWriters = new ArrayList<HeaderWriter>();
|
||||
new HeaderWriterFilter(headerWriters);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void noHeadersConfigured() throws Exception {
|
||||
List<HeaderWriter> headerWriters = new ArrayList<HeaderWriter>();
|
||||
new HeaderWriterFilter(headerWriters);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullWriters() throws Exception {
|
||||
new HeaderWriterFilter(null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullWriters() throws Exception {
|
||||
new HeaderWriterFilter(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void additionalHeadersShouldBeAddedToTheResponse() throws Exception {
|
||||
List<HeaderWriter> headerWriters = new ArrayList<HeaderWriter>();
|
||||
headerWriters.add(writer1);
|
||||
headerWriters.add(writer2);
|
||||
@Test
|
||||
public void additionalHeadersShouldBeAddedToTheResponse() throws Exception {
|
||||
List<HeaderWriter> headerWriters = new ArrayList<HeaderWriter>();
|
||||
headerWriters.add(writer1);
|
||||
headerWriters.add(writer2);
|
||||
|
||||
HeaderWriterFilter filter = new HeaderWriterFilter(headerWriters);
|
||||
HeaderWriterFilter filter = new HeaderWriterFilter(headerWriters);
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain filterChain = new MockFilterChain();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
MockFilterChain filterChain = new MockFilterChain();
|
||||
|
||||
filter.doFilter(request, response, filterChain);
|
||||
filter.doFilter(request, response, filterChain);
|
||||
|
||||
verify(writer1).writeHeaders(request, response);
|
||||
verify(writer2).writeHeaders(request, response);
|
||||
assertThat(filterChain.getRequest()).isEqualTo(request); // verify the filterChain continued
|
||||
}
|
||||
verify(writer1).writeHeaders(request, response);
|
||||
verify(writer2).writeHeaders(request, response);
|
||||
assertThat(filterChain.getRequest()).isEqualTo(request); // verify the filterChain
|
||||
// continued
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,26 +30,28 @@ import org.springframework.mock.web.MockHttpServletResponse;
|
||||
*/
|
||||
public class CacheControlHeadersWriterTests {
|
||||
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletRequest request;
|
||||
|
||||
private MockHttpServletResponse response;
|
||||
private MockHttpServletResponse response;
|
||||
|
||||
private CacheControlHeadersWriter writer;
|
||||
private CacheControlHeadersWriter writer;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
writer = new CacheControlHeadersWriter();
|
||||
}
|
||||
@Before
|
||||
public void setup() {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
writer = new CacheControlHeadersWriter();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeaders() {
|
||||
writer.writeHeaders(request, response);
|
||||
@Test
|
||||
public void writeHeaders() {
|
||||
writer.writeHeaders(request, response);
|
||||
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(3);
|
||||
assertThat(response.getHeaderValues("Cache-Control")).isEqualTo(Arrays.asList("no-cache, no-store, max-age=0, must-revalidate"));
|
||||
assertThat(response.getHeaderValues("Pragma")).isEqualTo(Arrays.asList("no-cache"));
|
||||
assertThat(response.getHeaderValues("Expires")).isEqualTo(Arrays.asList("0"));
|
||||
}
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(3);
|
||||
assertThat(response.getHeaderValues("Cache-Control")).isEqualTo(
|
||||
Arrays.asList("no-cache, no-store, max-age=0, must-revalidate"));
|
||||
assertThat(response.getHeaderValues("Pragma")).isEqualTo(
|
||||
Arrays.asList("no-cache"));
|
||||
assertThat(response.getHeaderValues("Expires")).isEqualTo(Arrays.asList("0"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,50 +35,50 @@ import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class DelegatingRequestMatcherHeaderWriterTests {
|
||||
@Mock
|
||||
private RequestMatcher matcher;
|
||||
@Mock
|
||||
private RequestMatcher matcher;
|
||||
|
||||
@Mock
|
||||
private HeaderWriter delegate;
|
||||
@Mock
|
||||
private HeaderWriter delegate;
|
||||
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletRequest request;
|
||||
|
||||
private MockHttpServletResponse response;
|
||||
private MockHttpServletResponse response;
|
||||
|
||||
private DelegatingRequestMatcherHeaderWriter headerWriter;
|
||||
private DelegatingRequestMatcherHeaderWriter headerWriter;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
headerWriter = new DelegatingRequestMatcherHeaderWriter(matcher, delegate);
|
||||
}
|
||||
@Before
|
||||
public void setup() {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
headerWriter = new DelegatingRequestMatcherHeaderWriter(matcher, delegate);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullRequestMatcher() {
|
||||
new DelegatingRequestMatcherHeaderWriter(null, delegate);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullRequestMatcher() {
|
||||
new DelegatingRequestMatcherHeaderWriter(null, delegate);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullDelegate() {
|
||||
new DelegatingRequestMatcherHeaderWriter(matcher, null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullDelegate() {
|
||||
new DelegatingRequestMatcherHeaderWriter(matcher, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersOnMatch() {
|
||||
when(matcher.matches(request)).thenReturn(true);
|
||||
@Test
|
||||
public void writeHeadersOnMatch() {
|
||||
when(matcher.matches(request)).thenReturn(true);
|
||||
|
||||
headerWriter.writeHeaders(request, response);
|
||||
headerWriter.writeHeaders(request, response);
|
||||
|
||||
verify(delegate).writeHeaders(request, response);
|
||||
}
|
||||
verify(delegate).writeHeaders(request, response);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersOnNoMatch() {
|
||||
when(matcher.matches(request)).thenReturn(false);
|
||||
@Test
|
||||
public void writeHeadersOnNoMatch() {
|
||||
when(matcher.matches(request)).thenReturn(false);
|
||||
|
||||
headerWriter.writeHeaders(request, response);
|
||||
headerWriter.writeHeaders(request, response);
|
||||
|
||||
verify(delegate, times(0)).writeHeaders(request, response);
|
||||
}
|
||||
verify(delegate, times(0)).writeHeaders(request, response);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,117 +29,125 @@ import org.springframework.security.web.util.matcher.AnyRequestMatcher;
|
||||
*
|
||||
*/
|
||||
public class HstsHeaderWriterTests {
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletResponse response;
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletResponse response;
|
||||
|
||||
private HstsHeaderWriter writer;
|
||||
private HstsHeaderWriter writer;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
request = new MockHttpServletRequest();
|
||||
request.setSecure(true);
|
||||
response = new MockHttpServletResponse();
|
||||
@Before
|
||||
public void setup() {
|
||||
request = new MockHttpServletRequest();
|
||||
request.setSecure(true);
|
||||
response = new MockHttpServletResponse();
|
||||
|
||||
writer = new HstsHeaderWriter();
|
||||
}
|
||||
writer = new HstsHeaderWriter();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void allArgsCustomConstructorWriteHeaders() {
|
||||
request.setSecure(false);
|
||||
writer = new HstsHeaderWriter(AnyRequestMatcher.INSTANCE, 15768000, false);
|
||||
@Test
|
||||
public void allArgsCustomConstructorWriteHeaders() {
|
||||
request.setSecure(false);
|
||||
writer = new HstsHeaderWriter(AnyRequestMatcher.INSTANCE, 15768000, false);
|
||||
|
||||
writer.writeHeaders(request, response);
|
||||
writer.writeHeaders(request, response);
|
||||
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=15768000");
|
||||
}
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeader("Strict-Transport-Security")).isEqualTo(
|
||||
"max-age=15768000");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void maxAgeAndIncludeSubdomainsCustomConstructorWriteHeaders() {
|
||||
request.setSecure(false);
|
||||
writer = new HstsHeaderWriter(AnyRequestMatcher.INSTANCE, 15768000, false);
|
||||
@Test
|
||||
public void maxAgeAndIncludeSubdomainsCustomConstructorWriteHeaders() {
|
||||
request.setSecure(false);
|
||||
writer = new HstsHeaderWriter(AnyRequestMatcher.INSTANCE, 15768000, false);
|
||||
|
||||
writer.writeHeaders(request, response);
|
||||
writer.writeHeaders(request, response);
|
||||
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=15768000");
|
||||
}
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeader("Strict-Transport-Security")).isEqualTo(
|
||||
"max-age=15768000");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void maxAgeCustomConstructorWriteHeaders() {
|
||||
writer = new HstsHeaderWriter(15768000);
|
||||
@Test
|
||||
public void maxAgeCustomConstructorWriteHeaders() {
|
||||
writer = new HstsHeaderWriter(15768000);
|
||||
|
||||
writer.writeHeaders(request, response);
|
||||
writer.writeHeaders(request, response);
|
||||
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=15768000 ; includeSubDomains");
|
||||
}
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeader("Strict-Transport-Security")).isEqualTo(
|
||||
"max-age=15768000 ; includeSubDomains");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void includeSubDomainsCustomConstructorWriteHeaders() {
|
||||
writer = new HstsHeaderWriter(false);
|
||||
@Test
|
||||
public void includeSubDomainsCustomConstructorWriteHeaders() {
|
||||
writer = new HstsHeaderWriter(false);
|
||||
|
||||
writer.writeHeaders(request, response);
|
||||
writer.writeHeaders(request, response);
|
||||
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=31536000");
|
||||
}
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeader("Strict-Transport-Security")).isEqualTo(
|
||||
"max-age=31536000");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersDefaultValues() {
|
||||
writer.writeHeaders(request, response);
|
||||
@Test
|
||||
public void writeHeadersDefaultValues() {
|
||||
writer.writeHeaders(request, response);
|
||||
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=31536000 ; includeSubDomains");
|
||||
}
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeader("Strict-Transport-Security")).isEqualTo(
|
||||
"max-age=31536000 ; includeSubDomains");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersIncludeSubDomainsFalse() {
|
||||
writer.setIncludeSubDomains(false);
|
||||
@Test
|
||||
public void writeHeadersIncludeSubDomainsFalse() {
|
||||
writer.setIncludeSubDomains(false);
|
||||
|
||||
writer.writeHeaders(request, response);
|
||||
writer.writeHeaders(request, response);
|
||||
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=31536000");
|
||||
}
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeader("Strict-Transport-Security")).isEqualTo(
|
||||
"max-age=31536000");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersCustomMaxAgeInSeconds() {
|
||||
writer.setMaxAgeInSeconds(1);
|
||||
@Test
|
||||
public void writeHeadersCustomMaxAgeInSeconds() {
|
||||
writer.setMaxAgeInSeconds(1);
|
||||
|
||||
writer.writeHeaders(request, response);
|
||||
writer.writeHeaders(request, response);
|
||||
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=1 ; includeSubDomains");
|
||||
}
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeader("Strict-Transport-Security")).isEqualTo(
|
||||
"max-age=1 ; includeSubDomains");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersInsecureRequestDoesNotWriteHeader() {
|
||||
request.setSecure(false);
|
||||
@Test
|
||||
public void writeHeadersInsecureRequestDoesNotWriteHeader() {
|
||||
request.setSecure(false);
|
||||
|
||||
writer.writeHeaders(request, response);
|
||||
writer.writeHeaders(request, response);
|
||||
|
||||
assertThat(response.getHeaderNames().isEmpty()).isTrue();
|
||||
}
|
||||
assertThat(response.getHeaderNames().isEmpty()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersAnyRequestMatcher() {
|
||||
writer.setRequestMatcher(AnyRequestMatcher.INSTANCE);
|
||||
request.setSecure(false);
|
||||
@Test
|
||||
public void writeHeadersAnyRequestMatcher() {
|
||||
writer.setRequestMatcher(AnyRequestMatcher.INSTANCE);
|
||||
request.setSecure(false);
|
||||
|
||||
writer.writeHeaders(request, response);
|
||||
writer.writeHeaders(request, response);
|
||||
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=31536000 ; includeSubDomains");
|
||||
}
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeader("Strict-Transport-Security")).isEqualTo(
|
||||
"max-age=31536000 ; includeSubDomains");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setMaxAgeInSecondsToNegative() {
|
||||
writer.setMaxAgeInSeconds(-1);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setMaxAgeInSecondsToNegative() {
|
||||
writer.setMaxAgeInSeconds(-1);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setRequestMatcherToNull() {
|
||||
writer.setRequestMatcher(null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setRequestMatcherToNull() {
|
||||
writer.setRequestMatcher(null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,60 +35,65 @@ import org.springframework.security.web.header.writers.StaticHeadersWriter;
|
||||
* @since 3.2
|
||||
*/
|
||||
public class StaticHeaderWriterTests {
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletResponse response;
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletResponse response;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
}
|
||||
@Before
|
||||
public void setup() {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullHeaders() {
|
||||
new StaticHeadersWriter(null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullHeaders() {
|
||||
new StaticHeadersWriter(null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorEmptyHeaders() {
|
||||
new StaticHeadersWriter(Collections.<Header>emptyList());
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorEmptyHeaders() {
|
||||
new StaticHeadersWriter(Collections.<Header> emptyList());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullHeaderName() {
|
||||
new StaticHeadersWriter(null, "value1");
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullHeaderName() {
|
||||
new StaticHeadersWriter(null, "value1");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullHeaderValues() {
|
||||
new StaticHeadersWriter("name", (String[]) null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullHeaderValues() {
|
||||
new StaticHeadersWriter("name", (String[]) null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorContainsNullHeaderValue() {
|
||||
new StaticHeadersWriter("name", "value1", null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorContainsNullHeaderValue() {
|
||||
new StaticHeadersWriter("name", "value1", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sameHeaderShouldBeReturned() {
|
||||
String headerName = "X-header";
|
||||
String headerValue = "foo";
|
||||
StaticHeadersWriter factory = new StaticHeadersWriter(headerName, headerValue);
|
||||
@Test
|
||||
public void sameHeaderShouldBeReturned() {
|
||||
String headerName = "X-header";
|
||||
String headerValue = "foo";
|
||||
StaticHeadersWriter factory = new StaticHeadersWriter(headerName, headerValue);
|
||||
|
||||
factory.writeHeaders(request, response);
|
||||
assertThat(response.getHeaderValues(headerName)).isEqualTo(Arrays.asList(headerValue));
|
||||
}
|
||||
factory.writeHeaders(request, response);
|
||||
assertThat(response.getHeaderValues(headerName)).isEqualTo(
|
||||
Arrays.asList(headerValue));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersMulti() {
|
||||
Header pragma = new Header("Pragma","no-cache");
|
||||
Header cacheControl= new Header("Cache-Control","no-cache","no-store","must-revalidate");
|
||||
StaticHeadersWriter factory = new StaticHeadersWriter(Arrays.asList(pragma, cacheControl));
|
||||
@Test
|
||||
public void writeHeadersMulti() {
|
||||
Header pragma = new Header("Pragma", "no-cache");
|
||||
Header cacheControl = new Header("Cache-Control", "no-cache", "no-store",
|
||||
"must-revalidate");
|
||||
StaticHeadersWriter factory = new StaticHeadersWriter(Arrays.asList(pragma,
|
||||
cacheControl));
|
||||
|
||||
factory.writeHeaders(request, response);
|
||||
factory.writeHeaders(request, response);
|
||||
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(2);
|
||||
assertThat(response.getHeaderValues(pragma.getName())).isEqualTo(pragma.getValues());
|
||||
assertThat(response.getHeaderValues(cacheControl.getName())).isEqualTo(cacheControl.getValues());
|
||||
}
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(2);
|
||||
assertThat(response.getHeaderValues(pragma.getName())).isEqualTo(
|
||||
pragma.getValues());
|
||||
assertThat(response.getHeaderValues(cacheControl.getName())).isEqualTo(
|
||||
cacheControl.getValues());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,24 +30,25 @@ import org.springframework.mock.web.MockHttpServletResponse;
|
||||
*/
|
||||
public class XContentTypeOptionsHeaderWriterTests {
|
||||
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletRequest request;
|
||||
|
||||
private MockHttpServletResponse response;
|
||||
private MockHttpServletResponse response;
|
||||
|
||||
private XContentTypeOptionsHeaderWriter writer;
|
||||
private XContentTypeOptionsHeaderWriter writer;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
writer = new XContentTypeOptionsHeaderWriter();
|
||||
}
|
||||
@Before
|
||||
public void setup() {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
writer = new XContentTypeOptionsHeaderWriter();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeaders() {
|
||||
writer.writeHeaders(request, response);
|
||||
@Test
|
||||
public void writeHeaders() {
|
||||
writer.writeHeaders(request, response);
|
||||
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeaderValues("X-Content-Type-Options")).isEqualTo(Arrays.asList("nosniff"));
|
||||
}
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeaderValues("X-Content-Type-Options")).isEqualTo(
|
||||
Arrays.asList("nosniff"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,64 +30,67 @@ import org.springframework.mock.web.MockHttpServletResponse;
|
||||
*/
|
||||
public class XXssProtectionHeaderWriterTests {
|
||||
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletRequest request;
|
||||
|
||||
private MockHttpServletResponse response;
|
||||
private MockHttpServletResponse response;
|
||||
|
||||
private XXssProtectionHeaderWriter writer;
|
||||
private XXssProtectionHeaderWriter writer;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
writer = new XXssProtectionHeaderWriter();
|
||||
}
|
||||
@Before
|
||||
public void setup() {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
writer = new XXssProtectionHeaderWriter();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeaders() {
|
||||
writer.writeHeaders(request, response);
|
||||
@Test
|
||||
public void writeHeaders() {
|
||||
writer.writeHeaders(request, response);
|
||||
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeaderValues("X-XSS-Protection")).isEqualTo(Arrays.asList("1; mode=block"));
|
||||
}
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeaderValues("X-XSS-Protection")).isEqualTo(
|
||||
Arrays.asList("1; mode=block"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersNoBlock() {
|
||||
writer.setBlock(false);
|
||||
@Test
|
||||
public void writeHeadersNoBlock() {
|
||||
writer.setBlock(false);
|
||||
|
||||
writer.writeHeaders(request, response);
|
||||
writer.writeHeaders(request, response);
|
||||
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeaderValues("X-XSS-Protection")).isEqualTo(Arrays.asList("1"));
|
||||
}
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeaderValues("X-XSS-Protection")).isEqualTo(
|
||||
Arrays.asList("1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersDisabled() {
|
||||
writer.setBlock(false);
|
||||
writer.setEnabled(false);
|
||||
@Test
|
||||
public void writeHeadersDisabled() {
|
||||
writer.setBlock(false);
|
||||
writer.setEnabled(false);
|
||||
|
||||
writer.writeHeaders(request, response);
|
||||
writer.writeHeaders(request, response);
|
||||
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeaderValues("X-XSS-Protection")).isEqualTo(Arrays.asList("0"));
|
||||
}
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeaderValues("X-XSS-Protection")).isEqualTo(
|
||||
Arrays.asList("0"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void setEnabledFalseWithBlockTrue() {
|
||||
writer.setEnabled(false);
|
||||
@Test
|
||||
public void setEnabledFalseWithBlockTrue() {
|
||||
writer.setEnabled(false);
|
||||
|
||||
writer.writeHeaders(request, response);
|
||||
writer.writeHeaders(request, response);
|
||||
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeaderValues("X-XSS-Protection")).isEqualTo(Arrays.asList("0"));
|
||||
}
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeaderValues("X-XSS-Protection")).isEqualTo(
|
||||
Arrays.asList("0"));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void setBlockTrueWithEnabledFalse() {
|
||||
writer.setBlock(false);
|
||||
writer.setEnabled(false);
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void setBlockTrueWithEnabledFalse() {
|
||||
writer.setBlock(false);
|
||||
writer.setEnabled(false);
|
||||
|
||||
writer.setBlock(true);
|
||||
}
|
||||
writer.setBlock(true);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,76 +27,72 @@ import org.springframework.security.web.header.writers.frameoptions.AbstractRequ
|
||||
*
|
||||
*/
|
||||
public class AbstractRequestParameterAllowFromStrategyTests {
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletRequest request;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
request = new MockHttpServletRequest();
|
||||
}
|
||||
@Before
|
||||
public void setup() {
|
||||
request = new MockHttpServletRequest();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nullAllowFromParameterValue() {
|
||||
RequestParameterAllowFromStrategyStub strategy = new RequestParameterAllowFromStrategyStub(true);
|
||||
@Test
|
||||
public void nullAllowFromParameterValue() {
|
||||
RequestParameterAllowFromStrategyStub strategy = new RequestParameterAllowFromStrategyStub(
|
||||
true);
|
||||
|
||||
assertThat(
|
||||
strategy
|
||||
.getAllowFromValue(request)).isEqualTo("DENY");
|
||||
}
|
||||
assertThat(strategy.getAllowFromValue(request)).isEqualTo("DENY");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void emptyAllowFromParameterValue() {
|
||||
request.setParameter("x-frames-allow-from", "");
|
||||
RequestParameterAllowFromStrategyStub strategy = new RequestParameterAllowFromStrategyStub(true);
|
||||
@Test
|
||||
public void emptyAllowFromParameterValue() {
|
||||
request.setParameter("x-frames-allow-from", "");
|
||||
RequestParameterAllowFromStrategyStub strategy = new RequestParameterAllowFromStrategyStub(
|
||||
true);
|
||||
|
||||
assertThat(
|
||||
strategy
|
||||
.getAllowFromValue(request)).isEqualTo("DENY");
|
||||
}
|
||||
assertThat(strategy.getAllowFromValue(request)).isEqualTo("DENY");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void emptyAllowFromCustomParameterValue() {
|
||||
String customParam = "custom";
|
||||
request.setParameter(customParam, "");
|
||||
RequestParameterAllowFromStrategyStub strategy = new RequestParameterAllowFromStrategyStub(true);
|
||||
strategy.setAllowFromParameterName(customParam);
|
||||
@Test
|
||||
public void emptyAllowFromCustomParameterValue() {
|
||||
String customParam = "custom";
|
||||
request.setParameter(customParam, "");
|
||||
RequestParameterAllowFromStrategyStub strategy = new RequestParameterAllowFromStrategyStub(
|
||||
true);
|
||||
strategy.setAllowFromParameterName(customParam);
|
||||
|
||||
assertThat(
|
||||
strategy
|
||||
.getAllowFromValue(request)).isEqualTo("DENY");
|
||||
}
|
||||
assertThat(strategy.getAllowFromValue(request)).isEqualTo("DENY");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void allowFromParameterValueAllowed() {
|
||||
String value = "https://example.com";
|
||||
request.setParameter("x-frames-allow-from", value);
|
||||
RequestParameterAllowFromStrategyStub strategy = new RequestParameterAllowFromStrategyStub(true);
|
||||
@Test
|
||||
public void allowFromParameterValueAllowed() {
|
||||
String value = "https://example.com";
|
||||
request.setParameter("x-frames-allow-from", value);
|
||||
RequestParameterAllowFromStrategyStub strategy = new RequestParameterAllowFromStrategyStub(
|
||||
true);
|
||||
|
||||
assertThat(
|
||||
strategy
|
||||
.getAllowFromValue(request)).isEqualTo(value);
|
||||
}
|
||||
assertThat(strategy.getAllowFromValue(request)).isEqualTo(value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void allowFromParameterValueDenied() {
|
||||
String value = "https://example.com";
|
||||
request.setParameter("x-frames-allow-from", value);
|
||||
RequestParameterAllowFromStrategyStub strategy = new RequestParameterAllowFromStrategyStub(false);
|
||||
@Test
|
||||
public void allowFromParameterValueDenied() {
|
||||
String value = "https://example.com";
|
||||
request.setParameter("x-frames-allow-from", value);
|
||||
RequestParameterAllowFromStrategyStub strategy = new RequestParameterAllowFromStrategyStub(
|
||||
false);
|
||||
|
||||
assertThat(
|
||||
strategy
|
||||
.getAllowFromValue(request)).isEqualTo("DENY");
|
||||
}
|
||||
assertThat(strategy.getAllowFromValue(request)).isEqualTo("DENY");
|
||||
}
|
||||
|
||||
private static class RequestParameterAllowFromStrategyStub extends AbstractRequestParameterAllowFromStrategy {
|
||||
private boolean match;
|
||||
private static class RequestParameterAllowFromStrategyStub extends
|
||||
AbstractRequestParameterAllowFromStrategy {
|
||||
private boolean match;
|
||||
|
||||
RequestParameterAllowFromStrategyStub(boolean match) {
|
||||
this.match = match;
|
||||
}
|
||||
RequestParameterAllowFromStrategyStub(boolean match) {
|
||||
this.match = match;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean allowed(String allowFromOrigin) {
|
||||
return match;
|
||||
}
|
||||
}
|
||||
@Override
|
||||
protected boolean allowed(String allowFromOrigin) {
|
||||
return match;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,75 +37,77 @@ import org.springframework.security.web.header.writers.frameoptions.XFrameOption
|
||||
*/
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class FrameOptionsHeaderWriterTests {
|
||||
@Mock
|
||||
private AllowFromStrategy strategy;
|
||||
@Mock
|
||||
private AllowFromStrategy strategy;
|
||||
|
||||
private MockHttpServletResponse response;
|
||||
private MockHttpServletResponse response;
|
||||
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletRequest request;
|
||||
|
||||
private XFrameOptionsHeaderWriter writer;
|
||||
private XFrameOptionsHeaderWriter writer;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
}
|
||||
@Before
|
||||
public void setup() {
|
||||
request = new MockHttpServletRequest();
|
||||
response = new MockHttpServletResponse();
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullMode() {
|
||||
new XFrameOptionsHeaderWriter((XFrameOptionsMode)null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullMode() {
|
||||
new XFrameOptionsHeaderWriter((XFrameOptionsMode) null);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorAllowFromNoAllowFromStrategy() {
|
||||
new XFrameOptionsHeaderWriter(XFrameOptionsMode.ALLOW_FROM);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorAllowFromNoAllowFromStrategy() {
|
||||
new XFrameOptionsHeaderWriter(XFrameOptionsMode.ALLOW_FROM);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullAllowFromStrategy() {
|
||||
new XFrameOptionsHeaderWriter((AllowFromStrategy)null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void constructorNullAllowFromStrategy() {
|
||||
new XFrameOptionsHeaderWriter((AllowFromStrategy) null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersAllowFromReturnsNull() {
|
||||
writer = new XFrameOptionsHeaderWriter(strategy);
|
||||
@Test
|
||||
public void writeHeadersAllowFromReturnsNull() {
|
||||
writer = new XFrameOptionsHeaderWriter(strategy);
|
||||
|
||||
writer.writeHeaders(request, response);
|
||||
writer.writeHeaders(request, response);
|
||||
|
||||
assertThat(response.getHeaderNames().isEmpty()).isTrue();
|
||||
}
|
||||
assertThat(response.getHeaderNames().isEmpty()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersAllowFrom() {
|
||||
String allowFromValue = "https://example.com/";
|
||||
when(strategy.getAllowFromValue(request)).thenReturn(allowFromValue);
|
||||
writer = new XFrameOptionsHeaderWriter(strategy);
|
||||
@Test
|
||||
public void writeHeadersAllowFrom() {
|
||||
String allowFromValue = "https://example.com/";
|
||||
when(strategy.getAllowFromValue(request)).thenReturn(allowFromValue);
|
||||
writer = new XFrameOptionsHeaderWriter(strategy);
|
||||
|
||||
writer.writeHeaders(request, response);
|
||||
writer.writeHeaders(request, response);
|
||||
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeader(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER)).isEqualTo("ALLOW-FROM " + allowFromValue);
|
||||
}
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeader(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER))
|
||||
.isEqualTo("ALLOW-FROM " + allowFromValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersDeny() {
|
||||
writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.DENY);
|
||||
@Test
|
||||
public void writeHeadersDeny() {
|
||||
writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.DENY);
|
||||
|
||||
writer.writeHeaders(request, response);
|
||||
writer.writeHeaders(request, response);
|
||||
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeader(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER)).isEqualTo("DENY");
|
||||
}
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeader(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER))
|
||||
.isEqualTo("DENY");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void writeHeadersSameOrigin() {
|
||||
writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN);
|
||||
|
||||
@Test
|
||||
public void writeHeadersSameOrigin() {
|
||||
writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN);
|
||||
writer.writeHeaders(request, response);
|
||||
|
||||
writer.writeHeaders(request, response);
|
||||
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeader(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER)).isEqualTo("SAMEORIGIN");
|
||||
}
|
||||
assertThat(response.getHeaderNames().size()).isEqualTo(1);
|
||||
assertThat(response.getHeader(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER))
|
||||
.isEqualTo("SAMEORIGIN");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,40 +15,42 @@ import org.springframework.security.web.header.writers.frameoptions.RegExpAllowF
|
||||
*/
|
||||
public class RegExpAllowFromStrategyTests {
|
||||
|
||||
@Test(expected = PatternSyntaxException.class)
|
||||
public void invalidRegularExpressionShouldLeadToException() {
|
||||
new RegExpAllowFromStrategy("[a-z");
|
||||
}
|
||||
@Test(expected = PatternSyntaxException.class)
|
||||
public void invalidRegularExpressionShouldLeadToException() {
|
||||
new RegExpAllowFromStrategy("[a-z");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void nullRegularExpressionShouldLeadToException() {
|
||||
new RegExpAllowFromStrategy(null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void nullRegularExpressionShouldLeadToException() {
|
||||
new RegExpAllowFromStrategy(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void subdomainMatchingRegularExpression() {
|
||||
RegExpAllowFromStrategy strategy = new RegExpAllowFromStrategy("^http://([a-z0-9]*?\\.)test\\.com");
|
||||
strategy.setAllowFromParameterName("from");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
@Test
|
||||
public void subdomainMatchingRegularExpression() {
|
||||
RegExpAllowFromStrategy strategy = new RegExpAllowFromStrategy(
|
||||
"^http://([a-z0-9]*?\\.)test\\.com");
|
||||
strategy.setAllowFromParameterName("from");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
request.setParameter("from", "http://abc.test.com");
|
||||
String result1 = strategy.getAllowFromValue(request);
|
||||
assertThat(result1, is("http://abc.test.com"));
|
||||
request.setParameter("from", "http://abc.test.com");
|
||||
String result1 = strategy.getAllowFromValue(request);
|
||||
assertThat(result1, is("http://abc.test.com"));
|
||||
|
||||
request.setParameter("from", "http://foo.test.com");
|
||||
String result2 = strategy.getAllowFromValue(request);
|
||||
assertThat(result2, is("http://foo.test.com"));
|
||||
request.setParameter("from", "http://foo.test.com");
|
||||
String result2 = strategy.getAllowFromValue(request);
|
||||
assertThat(result2, is("http://foo.test.com"));
|
||||
|
||||
request.setParameter("from", "http://test.foobar.com");
|
||||
String result3 = strategy.getAllowFromValue(request);
|
||||
assertThat(result3, is("DENY"));
|
||||
}
|
||||
request.setParameter("from", "http://test.foobar.com");
|
||||
String result3 = strategy.getAllowFromValue(request);
|
||||
assertThat(result3, is("DENY"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void noParameterShouldDeny() {
|
||||
RegExpAllowFromStrategy strategy = new RegExpAllowFromStrategy("^http://([a-z0-9]*?\\.)test\\.com");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
String result1 = strategy.getAllowFromValue(request);
|
||||
assertThat(result1, is("DENY"));
|
||||
}
|
||||
@Test
|
||||
public void noParameterShouldDeny() {
|
||||
RegExpAllowFromStrategy strategy = new RegExpAllowFromStrategy(
|
||||
"^http://([a-z0-9]*?\\.)test\\.com");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
String result1 = strategy.getAllowFromValue(request);
|
||||
assertThat(result1, is("DENY"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,10 +16,10 @@ import static org.junit.Assert.assertEquals;
|
||||
*/
|
||||
public class StaticAllowFromStrategyTests {
|
||||
|
||||
@Test
|
||||
public void shouldReturnUri() {
|
||||
String uri = "http://www.test.com";
|
||||
StaticAllowFromStrategy strategy = new StaticAllowFromStrategy(URI.create(uri));
|
||||
assertEquals(uri, strategy.getAllowFromValue(new MockHttpServletRequest()));
|
||||
}
|
||||
@Test
|
||||
public void shouldReturnUri() {
|
||||
String uri = "http://www.test.com";
|
||||
StaticAllowFromStrategy strategy = new StaticAllowFromStrategy(URI.create(uri));
|
||||
assertEquals(uri, strategy.getAllowFromValue(new MockHttpServletRequest()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,68 +18,67 @@ import static org.springframework.test.util.MatcherAssertionErrors.assertThat;
|
||||
*/
|
||||
public class WhiteListedAllowFromStrategyTests {
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void emptyListShouldThrowException() {
|
||||
new WhiteListedAllowFromStrategy(new ArrayList<String>());
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void emptyListShouldThrowException() {
|
||||
new WhiteListedAllowFromStrategy(new ArrayList<String>());
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void nullListShouldThrowException() {
|
||||
new WhiteListedAllowFromStrategy(null);
|
||||
}
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void nullListShouldThrowException() {
|
||||
new WhiteListedAllowFromStrategy(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void listWithSingleElementShouldMatch() {
|
||||
List<String> allowed = new ArrayList<String>();
|
||||
allowed.add("http://www.test.com");
|
||||
WhiteListedAllowFromStrategy strategy = new WhiteListedAllowFromStrategy(allowed);
|
||||
strategy.setAllowFromParameterName("from");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setParameter("from", "http://www.test.com");
|
||||
@Test
|
||||
public void listWithSingleElementShouldMatch() {
|
||||
List<String> allowed = new ArrayList<String>();
|
||||
allowed.add("http://www.test.com");
|
||||
WhiteListedAllowFromStrategy strategy = new WhiteListedAllowFromStrategy(allowed);
|
||||
strategy.setAllowFromParameterName("from");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setParameter("from", "http://www.test.com");
|
||||
|
||||
String result = strategy.getAllowFromValue(request);
|
||||
assertThat(result, is("http://www.test.com"));
|
||||
}
|
||||
String result = strategy.getAllowFromValue(request);
|
||||
assertThat(result, is("http://www.test.com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void listWithMultipleElementShouldMatch() {
|
||||
List<String> allowed = new ArrayList<String>();
|
||||
allowed.add("http://www.test.com");
|
||||
allowed.add("http://www.springsource.org");
|
||||
WhiteListedAllowFromStrategy strategy = new WhiteListedAllowFromStrategy(allowed);
|
||||
strategy.setAllowFromParameterName("from");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setParameter("from", "http://www.test.com");
|
||||
@Test
|
||||
public void listWithMultipleElementShouldMatch() {
|
||||
List<String> allowed = new ArrayList<String>();
|
||||
allowed.add("http://www.test.com");
|
||||
allowed.add("http://www.springsource.org");
|
||||
WhiteListedAllowFromStrategy strategy = new WhiteListedAllowFromStrategy(allowed);
|
||||
strategy.setAllowFromParameterName("from");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setParameter("from", "http://www.test.com");
|
||||
|
||||
String result = strategy.getAllowFromValue(request);
|
||||
assertThat(result, is("http://www.test.com"));
|
||||
}
|
||||
String result = strategy.getAllowFromValue(request);
|
||||
assertThat(result, is("http://www.test.com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void listWithSingleElementShouldNotMatch() {
|
||||
List<String> allowed = new ArrayList<String>();
|
||||
allowed.add("http://www.test.com");
|
||||
WhiteListedAllowFromStrategy strategy = new WhiteListedAllowFromStrategy(allowed);
|
||||
strategy.setAllowFromParameterName("from");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setParameter("from", "http://www.test123.com");
|
||||
@Test
|
||||
public void listWithSingleElementShouldNotMatch() {
|
||||
List<String> allowed = new ArrayList<String>();
|
||||
allowed.add("http://www.test.com");
|
||||
WhiteListedAllowFromStrategy strategy = new WhiteListedAllowFromStrategy(allowed);
|
||||
strategy.setAllowFromParameterName("from");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setParameter("from", "http://www.test123.com");
|
||||
|
||||
String result = strategy.getAllowFromValue(request);
|
||||
assertThat(result, is("DENY"));
|
||||
}
|
||||
String result = strategy.getAllowFromValue(request);
|
||||
assertThat(result, is("DENY"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestWithoutParameterShouldNotMatch() {
|
||||
List<String> allowed = new ArrayList<String>();
|
||||
allowed.add("http://www.test.com");
|
||||
WhiteListedAllowFromStrategy strategy = new WhiteListedAllowFromStrategy(allowed);
|
||||
strategy.setAllowFromParameterName("from");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
@Test
|
||||
public void requestWithoutParameterShouldNotMatch() {
|
||||
List<String> allowed = new ArrayList<String>();
|
||||
allowed.add("http://www.test.com");
|
||||
WhiteListedAllowFromStrategy strategy = new WhiteListedAllowFromStrategy(allowed);
|
||||
strategy.setAllowFromParameterName("from");
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
String result = strategy.getAllowFromValue(request);
|
||||
assertThat(result, is("DENY"));
|
||||
|
||||
}
|
||||
String result = strategy.getAllowFromValue(request);
|
||||
assertThat(result, is("DENY"));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -59,154 +59,170 @@ import org.springframework.security.web.jaasapi.JaasApiIntegrationFilter;
|
||||
* @author Rob Winch
|
||||
*/
|
||||
public class JaasApiIntegrationFilterTests {
|
||||
//~ Instance fields ================================================================================================
|
||||
private JaasApiIntegrationFilter filter;
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletResponse response;
|
||||
private Authentication token;
|
||||
private Subject authenticatedSubject;
|
||||
private Configuration testConfiguration;
|
||||
private CallbackHandler callbackHandler;
|
||||
//~ Methods ========================================================================================================
|
||||
// ~ Instance fields
|
||||
// ================================================================================================
|
||||
private JaasApiIntegrationFilter filter;
|
||||
private MockHttpServletRequest request;
|
||||
private MockHttpServletResponse response;
|
||||
private Authentication token;
|
||||
private Subject authenticatedSubject;
|
||||
private Configuration testConfiguration;
|
||||
private CallbackHandler callbackHandler;
|
||||
|
||||
@Before
|
||||
public void onBeforeTests() throws Exception {
|
||||
this.filter = new JaasApiIntegrationFilter();
|
||||
this.request = new MockHttpServletRequest();
|
||||
this.response = new MockHttpServletResponse();
|
||||
// ~ Methods
|
||||
// ========================================================================================================
|
||||
|
||||
authenticatedSubject = new Subject();
|
||||
authenticatedSubject.getPrincipals().add(new Principal() {
|
||||
public String getName() {
|
||||
return "principal";
|
||||
}
|
||||
});
|
||||
authenticatedSubject.getPrivateCredentials().add("password");
|
||||
authenticatedSubject.getPublicCredentials().add("username");
|
||||
callbackHandler = new CallbackHandler() {
|
||||
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
|
||||
for (Callback callback : callbacks) {
|
||||
if (callback instanceof NameCallback) {
|
||||
((NameCallback) callback).setName("user");
|
||||
} else if (callback instanceof PasswordCallback) {
|
||||
((PasswordCallback) callback).setPassword("password".toCharArray());
|
||||
} else if (callback instanceof TextInputCallback) {
|
||||
// ignore
|
||||
} else {
|
||||
throw new UnsupportedCallbackException(callback, "Unrecognized Callback " + callback);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
testConfiguration = new Configuration() {
|
||||
public void refresh() {
|
||||
}
|
||||
@Before
|
||||
public void onBeforeTests() throws Exception {
|
||||
this.filter = new JaasApiIntegrationFilter();
|
||||
this.request = new MockHttpServletRequest();
|
||||
this.response = new MockHttpServletResponse();
|
||||
|
||||
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
|
||||
return new AppConfigurationEntry[] { new AppConfigurationEntry(TestLoginModule.class.getName(),
|
||||
LoginModuleControlFlag.REQUIRED, new HashMap<String, String>()) };
|
||||
}
|
||||
};
|
||||
LoginContext ctx = new LoginContext("SubjectDoAsFilterTest", authenticatedSubject, callbackHandler,
|
||||
testConfiguration);
|
||||
ctx.login();
|
||||
token = new JaasAuthenticationToken("username", "password", AuthorityUtils.createAuthorityList("ROLE_ADMIN"),
|
||||
ctx);
|
||||
authenticatedSubject = new Subject();
|
||||
authenticatedSubject.getPrincipals().add(new Principal() {
|
||||
public String getName() {
|
||||
return "principal";
|
||||
}
|
||||
});
|
||||
authenticatedSubject.getPrivateCredentials().add("password");
|
||||
authenticatedSubject.getPublicCredentials().add("username");
|
||||
callbackHandler = new CallbackHandler() {
|
||||
public void handle(Callback[] callbacks) throws IOException,
|
||||
UnsupportedCallbackException {
|
||||
for (Callback callback : callbacks) {
|
||||
if (callback instanceof NameCallback) {
|
||||
((NameCallback) callback).setName("user");
|
||||
}
|
||||
else if (callback instanceof PasswordCallback) {
|
||||
((PasswordCallback) callback).setPassword("password"
|
||||
.toCharArray());
|
||||
}
|
||||
else if (callback instanceof TextInputCallback) {
|
||||
// ignore
|
||||
}
|
||||
else {
|
||||
throw new UnsupportedCallbackException(callback,
|
||||
"Unrecognized Callback " + callback);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
testConfiguration = new Configuration() {
|
||||
public void refresh() {
|
||||
}
|
||||
|
||||
// just in case someone forgot to clear the context
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
|
||||
return new AppConfigurationEntry[] { new AppConfigurationEntry(
|
||||
TestLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED,
|
||||
new HashMap<String, String>()) };
|
||||
}
|
||||
};
|
||||
LoginContext ctx = new LoginContext("SubjectDoAsFilterTest",
|
||||
authenticatedSubject, callbackHandler, testConfiguration);
|
||||
ctx.login();
|
||||
token = new JaasAuthenticationToken("username", "password",
|
||||
AuthorityUtils.createAuthorityList("ROLE_ADMIN"), ctx);
|
||||
|
||||
@After
|
||||
public void onAfterTests() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
// just in case someone forgot to clear the context
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure a Subject was not setup in some other manner.
|
||||
*/
|
||||
@Test
|
||||
public void currentSubjectNull() {
|
||||
assertNull(Subject.getSubject(AccessController.getContext()));
|
||||
}
|
||||
@After
|
||||
public void onAfterTests() {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void obtainSubjectNullAuthentication() {
|
||||
assertNullSubject(filter.obtainSubject(request));
|
||||
}
|
||||
/**
|
||||
* Ensure a Subject was not setup in some other manner.
|
||||
*/
|
||||
@Test
|
||||
public void currentSubjectNull() {
|
||||
assertNull(Subject.getSubject(AccessController.getContext()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void obtainSubjectNonJaasAuthentication() {
|
||||
Authentication authentication = new TestingAuthenticationToken("un", "pwd");
|
||||
authentication.setAuthenticated(true);
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
assertNullSubject(filter.obtainSubject(request));
|
||||
}
|
||||
@Test
|
||||
public void obtainSubjectNullAuthentication() {
|
||||
assertNullSubject(filter.obtainSubject(request));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void obtainSubjectNullLoginContext() {
|
||||
token = new JaasAuthenticationToken("un", "pwd", AuthorityUtils.createAuthorityList("ROLE_ADMIN"), null);
|
||||
SecurityContextHolder.getContext().setAuthentication(token);
|
||||
assertNullSubject(filter.obtainSubject(request));
|
||||
}
|
||||
@Test
|
||||
public void obtainSubjectNonJaasAuthentication() {
|
||||
Authentication authentication = new TestingAuthenticationToken("un", "pwd");
|
||||
authentication.setAuthenticated(true);
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
assertNullSubject(filter.obtainSubject(request));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void obtainSubjectNullSubject() throws Exception {
|
||||
LoginContext ctx = new LoginContext("obtainSubjectNullSubject", null, callbackHandler, testConfiguration);
|
||||
assertNull(ctx.getSubject());
|
||||
token = new JaasAuthenticationToken("un", "pwd", AuthorityUtils.createAuthorityList("ROLE_ADMIN"), ctx);
|
||||
SecurityContextHolder.getContext().setAuthentication(token);
|
||||
assertNullSubject(filter.obtainSubject(request));
|
||||
}
|
||||
@Test
|
||||
public void obtainSubjectNullLoginContext() {
|
||||
token = new JaasAuthenticationToken("un", "pwd",
|
||||
AuthorityUtils.createAuthorityList("ROLE_ADMIN"), null);
|
||||
SecurityContextHolder.getContext().setAuthentication(token);
|
||||
assertNullSubject(filter.obtainSubject(request));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void obtainSubject() throws Exception {
|
||||
SecurityContextHolder.getContext().setAuthentication(token);
|
||||
assertEquals(authenticatedSubject, filter.obtainSubject(request));
|
||||
}
|
||||
@Test
|
||||
public void obtainSubjectNullSubject() throws Exception {
|
||||
LoginContext ctx = new LoginContext("obtainSubjectNullSubject", null,
|
||||
callbackHandler, testConfiguration);
|
||||
assertNull(ctx.getSubject());
|
||||
token = new JaasAuthenticationToken("un", "pwd",
|
||||
AuthorityUtils.createAuthorityList("ROLE_ADMIN"), ctx);
|
||||
SecurityContextHolder.getContext().setAuthentication(token);
|
||||
assertNullSubject(filter.obtainSubject(request));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterCurrentSubjectPopulated() throws Exception {
|
||||
SecurityContextHolder.getContext().setAuthentication(token);
|
||||
assertJaasSubjectEquals(authenticatedSubject);
|
||||
}
|
||||
@Test
|
||||
public void obtainSubject() throws Exception {
|
||||
SecurityContextHolder.getContext().setAuthentication(token);
|
||||
assertEquals(authenticatedSubject, filter.obtainSubject(request));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterAuthenticationNotAuthenticated() throws Exception {
|
||||
// Authentication is null, so no Subject is populated.
|
||||
token.setAuthenticated(false);
|
||||
SecurityContextHolder.getContext().setAuthentication(token);
|
||||
assertJaasSubjectEquals(null);
|
||||
filter.setCreateEmptySubject(true);
|
||||
assertJaasSubjectEquals(new Subject());
|
||||
}
|
||||
@Test
|
||||
public void doFilterCurrentSubjectPopulated() throws Exception {
|
||||
SecurityContextHolder.getContext().setAuthentication(token);
|
||||
assertJaasSubjectEquals(authenticatedSubject);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void doFilterAuthenticationNull() throws Exception {
|
||||
assertJaasSubjectEquals(null);
|
||||
filter.setCreateEmptySubject(true);
|
||||
assertJaasSubjectEquals(new Subject());
|
||||
}
|
||||
@Test
|
||||
public void doFilterAuthenticationNotAuthenticated() throws Exception {
|
||||
// Authentication is null, so no Subject is populated.
|
||||
token.setAuthenticated(false);
|
||||
SecurityContextHolder.getContext().setAuthentication(token);
|
||||
assertJaasSubjectEquals(null);
|
||||
filter.setCreateEmptySubject(true);
|
||||
assertJaasSubjectEquals(new Subject());
|
||||
}
|
||||
|
||||
//~ Helper Methods ====================================================================================================
|
||||
@Test
|
||||
public void doFilterAuthenticationNull() throws Exception {
|
||||
assertJaasSubjectEquals(null);
|
||||
filter.setCreateEmptySubject(true);
|
||||
assertJaasSubjectEquals(new Subject());
|
||||
}
|
||||
|
||||
private void assertJaasSubjectEquals(final Subject expectedValue) throws Exception {
|
||||
MockFilterChain chain = new MockFilterChain() {
|
||||
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
|
||||
// See if the subject was updated
|
||||
Subject currentSubject = Subject.getSubject(AccessController.getContext());
|
||||
assertEquals(expectedValue, currentSubject);
|
||||
// ~ Helper Methods
|
||||
// ====================================================================================================
|
||||
|
||||
// run so we know the chain was executed
|
||||
super.doFilter(request, response);
|
||||
}
|
||||
};
|
||||
filter.doFilter(request, response, chain);
|
||||
// ensure that the chain was actually invoked
|
||||
assertNotNull(chain.getRequest());
|
||||
}
|
||||
private void assertJaasSubjectEquals(final Subject expectedValue) throws Exception {
|
||||
MockFilterChain chain = new MockFilterChain() {
|
||||
public void doFilter(ServletRequest request, ServletResponse response)
|
||||
throws IOException, ServletException {
|
||||
// See if the subject was updated
|
||||
Subject currentSubject = Subject
|
||||
.getSubject(AccessController.getContext());
|
||||
assertEquals(expectedValue, currentSubject);
|
||||
|
||||
private void assertNullSubject(Subject subject) {
|
||||
assertNull("Subject is expected to be null, but is not. Got " + subject, subject);
|
||||
}
|
||||
// run so we know the chain was executed
|
||||
super.doFilter(request, response);
|
||||
}
|
||||
};
|
||||
filter.doFilter(request, response, chain);
|
||||
// ensure that the chain was actually invoked
|
||||
assertNotNull(chain.getRequest());
|
||||
}
|
||||
|
||||
private void assertNullSubject(Subject subject) {
|
||||
assertNull("Subject is expected to be null, but is not. Got " + subject, subject);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user