Always use 'this.' when accessing fields

Apply an Eclipse cleanup rules to ensure that fields are always accessed
using `this.`. This aligns with the style used by Spring Framework and
helps users quickly see the difference between a local and member
variable.

Issue gh-8945
This commit is contained in:
Phillip Webb
2020-07-26 11:51:05 -07:00
committed by Rob Winch
parent 6894ff5d12
commit 8866fa6fb0
793 changed files with 8689 additions and 8459 deletions

View File

@@ -36,7 +36,7 @@ public class MockFilterConfig implements FilterConfig {
}
public String getInitParameter(String arg0) {
Object result = map.get(arg0);
Object result = this.map.get(arg0);
if (result != null) {
return (String) result;
@@ -55,7 +55,7 @@ public class MockFilterConfig implements FilterConfig {
}
public void setInitParmeter(String parameter, String value) {
map.put(parameter, value);
this.map.put(parameter, value);
}
}

View File

@@ -38,10 +38,10 @@ public class MockPortResolver implements PortResolver {
public int getServerPort(ServletRequest request) {
if ((request.getScheme() != null) && request.getScheme().equals("https")) {
return https;
return this.https;
}
else {
return http;
return this.http;
}
}

View File

@@ -37,7 +37,7 @@ public final class WebTestHandler {
private final WebHandler handler;
private WebTestHandler(WebFilter... filters) {
this.handler = new FilteringWebHandler(webHandler, Arrays.asList(filters));
this.handler = new FilteringWebHandler(this.webHandler, Arrays.asList(filters));
}
public WebHandlerResult exchange(BaseBuilder<?> baseBuilder) {
@@ -46,8 +46,8 @@ public final class WebTestHandler {
}
public WebHandlerResult exchange(ServerWebExchange exchange) {
handler.handle(exchange).block();
return new WebHandlerResult(webHandler.exchange);
this.handler.handle(exchange).block();
return new WebHandlerResult(this.webHandler.exchange);
}
public static final class WebHandlerResult {
@@ -59,7 +59,7 @@ public final class WebTestHandler {
}
public ServerWebExchange getExchange() {
return exchange;
return this.exchange;
}
}

View File

@@ -71,21 +71,21 @@ public class FilterChainProxyTests {
@Before
public void setup() throws Exception {
matcher = mock(RequestMatcher.class);
filter = mock(Filter.class);
this.matcher = mock(RequestMatcher.class);
this.filter = mock(Filter.class);
doAnswer((Answer<Object>) inv -> {
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(), any(), any());
fcp = new FilterChainProxy(new DefaultSecurityFilterChain(matcher, Arrays.asList(filter)));
fcp.setFilterChainValidator(mock(FilterChainProxy.FilterChainValidator.class));
request = new MockHttpServletRequest("GET", "");
request.setServletPath("/path");
response = new MockHttpServletResponse();
chain = mock(FilterChain.class);
}).when(this.filter).doFilter(any(), any(), any());
this.fcp = new FilterChainProxy(new DefaultSecurityFilterChain(this.matcher, Arrays.asList(this.filter)));
this.fcp.setFilterChainValidator(mock(FilterChainProxy.FilterChainValidator.class));
this.request = new MockHttpServletRequest("GET", "");
this.request.setServletPath("/path");
this.response = new MockHttpServletResponse();
this.chain = mock(FilterChain.class);
}
@After
@@ -95,58 +95,60 @@ public class FilterChainProxyTests {
@Test
public void toStringCallSucceeds() {
fcp.afterPropertiesSet();
fcp.toString();
this.fcp.afterPropertiesSet();
this.fcp.toString();
}
@Test
public void securityFilterChainIsNotInvokedIfMatchFails() throws Exception {
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(false);
fcp.doFilter(request, response, chain);
assertThat(fcp.getFilterChains()).hasSize(1);
assertThat(fcp.getFilterChains().get(0).getFilters().get(0)).isSameAs(filter);
when(this.matcher.matches(any(HttpServletRequest.class))).thenReturn(false);
this.fcp.doFilter(this.request, this.response, this.chain);
assertThat(this.fcp.getFilterChains()).hasSize(1);
assertThat(this.fcp.getFilterChains().get(0).getFilters().get(0)).isSameAs(this.filter);
verifyZeroInteractions(filter);
verifyZeroInteractions(this.filter);
// The actual filter chain should be invoked though
verify(chain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(this.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);
when(this.matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
this.fcp.doFilter(this.request, this.response, this.chain);
verify(filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), any(FilterChain.class));
verify(chain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(FilterChain.class));
verify(this.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));
this.fcp = new FilterChainProxy(new DefaultSecurityFilterChain(this.matcher, noFilters));
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
fcp.doFilter(request, response, chain);
when(this.matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
this.fcp.doFilter(this.request, this.response, this.chain);
verify(chain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(this.chain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@Test
public void requestIsWrappedForMatchingAndFilteringWhenMatchIsFound() throws Exception {
when(matcher.matches(any())).thenReturn(true);
fcp.doFilter(request, response, chain);
verify(matcher).matches(any(FirewalledRequest.class));
verify(filter).doFilter(any(FirewalledRequest.class), any(HttpServletResponse.class), any(FilterChain.class));
verify(chain).doFilter(any(), any(HttpServletResponse.class));
when(this.matcher.matches(any())).thenReturn(true);
this.fcp.doFilter(this.request, this.response, this.chain);
verify(this.matcher).matches(any(FirewalledRequest.class));
verify(this.filter).doFilter(any(FirewalledRequest.class), any(HttpServletResponse.class),
any(FilterChain.class));
verify(this.chain).doFilter(any(), 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));
when(this.matcher.matches(any(HttpServletRequest.class))).thenReturn(false);
this.fcp.doFilter(this.request, this.response, this.chain);
verify(this.matcher).matches(any(FirewalledRequest.class));
verifyZeroInteractions(this.filter);
verify(this.chain).doFilter(any(FirewalledRequest.class), any(HttpServletResponse.class));
}
@Test
@@ -155,10 +157,10 @@ public class FilterChainProxyTests {
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);
this.fcp.setFirewall(fw);
when(fw.getFirewalledRequest(this.request)).thenReturn(fwr);
when(this.matcher.matches(any(HttpServletRequest.class))).thenReturn(false);
this.fcp.doFilter(this.request, this.response, this.chain);
verify(fwr).reset();
}
@@ -166,50 +168,52 @@ public class FilterChainProxyTests {
@Test
public void bothWrappersAreResetWithNestedFcps() throws Exception {
HttpFirewall fw = mock(HttpFirewall.class);
FilterChainProxy firstFcp = new FilterChainProxy(new DefaultSecurityFilterChain(matcher, fcp));
FilterChainProxy firstFcp = new FilterChainProxy(new DefaultSecurityFilterChain(this.matcher, this.fcp));
firstFcp.setFirewall(fw);
fcp.setFirewall(fw);
this.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(this.request)).thenReturn(firstFwr);
when(fw.getFirewalledRequest(firstFwr)).thenReturn(fwr);
when(fwr.getRequest()).thenReturn(firstFwr);
when(firstFwr.getRequest()).thenReturn(request);
when(matcher.matches(any())).thenReturn(true);
firstFcp.doFilter(request, response, chain);
when(firstFwr.getRequest()).thenReturn(this.request);
when(this.matcher.matches(any())).thenReturn(true);
firstFcp.doFilter(this.request, this.response, this.chain);
verify(firstFwr).reset();
verify(fwr).reset();
}
@Test
public void doFilterClearsSecurityContextHolder() throws Exception {
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
when(this.matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
doAnswer((Answer<Object>) inv -> {
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("username", "password"));
return null;
}).when(filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), any(FilterChain.class));
}).when(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(FilterChain.class));
fcp.doFilter(request, response, chain);
this.fcp.doFilter(this.request, this.response, this.chain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void doFilterClearsSecurityContextHolderWithException() throws Exception {
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
when(this.matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
doAnswer((Answer<Object>) inv -> {
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("username", "password"));
throw new ServletException("oops");
}).when(filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), any(FilterChain.class));
}).when(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(FilterChain.class));
try {
fcp.doFilter(request, response, chain);
this.fcp.doFilter(this.request, this.response, this.chain);
fail("Expected Exception");
}
catch (ServletException success) {
@@ -222,22 +226,23 @@ public class FilterChainProxyTests {
@Test
public void doFilterClearsSecurityContextHolderOnceOnForwards() throws Exception {
final FilterChain innerChain = mock(FilterChain.class);
when(matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
when(this.matcher.matches(any(HttpServletRequest.class))).thenReturn(true);
doAnswer((Answer<Object>) inv -> {
TestingAuthenticationToken expected = new TestingAuthenticationToken("username", "password");
SecurityContextHolder.getContext().setAuthentication(expected);
doAnswer((Answer<Object>) inv1 -> {
innerChain.doFilter(request, response);
innerChain.doFilter(this.request, this.response);
return null;
}).when(filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
}).when(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(FilterChain.class));
fcp.doFilter(request, response, innerChain);
this.fcp.doFilter(this.request, this.response, innerChain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(expected);
return null;
}).when(filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), any(FilterChain.class));
}).when(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(FilterChain.class));
fcp.doFilter(request, response, chain);
this.fcp.doFilter(this.request, this.response, this.chain);
verify(innerChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
@@ -245,19 +250,19 @@ public class FilterChainProxyTests {
@Test(expected = IllegalArgumentException.class)
public void setRequestRejectedHandlerDoesNotAcceptNull() {
fcp.setRequestRejectedHandler(null);
this.fcp.setRequestRejectedHandler(null);
}
@Test
public void requestRejectedHandlerIsCalledIfFirewallThrowsRequestRejectedException() throws Exception {
HttpFirewall fw = mock(HttpFirewall.class);
RequestRejectedHandler rjh = mock(RequestRejectedHandler.class);
fcp.setFirewall(fw);
fcp.setRequestRejectedHandler(rjh);
this.fcp.setFirewall(fw);
this.fcp.setRequestRejectedHandler(rjh);
RequestRejectedException requestRejectedException = new RequestRejectedException("Contains illegal chars");
when(fw.getFirewalledRequest(request)).thenThrow(requestRejectedException);
fcp.doFilter(request, response, chain);
verify(rjh).handle(eq(request), eq(response), eq((requestRejectedException)));
when(fw.getFirewalledRequest(this.request)).thenThrow(requestRejectedException);
this.fcp.doFilter(this.request, this.response, this.chain);
verify(rjh).handle(eq(this.request), eq(this.response), eq((requestRejectedException)));
}
}

View File

@@ -56,43 +56,43 @@ public class DefaultWebInvocationPrivilegeEvaluatorTests {
@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));
this.interceptor = new FilterSecurityInterceptor();
this.ods = mock(FilterInvocationSecurityMetadataSource.class);
this.adm = mock(AccessDecisionManager.class);
this.ram = mock(RunAsManager.class);
this.interceptor.setAuthenticationManager(mock(AuthenticationManager.class));
this.interceptor.setSecurityMetadataSource(this.ods);
this.interceptor.setAccessDecisionManager(this.adm);
this.interceptor.setRunAsManager(this.ram);
this.interceptor.setApplicationEventPublisher(mock(ApplicationEventPublisher.class));
SecurityContextHolder.clearContext();
}
@Test
public void permitsAccessIfNoMatchingAttributesAndPublicInvocationsAllowed() {
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(interceptor);
when(ods.getAttributes(anyObject())).thenReturn(null);
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(this.interceptor);
when(this.ods.getAttributes(anyObject())).thenReturn(null);
assertThat(wipe.isAllowed("/context", "/foo/index.jsp", "GET", mock(Authentication.class))).isTrue();
}
@Test
public void deniesAccessIfNoMatchingAttributesAndPublicInvocationsNotAllowed() {
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(interceptor);
when(ods.getAttributes(anyObject())).thenReturn(null);
interceptor.setRejectPublicInvocations(true);
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(this.interceptor);
when(this.ods.getAttributes(anyObject())).thenReturn(null);
this.interceptor.setRejectPublicInvocations(true);
assertThat(wipe.isAllowed("/context", "/foo/index.jsp", "GET", mock(Authentication.class))).isFalse();
}
@Test
public void deniesAccessIfAuthenticationIsNull() {
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(interceptor);
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(this.interceptor);
assertThat(wipe.isAllowed("/foo/index.jsp", null)).isFalse();
}
@Test
public void allowsAccessIfAccessDecisionManagerDoes() {
Authentication token = new TestingAuthenticationToken("test", "Password", "MOCK_INDEX");
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(interceptor);
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(this.interceptor);
assertThat(wipe.isAllowed("/foo/index.jsp", token)).isTrue();
}
@@ -100,9 +100,9 @@ public class DefaultWebInvocationPrivilegeEvaluatorTests {
@Test
public void deniesAccessIfAccessDecisionManagerDoes() {
Authentication token = new TestingAuthenticationToken("test", "Password", "MOCK_INDEX");
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(interceptor);
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(this.interceptor);
doThrow(new AccessDeniedException("")).when(adm).decide(any(Authentication.class), anyObject(), anyList());
doThrow(new AccessDeniedException("")).when(this.adm).decide(any(Authentication.class), anyObject(), anyList());
assertThat(wipe.isAllowed("/foo/index.jsp", token)).isFalse();
}

View File

@@ -59,35 +59,35 @@ public class DelegatingAccessDeniedHandlerTests {
@Before
public void setup() {
handlers = new LinkedHashMap<>();
this.handlers = new LinkedHashMap<>();
}
@Test
public void moreSpecificDoesNotInvokeLessSpecific() throws Exception {
handlers.put(CsrfException.class, handler1);
handler = new DelegatingAccessDeniedHandler(handlers, handler3);
this.handlers.put(CsrfException.class, this.handler1);
this.handler = new DelegatingAccessDeniedHandler(this.handlers, this.handler3);
AccessDeniedException accessDeniedException = new AccessDeniedException("");
handler.handle(request, response, accessDeniedException);
this.handler.handle(this.request, this.response, accessDeniedException);
verify(handler1, never()).handle(any(HttpServletRequest.class), any(HttpServletResponse.class),
verify(this.handler1, never()).handle(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(AccessDeniedException.class));
verify(handler3).handle(request, response, accessDeniedException);
verify(this.handler3).handle(this.request, this.response, accessDeniedException);
}
@Test
public void matchesDoesNotInvokeDefault() throws Exception {
handlers.put(InvalidCsrfTokenException.class, handler1);
handlers.put(MissingCsrfTokenException.class, handler2);
handler = new DelegatingAccessDeniedHandler(handlers, handler3);
this.handlers.put(InvalidCsrfTokenException.class, this.handler1);
this.handlers.put(MissingCsrfTokenException.class, this.handler2);
this.handler = new DelegatingAccessDeniedHandler(this.handlers, this.handler3);
AccessDeniedException accessDeniedException = new MissingCsrfTokenException("123");
handler.handle(request, response, accessDeniedException);
this.handler.handle(this.request, this.response, accessDeniedException);
verify(handler1, never()).handle(any(HttpServletRequest.class), any(HttpServletResponse.class),
verify(this.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),
verify(this.handler2).handle(this.request, this.response, accessDeniedException);
verify(this.handler3, never()).handle(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(AccessDeniedException.class));
}

View File

@@ -101,7 +101,7 @@ public class ExceptionTranslationFilterTests {
new AnonymousAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("IGNORED")));
// Test
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint);
filter.setAuthenticationTrustResolver(new AuthenticationTrustResolverImpl());
assertThat(filter.getAuthenticationTrustResolver()).isNotNull();
@@ -134,7 +134,7 @@ public class ExceptionTranslationFilterTests {
SecurityContextHolder.setContext(securityContext);
// Test
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint);
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, fc);
assertThat(response.getRedirectedUrl()).isEqualTo("/mycontext/login.jsp");
@@ -161,7 +161,7 @@ public class ExceptionTranslationFilterTests {
adh.setErrorPage("/error.jsp");
// Test
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint);
filter.setAccessDeniedHandler(adh);
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -217,7 +217,7 @@ public class ExceptionTranslationFilterTests {
any(HttpServletResponse.class));
// Test
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint);
filter.afterPropertiesSet();
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, fc);
@@ -244,7 +244,7 @@ public class ExceptionTranslationFilterTests {
// Test
HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint, requestCache);
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint, requestCache);
requestCache.setPortResolver(new MockPortResolver(8080, 8443));
filter.afterPropertiesSet();
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -260,7 +260,7 @@ public class ExceptionTranslationFilterTests {
@Test(expected = IllegalArgumentException.class)
public void startupDetectsMissingRequestCache() {
new ExceptionTranslationFilter(mockEntryPoint, null);
new ExceptionTranslationFilter(this.mockEntryPoint, null);
}
@Test
@@ -270,8 +270,8 @@ public class ExceptionTranslationFilterTests {
request.setServletPath("/secure/page.html");
// Test
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
assertThat(filter.getAuthenticationEntryPoint()).isSameAs(mockEntryPoint);
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint);
assertThat(filter.getAuthenticationEntryPoint()).isSameAs(this.mockEntryPoint);
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, mock(FilterChain.class));
@@ -279,7 +279,7 @@ public class ExceptionTranslationFilterTests {
@Test
public void thrownIOExceptionServletExceptionAndRuntimeExceptionsAreRethrown() throws Exception {
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint);
filter.afterPropertiesSet();
Exception[] exceptions = { new IOException(), new ServletException(), new RuntimeException() };
@@ -307,12 +307,12 @@ public class ExceptionTranslationFilterTests {
};
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(mockEntryPoint);
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint);
assertThatThrownBy(() -> filter.doFilter(request, response, chain)).isInstanceOf(ServletException.class)
.hasCauseInstanceOf(AccessDeniedException.class);
verifyZeroInteractions(mockEntryPoint);
verifyZeroInteractions(this.mockEntryPoint);
}
private AuthenticationEntryPoint mockEntryPoint = (request, response, authException) -> response

View File

@@ -162,13 +162,13 @@ public class ChannelProcessingFilterTests {
}
public void decide(FilterInvocation invocation, Collection<ConfigAttribute> config) throws IOException {
if (commitAResponse) {
if (this.commitAResponse) {
invocation.getHttpResponse().sendRedirect("/redirected");
}
}
public boolean supports(ConfigAttribute attribute) {
if (attribute.getAttribute().equals(supportAttribute)) {
if (attribute.getAttribute().equals(this.supportAttribute)) {
return true;
}
else {
@@ -195,8 +195,8 @@ public class ChannelProcessingFilterTests {
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
FilterInvocation fi = (FilterInvocation) object;
if (servletPath.equals(fi.getHttpRequest().getServletPath())) {
return toReturn;
if (this.servletPath.equals(fi.getHttpRequest().getServletPath())) {
return this.toReturn;
}
else {
return null;
@@ -204,11 +204,11 @@ public class ChannelProcessingFilterTests {
}
public Collection<ConfigAttribute> getAllConfigAttributes() {
if (!provideIterator) {
if (!this.provideIterator) {
return null;
}
return toReturn;
return this.toReturn;
}
public boolean supports(Class<?> clazz) {

View File

@@ -54,7 +54,7 @@ public class DefaultWebSecurityExpressionHandlerTests {
@Before
public void setup() {
handler = new DefaultWebSecurityExpressionHandler();
this.handler = new DefaultWebSecurityExpressionHandler();
}
@After
@@ -68,29 +68,29 @@ public class DefaultWebSecurityExpressionHandlerTests {
RootBeanDefinition bean = new RootBeanDefinition(SecurityConfig.class);
bean.getConstructorArgumentValues().addGenericArgumentValue("ROLE_A");
appContext.registerBeanDefinition("role", bean);
handler.setApplicationContext(appContext);
this.handler.setApplicationContext(appContext);
EvaluationContext ctx = handler.createEvaluationContext(mock(Authentication.class),
EvaluationContext ctx = this.handler.createEvaluationContext(mock(Authentication.class),
mock(FilterInvocation.class));
ExpressionParser parser = handler.getExpressionParser();
ExpressionParser parser = this.handler.getExpressionParser();
assertThat(parser.parseExpression("@role.getAttribute() == 'ROLE_A'").getValue(ctx, Boolean.class)).isTrue();
assertThat(parser.parseExpression("@role.attribute == 'ROLE_A'").getValue(ctx, Boolean.class)).isTrue();
}
@Test(expected = IllegalArgumentException.class)
public void setTrustResolverNull() {
handler.setTrustResolver(null);
this.handler.setTrustResolver(null);
}
@Test
public void createEvaluationContextCustomTrustResolver() {
handler.setTrustResolver(trustResolver);
this.handler.setTrustResolver(this.trustResolver);
Expression expression = handler.getExpressionParser().parseExpression("anonymous");
EvaluationContext context = handler.createEvaluationContext(authentication, invocation);
Expression expression = this.handler.getExpressionParser().parseExpression("anonymous");
EvaluationContext context = this.handler.createEvaluationContext(this.authentication, this.invocation);
assertThat(expression.getValue(context, Boolean.class)).isFalse();
verify(trustResolver).isAnonymous(authentication);
verify(this.trustResolver).isAnonymous(this.authentication);
}
}

View File

@@ -60,8 +60,9 @@ public class WebExpressionVoterTests {
@Test
public void abstainsIfNoAttributeFound() {
WebExpressionVoter voter = new WebExpressionVoter();
assertThat(voter.vote(user, new FilterInvocation("/path", "GET"), SecurityConfig.createList("A", "B", "C")))
.isEqualTo(AccessDecisionVoter.ACCESS_ABSTAIN);
assertThat(
voter.vote(this.user, new FilterInvocation("/path", "GET"), SecurityConfig.createList("A", "B", "C")))
.isEqualTo(AccessDecisionVoter.ACCESS_ABSTAIN);
}
@Test
@@ -76,16 +77,16 @@ public class WebExpressionVoterTests {
SecurityExpressionHandler eh = mock(SecurityExpressionHandler.class);
FilterInvocation fi = new FilterInvocation("/path", "GET");
voter.setExpressionHandler(eh);
when(eh.createEvaluationContext(user, fi)).thenReturn(ctx);
when(eh.createEvaluationContext(this.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);
assertThat(voter.vote(user, fi, attributes)).isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
assertThat(voter.vote(this.user, fi, attributes)).isEqualTo(AccessDecisionVoter.ACCESS_GRANTED);
// Second time false
assertThat(voter.vote(user, fi, attributes)).isEqualTo(AccessDecisionVoter.ACCESS_DENIED);
assertThat(voter.vote(this.user, fi, attributes)).isEqualTo(AccessDecisionVoter.ACCESS_DENIED);
}
// SEC-2507

View File

@@ -76,17 +76,17 @@ public class FilterSecurityInterceptorTests {
@Before
public final void setUp() {
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);
this.interceptor = new FilterSecurityInterceptor();
this.am = mock(AuthenticationManager.class);
this.ods = mock(FilterInvocationSecurityMetadataSource.class);
this.adm = mock(AccessDecisionManager.class);
this.ram = mock(RunAsManager.class);
this.publisher = mock(ApplicationEventPublisher.class);
this.interceptor.setAuthenticationManager(this.am);
this.interceptor.setSecurityMetadataSource(this.ods);
this.interceptor.setAccessDecisionManager(this.adm);
this.interceptor.setRunAsManager(this.ram);
this.interceptor.setApplicationEventPublisher(this.publisher);
SecurityContextHolder.clearContext();
}
@@ -97,14 +97,14 @@ public class FilterSecurityInterceptorTests {
@Test(expected = IllegalArgumentException.class)
public void testEnsuresAccessDecisionManagerSupportsFilterInvocationClass() throws Exception {
when(adm.supports(FilterInvocation.class)).thenReturn(true);
interceptor.afterPropertiesSet();
when(this.adm.supports(FilterInvocation.class)).thenReturn(true);
this.interceptor.afterPropertiesSet();
}
@Test(expected = IllegalArgumentException.class)
public void testEnsuresRunAsManagerSupportsFilterInvocationClass() throws Exception {
when(adm.supports(FilterInvocation.class)).thenReturn(false);
interceptor.afterPropertiesSet();
when(this.adm.supports(FilterInvocation.class)).thenReturn(false);
this.interceptor.afterPropertiesSet();
}
/**
@@ -120,12 +120,12 @@ public class FilterSecurityInterceptorTests {
FilterInvocation fi = createinvocation();
when(ods.getAttributes(fi)).thenReturn(SecurityConfig.createList("MOCK_OK"));
when(this.ods.getAttributes(fi)).thenReturn(SecurityConfig.createList("MOCK_OK"));
interceptor.invoke(fi);
this.interceptor.invoke(fi);
// SEC-1697
verify(publisher, never()).publishEvent(any(AuthorizedEvent.class));
verify(this.publisher, never()).publishEvent(any(AuthorizedEvent.class));
}
@Test
@@ -138,13 +138,13 @@ public class FilterSecurityInterceptorTests {
doThrow(new RuntimeException()).when(chain).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
when(ods.getAttributes(fi)).thenReturn(SecurityConfig.createList("MOCK_OK"));
when(this.ods.getAttributes(fi)).thenReturn(SecurityConfig.createList("MOCK_OK"));
AfterInvocationManager aim = mock(AfterInvocationManager.class);
interceptor.setAfterInvocationManager(aim);
this.interceptor.setAfterInvocationManager(aim);
try {
interceptor.invoke(fi);
this.interceptor.invoke(fi);
fail("Expected exception");
}
catch (RuntimeException expected) {
@@ -165,20 +165,20 @@ public class FilterSecurityInterceptorTests {
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);
this.interceptor.setRunAsManager(runAsManager);
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"));
when(this.ods.getAttributes(fi)).thenReturn(SecurityConfig.createList("MOCK_OK"));
AfterInvocationManager aim = mock(AfterInvocationManager.class);
interceptor.setAfterInvocationManager(aim);
this.interceptor.setAfterInvocationManager(aim);
try {
interceptor.invoke(fi);
this.interceptor.invoke(fi);
fail("Expected exception");
}
catch (RuntimeException expected) {

View File

@@ -83,10 +83,10 @@ public class AbstractAuthenticationProcessingFilterTests {
@Before
public void setUp() {
successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setDefaultTargetUrl("/logged_in.jsp");
failureHandler = new SimpleUrlAuthenticationFailureHandler();
failureHandler.setDefaultFailureUrl("/failed.jsp");
this.successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
this.successHandler.setDefaultTargetUrl("/logged_in.jsp");
this.failureHandler = new SimpleUrlAuthenticationFailureHandler();
this.failureHandler.setDefaultFailureUrl("/failed.jsp");
SecurityContextHolder.clearContext();
}
@@ -128,7 +128,7 @@ public class AbstractAuthenticationProcessingFilterTests {
// Setup our test object, to grant access
MockAuthenticationFilter filter = new MockAuthenticationFilter(true);
filter.setFilterProcessesUrl("/j_OTHER_LOCATION");
filter.setAuthenticationSuccessHandler(successHandler);
filter.setAuthenticationSuccessHandler(this.successHandler);
// Test
filter.doFilter(request, response, chain);
@@ -192,8 +192,8 @@ public class AbstractAuthenticationProcessingFilterTests {
filter.setFilterProcessesUrl("/j_mock_post");
filter.setSessionAuthenticationStrategy(mock(SessionAuthenticationStrategy.class));
filter.setAuthenticationSuccessHandler(successHandler);
filter.setAuthenticationFailureHandler(failureHandler);
filter.setAuthenticationSuccessHandler(this.successHandler);
filter.setAuthenticationFailureHandler(this.failureHandler);
filter.setAuthenticationManager(mock(AuthenticationManager.class));
filter.afterPropertiesSet();
@@ -225,8 +225,8 @@ public class AbstractAuthenticationProcessingFilterTests {
mock(AuthenticationManager.class));
filter.setSessionAuthenticationStrategy(mock(SessionAuthenticationStrategy.class));
filter.setAuthenticationSuccessHandler(successHandler);
filter.setAuthenticationFailureHandler(failureHandler);
filter.setAuthenticationSuccessHandler(this.successHandler);
filter.setAuthenticationFailureHandler(this.failureHandler);
filter.afterPropertiesSet();
// Test
@@ -259,8 +259,8 @@ public class AbstractAuthenticationProcessingFilterTests {
new AntPathRequestMatcher("/j_eradicate_corona_virus"), mock(AuthenticationManager.class));
filter.setSessionAuthenticationStrategy(mock(SessionAuthenticationStrategy.class));
filter.setAuthenticationSuccessHandler(successHandler);
filter.setAuthenticationFailureHandler(failureHandler);
filter.setAuthenticationSuccessHandler(this.successHandler);
filter.setAuthenticationFailureHandler(this.failureHandler);
filter.afterPropertiesSet();
// Test
@@ -275,9 +275,9 @@ public class AbstractAuthenticationProcessingFilterTests {
@Test
public void testStartupDetectsInvalidAuthenticationManager() {
AbstractAuthenticationProcessingFilter filter = new MockAuthenticationFilter();
filter.setAuthenticationFailureHandler(failureHandler);
successHandler.setDefaultTargetUrl("/");
filter.setAuthenticationSuccessHandler(successHandler);
filter.setAuthenticationFailureHandler(this.failureHandler);
this.successHandler.setDefaultTargetUrl("/");
filter.setAuthenticationSuccessHandler(this.successHandler);
filter.setFilterProcessesUrl("/login");
try {
@@ -292,9 +292,9 @@ public class AbstractAuthenticationProcessingFilterTests {
@Test
public void testStartupDetectsInvalidFilterProcessesUrl() {
AbstractAuthenticationProcessingFilter filter = new MockAuthenticationFilter();
filter.setAuthenticationFailureHandler(failureHandler);
filter.setAuthenticationFailureHandler(this.failureHandler);
filter.setAuthenticationManager(mock(AuthenticationManager.class));
filter.setAuthenticationSuccessHandler(successHandler);
filter.setAuthenticationSuccessHandler(this.successHandler);
try {
filter.setFilterProcessesUrl(null);
@@ -321,7 +321,7 @@ public class AbstractAuthenticationProcessingFilterTests {
// Setup our test object, to grant access
MockAuthenticationFilter filter = new MockAuthenticationFilter(true);
filter.setFilterProcessesUrl("/j_mock_post");
filter.setAuthenticationSuccessHandler(successHandler);
filter.setAuthenticationSuccessHandler(this.successHandler);
// Test
filter.doFilter(request, response, chain);
@@ -339,7 +339,7 @@ public class AbstractAuthenticationProcessingFilterTests {
// Setup our test object, to deny access
filter = new MockAuthenticationFilter(false);
filter.setFilterProcessesUrl("/j_mock_post");
filter.setAuthenticationFailureHandler(failureHandler);
filter.setAuthenticationFailureHandler(this.failureHandler);
// Test
filter.doFilter(request, response, chain);
@@ -414,8 +414,8 @@ public class AbstractAuthenticationProcessingFilterTests {
// Reject authentication, so exception would normally be stored in session
MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
failureHandler.setAllowSessionCreation(false);
filter.setAuthenticationFailureHandler(failureHandler);
this.failureHandler.setAllowSessionCreation(false);
filter.setAuthenticationFailureHandler(this.failureHandler);
filter.doFilter(request, response, chain);
@@ -434,8 +434,8 @@ public class AbstractAuthenticationProcessingFilterTests {
MockHttpServletResponse response = new MockHttpServletResponse();
MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
successHandler.setDefaultTargetUrl("https://monkeymachine.co.uk/");
filter.setAuthenticationSuccessHandler(successHandler);
this.successHandler.setDefaultTargetUrl("https://monkeymachine.co.uk/");
filter.setAuthenticationSuccessHandler(this.successHandler);
filter.doFilter(request, response, chain);
@@ -456,8 +456,8 @@ public class AbstractAuthenticationProcessingFilterTests {
MockAuthenticationFilter filter = new MockAuthenticationFilter(false);
ReflectionTestUtils.setField(filter, "logger", logger);
filter.exceptionToThrow = new InternalAuthenticationServiceException("Mock requested to do so");
successHandler.setDefaultTargetUrl("https://monkeymachine.co.uk/");
filter.setAuthenticationSuccessHandler(successHandler);
this.successHandler.setDefaultTargetUrl("https://monkeymachine.co.uk/");
filter.setAuthenticationSuccessHandler(this.successHandler);
filter.doFilter(request, response, chain);
@@ -508,12 +508,12 @@ public class AbstractAuthenticationProcessingFilterTests {
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
if (grantAccess) {
if (this.grantAccess) {
return new UsernamePasswordAuthenticationToken("test", "test",
AuthorityUtils.createAuthorityList("TEST"));
}
else {
throw exceptionToThrow;
throw this.exceptionToThrow;
}
}
@@ -533,7 +533,7 @@ public class AbstractAuthenticationProcessingFilterTests {
}
public void doFilter(ServletRequest request, ServletResponse response) {
if (!expectToProceed) {
if (!this.expectToProceed) {
fail("Did not expect filter chain to proceed");
}
}

View File

@@ -115,7 +115,7 @@ public class AnonymousAuthenticationFilterTests {
}
public void doFilter(ServletRequest request, ServletResponse response) {
if (!expectToProceed) {
if (!this.expectToProceed) {
fail("Did not expect filter chain to proceed");
}
}

View File

@@ -212,7 +212,7 @@ public class AuthenticationFilterTests {
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
filter.setSuccessHandler(successHandler);
filter.setSuccessHandler(this.successHandler);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -232,7 +232,7 @@ public class AuthenticationFilterTests {
AuthenticationFilter filter = new AuthenticationFilter(this.authenticationManagerResolver,
this.authenticationConverter);
filter.setSuccessHandler(successHandler);
filter.setSuccessHandler(this.successHandler);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
MockHttpServletResponse response = new MockHttpServletResponse();

View File

@@ -49,9 +49,9 @@ public class DefaultLoginPageGeneratingFilterTests {
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"), new MockHttpServletResponse(), this.chain);
filter.doFilter(new MockHttpServletRequest("GET", "/login;pathparam=unused"), new MockHttpServletResponse(),
chain);
this.chain);
}
@Test
@@ -60,7 +60,7 @@ public class DefaultLoginPageGeneratingFilterTests {
new UsernamePasswordAuthenticationFilter());
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(new MockHttpServletRequest("GET", "/login"), response, chain);
filter.doFilter(new MockHttpServletRequest("GET", "/login"), response, this.chain);
assertThat(response.getContentAsString()).isNotEmpty();
}
@@ -72,7 +72,7 @@ public class DefaultLoginPageGeneratingFilterTests {
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/login");
filter.doFilter(request, response, chain);
filter.doFilter(request, response, this.chain);
assertThat(response.getContentAsString()).isEmpty();
}
@@ -85,7 +85,7 @@ public class DefaultLoginPageGeneratingFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/context/login");
request.setContextPath("/context");
filter.doFilter(request, response, chain);
filter.doFilter(request, response, this.chain);
assertThat(response.getContentAsString()).isNotEmpty();
}
@@ -96,7 +96,7 @@ public class DefaultLoginPageGeneratingFilterTests {
new UsernamePasswordAuthenticationFilter());
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(new MockHttpServletRequest("GET", "/api/login"), response, chain);
filter.doFilter(new MockHttpServletRequest("GET", "/api/login"), response, this.chain);
assertThat(response.getContentAsString()).isEmpty();
}
@@ -110,7 +110,7 @@ public class DefaultLoginPageGeneratingFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/login");
request.setQueryString("error");
filter.doFilter(request, response, chain);
filter.doFilter(request, response, this.chain);
assertThat(response.getContentAsString()).isNotEmpty();
}
@@ -124,7 +124,7 @@ public class DefaultLoginPageGeneratingFilterTests {
Collections.singletonMap("XYUU", "\u8109\u640F\u7F51\u5E10\u6237\u767B\u5F55"));
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/login");
filter.doFilter(request, response, chain);
filter.doFilter(request, response, this.chain);
assertThat(response
.getContentLength() == response.getContentAsString().getBytes(response.getCharacterEncoding()).length)
.isTrue();
@@ -139,7 +139,7 @@ public class DefaultLoginPageGeneratingFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/login");
request.setQueryString("not");
filter.doFilter(request, response, chain);
filter.doFilter(request, response, this.chain);
assertThat(response.getContentAsString()).isEmpty();
}
@@ -147,7 +147,7 @@ public class DefaultLoginPageGeneratingFilterTests {
@Test
public void generatingPageWithOpenIdFilterOnlyIsSuccessFul() throws Exception {
DefaultLoginPageGeneratingFilter filter = new DefaultLoginPageGeneratingFilter(new MockProcessingFilter());
filter.doFilter(new MockHttpServletRequest("GET", "/login"), new MockHttpServletResponse(), chain);
filter.doFilter(new MockHttpServletRequest("GET", "/login"), new MockHttpServletResponse(), this.chain);
}
// Fake OpenID filter (since it's not in this module
@@ -182,7 +182,7 @@ public class DefaultLoginPageGeneratingFilterTests {
"Bad credentials", Locale.KOREA);
request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, new BadCredentialsException(message));
filter.doFilter(request, new MockHttpServletResponse(), chain);
filter.doFilter(request, new MockHttpServletResponse(), this.chain);
}
// gh-5394
@@ -197,7 +197,7 @@ public class DefaultLoginPageGeneratingFilterTests {
Collections.singletonMap("/oauth2/authorization/google", clientName));
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(new MockHttpServletRequest("GET", "/login"), response, chain);
filter.doFilter(new MockHttpServletRequest("GET", "/login"), response, this.chain);
assertThat(response.getContentAsString())
.contains("<a href=\"/oauth2/authorization/google\">Google &lt; &gt; &quot; &#39; &amp;</a>");
@@ -213,7 +213,7 @@ public class DefaultLoginPageGeneratingFilterTests {
filter.setSaml2AuthenticationUrlToProviderName(Collections.singletonMap("/saml/sso/google", clientName));
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(new MockHttpServletRequest("GET", "/login"), response, chain);
filter.doFilter(new MockHttpServletRequest("GET", "/login"), response, this.chain);
assertThat(response.getContentAsString()).contains("Login with SAML 2.0");
assertThat(response.getContentAsString())

View File

@@ -56,9 +56,9 @@ public class DelegatingAuthenticationEntryPointContextTests {
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),
this.daep.commence(request, null, null);
verify(this.firstAEP).commence(request, null, null);
verify(this.defaultAEP, never()).commence(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(AuthenticationException.class));
}
@@ -68,9 +68,9 @@ public class DelegatingAuthenticationEntryPointContextTests {
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),
this.daep.commence(request, null, null);
verify(this.defaultAEP).commence(request, null, null);
verify(this.firstAEP, never()).commence(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(AuthenticationException.class));
}

View File

@@ -50,23 +50,23 @@ public class DelegatingAuthenticationEntryPointTests {
@Before
public void before() {
defaultEntryPoint = mock(AuthenticationEntryPoint.class);
entryPoints = new LinkedHashMap<>();
daep = new DelegatingAuthenticationEntryPoint(entryPoints);
daep.setDefaultEntryPoint(defaultEntryPoint);
this.defaultEntryPoint = mock(AuthenticationEntryPoint.class);
this.entryPoints = new LinkedHashMap<>();
this.daep = new DelegatingAuthenticationEntryPoint(this.entryPoints);
this.daep.setDefaultEntryPoint(this.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);
when(firstRM.matches(this.request)).thenReturn(false);
this.entryPoints.put(firstRM, firstAEP);
daep.commence(request, null, null);
this.daep.commence(this.request, null, null);
verify(defaultEntryPoint).commence(request, null, null);
verify(firstAEP, never()).commence(request, null, null);
verify(this.defaultEntryPoint).commence(this.request, null, null);
verify(firstAEP, never()).commence(this.request, null, null);
}
@Test
@@ -75,16 +75,16 @@ public class DelegatingAuthenticationEntryPointTests {
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);
when(firstRM.matches(this.request)).thenReturn(true);
this.entryPoints.put(firstRM, firstAEP);
this.entryPoints.put(secondRM, secondAEP);
daep.commence(request, null, null);
this.daep.commence(this.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(this.request, null, null);
verify(secondAEP, never()).commence(this.request, null, null);
verify(this.defaultEntryPoint, never()).commence(this.request, null, null);
verify(secondRM, never()).matches(this.request);
}
@Test
@@ -93,16 +93,16 @@ public class DelegatingAuthenticationEntryPointTests {
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);
when(firstRM.matches(this.request)).thenReturn(false);
when(secondRM.matches(this.request)).thenReturn(true);
this.entryPoints.put(firstRM, firstAEP);
this.entryPoints.put(secondRM, secondAEP);
daep.commence(request, null, null);
this.daep.commence(this.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(this.request, null, null);
verify(firstAEP, never()).commence(this.request, null, null);
verify(this.defaultEntryPoint, never()).commence(this.request, null, null);
}
}

View File

@@ -71,76 +71,76 @@ public class DelegatingAuthenticationFailureHandlerTests {
@Before
public void setup() {
handlers = new LinkedHashMap<>();
this.handlers = new LinkedHashMap<>();
}
@Test
public void handleByDefaultHandler() throws Exception {
handlers.put(BadCredentialsException.class, handler1);
handler = new DelegatingAuthenticationFailureHandler(handlers, defaultHandler);
this.handlers.put(BadCredentialsException.class, this.handler1);
this.handler = new DelegatingAuthenticationFailureHandler(this.handlers, this.defaultHandler);
AuthenticationException exception = new AccountExpiredException("");
handler.onAuthenticationFailure(request, response, exception);
this.handler.onAuthenticationFailure(this.request, this.response, exception);
verifyZeroInteractions(handler1, handler2);
verify(defaultHandler).onAuthenticationFailure(request, response, exception);
verifyZeroInteractions(this.handler1, this.handler2);
verify(this.defaultHandler).onAuthenticationFailure(this.request, this.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);
this.handlers.put(BadCredentialsException.class, this.handler1); // same type
this.handlers.put(AccountStatusException.class, this.handler2);
this.handler = new DelegatingAuthenticationFailureHandler(this.handlers, this.defaultHandler);
AuthenticationException exception = new BadCredentialsException("");
handler.onAuthenticationFailure(request, response, exception);
this.handler.onAuthenticationFailure(this.request, this.response, exception);
verifyZeroInteractions(handler2, defaultHandler);
verify(handler1).onAuthenticationFailure(request, response, exception);
verifyZeroInteractions(this.handler2, this.defaultHandler);
verify(this.handler1).onAuthenticationFailure(this.request, this.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);
this.handlers.put(BadCredentialsException.class, this.handler1);
this.handlers.put(AccountStatusException.class, this.handler2); // super type of
// CredentialsExpiredException
this.handler = new DelegatingAuthenticationFailureHandler(this.handlers, this.defaultHandler);
AuthenticationException exception = new CredentialsExpiredException("");
handler.onAuthenticationFailure(request, response, exception);
this.handler.onAuthenticationFailure(this.request, this.response, exception);
verifyZeroInteractions(handler1, defaultHandler);
verify(handler2).onAuthenticationFailure(request, response, exception);
verifyZeroInteractions(this.handler1, this.defaultHandler);
verify(this.handler2).onAuthenticationFailure(this.request, this.response, exception);
}
@Test
public void handlersIsNull() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("handlers cannot be null or empty");
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("handlers cannot be null or empty");
new DelegatingAuthenticationFailureHandler(null, defaultHandler);
new DelegatingAuthenticationFailureHandler(null, this.defaultHandler);
}
@Test
public void handlersIsEmpty() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("handlers cannot be null or empty");
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("handlers cannot be null or empty");
new DelegatingAuthenticationFailureHandler(handlers, defaultHandler);
new DelegatingAuthenticationFailureHandler(this.handlers, this.defaultHandler);
}
@Test
public void defaultHandlerIsNull() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("defaultHandler cannot be null");
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("defaultHandler cannot be null");
handlers.put(BadCredentialsException.class, handler1);
new DelegatingAuthenticationFailureHandler(handlers, null);
this.handlers.put(BadCredentialsException.class, this.handler1);
new DelegatingAuthenticationFailureHandler(this.handlers, null);
}

View File

@@ -42,11 +42,11 @@ public class HttpStatusEntryPointTests {
@SuppressWarnings("serial")
@Before
public void setup() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
authException = new AuthenticationException("") {
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.authException = new AuthenticationException("") {
};
entryPoint = new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED);
this.entryPoint = new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED);
}
@Test(expected = IllegalArgumentException.class)
@@ -56,9 +56,9 @@ public class HttpStatusEntryPointTests {
@Test
public void unauthorized() throws Exception {
entryPoint.commence(request, response, authException);
this.entryPoint.commence(this.request, this.response, this.authException);
assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
assertThat(this.response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED.value());
}
}

View File

@@ -33,7 +33,7 @@ public class LogoutHandlerTests {
@Before
public void setUp() {
filter = new LogoutFilter("/success", new SecurityContextLogoutHandler());
this.filter = new LogoutFilter("/success", new SecurityContextLogoutHandler());
}
@Test
@@ -46,7 +46,7 @@ public class LogoutHandlerTests {
request.setQueryString("otherparam=blah");
DefaultHttpFirewall fw = new DefaultHttpFirewall();
assertThat(filter.requiresLogout(fw.getFirewalledRequest(request), response)).isTrue();
assertThat(this.filter.requiresLogout(fw.getFirewalledRequest(request), response)).isTrue();
}
@Test
@@ -59,7 +59,7 @@ public class LogoutHandlerTests {
request.setRequestURI("/context/logout?param=blah");
request.setQueryString("otherparam=blah");
assertThat(filter.requiresLogout(request, response)).isTrue();
assertThat(this.filter.requiresLogout(request, response)).isTrue();
}
}

View File

@@ -61,7 +61,7 @@ public class LogoutSuccessEventPublishingLogoutHandlerTests {
@Override
public void publishEvent(Object event) {
if (LogoutSuccessEvent.class.isAssignableFrom(event.getClass())) {
flag = true;
this.flag = true;
}
}

View File

@@ -43,10 +43,10 @@ public class SecurityContextLogoutHandlerTests {
@Before
public void setUp() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
handler = new SecurityContextLogoutHandler();
this.handler = new SecurityContextLogoutHandler();
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(
@@ -63,16 +63,16 @@ public class SecurityContextLogoutHandlerTests {
@Test
public void clearsAuthentication() {
SecurityContext beforeContext = SecurityContextHolder.getContext();
handler.logout(request, response, SecurityContextHolder.getContext().getAuthentication());
this.handler.logout(this.request, this.response, SecurityContextHolder.getContext().getAuthentication());
assertThat(beforeContext.getAuthentication()).isNull();
}
@Test
public void disableClearsAuthentication() {
handler.setClearAuthentication(false);
this.handler.setClearAuthentication(false);
SecurityContext beforeContext = SecurityContextHolder.getContext();
Authentication beforeAuthentication = beforeContext.getAuthentication();
handler.logout(request, response, SecurityContextHolder.getContext().getAuthentication());
this.handler.logout(this.request, this.response, SecurityContextHolder.getContext().getAuthentication());
assertThat(beforeContext.getAuthentication()).isNotNull();
assertThat(beforeContext.getAuthentication()).isSameAs(beforeAuthentication);

View File

@@ -59,7 +59,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
@Before
public void createFilter() {
filter = new AbstractPreAuthenticatedProcessingFilter() {
this.filter = new AbstractPreAuthenticatedProcessingFilter() {
protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
return "n/a";
}
@@ -80,9 +80,9 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
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));
this.filter.setAuthenticationManager(am);
this.filter.afterPropertiesSet();
this.filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), mock(FilterChain.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -92,10 +92,10 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
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));
this.filter.setContinueFilterChainOnUnsuccessfulAuthentication(false);
this.filter.setAuthenticationManager(am);
this.filter.afterPropertiesSet();
this.filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), mock(FilterChain.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -435,7 +435,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
private boolean initFilterBeanInvoked;
protected Object getPreAuthenticatedPrincipal(HttpServletRequest httpRequest) {
return principal;
return this.principal;
}
protected Object getPreAuthenticatedCredentials(HttpServletRequest httpRequest) {
@@ -445,7 +445,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
@Override
protected void initFilterBean() throws ServletException {
super.initFilterBean();
initFilterBeanInvoked = true;
this.initFilterBeanInvoked = true;
}
}

View File

@@ -40,7 +40,7 @@ public class PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests {
@Test
public void testToString() {
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(
getRequest("testUser", new String[] {}), gas);
getRequest("testUser", new String[] {}), this.gas);
String toString = details.toString();
assertThat(toString.contains("Role1")).as("toString should contain Role1").isTrue();
assertThat(toString.contains("Role2")).as("toString should contain Role2").isTrue();
@@ -49,11 +49,10 @@ public class PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests {
@Test
public void testGetSetPreAuthenticatedGrantedAuthorities() {
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(
getRequest("testUser", new String[] {}), gas);
getRequest("testUser", new String[] {}), this.gas);
List<GrantedAuthority> returnedGas = details.getGrantedAuthorities();
assertThat(gas.containsAll(returnedGas) && returnedGas.containsAll(gas))
.withFailMessage(
"Collections do not contain same elements; expected: " + gas + ", returned: " + returnedGas)
assertThat(this.gas.containsAll(returnedGas) && returnedGas.containsAll(this.gas)).withFailMessage(
"Collections do not contain same elements; expected: " + this.gas + ", returned: " + returnedGas)
.isTrue();
}
@@ -62,7 +61,7 @@ public class PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests {
private Set<String> roles = new HashSet<>(Arrays.asList(aRoles));
public boolean isUserInRole(String arg0) {
return roles.contains(arg0);
return this.roles.contains(arg0);
}
};
req.setRemoteUser(userName);

View File

@@ -170,7 +170,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests {
private Set<String> roles = new HashSet<>(Arrays.asList(aRoles));
public boolean isUserInRole(String arg0) {
return roles.contains(arg0);
return this.roles.contains(arg0);
}
};
req.setRemoteUser(userName);

View File

@@ -52,7 +52,7 @@ public class J2eePreAuthenticatedProcessingFilterTests {
private Set<String> roles = new HashSet<>(Arrays.asList(aRoles));
public boolean isUserInRole(String arg0) {
return roles.contains(arg0);
return this.roles.contains(arg0);
}
};
req.setRemoteUser(aUserName);

View File

@@ -32,37 +32,37 @@ public class SubjectDnX509PrincipalExtractorTests {
@Before
public void setUp() {
extractor = new SubjectDnX509PrincipalExtractor();
extractor.setMessageSource(new SpringSecurityMessageSource());
this.extractor = new SubjectDnX509PrincipalExtractor();
this.extractor.setMessageSource(new SpringSecurityMessageSource());
}
@Test(expected = IllegalArgumentException.class)
public void invalidRegexFails() {
extractor.setSubjectDnRegex("CN=(.*?,"); // missing closing bracket on group
this.extractor.setSubjectDnRegex("CN=(.*?,"); // missing closing bracket on group
}
@Test
public void defaultCNPatternReturnsExcpectedPrincipal() throws Exception {
Object principal = extractor.extractPrincipal(X509TestUtils.buildTestCertificate());
Object principal = this.extractor.extractPrincipal(X509TestUtils.buildTestCertificate());
assertThat(principal).isEqualTo("Luke Taylor");
}
@Test
public void matchOnEmailReturnsExpectedPrincipal() throws Exception {
extractor.setSubjectDnRegex("emailAddress=(.*?),");
Object principal = extractor.extractPrincipal(X509TestUtils.buildTestCertificate());
this.extractor.setSubjectDnRegex("emailAddress=(.*?),");
Object principal = this.extractor.extractPrincipal(X509TestUtils.buildTestCertificate());
assertThat(principal).isEqualTo("luke@monkeymachine");
}
@Test(expected = BadCredentialsException.class)
public void matchOnShoeSizeThrowsBadCredentials() throws Exception {
extractor.setSubjectDnRegex("shoeSize=(.*?),");
extractor.extractPrincipal(X509TestUtils.buildTestCertificate());
this.extractor.setSubjectDnRegex("shoeSize=(.*?),");
this.extractor.extractPrincipal(X509TestUtils.buildTestCertificate());
}
@Test
public void defaultCNPatternReturnsPrincipalAtEndOfDNString() throws Exception {
Object principal = extractor.extractPrincipal(X509TestUtils.buildTestCertificateWithCnAtEnd());
Object principal = this.extractor.extractPrincipal(X509TestUtils.buildTestCertificateWithCnAtEnd());
assertThat(principal).isEqualTo("Duke");
}

View File

@@ -58,17 +58,17 @@ public class AbstractRememberMeServicesTests {
@Before
public void setup() {
uds = new MockUserDetailsService(joe, false);
this.uds = new MockUserDetailsService(joe, false);
}
@Test(expected = InvalidCookieException.class)
public void nonBase64CookieShouldBeDetected() {
new MockRememberMeServices(uds).decodeCookie("nonBase64CookieValue%");
new MockRememberMeServices(this.uds).decodeCookie("nonBase64CookieValue%");
}
@Test
public void setAndGetAreConsistent() throws Exception {
MockRememberMeServices services = new MockRememberMeServices(uds);
MockRememberMeServices services = new MockRememberMeServices(this.uds);
assertThat(services.getCookieName()).isNotNull();
assertThat(services.getParameter()).isNotNull();
assertThat(services.getKey()).isEqualTo("xxxx");
@@ -78,7 +78,7 @@ public class AbstractRememberMeServicesTests {
assertThat(services.getCookieName()).isEqualTo("kookie");
services.setTokenValiditySeconds(600);
assertThat(services.getTokenValiditySeconds()).isEqualTo(600);
assertThat(services.getUserDetailsService()).isSameAs(uds);
assertThat(services.getUserDetailsService()).isSameAs(this.uds);
AuthenticationDetailsSource ads = Mockito.mock(AuthenticationDetailsSource.class);
services.setAuthenticationDetailsSource(ads);
assertThat(services.getAuthenticationDetailsSource()).isSameAs(ads);
@@ -88,7 +88,7 @@ public class AbstractRememberMeServicesTests {
@Test
public void cookieShouldBeCorrectlyEncodedAndDecoded() {
String[] cookie = new String[] { "name:with:colon", "cookie", "tokens", "blah" };
MockRememberMeServices services = new MockRememberMeServices(uds);
MockRememberMeServices services = new MockRememberMeServices(this.uds);
String encoded = services.encodeCookie(cookie);
// '=' aren't allowed in version 0 cookies.
@@ -101,7 +101,7 @@ public class AbstractRememberMeServicesTests {
@Test
public void cookieWithOpenIDidentifierAsNameIsEncodedAndDecoded() {
String[] cookie = new String[] { "https://id.openid.zz", "cookie", "tokens", "blah" };
MockRememberMeServices services = new MockRememberMeServices(uds);
MockRememberMeServices services = new MockRememberMeServices(this.uds);
String[] decoded = services.decodeCookie(services.encodeCookie(cookie));
assertThat(decoded).hasSize(4);
@@ -116,7 +116,7 @@ public class AbstractRememberMeServicesTests {
@Test
public void autoLoginShouldReturnNullIfNoLoginCookieIsPresented() {
MockRememberMeServices services = new MockRememberMeServices(uds);
MockRememberMeServices services = new MockRememberMeServices(this.uds);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -135,7 +135,7 @@ public class AbstractRememberMeServicesTests {
@Test
public void successfulAutoLoginReturnsExpectedAuthentication() throws Exception {
MockRememberMeServices services = new MockRememberMeServices(uds);
MockRememberMeServices services = new MockRememberMeServices(this.uds);
services.afterPropertiesSet();
assertThat(services.getUserDetailsService()).isNotNull();
@@ -151,7 +151,7 @@ public class AbstractRememberMeServicesTests {
@Test
public void autoLoginShouldFailIfCookieIsNotBase64() {
MockRememberMeServices services = new MockRememberMeServices(uds);
MockRememberMeServices services = new MockRememberMeServices(this.uds);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -163,7 +163,7 @@ public class AbstractRememberMeServicesTests {
@Test
public void autoLoginShouldFailIfCookieIsEmpty() {
MockRememberMeServices services = new MockRememberMeServices(uds);
MockRememberMeServices services = new MockRememberMeServices(this.uds);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -191,8 +191,8 @@ public class AbstractRememberMeServicesTests {
@Test
public void autoLoginShouldFailIfUserNotFound() {
uds.setThrowException(true);
MockRememberMeServices services = new MockRememberMeServices(uds);
this.uds.setThrowException(true);
MockRememberMeServices services = new MockRememberMeServices(this.uds);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(createLoginCookie("cookie:1:2"));
@@ -207,9 +207,9 @@ public class AbstractRememberMeServicesTests {
@Test
public void autoLoginShouldFailIfUserAccountIsLocked() {
MockRememberMeServices services = new MockRememberMeServices(uds);
MockRememberMeServices services = new MockRememberMeServices(this.uds);
services.setUserDetailsChecker(new AccountStatusUserDetailsChecker());
uds.toReturn = new User("joe", "password", false, true, true, true, joe.getAuthorities());
this.uds.toReturn = new User("joe", "password", false, true, true, true, joe.getAuthorities());
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(createLoginCookie("cookie:1:2"));
@@ -224,8 +224,8 @@ public class AbstractRememberMeServicesTests {
@Test
public void loginFailShouldCancelCookie() {
uds.setThrowException(true);
MockRememberMeServices services = new MockRememberMeServices(uds);
this.uds.setThrowException(true);
MockRememberMeServices services = new MockRememberMeServices(this.uds);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContextPath("contextpath");
@@ -239,7 +239,7 @@ public class AbstractRememberMeServicesTests {
@Test
public void logoutShouldCancelCookie() {
MockRememberMeServices services = new MockRememberMeServices(uds);
MockRememberMeServices services = new MockRememberMeServices(this.uds);
services.setCookieDomain("spring.io");
MockHttpServletRequest request = new MockHttpServletRequest();
@@ -261,7 +261,7 @@ public class AbstractRememberMeServicesTests {
@Test
public void cancelledCookieShouldUseSecureFlag() {
MockRememberMeServices services = new MockRememberMeServices(uds);
MockRememberMeServices services = new MockRememberMeServices(this.uds);
services.setCookieDomain("spring.io");
services.setUseSecureCookie(true);
@@ -285,7 +285,7 @@ public class AbstractRememberMeServicesTests {
@Test
public void cancelledCookieShouldUseRequestIsSecure() {
MockRememberMeServices services = new MockRememberMeServices(uds);
MockRememberMeServices services = new MockRememberMeServices(this.uds);
services.setCookieDomain("spring.io");
MockHttpServletRequest request = new MockHttpServletRequest();
@@ -309,7 +309,7 @@ public class AbstractRememberMeServicesTests {
@Test(expected = CookieTheftException.class)
public void cookieTheftExceptionShouldBeRethrown() {
MockRememberMeServices services = new MockRememberMeServices(uds) {
MockRememberMeServices services = new MockRememberMeServices(this.uds) {
protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request,
HttpServletResponse response) {
@@ -327,7 +327,7 @@ public class AbstractRememberMeServicesTests {
@Test
public void loginSuccessCallsOnLoginSuccessCorrectly() {
MockRememberMeServices services = new MockRememberMeServices(uds);
MockRememberMeServices services = new MockRememberMeServices(this.uds);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -338,26 +338,26 @@ public class AbstractRememberMeServicesTests {
assertThat(services.loginSuccessCalled).isFalse();
// Parameter set to true
services = new MockRememberMeServices(uds);
services = new MockRememberMeServices(this.uds);
request.setParameter(MockRememberMeServices.DEFAULT_PARAMETER, "true");
services.loginSuccess(request, response, auth);
assertThat(services.loginSuccessCalled).isTrue();
// Different parameter name, set to true
services = new MockRememberMeServices(uds);
services = new MockRememberMeServices(this.uds);
services.setParameter("my_parameter");
request.setParameter("my_parameter", "true");
services.loginSuccess(request, response, auth);
assertThat(services.loginSuccessCalled).isTrue();
// Parameter set to false
services = new MockRememberMeServices(uds);
services = new MockRememberMeServices(this.uds);
request.setParameter(MockRememberMeServices.DEFAULT_PARAMETER, "false");
services.loginSuccess(request, response, auth);
assertThat(services.loginSuccessCalled).isFalse();
// alwaysRemember set to true
services = new MockRememberMeServices(uds);
services = new MockRememberMeServices(this.uds);
services.setAlwaysRemember(true);
services.loginSuccess(request, response, auth);
assertThat(services.loginSuccessCalled).isTrue();
@@ -368,7 +368,7 @@ public class AbstractRememberMeServicesTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContextPath("contextpath");
MockRememberMeServices services = new MockRememberMeServices(uds) {
MockRememberMeServices services = new MockRememberMeServices(this.uds) {
protected String encodeCookie(String[] cookieTokens) {
return cookieTokens[0];
@@ -391,7 +391,7 @@ public class AbstractRememberMeServicesTests {
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContextPath("contextpath");
MockRememberMeServices services = new MockRememberMeServices(uds) {
MockRememberMeServices services = new MockRememberMeServices(this.uds) {
protected String encodeCookie(String[] cookieTokens) {
return cookieTokens[0];
@@ -409,7 +409,7 @@ public class AbstractRememberMeServicesTests {
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContextPath("contextpath");
MockRememberMeServices services = new MockRememberMeServices(uds);
MockRememberMeServices services = new MockRememberMeServices(this.uds);
services.setCookie(new String[] { "mycookie" }, 1000, request, response);
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(cookie.isHttpOnly()).isTrue();
@@ -470,7 +470,7 @@ public class AbstractRememberMeServicesTests {
}
private Cookie[] createLoginCookie(String cookieToken) {
MockRememberMeServices services = new MockRememberMeServices(uds);
MockRememberMeServices services = new MockRememberMeServices(this.uds);
Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
services.encodeCookie(StringUtils.delimitedListToStringArray(cookieToken, ":")));
@@ -501,7 +501,7 @@ public class AbstractRememberMeServicesTests {
protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication successfulAuthentication) {
loginSuccessCalled = true;
this.loginSuccessCalled = true;
}
protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request,
@@ -533,11 +533,11 @@ public class AbstractRememberMeServicesTests {
}
public UserDetails loadUserByUsername(String username) {
if (throwException) {
if (this.throwException) {
throw new UsernameNotFoundException("as requested by mock");
}
return toReturn;
return this.toReturn;
}
public void setThrowException(boolean value) {

View File

@@ -75,27 +75,27 @@ public class JdbcTokenRepositoryImplTests {
@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, "
this.repo = new JdbcTokenRepositoryImpl();
ReflectionTestUtils.setField(this.repo, "logger", this.logger);
this.repo.setDataSource(dataSource);
this.repo.initDao();
this.template = this.repo.getJdbcTemplate();
this.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");
this.template.execute("drop table persistent_logins");
}
@Test
public void createNewTokenInsertsCorrectData() {
Timestamp currentDate = new Timestamp(Calendar.getInstance().getTimeInMillis());
PersistentRememberMeToken token = new PersistentRememberMeToken("joeuser", "joesseries", "atoken", currentDate);
repo.createNewToken(token);
this.repo.createNewToken(token);
Map<String, Object> results = template.queryForMap("select * from persistent_logins");
Map<String, Object> results = this.template.queryForMap("select * from persistent_logins");
assertThat(results.get("last_used")).isEqualTo(currentDate);
assertThat(results.get("username")).isEqualTo("joeuser");
@@ -106,9 +106,9 @@ public class JdbcTokenRepositoryImplTests {
@Test
public void retrievingTokenReturnsCorrectData() {
template.execute("insert into persistent_logins (series, username, token, last_used) values "
this.template.execute("insert into persistent_logins (series, username, token, last_used) values "
+ "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')");
PersistentRememberMeToken token = repo.getTokenForSeries("joesseries");
PersistentRememberMeToken token = this.repo.getTokenForSeries("joesseries");
assertThat(token.getUsername()).isEqualTo("joeuser");
assertThat(token.getSeries()).isEqualTo("joesseries");
@@ -118,45 +118,45 @@ public class JdbcTokenRepositoryImplTests {
@Test
public void retrievingTokenWithDuplicateSeriesReturnsNull() {
template.execute("insert into persistent_logins (series, username, token, last_used) values "
this.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 "
this.template.execute("insert into persistent_logins (series, username, token, last_used) values "
+ "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')");
// List results =
// template.queryForList("select * from persistent_logins where series =
// 'joesseries'");
assertThat(repo.getTokenForSeries("joesseries")).isNull();
assertThat(this.repo.getTokenForSeries("joesseries")).isNull();
}
// SEC-1964
@Test
public void retrievingTokenWithNoSeriesReturnsNull() {
when(logger.isDebugEnabled()).thenReturn(true);
when(this.logger.isDebugEnabled()).thenReturn(true);
assertThat(repo.getTokenForSeries("missingSeries")).isNull();
assertThat(this.repo.getTokenForSeries("missingSeries")).isNull();
verify(logger).isDebugEnabled();
verify(logger).debug(eq("Querying token for series 'missingSeries' returned no results."),
verify(this.logger).isDebugEnabled();
verify(this.logger).debug(eq("Querying token for series 'missingSeries' returned no results."),
any(EmptyResultDataAccessException.class));
verifyNoMoreInteractions(logger);
verifyNoMoreInteractions(this.logger);
}
@Test
public void removingUserTokensDeletesData() {
template.execute("insert into persistent_logins (series, username, token, last_used) values "
this.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 "
this.template.execute("insert into persistent_logins (series, username, token, last_used) values "
+ "('joesseries', 'joeuser', 'atoken', '2007-10-09 18:19:25.000000000')");
// List results =
// template.queryForList("select * from persistent_logins where series =
// 'joesseries'");
repo.removeUserTokens("joeuser");
this.repo.removeUserTokens("joeuser");
List<Map<String, Object>> results = template
List<Map<String, Object>> results = this.template
.queryForList("select * from persistent_logins where username = 'joeuser'");
assertThat(results).isEmpty();
@@ -165,11 +165,11 @@ public class JdbcTokenRepositoryImplTests {
@Test
public void updatingTokenModifiesTokenValueAndLastUsed() {
Timestamp ts = new Timestamp(System.currentTimeMillis() - 1);
template.execute("insert into persistent_logins (series, username, token, last_used) values "
this.template.execute("insert into persistent_logins (series, username, token, last_used) values "
+ "('joesseries', 'joeuser', 'atoken', '" + ts.toString() + "')");
repo.updateToken("joesseries", "newtoken", new Date());
this.repo.updateToken("joesseries", "newtoken", new Date());
Map<String, Object> results = template
Map<String, Object> results = this.template
.queryForMap("select * from persistent_logins where series = 'joesseries'");
assertThat(results.get("username")).isEqualTo("joeuser");
@@ -181,13 +181,13 @@ public class JdbcTokenRepositoryImplTests {
@Test
public void createTableOnStartupCreatesCorrectTable() {
template.execute("drop table persistent_logins");
repo = new JdbcTokenRepositoryImpl();
repo.setDataSource(dataSource);
repo.setCreateTableOnStartup(true);
repo.initDao();
this.template.execute("drop table persistent_logins");
this.repo = new JdbcTokenRepositoryImpl();
this.repo.setDataSource(dataSource);
this.repo.setCreateTableOnStartup(true);
this.repo.initDao();
template.queryForList("select username,series,token,last_used from persistent_logins");
this.template.queryForList("select username,series,token,last_used from persistent_logins");
}
// SEC-2879

View File

@@ -41,75 +41,76 @@ public class PersistentTokenBasedRememberMeServicesTests {
@Before
public void setUpData() throws Exception {
services = new PersistentTokenBasedRememberMeServices("key",
this.services = new PersistentTokenBasedRememberMeServices("key",
new AbstractRememberMeServicesTests.MockUserDetailsService(AbstractRememberMeServicesTests.joe, false),
new InMemoryTokenRepositoryImpl());
services.setCookieName("mycookiename");
this.services.setCookieName("mycookiename");
// Default to 100 days (see SEC-1081).
services.setTokenValiditySeconds(100 * 24 * 60 * 60);
services.afterPropertiesSet();
this.services.setTokenValiditySeconds(100 * 24 * 60 * 60);
this.services.afterPropertiesSet();
}
@Test(expected = InvalidCookieException.class)
public void loginIsRejectedWithWrongNumberOfCookieTokens() {
services.processAutoLoginCookie(new String[] { "series", "token", "extra" }, new MockHttpServletRequest(),
this.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(),
this.services = create(null);
this.services.processAutoLoginCookie(new String[] { "series", "token" }, new MockHttpServletRequest(),
new MockHttpServletResponse());
}
@Test(expected = RememberMeAuthenticationException.class)
public void loginIsRejectedWhenTokenIsExpired() {
services = create(new PersistentRememberMeToken("joe", "series", "token",
this.services = create(new PersistentRememberMeToken("joe", "series", "token",
new Date(System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(1) - 100)));
services.setTokenValiditySeconds(1);
this.services.setTokenValiditySeconds(1);
services.processAutoLoginCookie(new String[] { "series", "token" }, new MockHttpServletRequest(),
this.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(),
this.services = create(new PersistentRememberMeToken("joe", "series", "wrongtoken", new Date()));
this.services.processAutoLoginCookie(new String[] { "series", "token" }, new MockHttpServletRequest(),
new MockHttpServletResponse());
}
@Test
public void successfulAutoLoginCreatesNewTokenAndCookieWithSameSeries() {
services = create(new PersistentRememberMeToken("joe", "series", "token", new Date()));
this.services = create(new PersistentRememberMeToken("joe", "series", "token", new Date()));
// 12 => b64 length will be 16
services.setTokenLength(12);
this.services.setTokenLength(12);
MockHttpServletResponse response = new MockHttpServletResponse();
services.processAutoLoginCookie(new String[] { "series", "token" }, new MockHttpServletRequest(), response);
assertThat(repo.getStoredToken().getSeries()).isEqualTo("series");
assertThat(repo.getStoredToken().getTokenValue().length()).isEqualTo(16);
String[] cookie = services.decodeCookie(response.getCookie("mycookiename").getValue());
this.services.processAutoLoginCookie(new String[] { "series", "token" }, new MockHttpServletRequest(),
response);
assertThat(this.repo.getStoredToken().getSeries()).isEqualTo("series");
assertThat(this.repo.getStoredToken().getTokenValue().length()).isEqualTo(16);
String[] cookie = this.services.decodeCookie(response.getCookie("mycookiename").getValue());
assertThat(cookie[0]).isEqualTo("series");
assertThat(cookie[1]).isEqualTo(repo.getStoredToken().getTokenValue());
assertThat(cookie[1]).isEqualTo(this.repo.getStoredToken().getTokenValue());
}
@Test
public void loginSuccessCreatesNewTokenAndCookieWithNewSeries() {
services = create(null);
services.setAlwaysRemember(true);
services.setTokenLength(12);
services.setSeriesLength(12);
this.services = create(null);
this.services.setAlwaysRemember(true);
this.services.setTokenLength(12);
this.services.setSeriesLength(12);
MockHttpServletResponse response = new MockHttpServletResponse();
services.loginSuccess(new MockHttpServletRequest(), response,
this.services.loginSuccess(new MockHttpServletRequest(), response,
new UsernamePasswordAuthenticationToken("joe", "password"));
assertThat(repo.getStoredToken().getSeries().length()).isEqualTo(16);
assertThat(repo.getStoredToken().getTokenValue().length()).isEqualTo(16);
assertThat(this.repo.getStoredToken().getSeries().length()).isEqualTo(16);
assertThat(this.repo.getStoredToken().getTokenValue().length()).isEqualTo(16);
String[] cookie = services.decodeCookie(response.getCookie("mycookiename").getValue());
String[] cookie = this.services.decodeCookie(response.getCookie("mycookiename").getValue());
assertThat(cookie[0]).isEqualTo(repo.getStoredToken().getSeries());
assertThat(cookie[1]).isEqualTo(repo.getStoredToken().getTokenValue());
assertThat(cookie[0]).isEqualTo(this.repo.getStoredToken().getSeries());
assertThat(cookie[1]).isEqualTo(this.repo.getStoredToken().getTokenValue());
}
@Test
@@ -118,21 +119,21 @@ public class PersistentTokenBasedRememberMeServicesTests {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
MockHttpServletResponse response = new MockHttpServletResponse();
services = create(new PersistentRememberMeToken("joe", "series", "token", new Date()));
services.logout(request, response, new TestingAuthenticationToken("joe", "somepass", "SOME_AUTH"));
this.services = create(new PersistentRememberMeToken("joe", "series", "token", new Date()));
this.services.logout(request, response, new TestingAuthenticationToken("joe", "somepass", "SOME_AUTH"));
Cookie returnedCookie = response.getCookie("mycookiename");
assertThat(returnedCookie).isNotNull();
assertThat(returnedCookie.getMaxAge()).isZero();
// SEC-1280
services.logout(request, response, null);
this.services.logout(request, response, null);
}
private PersistentTokenBasedRememberMeServices create(PersistentRememberMeToken token) {
repo = new MockTokenRepository(token);
this.repo = new MockTokenRepository(token);
PersistentTokenBasedRememberMeServices services = new PersistentTokenBasedRememberMeServices("key",
new AbstractRememberMeServicesTests.MockUserDetailsService(AbstractRememberMeServicesTests.joe, false),
repo);
this.repo);
services.setCookieName("mycookiename");
return services;
@@ -143,27 +144,27 @@ public class PersistentTokenBasedRememberMeServicesTests {
private PersistentRememberMeToken storedToken;
private MockTokenRepository(PersistentRememberMeToken token) {
storedToken = token;
this.storedToken = token;
}
public void createNewToken(PersistentRememberMeToken token) {
storedToken = token;
this.storedToken = token;
}
public void updateToken(String series, String tokenValue, Date lastUsed) {
storedToken = new PersistentRememberMeToken(storedToken.getUsername(), storedToken.getSeries(), tokenValue,
lastUsed);
this.storedToken = new PersistentRememberMeToken(this.storedToken.getUsername(),
this.storedToken.getSeries(), tokenValue, lastUsed);
}
public PersistentRememberMeToken getTokenForSeries(String seriesId) {
return storedToken;
return this.storedToken;
}
public void removeUserTokens(String username) {
}
PersistentRememberMeToken getStoredToken() {
return storedToken;
return this.storedToken;
}
}

View File

@@ -81,7 +81,7 @@ public class RememberMeAuthenticationFilterTests {
// Setup our filter correctly
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(mock(AuthenticationManager.class),
new MockRememberMeServices(remembered));
new MockRememberMeServices(this.remembered));
filter.afterPropertiesSet();
// Test
@@ -98,10 +98,10 @@ public class RememberMeAuthenticationFilterTests {
@Test
public void testOperationWhenNoAuthenticationInContextHolder() throws Exception {
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(remembered)).thenReturn(remembered);
when(am.authenticate(this.remembered)).thenReturn(this.remembered);
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am,
new MockRememberMeServices(remembered));
new MockRememberMeServices(this.remembered));
filter.afterPropertiesSet();
MockHttpServletRequest request = new MockHttpServletRequest();
@@ -110,7 +110,7 @@ public class RememberMeAuthenticationFilterTests {
filter.doFilter(request, new MockHttpServletResponse(), fc);
// Ensure filter setup with our remembered authentication object
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(remembered);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(this.remembered);
verify(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@@ -121,7 +121,7 @@ public class RememberMeAuthenticationFilterTests {
when(am.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException(""));
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am,
new MockRememberMeServices(remembered)) {
new MockRememberMeServices(this.remembered)) {
protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
AuthenticationException failed) {
super.onUnsuccessfulAuthentication(request, response, failed);
@@ -143,9 +143,9 @@ public class RememberMeAuthenticationFilterTests {
@Test
public void authenticationSuccessHandlerIsInvokedOnSuccessfulAuthenticationIfSet() throws Exception {
AuthenticationManager am = mock(AuthenticationManager.class);
when(am.authenticate(remembered)).thenReturn(remembered);
when(am.authenticate(this.remembered)).thenReturn(this.remembered);
RememberMeAuthenticationFilter filter = new RememberMeAuthenticationFilter(am,
new MockRememberMeServices(remembered));
new MockRememberMeServices(this.remembered));
filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler("/target"));
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -168,7 +168,7 @@ public class RememberMeAuthenticationFilterTests {
}
public Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) {
return authToReturn;
return this.authToReturn;
}
public void loginFail(HttpServletRequest request, HttpServletResponse response) {

View File

@@ -62,20 +62,20 @@ public class TokenBasedRememberMeServicesTests {
@Before
public void createTokenBasedRememberMeServices() {
uds = mock(UserDetailsService.class);
services = new TokenBasedRememberMeServices("key", uds);
this.uds = mock(UserDetailsService.class);
this.services = new TokenBasedRememberMeServices("key", this.uds);
}
void udsWillReturnUser() {
when(uds.loadUserByUsername(any(String.class))).thenReturn(user);
when(this.uds.loadUserByUsername(any(String.class))).thenReturn(this.user);
}
void udsWillThrowNotFound() {
when(uds.loadUserByUsername(any(String.class))).thenThrow(new UsernameNotFoundException(""));
when(this.uds.loadUserByUsername(any(String.class))).thenThrow(new UsernameNotFoundException(""));
}
void udsWillReturnNull() {
when(uds.loadUserByUsername(any(String.class))).thenReturn(null);
when(this.uds.loadUserByUsername(any(String.class))).thenReturn(null);
}
private long determineExpiryTimeFromBased64EncodedToken(String validToken) {
@@ -107,7 +107,7 @@ public class TokenBasedRememberMeServicesTests {
public void autoLoginReturnsNullIfNoCookiePresented() {
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication result = services.autoLogin(new MockHttpServletRequest(), response);
Authentication result = this.services.autoLogin(new MockHttpServletRequest(), response);
assertThat(result).isNull();
// No cookie set
assertThat(response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull();
@@ -120,7 +120,7 @@ public class TokenBasedRememberMeServicesTests {
request.setCookies(cookie);
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication result = services.autoLogin(request, response);
Authentication result = this.services.autoLogin(request, response);
assertThat(result).isNull();
assertThat(response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull();
@@ -135,7 +135,7 @@ public class TokenBasedRememberMeServicesTests {
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(services.autoLogin(request, response)).isNull();
assertThat(this.services.autoLogin(request, response)).isNull();
Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
assertThat(returnedCookie.getMaxAge()).isZero();
@@ -149,7 +149,7 @@ public class TokenBasedRememberMeServicesTests {
request.setCookies(cookie);
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(services.autoLogin(request, response)).isNull();
assertThat(this.services.autoLogin(request, response)).isNull();
Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
@@ -163,7 +163,7 @@ public class TokenBasedRememberMeServicesTests {
request.setCookies(cookie);
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(services.autoLogin(request, response)).isNull();
assertThat(this.services.autoLogin(request, response)).isNull();
Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
@@ -180,7 +180,7 @@ public class TokenBasedRememberMeServicesTests {
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(services.autoLogin(request, response)).isNull();
assertThat(this.services.autoLogin(request, response)).isNull();
Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
@@ -195,7 +195,7 @@ public class TokenBasedRememberMeServicesTests {
request.setCookies(cookie);
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(services.autoLogin(request, response)).isNull();
assertThat(this.services.autoLogin(request, response)).isNull();
Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
@@ -212,7 +212,7 @@ public class TokenBasedRememberMeServicesTests {
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(services.autoLogin(request, response)).isNull();
assertThat(this.services.autoLogin(request, response)).isNull();
Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
@@ -229,7 +229,7 @@ public class TokenBasedRememberMeServicesTests {
MockHttpServletResponse response = new MockHttpServletResponse();
services.autoLogin(request, response);
this.services.autoLogin(request, response);
}
@Test
@@ -242,31 +242,31 @@ public class TokenBasedRememberMeServicesTests {
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication result = services.autoLogin(request, response);
Authentication result = this.services.autoLogin(request, response);
assertThat(result).isNotNull();
assertThat(result.getPrincipal()).isEqualTo(user);
assertThat(result.getPrincipal()).isEqualTo(this.user);
}
@Test
public void testGettersSetters() {
assertThat(services.getUserDetailsService()).isEqualTo(uds);
assertThat(this.services.getUserDetailsService()).isEqualTo(this.uds);
assertThat(services.getKey()).isEqualTo("key");
assertThat(this.services.getKey()).isEqualTo("key");
assertThat(services.getParameter()).isEqualTo(DEFAULT_PARAMETER);
services.setParameter("some_param");
assertThat(services.getParameter()).isEqualTo("some_param");
assertThat(this.services.getParameter()).isEqualTo(DEFAULT_PARAMETER);
this.services.setParameter("some_param");
assertThat(this.services.getParameter()).isEqualTo("some_param");
services.setTokenValiditySeconds(12);
assertThat(services.getTokenValiditySeconds()).isEqualTo(12);
this.services.setTokenValiditySeconds(12);
assertThat(this.services.getTokenValiditySeconds()).isEqualTo(12);
}
@Test
public void loginFailClearsCookie() {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
services.loginFail(request, response);
this.services.loginFail(request, response);
Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(cookie).isNotNull();
@@ -290,20 +290,21 @@ public class TokenBasedRememberMeServicesTests {
@Test
public void loginSuccessNormalWithNonUserDetailsBasedPrincipalSetsExpectedCookie() {
// SEC-822
services.setTokenValiditySeconds(500000000);
this.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"));
this.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];
String expiryTime = this.services.decodeCookie(cookie.getValue())[1];
long expectedExpiryTime = 1000L * 500000000;
expectedExpiryTime += System.currentTimeMillis();
assertThat(Long.parseLong(expiryTime) > expectedExpiryTime - 10000).isTrue();
assertThat(cookie).isNotNull();
assertThat(cookie.getMaxAge()).isEqualTo(services.getTokenValiditySeconds());
assertThat(cookie.getMaxAge()).isEqualTo(this.services.getTokenValiditySeconds());
assertThat(Base64.isArrayByteBase64(cookie.getValue().getBytes())).isTrue();
assertThat(new Date().before(new Date(determineExpiryTimeFromBased64EncodedToken(cookie.getValue())))).isTrue();
}
@@ -314,11 +315,12 @@ public class TokenBasedRememberMeServicesTests {
request.addParameter(TokenBasedRememberMeServices.DEFAULT_PARAMETER, "true");
MockHttpServletResponse response = new MockHttpServletResponse();
services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password", "ROLE_ABC"));
this.services.loginSuccess(request, response,
new TestingAuthenticationToken("someone", "password", "ROLE_ABC"));
Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(cookie).isNotNull();
assertThat(cookie.getMaxAge()).isEqualTo(services.getTokenValiditySeconds());
assertThat(cookie.getMaxAge()).isEqualTo(this.services.getTokenValiditySeconds());
assertThat(Base64.isArrayByteBase64(cookie.getValue().getBytes())).isTrue();
assertThat(new Date().before(new Date(determineExpiryTimeFromBased64EncodedToken(cookie.getValue())))).isTrue();
}
@@ -327,7 +329,7 @@ public class TokenBasedRememberMeServicesTests {
@Test
public void obtainPasswordReturnsNullForTokenWithNullCredentials() {
TestingAuthenticationToken token = new TestingAuthenticationToken("username", null);
assertThat(services.retrievePassword(token)).isNull();
assertThat(this.services.retrievePassword(token)).isNull();
}
// SEC-949
@@ -337,8 +339,9 @@ public class TokenBasedRememberMeServicesTests {
request.addParameter(DEFAULT_PARAMETER, "true");
MockHttpServletResponse response = new MockHttpServletResponse();
services.setTokenValiditySeconds(-1);
services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password", "ROLE_ABC"));
this.services.setTokenValiditySeconds(-1);
this.services.loginSuccess(request, response,
new TestingAuthenticationToken("someone", "password", "ROLE_ABC"));
Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(cookie).isNotNull();

View File

@@ -74,30 +74,30 @@ public class CompositeSessionAuthenticationStrategyTests {
@Test
public void delegatesToAll() {
CompositeSessionAuthenticationStrategy strategy = new CompositeSessionAuthenticationStrategy(
Arrays.asList(strategy1, strategy2));
strategy.onAuthentication(authentication, request, response);
Arrays.asList(this.strategy1, this.strategy2));
strategy.onAuthentication(this.authentication, this.request, this.response);
verify(strategy1).onAuthentication(authentication, request, response);
verify(strategy2).onAuthentication(authentication, request, response);
verify(this.strategy1).onAuthentication(this.authentication, this.request, this.response);
verify(this.strategy2).onAuthentication(this.authentication, this.request, this.response);
}
@Test
public void delegateShortCircuits() {
doThrow(new SessionAuthenticationException("oops")).when(strategy1).onAuthentication(authentication, request,
response);
doThrow(new SessionAuthenticationException("oops")).when(this.strategy1).onAuthentication(this.authentication,
this.request, this.response);
CompositeSessionAuthenticationStrategy strategy = new CompositeSessionAuthenticationStrategy(
Arrays.asList(strategy1, strategy2));
Arrays.asList(this.strategy1, this.strategy2));
try {
strategy.onAuthentication(authentication, request, response);
strategy.onAuthentication(this.authentication, this.request, this.response);
fail("Expected Exception");
}
catch (SessionAuthenticationException success) {
}
verify(strategy1).onAuthentication(authentication, request, response);
verify(strategy2, times(0)).onAuthentication(authentication, request, response);
verify(this.strategy1).onAuthentication(this.authentication, this.request, this.response);
verify(this.strategy2, times(0)).onAuthentication(this.authentication, this.request, this.response);
}
}

View File

@@ -62,12 +62,13 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
@Before
public void setup() {
authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
sessionInformation = new SessionInformation(authentication.getPrincipal(), "unique", new Date(1374766134216L));
this.authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.sessionInformation = new SessionInformation(this.authentication.getPrincipal(), "unique",
new Date(1374766134216L));
strategy = new ConcurrentSessionControlAuthenticationStrategy(sessionRegistry);
this.strategy = new ConcurrentSessionControlAuthenticationStrategy(this.sessionRegistry);
}
@Test(expected = IllegalArgumentException.class)
@@ -77,84 +78,84 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
@Test
public void noRegisteredSession() {
when(sessionRegistry.getAllSessions(any(), anyBoolean()))
when(this.sessionRegistry.getAllSessions(any(), anyBoolean()))
.thenReturn(Collections.<SessionInformation>emptyList());
strategy.setMaximumSessions(1);
strategy.setExceptionIfMaximumExceeded(true);
this.strategy.setMaximumSessions(1);
this.strategy.setExceptionIfMaximumExceeded(true);
strategy.onAuthentication(authentication, request, response);
this.strategy.onAuthentication(this.authentication, this.request, this.response);
// 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);
MockHttpSession session = new MockHttpSession(new MockServletContext(), this.sessionInformation.getSessionId());
this.request.setSession(session);
when(this.sessionRegistry.getAllSessions(any(), anyBoolean()))
.thenReturn(Collections.<SessionInformation>singletonList(this.sessionInformation));
this.strategy.setMaximumSessions(1);
this.strategy.setExceptionIfMaximumExceeded(true);
strategy.onAuthentication(authentication, request, response);
this.strategy.onAuthentication(this.authentication, this.request, this.response);
// 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);
when(this.sessionRegistry.getAllSessions(any(), anyBoolean()))
.thenReturn(Collections.<SessionInformation>singletonList(this.sessionInformation));
this.strategy.setMaximumSessions(1);
this.strategy.setExceptionIfMaximumExceeded(true);
strategy.onAuthentication(authentication, request, response);
this.strategy.onAuthentication(this.authentication, this.request, this.response);
}
@Test
public void maxSessionsExpireExistingUser() {
when(sessionRegistry.getAllSessions(any(), anyBoolean()))
.thenReturn(Collections.<SessionInformation>singletonList(sessionInformation));
strategy.setMaximumSessions(1);
when(this.sessionRegistry.getAllSessions(any(), anyBoolean()))
.thenReturn(Collections.<SessionInformation>singletonList(this.sessionInformation));
this.strategy.setMaximumSessions(1);
strategy.onAuthentication(authentication, request, response);
this.strategy.onAuthentication(this.authentication, this.request, this.response);
assertThat(sessionInformation.isExpired()).isTrue();
assertThat(this.sessionInformation.isExpired()).isTrue();
}
@Test
public void maxSessionsExpireLeastRecentExistingUser() {
SessionInformation moreRecentSessionInfo = new SessionInformation(authentication.getPrincipal(), "unique",
SessionInformation moreRecentSessionInfo = new SessionInformation(this.authentication.getPrincipal(), "unique",
new Date(1374766999999L));
when(sessionRegistry.getAllSessions(any(), anyBoolean()))
.thenReturn(Arrays.<SessionInformation>asList(moreRecentSessionInfo, sessionInformation));
strategy.setMaximumSessions(2);
when(this.sessionRegistry.getAllSessions(any(), anyBoolean()))
.thenReturn(Arrays.<SessionInformation>asList(moreRecentSessionInfo, this.sessionInformation));
this.strategy.setMaximumSessions(2);
strategy.onAuthentication(authentication, request, response);
this.strategy.onAuthentication(this.authentication, this.request, this.response);
assertThat(sessionInformation.isExpired()).isTrue();
assertThat(this.sessionInformation.isExpired()).isTrue();
}
@Test
public void onAuthenticationWhenMaxSessionsExceededByTwoThenTwoSessionsExpired() {
SessionInformation oldestSessionInfo = new SessionInformation(authentication.getPrincipal(), "unique1",
SessionInformation oldestSessionInfo = new SessionInformation(this.authentication.getPrincipal(), "unique1",
new Date(1374766134214L));
SessionInformation secondOldestSessionInfo = new SessionInformation(authentication.getPrincipal(), "unique2",
new Date(1374766134215L));
when(sessionRegistry.getAllSessions(any(), anyBoolean())).thenReturn(
Arrays.<SessionInformation>asList(oldestSessionInfo, secondOldestSessionInfo, sessionInformation));
strategy.setMaximumSessions(2);
SessionInformation secondOldestSessionInfo = new SessionInformation(this.authentication.getPrincipal(),
"unique2", new Date(1374766134215L));
when(this.sessionRegistry.getAllSessions(any(), anyBoolean())).thenReturn(
Arrays.<SessionInformation>asList(oldestSessionInfo, secondOldestSessionInfo, this.sessionInformation));
this.strategy.setMaximumSessions(2);
strategy.onAuthentication(authentication, request, response);
this.strategy.onAuthentication(this.authentication, this.request, this.response);
assertThat(oldestSessionInfo.isExpired()).isTrue();
assertThat(secondOldestSessionInfo.isExpired()).isTrue();
assertThat(sessionInformation.isExpired()).isFalse();
assertThat(this.sessionInformation.isExpired()).isFalse();
}
@Test(expected = IllegalArgumentException.class)
public void setMessageSourceNull() {
strategy.setMessageSource(null);
this.strategy.setMessageSource(null);
}
}

View File

@@ -49,10 +49,10 @@ public class RegisterSessionAuthenticationStrategyTests {
@Before
public void setup() {
authenticationStrategy = new RegisterSessionAuthenticationStrategy(registry);
authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
this.authenticationStrategy = new RegisterSessionAuthenticationStrategy(this.registry);
this.authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER");
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
}
@Test(expected = IllegalArgumentException.class)
@@ -62,9 +62,9 @@ public class RegisterSessionAuthenticationStrategyTests {
@Test
public void onAuthenticationRegistersSession() {
authenticationStrategy.onAuthentication(authentication, request, response);
this.authenticationStrategy.onAuthentication(this.authentication, this.request, this.response);
verify(registry).registerNewSession(request.getSession().getId(), authentication.getPrincipal());
verify(this.registry).registerNewSession(this.request.getSession().getId(), this.authentication.getPrincipal());
}
}

View File

@@ -500,8 +500,8 @@ public class SwitchUserFilterTests {
// gh-3697
@Test
public void switchAuthorityRoleCannotBeNull() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("switchAuthorityRole cannot be null");
this.thrown.expect(IllegalArgumentException.class);
this.thrown.expectMessage("switchAuthorityRole cannot be null");
switchToUserWithAuthorityRole("dano", null);
}
@@ -559,16 +559,16 @@ public class SwitchUserFilterTests {
// wofat (account expired)
// steve (credentials expired)
if ("jacklord".equals(username) || "dano".equals(username)) {
return new User(username, password, true, true, true, true, ROLES_12);
return new User(username, this.password, true, true, true, true, ROLES_12);
}
else if ("mcgarrett".equals(username)) {
return new User(username, password, false, true, true, true, ROLES_12);
return new User(username, this.password, false, true, true, true, ROLES_12);
}
else if ("wofat".equals(username)) {
return new User(username, password, true, false, true, true, ROLES_12);
return new User(username, this.password, true, false, true, true, ROLES_12);
}
else if ("steve".equals(username)) {
return new User(username, password, true, true, false, true, ROLES_12);
return new User(username, this.password, true, true, false, true, ROLES_12);
}
else {
throw new UsernameNotFoundException("Could not find: " + username);

View File

@@ -48,7 +48,7 @@ public class BasicAuthenticationConverterTests {
@Before
public void setup() {
converter = new BasicAuthenticationConverter(authenticationDetailsSource);
this.converter = new BasicAuthenticationConverter(this.authenticationDetailsSource);
}
@Test
@@ -56,9 +56,9 @@ public class BasicAuthenticationConverterTests {
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
UsernamePasswordAuthenticationToken authentication = converter.convert(request);
UsernamePasswordAuthenticationToken authentication = this.converter.convert(request);
verify(authenticationDetailsSource).buildDetails(any());
verify(this.authenticationDetailsSource).buildDetails(any());
assertThat(authentication).isNotNull();
assertThat(authentication.getName()).isEqualTo("rod");
}
@@ -68,9 +68,9 @@ public class BasicAuthenticationConverterTests {
String token = "rod:koala";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "BaSiC " + new String(Base64.encodeBase64(token.getBytes())));
UsernamePasswordAuthenticationToken authentication = converter.convert(request);
UsernamePasswordAuthenticationToken authentication = this.converter.convert(request);
verify(authenticationDetailsSource).buildDetails(any());
verify(this.authenticationDetailsSource).buildDetails(any());
assertThat(authentication).isNotNull();
assertThat(authentication.getName()).isEqualTo("rod");
}
@@ -79,9 +79,9 @@ public class BasicAuthenticationConverterTests {
public void testWhenUnsupportedAuthorizationHeaderThenIgnored() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Bearer someOtherToken");
UsernamePasswordAuthenticationToken authentication = converter.convert(request);
UsernamePasswordAuthenticationToken authentication = this.converter.convert(request);
verifyZeroInteractions(authenticationDetailsSource);
verifyZeroInteractions(this.authenticationDetailsSource);
assertThat(authentication).isNull();
}
@@ -90,7 +90,7 @@ public class BasicAuthenticationConverterTests {
String token = "NOT_A_VALID_TOKEN_AS_MISSING_COLON";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
converter.convert(request);
this.converter.convert(request);
}
@Test(expected = BadCredentialsException.class)
@@ -98,7 +98,7 @@ public class BasicAuthenticationConverterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic NOT_VALID_BASE64");
converter.convert(request);
this.converter.convert(request);
}
@Test
@@ -106,9 +106,9 @@ public class BasicAuthenticationConverterTests {
String token = "rod:";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
UsernamePasswordAuthenticationToken authentication = converter.convert(request);
UsernamePasswordAuthenticationToken authentication = this.converter.convert(request);
verify(authenticationDetailsSource).buildDetails(any());
verify(this.authenticationDetailsSource).buildDetails(any());
assertThat(authentication).isNotNull();
assertThat(authentication.getName()).isEqualTo("rod");
assertThat(authentication.getCredentials()).isEqualTo("");
@@ -118,7 +118,7 @@ public class BasicAuthenticationConverterTests {
public void requestWhenEmptyBasicAuthorizationHeaderTokenThenError() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic ");
converter.convert(request);
this.converter.convert(request);
}
}

View File

@@ -68,11 +68,11 @@ public class BasicAuthenticationFilterTests {
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(""));
this.manager = mock(AuthenticationManager.class);
when(this.manager.authenticate(rodRequest)).thenReturn(rod);
when(this.manager.authenticate(not(eq(rodRequest)))).thenThrow(new BadCredentialsException(""));
filter = new BasicAuthenticationFilter(manager, new BasicAuthenticationEntryPoint());
this.filter = new BasicAuthenticationFilter(this.manager, new BasicAuthenticationEntryPoint());
}
@After
@@ -88,7 +88,7 @@ public class BasicAuthenticationFilterTests {
final MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
this.filter.doFilter(request, response, chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
@@ -98,8 +98,8 @@ public class BasicAuthenticationFilterTests {
@Test
public void testGettersSetters() {
assertThat(filter.getAuthenticationManager()).isNotNull();
assertThat(filter.getAuthenticationEntryPoint()).isNotNull();
assertThat(this.filter.getAuthenticationManager()).isNotNull();
assertThat(this.filter.getAuthenticationEntryPoint()).isNotNull();
}
@Test
@@ -112,7 +112,7 @@ public class BasicAuthenticationFilterTests {
final MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
this.filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
@@ -128,7 +128,7 @@ public class BasicAuthenticationFilterTests {
final MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
this.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();
@@ -145,7 +145,7 @@ public class BasicAuthenticationFilterTests {
// Test
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, new MockHttpServletResponse(), chain);
this.filter.doFilter(request, new MockHttpServletResponse(), chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
@@ -163,7 +163,7 @@ public class BasicAuthenticationFilterTests {
// Test
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, new MockHttpServletResponse(), chain);
this.filter.doFilter(request, new MockHttpServletResponse(), chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
@@ -179,7 +179,7 @@ public class BasicAuthenticationFilterTests {
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, new MockHttpServletResponse(), chain);
this.filter.doFilter(request, new MockHttpServletResponse(), chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
@@ -193,7 +193,7 @@ public class BasicAuthenticationFilterTests {
request.addHeader("Authorization", "SOME_OTHER_AUTHENTICATION_SCHEME");
request.setServletPath("/some_file.html");
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, new MockHttpServletResponse(), chain);
this.filter.doFilter(request, new MockHttpServletResponse(), chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
@@ -201,7 +201,7 @@ public class BasicAuthenticationFilterTests {
@Test(expected = IllegalArgumentException.class)
public void testStartupDetectsMissingAuthenticationEntryPoint() {
new BasicAuthenticationFilter(manager, null);
new BasicAuthenticationFilter(this.manager, null);
}
@Test(expected = IllegalArgumentException.class)
@@ -218,7 +218,7 @@ public class BasicAuthenticationFilterTests {
final MockHttpServletResponse response1 = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response1, chain);
this.filter.doFilter(request, response1, chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
@@ -234,7 +234,7 @@ public class BasicAuthenticationFilterTests {
final MockHttpServletResponse response2 = new MockHttpServletResponse();
chain = mock(FilterChain.class);
filter.doFilter(request, response2, chain);
this.filter.doFilter(request, response2, chain);
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
request.setServletPath("/some_file.html");
@@ -254,10 +254,10 @@ public class BasicAuthenticationFilterTests {
request.setServletPath("/some_file.html");
request.setSession(new MockHttpSession());
filter = new BasicAuthenticationFilter(manager);
assertThat(filter.isIgnoreFailure()).isTrue();
this.filter = new BasicAuthenticationFilter(this.manager);
assertThat(this.filter.isIgnoreFailure()).isTrue();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, new MockHttpServletResponse(), chain);
this.filter.doFilter(request, new MockHttpServletResponse(), chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
@@ -272,11 +272,11 @@ public class BasicAuthenticationFilterTests {
request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
request.setServletPath("/some_file.html");
request.setSession(new MockHttpSession());
assertThat(filter.isIgnoreFailure()).isFalse();
assertThat(this.filter.isIgnoreFailure()).isFalse();
final MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
this.filter.doFilter(request, response, chain);
// Test - the filter chain will not be invoked, as we get a 401 forbidden response
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
@@ -297,7 +297,7 @@ public class BasicAuthenticationFilterTests {
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
this.filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(200);
}
@@ -311,11 +311,11 @@ public class BasicAuthenticationFilterTests {
Authentication rod = new UsernamePasswordAuthenticationToken("rod", "äöü",
AuthorityUtils.createAuthorityList("ROLE_1"));
manager = mock(AuthenticationManager.class);
when(manager.authenticate(rodRequest)).thenReturn(rod);
when(manager.authenticate(not(eq(rodRequest)))).thenThrow(new BadCredentialsException(""));
this.manager = mock(AuthenticationManager.class);
when(this.manager.authenticate(rodRequest)).thenReturn(rod);
when(this.manager.authenticate(not(eq(rodRequest)))).thenThrow(new BadCredentialsException(""));
filter = new BasicAuthenticationFilter(manager, new BasicAuthenticationEntryPoint());
this.filter = new BasicAuthenticationFilter(this.manager, new BasicAuthenticationEntryPoint());
String token = "rod:äöü";
MockHttpServletRequest request = new MockHttpServletRequest();
@@ -329,7 +329,7 @@ public class BasicAuthenticationFilterTests {
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
this.filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
@@ -346,12 +346,12 @@ public class BasicAuthenticationFilterTests {
Authentication rod = new UsernamePasswordAuthenticationToken("rod", "äöü",
AuthorityUtils.createAuthorityList("ROLE_1"));
manager = mock(AuthenticationManager.class);
when(manager.authenticate(rodRequest)).thenReturn(rod);
when(manager.authenticate(not(eq(rodRequest)))).thenThrow(new BadCredentialsException(""));
this.manager = mock(AuthenticationManager.class);
when(this.manager.authenticate(rodRequest)).thenReturn(rod);
when(this.manager.authenticate(not(eq(rodRequest)))).thenThrow(new BadCredentialsException(""));
filter = new BasicAuthenticationFilter(manager, new BasicAuthenticationEntryPoint());
filter.setCredentialsCharset("ISO-8859-1");
this.filter = new BasicAuthenticationFilter(this.manager, new BasicAuthenticationEntryPoint());
this.filter.setCredentialsCharset("ISO-8859-1");
String token = "rod:äöü";
MockHttpServletRequest request = new MockHttpServletRequest();
@@ -365,7 +365,7 @@ public class BasicAuthenticationFilterTests {
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
this.filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
@@ -382,12 +382,12 @@ public class BasicAuthenticationFilterTests {
Authentication rod = new UsernamePasswordAuthenticationToken("rod", "äöü",
AuthorityUtils.createAuthorityList("ROLE_1"));
manager = mock(AuthenticationManager.class);
when(manager.authenticate(rodRequest)).thenReturn(rod);
when(manager.authenticate(not(eq(rodRequest)))).thenThrow(new BadCredentialsException(""));
this.manager = mock(AuthenticationManager.class);
when(this.manager.authenticate(rodRequest)).thenReturn(rod);
when(this.manager.authenticate(not(eq(rodRequest)))).thenThrow(new BadCredentialsException(""));
filter = new BasicAuthenticationFilter(manager, new BasicAuthenticationEntryPoint());
filter.setCredentialsCharset("ISO-8859-1");
this.filter = new BasicAuthenticationFilter(this.manager, new BasicAuthenticationEntryPoint());
this.filter.setCredentialsCharset("ISO-8859-1");
String token = "rod:äöü";
MockHttpServletRequest request = new MockHttpServletRequest();
@@ -401,7 +401,7 @@ public class BasicAuthenticationFilterTests {
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
this.filter.doFilter(request, response, chain);
assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
@@ -417,7 +417,7 @@ public class BasicAuthenticationFilterTests {
final MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filter.doFilter(request, response, chain);
this.filter.doFilter(request, response, chain);
verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);

View File

@@ -128,12 +128,12 @@ public class DigestAuthenticationFilterTests {
ep.setRealmName(REALM);
ep.setKey(KEY);
filter = new DigestAuthenticationFilter();
filter.setUserDetailsService(uds);
filter.setAuthenticationEntryPoint(ep);
this.filter = new DigestAuthenticationFilter();
this.filter.setUserDetailsService(uds);
this.filter.setAuthenticationEntryPoint(ep);
request = new MockHttpServletRequest("GET", REQUEST_URI);
request.setServletPath(REQUEST_URI);
this.request = new MockHttpServletRequest("GET", REQUEST_URI);
this.request.setServletPath(REQUEST_URI);
}
@Test
@@ -142,12 +142,12 @@ public class DigestAuthenticationFilterTests {
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, nonce, NC, CNONCE);
request.addHeader("Authorization",
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
Thread.sleep(1000); // ensures token expired
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
@@ -164,10 +164,10 @@ public class DigestAuthenticationFilterTests {
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, badNonce, NC, CNONCE);
request.addHeader("Authorization",
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, badNonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
assertThat(response.getStatus()).isEqualTo(401);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
@@ -175,7 +175,7 @@ public class DigestAuthenticationFilterTests {
@Test
public void testFilterIgnoresRequestsContainingNoAuthorizationHeader() throws Exception {
executeFilterInContainerSimulator(filter, request, true);
executeFilterInContainerSimulator(this.filter, this.request, true);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -199,9 +199,9 @@ public class DigestAuthenticationFilterTests {
public void testInvalidDigestAuthorizationTokenGeneratesError() throws Exception {
String token = "NOT_A_VALID_TOKEN_AS_MISSING_COLON";
request.addHeader("Authorization", "Digest " + new String(Base64.encodeBase64(token.getBytes())));
this.request.addHeader("Authorization", "Digest " + new String(Base64.encodeBase64(token.getBytes())));
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
assertThat(response.getStatus()).isEqualTo(401);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
@@ -209,9 +209,9 @@ public class DigestAuthenticationFilterTests {
@Test
public void testMalformedHeaderReturnsForbidden() throws Exception {
request.addHeader("Authorization", "Digest scsdcsdc");
this.request.addHeader("Authorization", "Digest scsdcsdc");
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
@@ -224,10 +224,10 @@ public class DigestAuthenticationFilterTests {
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, nonce, NC, CNONCE);
request.addHeader("Authorization",
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
@@ -239,10 +239,10 @@ public class DigestAuthenticationFilterTests {
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, nonce, NC, CNONCE);
request.addHeader("Authorization",
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
@@ -254,10 +254,10 @@ public class DigestAuthenticationFilterTests {
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, nonce, NC, CNONCE);
request.addHeader("Authorization",
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
@@ -269,10 +269,10 @@ public class DigestAuthenticationFilterTests {
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, nonce, NC, CNONCE);
request.addHeader("Authorization",
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, nonce, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
@@ -284,10 +284,10 @@ public class DigestAuthenticationFilterTests {
String responseDigest = DigestAuthUtils.generateDigest(true, USERNAME, REALM, encodedPassword, "GET",
REQUEST_URI, QOP, NONCE, NC, CNONCE);
request.addHeader("Authorization",
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
executeFilterInContainerSimulator(filter, request, true);
executeFilterInContainerSimulator(this.filter, this.request, true);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername())
@@ -299,10 +299,10 @@ public class DigestAuthenticationFilterTests {
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, NONCE, NC, CNONCE);
request.addHeader("Authorization",
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
executeFilterInContainerSimulator(filter, request, true);
executeFilterInContainerSimulator(this.filter, this.request, true);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername())
@@ -315,11 +315,11 @@ public class DigestAuthenticationFilterTests {
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, NONCE, NC, CNONCE);
request.addHeader("Authorization",
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
filter.setCreateAuthenticatedToken(true);
executeFilterInContainerSimulator(filter, request, true);
this.filter.setCreateAuthenticatedToken(true);
executeFilterInContainerSimulator(this.filter, this.request, true);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername())
@@ -331,9 +331,9 @@ public class DigestAuthenticationFilterTests {
@Test
public void otherAuthorizationSchemeIsIgnored() throws Exception {
request.addHeader("Authorization", "SOME_OTHER_AUTHENTICATION_SCHEME");
this.request.addHeader("Authorization", "SOME_OTHER_AUTHENTICATION_SCHEME");
executeFilterInContainerSimulator(filter, request, true);
executeFilterInContainerSimulator(this.filter, this.request, true);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -357,10 +357,10 @@ public class DigestAuthenticationFilterTests {
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, NONCE, NC, CNONCE);
request.addHeader("Authorization",
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
executeFilterInContainerSimulator(filter, request, true);
executeFilterInContainerSimulator(this.filter, this.request, true);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
@@ -368,11 +368,11 @@ public class DigestAuthenticationFilterTests {
responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, "WRONG_PASSWORD", "GET", REQUEST_URI,
QOP, NONCE, NC, CNONCE);
request = new MockHttpServletRequest();
request.addHeader("Authorization",
this.request = new MockHttpServletRequest();
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
// Check we lost our previous authentication
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
@@ -386,10 +386,10 @@ public class DigestAuthenticationFilterTests {
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, NONCE, NC, "DIFFERENT_CNONCE");
request.addHeader("Authorization",
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, cnonce));
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
@@ -401,10 +401,10 @@ public class DigestAuthenticationFilterTests {
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, password, "GET", REQUEST_URI,
QOP, NONCE, NC, CNONCE);
request.addHeader("Authorization",
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
@@ -416,10 +416,10 @@ public class DigestAuthenticationFilterTests {
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, realm, PASSWORD, "GET", REQUEST_URI,
QOP, NONCE, NC, CNONCE);
request.addHeader("Authorization",
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, realm, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
@@ -430,10 +430,10 @@ public class DigestAuthenticationFilterTests {
String responseDigest = DigestAuthUtils.generateDigest(false, "NOT_A_KNOWN_USER", REALM, PASSWORD, "GET",
REQUEST_URI, QOP, NONCE, NC, CNONCE);
request.addHeader("Authorization",
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
MockHttpServletResponse response = executeFilterInContainerSimulator(filter, request, false);
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, false);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
assertThat(response.getStatus()).isEqualTo(401);
@@ -452,11 +452,11 @@ public class DigestAuthenticationFilterTests {
String responseDigest = DigestAuthUtils.generateDigest(false, USERNAME, REALM, PASSWORD, "GET", REQUEST_URI,
QOP, NONCE, NC, CNONCE);
request.addHeader("Authorization",
this.request.addHeader("Authorization",
createAuthorizationHeader(USERNAME, REALM, NONCE, REQUEST_URI, responseDigest, QOP, NC, CNONCE));
filter.setCreateAuthenticatedToken(true);
executeFilterInContainerSimulator(filter, request, true);
this.filter.setCreateAuthenticatedToken(true);
executeFilterInContainerSimulator(this.filter, this.request, true);
assertThat(existingAuthentication).isSameAs(existingContext.getAuthentication());
}

View File

@@ -49,7 +49,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
@Before
public void setup() {
resolver = new AuthenticationPrincipalArgumentResolver();
this.resolver = new AuthenticationPrincipalArgumentResolver();
}
@After
@@ -59,84 +59,88 @@ public class AuthenticationPrincipalArgumentResolverTests {
@Test
public void supportsParameterNoAnnotation() {
assertThat(resolver.supportsParameter(showUserNoAnnotation())).isFalse();
assertThat(this.resolver.supportsParameter(showUserNoAnnotation())).isFalse();
}
@Test
public void supportsParameterAnnotation() {
assertThat(resolver.supportsParameter(showUserAnnotationObject())).isTrue();
assertThat(this.resolver.supportsParameter(showUserAnnotationObject())).isTrue();
}
@Test
public void supportsParameterCustomAnnotation() {
assertThat(resolver.supportsParameter(showUserCustomAnnotation())).isTrue();
assertThat(this.resolver.supportsParameter(showUserCustomAnnotation())).isTrue();
}
@Test
public void resolveArgumentNullAuthentication() throws Exception {
assertThat(resolver.resolveArgument(showUserAnnotationString(), null, null, null)).isNull();
assertThat(this.resolver.resolveArgument(showUserAnnotationString(), null, null, null)).isNull();
}
@Test
public void resolveArgumentNullPrincipal() throws Exception {
setAuthenticationPrincipal(null);
assertThat(resolver.resolveArgument(showUserAnnotationString(), null, null, null)).isNull();
assertThat(this.resolver.resolveArgument(showUserAnnotationString(), null, null, null)).isNull();
}
@Test
public void resolveArgumentString() throws Exception {
setAuthenticationPrincipal("john");
assertThat(resolver.resolveArgument(showUserAnnotationString(), null, null, null)).isEqualTo(expectedPrincipal);
assertThat(this.resolver.resolveArgument(showUserAnnotationString(), null, null, null))
.isEqualTo(this.expectedPrincipal);
}
@Test
public void resolveArgumentPrincipalStringOnObject() throws Exception {
setAuthenticationPrincipal("john");
assertThat(resolver.resolveArgument(showUserAnnotationObject(), null, null, null)).isEqualTo(expectedPrincipal);
assertThat(this.resolver.resolveArgument(showUserAnnotationObject(), null, null, null))
.isEqualTo(this.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);
assertThat(this.resolver.resolveArgument(showUserAnnotationUserDetails(), null, null, null))
.isEqualTo(this.expectedPrincipal);
}
@Test
public void resolveArgumentCustomUserPrincipal() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
assertThat(resolver.resolveArgument(showUserAnnotationCustomUserPrincipal(), null, null, null))
.isEqualTo(expectedPrincipal);
assertThat(this.resolver.resolveArgument(showUserAnnotationCustomUserPrincipal(), null, null, null))
.isEqualTo(this.expectedPrincipal);
}
@Test
public void resolveArgumentCustomAnnotation() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
assertThat(resolver.resolveArgument(showUserCustomAnnotation(), null, null, null)).isEqualTo(expectedPrincipal);
assertThat(this.resolver.resolveArgument(showUserCustomAnnotation(), null, null, null))
.isEqualTo(this.expectedPrincipal);
}
@Test
public void resolveArgumentNullOnInvalidType() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
assertThat(resolver.resolveArgument(showUserAnnotationString(), null, null, null)).isNull();
assertThat(this.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);
this.resolver.resolveArgument(showUserAnnotationErrorOnInvalidType(), null, null, null);
}
@Test(expected = ClassCastException.class)
public void resolveArgumentCustomserErrorOnInvalidType() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
resolver.resolveArgument(showUserAnnotationCurrentUserErrorOnInvalidType(), null, null, null);
this.resolver.resolveArgument(showUserAnnotationCurrentUserErrorOnInvalidType(), null, null, null);
}
@Test
public void resolveArgumentObject() throws Exception {
setAuthenticationPrincipal(new Object());
assertThat(resolver.resolveArgument(showUserAnnotationObject(), null, null, null)).isEqualTo(expectedPrincipal);
assertThat(this.resolver.resolveArgument(showUserAnnotationObject(), null, null, null))
.isEqualTo(this.expectedPrincipal);
}
private MethodParameter showUserNoAnnotation() {
@@ -226,7 +230,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
private void setAuthenticationPrincipal(Object principal) {
this.expectedPrincipal = principal;
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken(expectedPrincipal, "password", "ROLE_USER"));
.setAuthentication(new TestingAuthenticationToken(this.expectedPrincipal, "password", "ROLE_USER"));
}
}

View File

@@ -120,7 +120,7 @@ public class HttpSessionSecurityContextRepositoryTests {
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContext context = repo.loadContext(holder);
// Change context
context.setAuthentication(testToken);
context.setAuthentication(this.testToken);
repo.saveContext(context, holder.getRequest(), holder.getResponse());
assertThat(request.getSession(false)).isNull();
}
@@ -130,13 +130,13 @@ public class HttpSessionSecurityContextRepositoryTests {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
repo.setSpringSecurityContextKey("imTheContext");
MockHttpServletRequest request = new MockHttpServletRequest();
SecurityContextHolder.getContext().setAuthentication(testToken);
SecurityContextHolder.getContext().setAuthentication(this.testToken);
request.getSession().setAttribute("imTheContext", SecurityContextHolder.getContext());
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContext context = repo.loadContext(holder);
assertThat(context).isNotNull();
assertThat(context.getAuthentication()).isEqualTo(testToken);
assertThat(context.getAuthentication()).isEqualTo(this.testToken);
// Won't actually be saved as it hasn't changed, but go through the use case
// anyway
repo.saveContext(context, holder.getRequest(), holder.getResponse());
@@ -151,7 +151,7 @@ public class HttpSessionSecurityContextRepositoryTests {
// Set up an existing authenticated context, mocking that it is in the session
// already
SecurityContext ctx = SecurityContextHolder.getContext();
ctx.setAuthentication(testToken);
ctx.setAuthentication(this.testToken);
HttpSession session = mock(HttpSession.class);
when(session.getAttribute(SPRING_SECURITY_CONTEXT_KEY)).thenReturn(ctx);
request.setSession(session);
@@ -171,7 +171,7 @@ public class HttpSessionSecurityContextRepositoryTests {
public void nonSecurityContextInSessionIsIgnored() {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
MockHttpServletRequest request = new MockHttpServletRequest();
SecurityContextHolder.getContext().setAuthentication(testToken);
SecurityContextHolder.getContext().setAuthentication(this.testToken);
request.getSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY, "NotASecurityContextInstance");
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
@@ -189,7 +189,7 @@ public class HttpSessionSecurityContextRepositoryTests {
SecurityContext context = repo.loadContext(holder);
assertThat(request.getSession(false)).isNull();
// Simulate authentication during the request
context.setAuthentication(testToken);
context.setAuthentication(this.testToken);
repo.saveContext(context, holder.getRequest(), holder.getResponse());
assertThat(request.getSession(false)).isNotNull();
assertThat(request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isEqualTo(context);
@@ -203,7 +203,7 @@ public class HttpSessionSecurityContextRepositoryTests {
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(testToken);
SecurityContextHolder.getContext().setAuthentication(this.testToken);
holder.getResponse().sendRedirect("/doesntmatter");
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext());
assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue();
@@ -220,7 +220,7 @@ public class HttpSessionSecurityContextRepositoryTests {
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(testToken);
SecurityContextHolder.getContext().setAuthentication(this.testToken);
holder.getResponse().sendError(404);
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext());
@@ -239,7 +239,7 @@ public class HttpSessionSecurityContextRepositoryTests {
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(testToken);
SecurityContextHolder.getContext().setAuthentication(this.testToken);
holder.getResponse().flushBuffer();
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext());
assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue();
@@ -257,7 +257,7 @@ public class HttpSessionSecurityContextRepositoryTests {
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(testToken);
SecurityContextHolder.getContext().setAuthentication(this.testToken);
holder.getResponse().getWriter().flush();
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext());
assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue();
@@ -275,7 +275,7 @@ public class HttpSessionSecurityContextRepositoryTests {
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(testToken);
SecurityContextHolder.getContext().setAuthentication(this.testToken);
holder.getResponse().getWriter().close();
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext());
assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue();
@@ -293,7 +293,7 @@ public class HttpSessionSecurityContextRepositoryTests {
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(testToken);
SecurityContextHolder.getContext().setAuthentication(this.testToken);
holder.getResponse().getOutputStream().flush();
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext());
assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue();
@@ -311,7 +311,7 @@ public class HttpSessionSecurityContextRepositoryTests {
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(testToken);
SecurityContextHolder.getContext().setAuthentication(this.testToken);
holder.getResponse().getOutputStream().close();
assertThat(request.getSession().getAttribute("imTheContext")).isEqualTo(SecurityContextHolder.getContext());
assertThat(((SaveContextOnUpdateOrErrorResponseWrapper) holder.getResponse()).isContextSaved()).isTrue();
@@ -331,7 +331,7 @@ public class HttpSessionSecurityContextRepositoryTests {
when(response.getOutputStream()).thenReturn(outputstream);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(testToken);
SecurityContextHolder.getContext().setAuthentication(this.testToken);
holder.getResponse().getOutputStream().close();
verify(outputstream).close();
}
@@ -347,7 +347,7 @@ public class HttpSessionSecurityContextRepositoryTests {
when(response.getOutputStream()).thenReturn(outputstream);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(testToken);
SecurityContextHolder.getContext().setAuthentication(this.testToken);
holder.getResponse().getOutputStream().flush();
verify(outputstream).flush();
}
@@ -360,7 +360,7 @@ public class HttpSessionSecurityContextRepositoryTests {
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(testToken);
SecurityContextHolder.getContext().setAuthentication(this.testToken);
request.getSession().invalidate();
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
assertThat(request.getSession(false)).isNull();
@@ -386,12 +386,12 @@ public class HttpSessionSecurityContextRepositoryTests {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
MockHttpServletRequest request = new MockHttpServletRequest();
SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext();
ctxInSession.setAuthentication(testToken);
ctxInSession.setAuthentication(this.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()));
.setAuthentication(new AnonymousAuthenticationToken("x", "x", this.testToken.getAuthorities()));
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
assertThat(request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isNull();
}
@@ -402,7 +402,7 @@ public class HttpSessionSecurityContextRepositoryTests {
repo.setSpringSecurityContextKey("imTheContext");
MockHttpServletRequest request = new MockHttpServletRequest();
SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext();
ctxInSession.setAuthentication(testToken);
ctxInSession.setAuthentication(this.testToken);
request.getSession().setAttribute("imTheContext", ctxInSession);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse());
repo.loadContext(holder);
@@ -419,7 +419,7 @@ public class HttpSessionSecurityContextRepositoryTests {
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse());
repo.loadContext(holder);
SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext();
ctxInSession.setAuthentication(testToken);
ctxInSession.setAuthentication(this.testToken);
request.getSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY, ctxInSession);
SecurityContextHolder.getContext().setAuthentication(
new AnonymousAuthenticationToken("x", "x", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
@@ -433,7 +433,7 @@ public class HttpSessionSecurityContextRepositoryTests {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
MockHttpServletRequest request = new MockHttpServletRequest();
SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext();
ctxInSession.setAuthentication(testToken);
ctxInSession.setAuthentication(this.testToken);
request.getSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY, ctxInSession);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse());
@@ -492,7 +492,7 @@ public class HttpSessionSecurityContextRepositoryTests {
@Test
public void saveContextCustomTrustResolver() {
SecurityContext contextToSave = SecurityContextHolder.createEmptyContext();
contextToSave.setAuthentication(testToken);
contextToSave.setAuthentication(this.testToken);
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
MockHttpServletRequest request = new MockHttpServletRequest();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse());
@@ -521,7 +521,7 @@ public class HttpSessionSecurityContextRepositoryTests {
SecurityContext context = repo.loadContext(holder);
assertThat(request.getSession(false)).isNull();
// Simulate authentication during the request
context.setAuthentication(testToken);
context.setAuthentication(this.testToken);
repo.saveContext(context, new HttpServletRequestWrapper(holder.getRequest()),
new HttpServletResponseWrapper(holder.getResponse()));
@@ -536,7 +536,7 @@ public class HttpSessionSecurityContextRepositoryTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(testToken);
context.setAuthentication(this.testToken);
repo.saveContext(context, request, response);
}

View File

@@ -47,9 +47,9 @@ public class SaveContextOnUpdateOrErrorResponseWrapperTests {
@Before
public void setUp() {
response = new MockHttpServletResponse();
wrappedResponse = new SaveContextOnUpdateOrErrorResponseWrapperStub(response, true);
SecurityContextHolder.setContext(securityContext);
this.response = new MockHttpServletResponse();
this.wrappedResponse = new SaveContextOnUpdateOrErrorResponseWrapperStub(this.response, true);
SecurityContextHolder.setContext(this.securityContext);
}
@After
@@ -60,121 +60,121 @@ public class SaveContextOnUpdateOrErrorResponseWrapperTests {
@Test
public void sendErrorSavesSecurityContext() throws Exception {
int error = HttpServletResponse.SC_FORBIDDEN;
wrappedResponse.sendError(error);
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
assertThat(response.getStatus()).isEqualTo(error);
this.wrappedResponse.sendError(error);
assertThat(this.wrappedResponse.securityContext).isEqualTo(this.securityContext);
assertThat(this.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);
this.wrappedResponse.disableSaveOnResponseCommitted();
this.wrappedResponse.sendError(error);
assertThat(this.wrappedResponse.securityContext).isNull();
assertThat(this.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);
this.wrappedResponse.sendError(error, message);
assertThat(this.wrappedResponse.securityContext).isEqualTo(this.securityContext);
assertThat(this.response.getStatus()).isEqualTo(error);
assertThat(this.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);
this.wrappedResponse.disableSaveOnResponseCommitted();
this.wrappedResponse.sendError(error, message);
assertThat(this.wrappedResponse.securityContext).isNull();
assertThat(this.response.getStatus()).isEqualTo(error);
assertThat(this.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);
this.wrappedResponse.sendRedirect(url);
assertThat(this.wrappedResponse.securityContext).isEqualTo(this.securityContext);
assertThat(this.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);
this.wrappedResponse.disableSaveOnResponseCommitted();
this.wrappedResponse.sendRedirect(url);
assertThat(this.wrappedResponse.securityContext).isNull();
assertThat(this.response.getRedirectedUrl()).isEqualTo(url);
}
@Test
public void outputFlushSavesSecurityContext() throws Exception {
wrappedResponse.getOutputStream().flush();
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
this.wrappedResponse.getOutputStream().flush();
assertThat(this.wrappedResponse.securityContext).isEqualTo(this.securityContext);
}
@Test
public void outputFlushSkipsSaveSecurityContextDisables() throws Exception {
wrappedResponse.disableSaveOnResponseCommitted();
wrappedResponse.getOutputStream().flush();
assertThat(wrappedResponse.securityContext).isNull();
this.wrappedResponse.disableSaveOnResponseCommitted();
this.wrappedResponse.getOutputStream().flush();
assertThat(this.wrappedResponse.securityContext).isNull();
}
@Test
public void outputCloseSavesSecurityContext() throws Exception {
wrappedResponse.getOutputStream().close();
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
this.wrappedResponse.getOutputStream().close();
assertThat(this.wrappedResponse.securityContext).isEqualTo(this.securityContext);
}
@Test
public void outputCloseSkipsSaveSecurityContextDisables() throws Exception {
wrappedResponse.disableSaveOnResponseCommitted();
wrappedResponse.getOutputStream().close();
assertThat(wrappedResponse.securityContext).isNull();
this.wrappedResponse.disableSaveOnResponseCommitted();
this.wrappedResponse.getOutputStream().close();
assertThat(this.wrappedResponse.securityContext).isNull();
}
@Test
public void writerFlushSavesSecurityContext() throws Exception {
wrappedResponse.getWriter().flush();
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
this.wrappedResponse.getWriter().flush();
assertThat(this.wrappedResponse.securityContext).isEqualTo(this.securityContext);
}
@Test
public void writerFlushSkipsSaveSecurityContextDisables() throws Exception {
wrappedResponse.disableSaveOnResponseCommitted();
wrappedResponse.getWriter().flush();
assertThat(wrappedResponse.securityContext).isNull();
this.wrappedResponse.disableSaveOnResponseCommitted();
this.wrappedResponse.getWriter().flush();
assertThat(this.wrappedResponse.securityContext).isNull();
}
@Test
public void writerCloseSavesSecurityContext() throws Exception {
wrappedResponse.getWriter().close();
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
this.wrappedResponse.getWriter().close();
assertThat(this.wrappedResponse.securityContext).isEqualTo(this.securityContext);
}
@Test
public void writerCloseSkipsSaveSecurityContextDisables() throws Exception {
wrappedResponse.disableSaveOnResponseCommitted();
wrappedResponse.getWriter().close();
assertThat(wrappedResponse.securityContext).isNull();
this.wrappedResponse.disableSaveOnResponseCommitted();
this.wrappedResponse.getWriter().close();
assertThat(this.wrappedResponse.securityContext).isNull();
}
@Test
public void flushBufferSavesSecurityContext() throws Exception {
wrappedResponse.flushBuffer();
assertThat(wrappedResponse.securityContext).isEqualTo(securityContext);
this.wrappedResponse.flushBuffer();
assertThat(this.wrappedResponse.securityContext).isEqualTo(this.securityContext);
}
@Test
public void flushBufferSkipsSaveSecurityContextDisables() throws Exception {
wrappedResponse.disableSaveOnResponseCommitted();
wrappedResponse.flushBuffer();
assertThat(wrappedResponse.securityContext).isNull();
this.wrappedResponse.disableSaveOnResponseCommitted();
this.wrappedResponse.flushBuffer();
assertThat(this.wrappedResponse.securityContext).isNull();
}
private static class SaveContextOnUpdateOrErrorResponseWrapperStub
@@ -188,7 +188,7 @@ public class SaveContextOnUpdateOrErrorResponseWrapperTests {
@Override
protected void saveContext(SecurityContext context) {
securityContext = context;
this.securityContext = context;
}
}

View File

@@ -54,7 +54,7 @@ public class SecurityContextPersistenceFilterTests {
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpServletResponse response = new MockHttpServletResponse();
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
SecurityContextHolder.getContext().setAuthentication(testToken);
SecurityContextHolder.getContext().setAuthentication(this.testToken);
filter.doFilter(request, response, chain);
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
@@ -67,7 +67,7 @@ public class SecurityContextPersistenceFilterTests {
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpServletResponse response = new MockHttpServletResponse();
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter();
SecurityContextHolder.getContext().setAuthentication(testToken);
SecurityContextHolder.getContext().setAuthentication(this.testToken);
doThrow(new IOException()).when(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
try {
filter.doFilter(request, response, chain);
@@ -86,7 +86,7 @@ public class SecurityContextPersistenceFilterTests {
final TestingAuthenticationToken beforeAuth = new TestingAuthenticationToken("someoneelse", "passwd", "ROLE_B");
final SecurityContext scBefore = new SecurityContextImpl();
final SecurityContext scExpectedAfter = new SecurityContextImpl();
scExpectedAfter.setAuthentication(testToken);
scExpectedAfter.setAuthentication(this.testToken);
scBefore.setAuthentication(beforeAuth);
final SecurityContextRepository repo = mock(SecurityContextRepository.class);
SecurityContextPersistenceFilter filter = new SecurityContextPersistenceFilter(repo);

View File

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

View File

@@ -70,18 +70,18 @@ public class WebAsyncManagerIntegrationFilterTests {
@Before
public void setUp() {
filterChain = new MockFilterChain();
this.filterChain = new MockFilterChain();
threadFactory = new JoinableThreadFactory();
this.threadFactory = new JoinableThreadFactory();
SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor();
executor.setThreadFactory(threadFactory);
executor.setThreadFactory(this.threadFactory);
asyncManager = WebAsyncUtils.getAsyncManager(request);
asyncManager.setAsyncWebRequest(asyncWebRequest);
asyncManager.setTaskExecutor(executor);
when(request.getAttribute(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE)).thenReturn(asyncManager);
this.asyncManager = WebAsyncUtils.getAsyncManager(this.request);
this.asyncManager.setAsyncWebRequest(this.asyncWebRequest);
this.asyncManager.setTaskExecutor(executor);
when(this.request.getAttribute(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE)).thenReturn(this.asyncManager);
filter = new WebAsyncManagerIntegrationFilter();
this.filter = new WebAsyncManagerIntegrationFilter();
}
@After
@@ -91,37 +91,39 @@ public class WebAsyncManagerIntegrationFilterTests {
@Test
public void doFilterInternalRegistersSecurityContextCallableProcessor() throws Exception {
SecurityContextHolder.setContext(securityContext);
asyncManager.registerCallableInterceptors(new CallableProcessingInterceptorAdapter() {
SecurityContextHolder.setContext(this.securityContext);
this.asyncManager.registerCallableInterceptors(new CallableProcessingInterceptorAdapter() {
@Override
public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) {
assertThat(SecurityContextHolder.getContext()).isNotSameAs(securityContext);
assertThat(SecurityContextHolder.getContext())
.isNotSameAs(WebAsyncManagerIntegrationFilterTests.this.securityContext);
}
});
filter.doFilterInternal(request, response, filterChain);
this.filter.doFilterInternal(this.request, this.response, this.filterChain);
VerifyingCallable verifyingCallable = new VerifyingCallable();
asyncManager.startCallableProcessing(verifyingCallable);
threadFactory.join();
assertThat(asyncManager.getConcurrentResult()).isSameAs(securityContext);
this.asyncManager.startCallableProcessing(verifyingCallable);
this.threadFactory.join();
assertThat(this.asyncManager.getConcurrentResult()).isSameAs(this.securityContext);
}
@Test
public void doFilterInternalRegistersSecurityContextCallableProcessorContextUpdated() throws Exception {
SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext());
asyncManager.registerCallableInterceptors(new CallableProcessingInterceptorAdapter() {
this.asyncManager.registerCallableInterceptors(new CallableProcessingInterceptorAdapter() {
@Override
public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) {
assertThat(SecurityContextHolder.getContext()).isNotSameAs(securityContext);
assertThat(SecurityContextHolder.getContext())
.isNotSameAs(WebAsyncManagerIntegrationFilterTests.this.securityContext);
}
});
filter.doFilterInternal(request, response, filterChain);
SecurityContextHolder.setContext(securityContext);
this.filter.doFilterInternal(this.request, this.response, this.filterChain);
SecurityContextHolder.setContext(this.securityContext);
VerifyingCallable verifyingCallable = new VerifyingCallable();
asyncManager.startCallableProcessing(verifyingCallable);
threadFactory.join();
assertThat(asyncManager.getConcurrentResult()).isSameAs(securityContext);
this.asyncManager.startCallableProcessing(verifyingCallable);
this.threadFactory.join();
assertThat(this.asyncManager.getConcurrentResult()).isSameAs(this.securityContext);
}
private static final class JoinableThreadFactory implements ThreadFactory {
@@ -129,12 +131,12 @@ public class WebAsyncManagerIntegrationFilterTests {
private Thread t;
public Thread newThread(Runnable r) {
t = new Thread(r);
return t;
this.t = new Thread(r);
return this.t;
}
public void join() throws InterruptedException {
t.join();
this.t.join();
}
}

View File

@@ -45,9 +45,9 @@ public class CsrfLogoutHandlerTests {
@Before
public void setup() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
handler = new CsrfLogoutHandler(csrfTokenRepository);
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.handler = new CsrfLogoutHandler(this.csrfTokenRepository);
}
@Test(expected = IllegalArgumentException.class)
@@ -57,9 +57,10 @@ public class CsrfLogoutHandlerTests {
@Test
public void logoutRemovesCsrfToken() {
handler.logout(request, response, new TestingAuthenticationToken("user", "password", "ROLE_USER"));
this.handler.logout(this.request, this.response,
new TestingAuthenticationToken("user", "password", "ROLE_USER"));
verify(csrfTokenRepository).saveToken(null, request, response);
verify(this.csrfTokenRepository).saveToken(null, this.request, this.response);
}
}

View File

@@ -31,32 +31,32 @@ public class DefaultCsrfTokenTests {
@Test(expected = IllegalArgumentException.class)
public void constructorNullHeaderName() {
new DefaultCsrfToken(null, parameterName, tokenValue);
new DefaultCsrfToken(null, this.parameterName, this.tokenValue);
}
@Test(expected = IllegalArgumentException.class)
public void constructorEmptyHeaderName() {
new DefaultCsrfToken("", parameterName, tokenValue);
new DefaultCsrfToken("", this.parameterName, this.tokenValue);
}
@Test(expected = IllegalArgumentException.class)
public void constructorNullParameterName() {
new DefaultCsrfToken(headerName, null, tokenValue);
new DefaultCsrfToken(this.headerName, null, this.tokenValue);
}
@Test(expected = IllegalArgumentException.class)
public void constructorEmptyParameterName() {
new DefaultCsrfToken(headerName, "", tokenValue);
new DefaultCsrfToken(this.headerName, "", this.tokenValue);
}
@Test(expected = IllegalArgumentException.class)
public void constructorNullTokenValue() {
new DefaultCsrfToken(headerName, parameterName, null);
new DefaultCsrfToken(this.headerName, this.parameterName, null);
}
@Test(expected = IllegalArgumentException.class)
public void constructorEmptyTokenValue() {
new DefaultCsrfToken(headerName, parameterName, "");
new DefaultCsrfToken(this.headerName, this.parameterName, "");
}
}

View File

@@ -39,19 +39,19 @@ public class HttpSessionCsrfTokenRepositoryTests {
@Before
public void setup() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
repo = new HttpSessionCsrfTokenRepository();
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.repo = new HttpSessionCsrfTokenRepository();
}
@Test
public void generateToken() {
token = repo.generateToken(request);
this.token = this.repo.generateToken(this.request);
assertThat(token.getParameterName()).isEqualTo("_csrf");
assertThat(token.getToken()).isNotEmpty();
assertThat(this.token.getParameterName()).isEqualTo("_csrf");
assertThat(this.token.getToken()).isNotEmpty();
CsrfToken loadedToken = repo.loadToken(request);
CsrfToken loadedToken = this.repo.loadToken(this.request);
assertThat(loadedToken).isNull();
}
@@ -59,44 +59,44 @@ public class HttpSessionCsrfTokenRepositoryTests {
@Test
public void generateCustomParameter() {
String paramName = "_csrf";
repo.setParameterName(paramName);
this.repo.setParameterName(paramName);
token = repo.generateToken(request);
this.token = this.repo.generateToken(this.request);
assertThat(token.getParameterName()).isEqualTo(paramName);
assertThat(token.getToken()).isNotEmpty();
assertThat(this.token.getParameterName()).isEqualTo(paramName);
assertThat(this.token.getToken()).isNotEmpty();
}
@Test
public void generateCustomHeader() {
String headerName = "CSRF";
repo.setHeaderName(headerName);
this.repo.setHeaderName(headerName);
token = repo.generateToken(request);
this.token = this.repo.generateToken(this.request);
assertThat(token.getHeaderName()).isEqualTo(headerName);
assertThat(token.getToken()).isNotEmpty();
assertThat(this.token.getHeaderName()).isEqualTo(headerName);
assertThat(this.token.getToken()).isNotEmpty();
}
@Test
public void loadTokenNull() {
assertThat(repo.loadToken(request)).isNull();
assertThat(request.getSession(false)).isNull();
assertThat(this.repo.loadToken(this.request)).isNull();
assertThat(this.request.getSession(false)).isNull();
}
@Test
public void loadTokenNullWhenSessionExists() {
request.getSession();
assertThat(repo.loadToken(request)).isNull();
this.request.getSession();
assertThat(this.repo.loadToken(this.request)).isNull();
}
@Test
public void saveToken() {
CsrfToken tokenToSave = new DefaultCsrfToken("123", "abc", "def");
repo.saveToken(tokenToSave, request, response);
this.repo.saveToken(tokenToSave, this.request, this.response);
String attrName = request.getSession().getAttributeNames().nextElement();
CsrfToken loadedToken = (CsrfToken) request.getSession().getAttribute(attrName);
String attrName = this.request.getSession().getAttributeNames().nextElement();
CsrfToken loadedToken = (CsrfToken) this.request.getSession().getAttribute(attrName);
assertThat(loadedToken).isEqualTo(tokenToSave);
}
@@ -105,10 +105,10 @@ public class HttpSessionCsrfTokenRepositoryTests {
public void saveTokenCustomSessionAttribute() {
CsrfToken tokenToSave = new DefaultCsrfToken("123", "abc", "def");
String sessionAttributeName = "custom";
repo.setSessionAttributeName(sessionAttributeName);
repo.saveToken(tokenToSave, request, response);
this.repo.setSessionAttributeName(sessionAttributeName);
this.repo.saveToken(tokenToSave, this.request, this.response);
CsrfToken loadedToken = (CsrfToken) request.getSession().getAttribute(sessionAttributeName);
CsrfToken loadedToken = (CsrfToken) this.request.getSession().getAttribute(sessionAttributeName);
assertThat(loadedToken).isEqualTo(tokenToSave);
}
@@ -117,37 +117,37 @@ public class HttpSessionCsrfTokenRepositoryTests {
public void saveTokenNullToken() {
saveToken();
repo.saveToken(null, request, response);
this.repo.saveToken(null, this.request, this.response);
assertThat(request.getSession().getAttributeNames().hasMoreElements()).isFalse();
assertThat(this.request.getSession().getAttributeNames().hasMoreElements()).isFalse();
}
@Test
public void saveTokenNullTokenWhenSessionNotExists() {
repo.saveToken(null, request, response);
this.repo.saveToken(null, this.request, this.response);
assertThat(request.getSession(false)).isNull();
assertThat(this.request.getSession(false)).isNull();
}
@Test(expected = IllegalArgumentException.class)
public void setSessionAttributeNameEmpty() {
repo.setSessionAttributeName("");
this.repo.setSessionAttributeName("");
}
@Test(expected = IllegalArgumentException.class)
public void setSessionAttributeNameNull() {
repo.setSessionAttributeName(null);
this.repo.setSessionAttributeName(null);
}
@Test(expected = IllegalArgumentException.class)
public void setParameterNameEmpty() {
repo.setParameterName("");
this.repo.setParameterName("");
}
@Test(expected = IllegalArgumentException.class)
public void setParameterNameNull() {
repo.setParameterName(null);
this.repo.setParameterName(null);
}
}

View File

@@ -77,45 +77,45 @@ public class DebugFilterTests {
@Before
public void setUp() {
when(request.getHeaderNames()).thenReturn(Collections.enumeration(Collections.<String>emptyList()));
when(request.getServletPath()).thenReturn("/login");
filter = new DebugFilter(fcp);
ReflectionTestUtils.setField(filter, "logger", logger);
requestAttr = DebugFilter.ALREADY_FILTERED_ATTR_NAME;
when(this.request.getHeaderNames()).thenReturn(Collections.enumeration(Collections.<String>emptyList()));
when(this.request.getServletPath()).thenReturn("/login");
this.filter = new DebugFilter(this.fcp);
ReflectionTestUtils.setField(this.filter, "logger", this.logger);
this.requestAttr = DebugFilter.ALREADY_FILTERED_ATTR_NAME;
}
@Test
public void doFilterProcessesRequests() throws Exception {
filter.doFilter(request, response, filterChain);
this.filter.doFilter(this.request, this.response, this.filterChain);
verify(logger).info(anyString());
verify(request).setAttribute(requestAttr, Boolean.TRUE);
verify(fcp).doFilter(requestCaptor.capture(), eq(response), eq(filterChain));
assertThat(requestCaptor.getValue().getClass()).isEqualTo(DebugRequestWrapper.class);
verify(request).removeAttribute(requestAttr);
verify(this.logger).info(anyString());
verify(this.request).setAttribute(this.requestAttr, Boolean.TRUE);
verify(this.fcp).doFilter(this.requestCaptor.capture(), eq(this.response), eq(this.filterChain));
assertThat(this.requestCaptor.getValue().getClass()).isEqualTo(DebugRequestWrapper.class);
verify(this.request).removeAttribute(this.requestAttr);
}
// SEC-1901
@Test
public void doFilterProcessesForwardedRequests() throws Exception {
when(request.getAttribute(requestAttr)).thenReturn(Boolean.TRUE);
when(this.request.getAttribute(this.requestAttr)).thenReturn(Boolean.TRUE);
HttpServletRequest request = new DebugRequestWrapper(this.request);
filter.doFilter(request, response, filterChain);
this.filter.doFilter(request, this.response, this.filterChain);
verify(logger).info(anyString());
verify(fcp).doFilter(request, response, filterChain);
verify(this.request, never()).removeAttribute(requestAttr);
verify(this.logger).info(anyString());
verify(this.fcp).doFilter(request, this.response, this.filterChain);
verify(this.request, never()).removeAttribute(this.requestAttr);
}
@Test
public void doFilterDoesNotWrapWithDebugRequestWrapperAgain() throws Exception {
when(request.getAttribute(requestAttr)).thenReturn(Boolean.TRUE);
when(this.request.getAttribute(this.requestAttr)).thenReturn(Boolean.TRUE);
HttpServletRequest fireWalledRequest = new HttpServletRequestWrapper(new DebugRequestWrapper(this.request));
filter.doFilter(fireWalledRequest, response, filterChain);
this.filter.doFilter(fireWalledRequest, this.response, this.filterChain);
verify(fcp).doFilter(fireWalledRequest, response, filterChain);
verify(this.fcp).doFilter(fireWalledRequest, this.response, this.filterChain);
}
@Test
@@ -128,12 +128,12 @@ public class DebugFilterTests {
request.addHeader("A", "Another Value");
request.addHeader("B", "B Value");
filter.doFilter(request, response, filterChain);
this.filter.doFilter(request, this.response, this.filterChain);
verify(logger).info(logCaptor.capture());
verify(this.logger).info(this.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"
assertThat(this.logCaptor.getValue()).isEqualTo("Request received for GET '/path/':\n" + "\n" + request + "\n"
+ "\n" + "servletPath:/path\n" + "pathInfo:/\n" + "headers: \n" + "A: A Value, Another Value\n"
+ "B: B Value\n" + "\n" + "\n" + "Security filter chain: no match");
}

View File

@@ -43,57 +43,57 @@ public class FirewalledResponseTests {
@Before
public void setup() {
response = mock(HttpServletResponse.class);
fwResponse = new FirewalledResponse(response);
this.response = mock(HttpServletResponse.class);
this.fwResponse = new FirewalledResponse(this.response);
}
@Test
public void sendRedirectWhenValidThenNoException() throws Exception {
fwResponse.sendRedirect("/theURL");
this.fwResponse.sendRedirect("/theURL");
verify(response).sendRedirect("/theURL");
verify(this.response).sendRedirect("/theURL");
}
@Test
public void sendRedirectWhenNullThenDelegateInvoked() throws Exception {
fwResponse.sendRedirect(null);
this.fwResponse.sendRedirect(null);
verify(response).sendRedirect(null);
verify(this.response).sendRedirect(null);
}
@Test
public void sendRedirectWhenHasCrlfThenThrowsException() throws Exception {
expectCrlfValidationException();
fwResponse.sendRedirect("/theURL\r\nsomething");
this.fwResponse.sendRedirect("/theURL\r\nsomething");
}
@Test
public void addHeaderWhenValidThenDelegateInvoked() {
fwResponse.addHeader("foo", "bar");
this.fwResponse.addHeader("foo", "bar");
verify(response).addHeader("foo", "bar");
verify(this.response).addHeader("foo", "bar");
}
@Test
public void addHeaderWhenNullValueThenDelegateInvoked() {
fwResponse.addHeader("foo", null);
this.fwResponse.addHeader("foo", null);
verify(response).addHeader("foo", null);
verify(this.response).addHeader("foo", null);
}
@Test
public void addHeaderWhenHeaderValueHasCrlfThenException() {
expectCrlfValidationException();
fwResponse.addHeader("foo", "abc\r\nContent-Length:100");
this.fwResponse.addHeader("foo", "abc\r\nContent-Length:100");
}
@Test
public void addHeaderWhenHeaderNameHasCrlfThenException() {
expectCrlfValidationException();
fwResponse.addHeader("abc\r\nContent-Length:100", "bar");
this.fwResponse.addHeader("abc\r\nContent-Length:100", "bar");
}
@Test
@@ -103,16 +103,16 @@ public class FirewalledResponseTests {
cookie.setDomain("foobar");
cookie.setComment("foobar");
fwResponse.addCookie(cookie);
this.fwResponse.addCookie(cookie);
verify(response).addCookie(cookie);
verify(this.response).addCookie(cookie);
}
@Test
public void addCookieWhenNullThenDelegateInvoked() {
fwResponse.addCookie(null);
this.fwResponse.addCookie(null);
verify(response).addCookie(null);
verify(this.response).addCookie(null);
}
@Test
@@ -127,7 +127,7 @@ public class FirewalledResponseTests {
};
expectCrlfValidationException();
fwResponse.addCookie(cookie);
this.fwResponse.addCookie(cookie);
}
@Test
@@ -135,7 +135,7 @@ public class FirewalledResponseTests {
Cookie cookie = new Cookie("foo", "foo\r\nbar");
expectCrlfValidationException();
fwResponse.addCookie(cookie);
this.fwResponse.addCookie(cookie);
}
@Test
@@ -144,7 +144,7 @@ public class FirewalledResponseTests {
cookie.setPath("/foo\r\nbar");
expectCrlfValidationException();
fwResponse.addCookie(cookie);
this.fwResponse.addCookie(cookie);
}
@Test
@@ -153,7 +153,7 @@ public class FirewalledResponseTests {
cookie.setDomain("foo\r\nbar");
expectCrlfValidationException();
fwResponse.addCookie(cookie);
this.fwResponse.addCookie(cookie);
}
@Test
@@ -162,7 +162,7 @@ public class FirewalledResponseTests {
cookie.setComment("foo\r\nbar");
expectCrlfValidationException();
fwResponse.addCookie(cookie);
this.fwResponse.addCookie(cookie);
}
@Test
@@ -177,13 +177,13 @@ public class FirewalledResponseTests {
}
private void expectCrlfValidationException() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Invalid characters (CR/LF)");
this.expectedException.expect(IllegalArgumentException.class);
this.expectedException.expectMessage("Invalid characters (CR/LF)");
}
private void validateLineEnding(String name, String value) {
try {
fwResponse.validateCrlf(name, value);
this.fwResponse.validateCrlf(name, value);
fail("IllegalArgumentException should have thrown");
}
catch (IllegalArgumentException expected) {

View File

@@ -43,27 +43,27 @@ public class ContentSecurityPolicyHeaderWriterTests {
@Before
public void setup() {
request = new MockHttpServletRequest();
request.setSecure(true);
response = new MockHttpServletResponse();
writer = new ContentSecurityPolicyHeaderWriter(DEFAULT_POLICY_DIRECTIVES);
this.request = new MockHttpServletRequest();
this.request.setSecure(true);
this.response = new MockHttpServletResponse();
this.writer = new ContentSecurityPolicyHeaderWriter(DEFAULT_POLICY_DIRECTIVES);
}
@Test
public void writeHeadersWhenNoPolicyDirectivesThenUsesDefault() {
ContentSecurityPolicyHeaderWriter noPolicyWriter = new ContentSecurityPolicyHeaderWriter();
noPolicyWriter.writeHeaders(request, response);
noPolicyWriter.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader("Content-Security-Policy")).isEqualTo(DEFAULT_POLICY_DIRECTIVES);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Content-Security-Policy")).isEqualTo(DEFAULT_POLICY_DIRECTIVES);
}
@Test
public void writeHeadersContentSecurityPolicyDefault() {
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader("Content-Security-Policy")).isEqualTo(DEFAULT_POLICY_DIRECTIVES);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Content-Security-Policy")).isEqualTo(DEFAULT_POLICY_DIRECTIVES);
}
@Test
@@ -71,48 +71,48 @@ public class ContentSecurityPolicyHeaderWriterTests {
String policyDirectives = "default-src 'self'; " + "object-src plugins1.example.com plugins2.example.com; "
+ "script-src trustedscripts.example.com";
writer = new ContentSecurityPolicyHeaderWriter(policyDirectives);
writer.writeHeaders(request, response);
this.writer = new ContentSecurityPolicyHeaderWriter(policyDirectives);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader("Content-Security-Policy")).isEqualTo(policyDirectives);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Content-Security-Policy")).isEqualTo(policyDirectives);
}
@Test
public void writeHeadersWhenNoPolicyDirectivesReportOnlyThenUsesDefault() {
ContentSecurityPolicyHeaderWriter noPolicyWriter = new ContentSecurityPolicyHeaderWriter();
writer.setReportOnly(true);
noPolicyWriter.writeHeaders(request, response);
this.writer.setReportOnly(true);
noPolicyWriter.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader("Content-Security-Policy")).isEqualTo(DEFAULT_POLICY_DIRECTIVES);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Content-Security-Policy")).isEqualTo(DEFAULT_POLICY_DIRECTIVES);
}
@Test
public void writeHeadersContentSecurityPolicyReportOnlyDefault() {
writer.setReportOnly(true);
writer.writeHeaders(request, response);
this.writer.setReportOnly(true);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader("Content-Security-Policy-Report-Only")).isEqualTo(DEFAULT_POLICY_DIRECTIVES);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Content-Security-Policy-Report-Only")).isEqualTo(DEFAULT_POLICY_DIRECTIVES);
}
@Test
public void writeHeadersContentSecurityPolicyReportOnlyCustom() {
String policyDirectives = "default-src https:; report-uri https://example.com/";
writer = new ContentSecurityPolicyHeaderWriter(policyDirectives);
writer.setReportOnly(true);
writer.writeHeaders(request, response);
this.writer = new ContentSecurityPolicyHeaderWriter(policyDirectives);
this.writer.setReportOnly(true);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader("Content-Security-Policy-Report-Only")).isEqualTo(policyDirectives);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Content-Security-Policy-Report-Only")).isEqualTo(policyDirectives);
}
@Test(expected = IllegalArgumentException.class)
public void writeHeadersContentSecurityPolicyInvalid() {
writer = new ContentSecurityPolicyHeaderWriter("");
writer = new ContentSecurityPolicyHeaderWriter(null);
this.writer = new ContentSecurityPolicyHeaderWriter("");
this.writer = new ContentSecurityPolicyHeaderWriter(null);
}
@Test

View File

@@ -51,37 +51,37 @@ public class DelegatingRequestMatcherHeaderWriterTests {
@Before
public void setup() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
headerWriter = new DelegatingRequestMatcherHeaderWriter(matcher, delegate);
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.headerWriter = new DelegatingRequestMatcherHeaderWriter(this.matcher, this.delegate);
}
@Test(expected = IllegalArgumentException.class)
public void constructorNullRequestMatcher() {
new DelegatingRequestMatcherHeaderWriter(null, delegate);
new DelegatingRequestMatcherHeaderWriter(null, this.delegate);
}
@Test(expected = IllegalArgumentException.class)
public void constructorNullDelegate() {
new DelegatingRequestMatcherHeaderWriter(matcher, null);
new DelegatingRequestMatcherHeaderWriter(this.matcher, null);
}
@Test
public void writeHeadersOnMatch() {
when(matcher.matches(request)).thenReturn(true);
when(this.matcher.matches(this.request)).thenReturn(true);
headerWriter.writeHeaders(request, response);
this.headerWriter.writeHeaders(this.request, this.response);
verify(delegate).writeHeaders(request, response);
verify(this.delegate).writeHeaders(this.request, this.response);
}
@Test
public void writeHeadersOnNoMatch() {
when(matcher.matches(request)).thenReturn(false);
when(this.matcher.matches(this.request)).thenReturn(false);
headerWriter.writeHeaders(request, response);
this.headerWriter.writeHeaders(this.request, this.response);
verify(delegate, times(0)).writeHeaders(request, response);
verify(this.delegate, times(0)).writeHeaders(this.request, this.response);
}
}

View File

@@ -52,7 +52,7 @@ public class FeaturePolicyHeaderWriterTests {
@Test
public void writeHeadersFeaturePolicyDefault() {
writer.writeHeaders(this.request, this.response);
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Feature-Policy")).isEqualTo(DEFAULT_POLICY_DIRECTIVES);

View File

@@ -55,154 +55,154 @@ public class HpkpHeaderWriterTests {
@Before
public void setup() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
writer = new HpkpHeaderWriter();
this.writer = new HpkpHeaderWriter();
Map<String, String> defaultPins = new LinkedHashMap<>();
defaultPins.put("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=", "sha256");
writer.setPins(defaultPins);
this.writer.setPins(defaultPins);
request.setSecure(true);
this.request.setSecure(true);
}
@Test
public void writeHeadersDefaultValues() {
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader("Public-Key-Pins-Report-Only"))
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Public-Key-Pins-Report-Only"))
.isEqualTo("max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\"");
}
@Test
public void maxAgeCustomConstructorWriteHeaders() {
writer = new HpkpHeaderWriter(2592000);
writer.setPins(DEFAULT_PINS);
this.writer = new HpkpHeaderWriter(2592000);
this.writer.setPins(DEFAULT_PINS);
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader("Public-Key-Pins-Report-Only"))
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Public-Key-Pins-Report-Only"))
.isEqualTo("max-age=2592000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\"");
}
@Test
public void maxAgeAndIncludeSubdomainsCustomConstructorWriteHeaders() {
writer = new HpkpHeaderWriter(2592000, true);
writer.setPins(DEFAULT_PINS);
this.writer = new HpkpHeaderWriter(2592000, true);
this.writer.setPins(DEFAULT_PINS);
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader("Public-Key-Pins-Report-Only")).isEqualTo(
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Public-Key-Pins-Report-Only")).isEqualTo(
"max-age=2592000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\" ; includeSubDomains");
}
@Test
public void allArgsCustomConstructorWriteHeaders() {
writer = new HpkpHeaderWriter(2592000, true, false);
writer.setPins(DEFAULT_PINS);
this.writer = new HpkpHeaderWriter(2592000, true, false);
this.writer.setPins(DEFAULT_PINS);
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader("Public-Key-Pins")).isEqualTo(
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Public-Key-Pins")).isEqualTo(
"max-age=2592000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\" ; includeSubDomains");
}
@Test
public void writeHeadersCustomMaxAgeInSeconds() {
writer.setMaxAgeInSeconds(2592000);
this.writer.setMaxAgeInSeconds(2592000);
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader("Public-Key-Pins-Report-Only"))
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Public-Key-Pins-Report-Only"))
.isEqualTo("max-age=2592000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\"");
}
@Test
public void writeHeadersIncludeSubDomains() {
writer.setIncludeSubDomains(true);
this.writer.setIncludeSubDomains(true);
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader("Public-Key-Pins-Report-Only")).isEqualTo(
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Public-Key-Pins-Report-Only")).isEqualTo(
"max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\" ; includeSubDomains");
}
@Test
public void writeHeadersTerminateConnection() {
writer.setReportOnly(false);
this.writer.setReportOnly(false);
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader("Public-Key-Pins"))
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Public-Key-Pins"))
.isEqualTo("max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\"");
}
@Test
public void writeHeadersTerminateConnectionWithURI() throws URISyntaxException {
writer.setReportOnly(false);
writer.setReportUri(new URI("https://example.com/pkp-report"));
this.writer.setReportOnly(false);
this.writer.setReportUri(new URI("https://example.com/pkp-report"));
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader("Public-Key-Pins")).isEqualTo(
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Public-Key-Pins")).isEqualTo(
"max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\" ; report-uri=\"https://example.com/pkp-report\"");
}
@Test
public void writeHeadersTerminateConnectionWithURIAsString() {
writer.setReportOnly(false);
writer.setReportUri("https://example.com/pkp-report");
this.writer.setReportOnly(false);
this.writer.setReportUri("https://example.com/pkp-report");
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader("Public-Key-Pins")).isEqualTo(
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Public-Key-Pins")).isEqualTo(
"max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\" ; report-uri=\"https://example.com/pkp-report\"");
}
@Test
public void writeHeadersAddSha256Pins() {
writer.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=",
this.writer.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=",
"E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=");
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader("Public-Key-Pins-Report-Only")).isEqualTo(
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Public-Key-Pins-Report-Only")).isEqualTo(
"max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\" ; pin-sha256=\"E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=\"");
}
@Test
public void writeHeadersInsecureRequestDoesNotWriteHeader() {
request.setSecure(false);
this.request.setSecure(false);
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).isEmpty();
assertThat(this.response.getHeaderNames()).isEmpty();
}
@Test(expected = IllegalArgumentException.class)
public void setMaxAgeInSecondsToNegative() {
writer.setMaxAgeInSeconds(-1);
this.writer.setMaxAgeInSeconds(-1);
}
@Test(expected = IllegalArgumentException.class)
public void addSha256PinsWithNullPin() {
writer.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=", null);
this.writer.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=", null);
}
@Test(expected = IllegalArgumentException.class)
public void setIncorrectReportUri() {
writer.setReportUri("some url here...");
this.writer.setReportUri("some url here...");
}
@Test

View File

@@ -41,111 +41,114 @@ public class HstsHeaderWriterTests {
@Before
public void setup() {
request = new MockHttpServletRequest();
request.setSecure(true);
response = new MockHttpServletResponse();
this.request = new MockHttpServletRequest();
this.request.setSecure(true);
this.response = new MockHttpServletResponse();
writer = new HstsHeaderWriter();
this.writer = new HstsHeaderWriter();
}
@Test
public void allArgsCustomConstructorWriteHeaders() {
request.setSecure(false);
writer = new HstsHeaderWriter(AnyRequestMatcher.INSTANCE, 15768000, false);
this.request.setSecure(false);
this.writer = new HstsHeaderWriter(AnyRequestMatcher.INSTANCE, 15768000, false);
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=15768000");
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=15768000");
}
@Test
public void maxAgeAndIncludeSubdomainsCustomConstructorWriteHeaders() {
request.setSecure(false);
writer = new HstsHeaderWriter(AnyRequestMatcher.INSTANCE, 15768000, false);
this.request.setSecure(false);
this.writer = new HstsHeaderWriter(AnyRequestMatcher.INSTANCE, 15768000, false);
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=15768000");
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=15768000");
}
@Test
public void maxAgeCustomConstructorWriteHeaders() {
writer = new HstsHeaderWriter(15768000);
this.writer = new HstsHeaderWriter(15768000);
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=15768000 ; includeSubDomains");
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Strict-Transport-Security"))
.isEqualTo("max-age=15768000 ; includeSubDomains");
}
@Test
public void includeSubDomainsCustomConstructorWriteHeaders() {
writer = new HstsHeaderWriter(false);
this.writer = new HstsHeaderWriter(false);
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=31536000");
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=31536000");
}
@Test
public void writeHeadersDefaultValues() {
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=31536000 ; includeSubDomains");
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Strict-Transport-Security"))
.isEqualTo("max-age=31536000 ; includeSubDomains");
}
@Test
public void writeHeadersIncludeSubDomainsFalse() {
writer.setIncludeSubDomains(false);
this.writer.setIncludeSubDomains(false);
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=31536000");
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=31536000");
}
@Test
public void writeHeadersCustomMaxAgeInSeconds() {
writer.setMaxAgeInSeconds(1);
this.writer.setMaxAgeInSeconds(1);
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=1 ; includeSubDomains");
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=1 ; includeSubDomains");
}
@Test
public void writeHeadersInsecureRequestDoesNotWriteHeader() {
request.setSecure(false);
this.request.setSecure(false);
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames().isEmpty()).isTrue();
assertThat(this.response.getHeaderNames().isEmpty()).isTrue();
}
@Test
public void writeHeadersAnyRequestMatcher() {
writer.setRequestMatcher(AnyRequestMatcher.INSTANCE);
request.setSecure(false);
this.writer.setRequestMatcher(AnyRequestMatcher.INSTANCE);
this.request.setSecure(false);
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader("Strict-Transport-Security")).isEqualTo("max-age=31536000 ; includeSubDomains");
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Strict-Transport-Security"))
.isEqualTo("max-age=31536000 ; includeSubDomains");
}
@Test(expected = IllegalArgumentException.class)
public void setMaxAgeInSecondsToNegative() {
writer.setMaxAgeInSeconds(-1);
this.writer.setMaxAgeInSeconds(-1);
}
@Test(expected = IllegalArgumentException.class)
public void setRequestMatcherToNull() {
writer.setRequestMatcher(null);
this.writer.setRequestMatcher(null);
}
@Test

View File

@@ -53,7 +53,7 @@ public class ReferrerPolicyHeaderWriterTests {
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Referrer-Policy")).isEqualTo(DEFAULT_REFERRER_POLICY);
assertThat(this.response.getHeader("Referrer-Policy")).isEqualTo(this.DEFAULT_REFERRER_POLICY);
}
@Test

View File

@@ -43,8 +43,8 @@ public class StaticHeaderWriterTests {
@Before
public void setup() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
}
@Test(expected = IllegalArgumentException.class)
@@ -78,8 +78,8 @@ public class StaticHeaderWriterTests {
String headerValue = "foo";
StaticHeadersWriter factory = new StaticHeadersWriter(headerName, headerValue);
factory.writeHeaders(request, response);
assertThat(response.getHeaderValues(headerName)).isEqualTo(Arrays.asList(headerValue));
factory.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderValues(headerName)).isEqualTo(Arrays.asList(headerValue));
}
@Test
@@ -88,11 +88,11 @@ public class StaticHeaderWriterTests {
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(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(2);
assertThat(response.getHeaderValues(pragma.getName())).isEqualTo(pragma.getValues());
assertThat(response.getHeaderValues(cacheControl.getName())).isEqualTo(cacheControl.getValues());
assertThat(this.response.getHeaderNames()).hasSize(2);
assertThat(this.response.getHeaderValues(pragma.getName())).isEqualTo(pragma.getValues());
assertThat(this.response.getHeaderValues(cacheControl.getName())).isEqualTo(cacheControl.getValues());
}
@Test

View File

@@ -37,17 +37,17 @@ public class XContentTypeOptionsHeaderWriterTests {
@Before
public void setup() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
writer = new XContentTypeOptionsHeaderWriter();
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.writer = new XContentTypeOptionsHeaderWriter();
}
@Test
public void writeHeaders() {
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeaderValues("X-Content-Type-Options")).containsExactly("nosniff");
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeaderValues("X-Content-Type-Options")).containsExactly("nosniff");
}
}

View File

@@ -40,56 +40,56 @@ public class XXssProtectionHeaderWriterTests {
@Before
public void setup() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
writer = new XXssProtectionHeaderWriter();
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.writer = new XXssProtectionHeaderWriter();
}
@Test
public void writeHeaders() {
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeaderValues("X-XSS-Protection")).containsOnly("1; mode=block");
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeaderValues("X-XSS-Protection")).containsOnly("1; mode=block");
}
@Test
public void writeHeadersNoBlock() {
writer.setBlock(false);
this.writer.setBlock(false);
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeaderValues("X-XSS-Protection")).containsOnly("1");
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeaderValues("X-XSS-Protection")).containsOnly("1");
}
@Test
public void writeHeadersDisabled() {
writer.setBlock(false);
writer.setEnabled(false);
this.writer.setBlock(false);
this.writer.setEnabled(false);
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeaderValues("X-XSS-Protection")).containsOnly("0");
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeaderValues("X-XSS-Protection")).containsOnly("0");
}
@Test
public void setEnabledFalseWithBlockTrue() {
writer.setEnabled(false);
this.writer.setEnabled(false);
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeaderValues("X-XSS-Protection")).containsOnly("0");
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeaderValues("X-XSS-Protection")).containsOnly("0");
}
@Test(expected = IllegalArgumentException.class)
public void setBlockTrueWithEnabledFalse() {
writer.setBlock(false);
writer.setEnabled(false);
this.writer.setBlock(false);
this.writer.setEnabled(false);
writer.setBlock(true);
this.writer.setBlock(true);
}
@Test

View File

@@ -32,50 +32,50 @@ public class AbstractRequestParameterAllowFromStrategyTests {
@Before
public void setup() {
request = new MockHttpServletRequest();
this.request = new MockHttpServletRequest();
}
@Test
public void nullAllowFromParameterValue() {
RequestParameterAllowFromStrategyStub strategy = new RequestParameterAllowFromStrategyStub(true);
assertThat(strategy.getAllowFromValue(request)).isEqualTo("DENY");
assertThat(strategy.getAllowFromValue(this.request)).isEqualTo("DENY");
}
@Test
public void emptyAllowFromParameterValue() {
request.setParameter("x-frames-allow-from", "");
this.request.setParameter("x-frames-allow-from", "");
RequestParameterAllowFromStrategyStub strategy = new RequestParameterAllowFromStrategyStub(true);
assertThat(strategy.getAllowFromValue(request)).isEqualTo("DENY");
assertThat(strategy.getAllowFromValue(this.request)).isEqualTo("DENY");
}
@Test
public void emptyAllowFromCustomParameterValue() {
String customParam = "custom";
request.setParameter(customParam, "");
this.request.setParameter(customParam, "");
RequestParameterAllowFromStrategyStub strategy = new RequestParameterAllowFromStrategyStub(true);
strategy.setAllowFromParameterName(customParam);
assertThat(strategy.getAllowFromValue(request)).isEqualTo("DENY");
assertThat(strategy.getAllowFromValue(this.request)).isEqualTo("DENY");
}
@Test
public void allowFromParameterValueAllowed() {
String value = "https://example.com";
request.setParameter("x-frames-allow-from", value);
this.request.setParameter("x-frames-allow-from", value);
RequestParameterAllowFromStrategyStub strategy = new RequestParameterAllowFromStrategyStub(true);
assertThat(strategy.getAllowFromValue(request)).isEqualTo(value);
assertThat(strategy.getAllowFromValue(this.request)).isEqualTo(value);
}
@Test
public void allowFromParameterValueDenied() {
String value = "https://example.com";
request.setParameter("x-frames-allow-from", value);
this.request.setParameter("x-frames-allow-from", value);
RequestParameterAllowFromStrategyStub strategy = new RequestParameterAllowFromStrategyStub(false);
assertThat(strategy.getAllowFromValue(request)).isEqualTo("DENY");
assertThat(strategy.getAllowFromValue(this.request)).isEqualTo("DENY");
}
private static class RequestParameterAllowFromStrategyStub extends AbstractRequestParameterAllowFromStrategy {
@@ -88,7 +88,7 @@ public class AbstractRequestParameterAllowFromStrategyTests {
@Override
protected boolean allowed(String allowFromOrigin) {
return match;
return this.match;
}
}

View File

@@ -46,8 +46,8 @@ public class FrameOptionsHeaderWriterTests {
@Before
public void setup() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
}
@Test(expected = IllegalArgumentException.class)
@@ -67,56 +67,56 @@ public class FrameOptionsHeaderWriterTests {
@Test
public void writeHeadersAllowFromReturnsNull() {
writer = new XFrameOptionsHeaderWriter(strategy);
this.writer = new XFrameOptionsHeaderWriter(this.strategy);
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames().isEmpty()).isTrue();
assertThat(this.response.getHeaderNames().isEmpty()).isTrue();
}
@Test
public void writeHeadersAllowFrom() {
String allowFromValue = "https://example.com/";
when(strategy.getAllowFromValue(request)).thenReturn(allowFromValue);
writer = new XFrameOptionsHeaderWriter(strategy);
when(this.strategy.getAllowFromValue(this.request)).thenReturn(allowFromValue);
this.writer = new XFrameOptionsHeaderWriter(this.strategy);
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER))
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER))
.isEqualTo("ALLOW-FROM " + allowFromValue);
}
@Test
public void writeHeadersDeny() {
writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.DENY);
this.writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.DENY);
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER)).isEqualTo("DENY");
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER)).isEqualTo("DENY");
}
@Test
public void writeHeadersSameOrigin() {
writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN);
this.writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN);
writer.writeHeaders(request, response);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER)).isEqualTo("SAMEORIGIN");
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER)).isEqualTo("SAMEORIGIN");
}
@Test
public void writeHeadersTwiceLastWins() {
writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN);
writer.writeHeaders(request, response);
this.writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN);
this.writer.writeHeaders(this.request, this.response);
writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.DENY);
writer.writeHeaders(request, response);
this.writer = new XFrameOptionsHeaderWriter(XFrameOptionsMode.DENY);
this.writer.writeHeaders(this.request, this.response);
assertThat(response.getHeaderNames()).hasSize(1);
assertThat(response.getHeader(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER)).isEqualTo("DENY");
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER)).isEqualTo("DENY");
}
}

View File

@@ -78,11 +78,11 @@ public class JaasApiIntegrationFilterTests {
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
authenticatedSubject = new Subject();
authenticatedSubject.getPrincipals().add(() -> "principal");
authenticatedSubject.getPrivateCredentials().add("password");
authenticatedSubject.getPublicCredentials().add("username");
callbackHandler = callbacks -> {
this.authenticatedSubject = new Subject();
this.authenticatedSubject.getPrincipals().add(() -> "principal");
this.authenticatedSubject.getPrivateCredentials().add("password");
this.authenticatedSubject.getPublicCredentials().add("username");
this.callbackHandler = callbacks -> {
for (Callback callback : callbacks) {
if (callback instanceof NameCallback) {
((NameCallback) callback).setName("user");
@@ -98,7 +98,7 @@ public class JaasApiIntegrationFilterTests {
}
}
};
testConfiguration = new Configuration() {
this.testConfiguration = new Configuration() {
public void refresh() {
}
@@ -108,11 +108,11 @@ public class JaasApiIntegrationFilterTests {
LoginModuleControlFlag.REQUIRED, new HashMap<>()) };
}
};
LoginContext ctx = new LoginContext("SubjectDoAsFilterTest", authenticatedSubject, callbackHandler,
testConfiguration);
LoginContext ctx = new LoginContext("SubjectDoAsFilterTest", this.authenticatedSubject, this.callbackHandler,
this.testConfiguration);
ctx.login();
token = new JaasAuthenticationToken("username", "password", AuthorityUtils.createAuthorityList("ROLE_ADMIN"),
ctx);
this.token = new JaasAuthenticationToken("username", "password",
AuthorityUtils.createAuthorityList("ROLE_ADMIN"), ctx);
// just in case someone forgot to clear the context
SecurityContextHolder.clearContext();
@@ -133,7 +133,7 @@ public class JaasApiIntegrationFilterTests {
@Test
public void obtainSubjectNullAuthentication() {
assertNullSubject(filter.obtainSubject(request));
assertNullSubject(this.filter.obtainSubject(this.request));
}
@Test
@@ -141,51 +141,52 @@ public class JaasApiIntegrationFilterTests {
Authentication authentication = new TestingAuthenticationToken("un", "pwd");
authentication.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(authentication);
assertNullSubject(filter.obtainSubject(request));
assertNullSubject(this.filter.obtainSubject(this.request));
}
@Test
public void obtainSubjectNullLoginContext() {
token = new JaasAuthenticationToken("un", "pwd", AuthorityUtils.createAuthorityList("ROLE_ADMIN"), null);
SecurityContextHolder.getContext().setAuthentication(token);
assertNullSubject(filter.obtainSubject(request));
this.token = new JaasAuthenticationToken("un", "pwd", AuthorityUtils.createAuthorityList("ROLE_ADMIN"), null);
SecurityContextHolder.getContext().setAuthentication(this.token);
assertNullSubject(this.filter.obtainSubject(this.request));
}
@Test
public void obtainSubjectNullSubject() throws Exception {
LoginContext ctx = new LoginContext("obtainSubjectNullSubject", null, callbackHandler, testConfiguration);
LoginContext ctx = new LoginContext("obtainSubjectNullSubject", null, this.callbackHandler,
this.testConfiguration);
assertThat(ctx.getSubject()).isNull();
token = new JaasAuthenticationToken("un", "pwd", AuthorityUtils.createAuthorityList("ROLE_ADMIN"), ctx);
SecurityContextHolder.getContext().setAuthentication(token);
assertNullSubject(filter.obtainSubject(request));
this.token = new JaasAuthenticationToken("un", "pwd", AuthorityUtils.createAuthorityList("ROLE_ADMIN"), ctx);
SecurityContextHolder.getContext().setAuthentication(this.token);
assertNullSubject(this.filter.obtainSubject(this.request));
}
@Test
public void obtainSubject() {
SecurityContextHolder.getContext().setAuthentication(token);
assertThat(filter.obtainSubject(request)).isEqualTo(authenticatedSubject);
SecurityContextHolder.getContext().setAuthentication(this.token);
assertThat(this.filter.obtainSubject(this.request)).isEqualTo(this.authenticatedSubject);
}
@Test
public void doFilterCurrentSubjectPopulated() throws Exception {
SecurityContextHolder.getContext().setAuthentication(token);
assertJaasSubjectEquals(authenticatedSubject);
SecurityContextHolder.getContext().setAuthentication(this.token);
assertJaasSubjectEquals(this.authenticatedSubject);
}
@Test
public void doFilterAuthenticationNotAuthenticated() throws Exception {
// Authentication is null, so no Subject is populated.
token.setAuthenticated(false);
SecurityContextHolder.getContext().setAuthentication(token);
this.token.setAuthenticated(false);
SecurityContextHolder.getContext().setAuthentication(this.token);
assertJaasSubjectEquals(null);
filter.setCreateEmptySubject(true);
this.filter.setCreateEmptySubject(true);
assertJaasSubjectEquals(new Subject());
}
@Test
public void doFilterAuthenticationNull() throws Exception {
assertJaasSubjectEquals(null);
filter.setCreateEmptySubject(true);
this.filter.setCreateEmptySubject(true);
assertJaasSubjectEquals(new Subject());
}
@@ -202,7 +203,7 @@ public class JaasApiIntegrationFilterTests {
super.doFilter(request, response);
}
};
filter.doFilter(request, response, chain);
this.filter.doFilter(this.request, this.response, chain);
// ensure that the chain was actually invoked
assertThat(chain.getRequest()).isNotNull();
}

View File

@@ -31,9 +31,9 @@ public abstract class AbstractMixinTests {
@Before
public void setup() {
mapper = new ObjectMapper();
this.mapper = new ObjectMapper();
ClassLoader loader = getClass().getClassLoader();
mapper.registerModules(SecurityJackson2Modules.getModules(loader));
this.mapper.registerModules(SecurityJackson2Modules.getModules(loader));
}
}

View File

@@ -51,13 +51,13 @@ public class CookieMixinTests extends AbstractMixinTests {
@Test
public void serializeCookie() throws JsonProcessingException, JSONException {
Cookie cookie = new Cookie("demo", "cookie1");
String actualString = mapper.writeValueAsString(cookie);
String actualString = this.mapper.writeValueAsString(cookie);
JSONAssert.assertEquals(COOKIE_JSON, actualString, true);
}
@Test
public void deserializeCookie() throws IOException {
Cookie cookie = mapper.readValue(COOKIE_JSON, Cookie.class);
Cookie cookie = this.mapper.readValue(COOKIE_JSON, Cookie.class);
assertThat(cookie).isNotNull();
assertThat(cookie.getName()).isEqualTo("demo");
assertThat(cookie.getDomain()).isEqualTo("");

View File

@@ -46,13 +46,13 @@ public class DefaultCsrfTokenMixinTests extends AbstractMixinTests {
@Test
public void defaultCsrfTokenSerializedTest() throws JsonProcessingException, JSONException {
DefaultCsrfToken token = new DefaultCsrfToken("csrf-header", "_csrf", "1");
String serializedJson = mapper.writeValueAsString(token);
String serializedJson = this.mapper.writeValueAsString(token);
JSONAssert.assertEquals(CSRF_JSON, serializedJson, true);
}
@Test
public void defaultCsrfTokenDeserializeTest() throws IOException {
DefaultCsrfToken token = mapper.readValue(CSRF_JSON, DefaultCsrfToken.class);
DefaultCsrfToken token = this.mapper.readValue(CSRF_JSON, DefaultCsrfToken.class);
assertThat(token).isNotNull();
assertThat(token.getHeaderName()).isEqualTo("csrf-header");
assertThat(token.getParameterName()).isEqualTo("_csrf");
@@ -62,13 +62,13 @@ public class DefaultCsrfTokenMixinTests extends AbstractMixinTests {
@Test(expected = JsonMappingException.class)
public void defaultCsrfTokenDeserializeWithoutClassTest() throws IOException {
String tokenJson = "{\"headerName\": \"csrf-header\", \"parameterName\": \"_csrf\", \"token\": \"1\"}";
mapper.readValue(tokenJson, DefaultCsrfToken.class);
this.mapper.readValue(tokenJson, DefaultCsrfToken.class);
}
@Test(expected = JsonMappingException.class)
public void defaultCsrfTokenDeserializeNullValuesTest() throws IOException {
String tokenJson = "{\"@class\": \"org.springframework.security.web.csrf.DefaultCsrfToken\", \"headerName\": \"\", \"parameterName\": null, \"token\": \"1\"}";
mapper.readValue(tokenJson, DefaultCsrfToken.class);
this.mapper.readValue(tokenJson, DefaultCsrfToken.class);
}
}

View File

@@ -102,7 +102,7 @@ public class DefaultSavedRequestMixinTests extends AbstractMixinTests {
return new Cookie[] { new Cookie("SESSION", "123456789") };
}
};
String actualString = mapper.writerWithDefaultPrettyPrinter()
String actualString = this.mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(new DefaultSavedRequest(requestToWrite, new PortResolverImpl()));
JSONAssert.assertEquals(REQUEST_JSON, actualString, true);
}
@@ -115,13 +115,13 @@ public class DefaultSavedRequestMixinTests extends AbstractMixinTests {
.setRequestURL("http://localhost").setServerName("localhost").setRequestURI("")
.setLocales(Collections.singletonList(new Locale("en"))).setContextPath("").setMethod("")
.setServletPath("").build();
String actualString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(request);
String actualString = this.mapper.writerWithDefaultPrettyPrinter().writeValueAsString(request);
JSONAssert.assertEquals(REQUEST_JSON, actualString, true);
}
@Test
public void deserializeDefaultSavedRequest() throws IOException {
DefaultSavedRequest request = (DefaultSavedRequest) mapper.readValue(REQUEST_JSON, Object.class);
DefaultSavedRequest request = (DefaultSavedRequest) this.mapper.readValue(REQUEST_JSON, Object.class);
assertThat(request).isNotNull();
assertThat(request.getCookies()).hasSize(1);
assertThat(request.getLocales()).hasSize(1).contains(new Locale("en"));

View File

@@ -49,24 +49,24 @@ public class PreAuthenticatedAuthenticationTokenMixinTests extends AbstractMixin
@Before
public void setupExpected() {
expected = new PreAuthenticatedAuthenticationToken("principal", "credentials",
this.expected = new PreAuthenticatedAuthenticationToken("principal", "credentials",
AuthorityUtils.createAuthorityList("ROLE_USER"));
}
@Test
public void serializeWhenPrincipalCredentialsAuthoritiesThenSuccess()
throws JsonProcessingException, JSONException {
String serializedJson = mapper.writeValueAsString(expected);
String serializedJson = this.mapper.writeValueAsString(this.expected);
JSONAssert.assertEquals(PREAUTH_JSON, serializedJson, true);
}
@Test
public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws Exception {
PreAuthenticatedAuthenticationToken deserialized = mapper.readValue(PREAUTH_JSON,
PreAuthenticatedAuthenticationToken deserialized = this.mapper.readValue(PREAUTH_JSON,
PreAuthenticatedAuthenticationToken.class);
assertThat(deserialized).isNotNull();
assertThat(deserialized.isAuthenticated()).isTrue();
assertThat(deserialized.getAuthorities()).isEqualTo(expected.getAuthorities());
assertThat(deserialized.getAuthorities()).isEqualTo(this.expected.getAuthorities());
}
}

View File

@@ -61,16 +61,16 @@ public class SavedCookieMixinTests extends AbstractMixinTests {
@Test
public void serializeWithDefaultConfigurationTest() throws JsonProcessingException, JSONException {
SavedCookie savedCookie = new SavedCookie(new Cookie("SESSION", "123456789"));
String actualJson = mapper.writeValueAsString(savedCookie);
String actualJson = this.mapper.writeValueAsString(savedCookie);
JSONAssert.assertEquals(COOKIE_JSON, actualJson, true);
}
@Test
public void serializeWithOverrideConfigurationTest() throws JsonProcessingException, JSONException {
SavedCookie savedCookie = new SavedCookie(new Cookie("SESSION", "123456789"));
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.PUBLIC_ONLY)
this.mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.PUBLIC_ONLY)
.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.ANY);
String actualJson = mapper.writeValueAsString(savedCookie);
String actualJson = this.mapper.writeValueAsString(savedCookie);
JSONAssert.assertEquals(COOKIE_JSON, actualJson, true);
}
@@ -78,14 +78,14 @@ public class SavedCookieMixinTests extends AbstractMixinTests {
public void serializeSavedCookieWithList() throws JsonProcessingException, JSONException {
List<SavedCookie> savedCookies = new ArrayList<>();
savedCookies.add(new SavedCookie(new Cookie("SESSION", "123456789")));
String actualJson = mapper.writeValueAsString(savedCookies);
String actualJson = this.mapper.writeValueAsString(savedCookies);
JSONAssert.assertEquals(COOKIES_JSON, actualJson, true);
}
@Test
@SuppressWarnings("unchecked")
public void deserializeSavedCookieWithList() throws IOException {
List<SavedCookie> savedCookies = (List<SavedCookie>) mapper.readValue(COOKIES_JSON, Object.class);
List<SavedCookie> savedCookies = (List<SavedCookie>) this.mapper.readValue(COOKIES_JSON, Object.class);
assertThat(savedCookies).isNotNull().hasSize(1);
assertThat(savedCookies.get(0).getName()).isEqualTo("SESSION");
assertThat(savedCookies.get(0).getValue()).isEqualTo("123456789");
@@ -93,7 +93,7 @@ public class SavedCookieMixinTests extends AbstractMixinTests {
@Test
public void deserializeSavedCookieJsonTest() throws IOException {
SavedCookie savedCookie = (SavedCookie) mapper.readValue(COOKIE_JSON, Object.class);
SavedCookie savedCookie = (SavedCookie) this.mapper.readValue(COOKIE_JSON, Object.class);
assertThat(savedCookie).isNotNull();
assertThat(savedCookie.getName()).isEqualTo("SESSION");
assertThat(savedCookie.getValue()).isEqualTo("123456789");

View File

@@ -52,7 +52,7 @@ public class WebAuthenticationDetailsMixinTests extends AbstractMixinTests {
WebAuthenticationDetails details = new WebAuthenticationDetails(request);
WebAuthenticationDetails authenticationDetails = mapper.readValue(AUTHENTICATION_DETAILS_JSON,
WebAuthenticationDetails authenticationDetails = this.mapper.readValue(AUTHENTICATION_DETAILS_JSON,
WebAuthenticationDetails.class);
assertThat(details.equals(authenticationDetails));
}
@@ -63,13 +63,13 @@ public class WebAuthenticationDetailsMixinTests extends AbstractMixinTests {
request.setRemoteAddr("/localhost");
request.setSession(new MockHttpSession(null, "1"));
WebAuthenticationDetails details = new WebAuthenticationDetails(request);
String actualJson = mapper.writeValueAsString(details);
String actualJson = this.mapper.writeValueAsString(details);
JSONAssert.assertEquals(AUTHENTICATION_DETAILS_JSON, actualJson, true);
}
@Test
public void webAuthenticationDetailsDeserializeTest() throws IOException {
WebAuthenticationDetails details = mapper.readValue(AUTHENTICATION_DETAILS_JSON,
WebAuthenticationDetails details = this.mapper.readValue(AUTHENTICATION_DETAILS_JSON,
WebAuthenticationDetails.class);
assertThat(details).isNotNull();
assertThat(details.getRemoteAddress()).isEqualTo("/localhost");

View File

@@ -293,8 +293,8 @@ public final class ResolvableMethod {
@SafeVarargs
public final Builder<T> annotPresent(Class<? extends Annotation>... annotationTypes) {
String message = "annotationPresent=" + Arrays.toString(annotationTypes);
addFilter(message, method -> Arrays.stream(annotationTypes)
.allMatch(annotType -> AnnotatedElementUtils.findMergedAnnotation(method, annotType) != null));
addFilter(message, candidate -> Arrays.stream(annotationTypes)
.allMatch(annotType -> AnnotatedElementUtils.findMergedAnnotation(candidate, annotType) != null));
return this;
}
@@ -304,13 +304,13 @@ public final class ResolvableMethod {
@SafeVarargs
public final Builder<T> annotNotPresent(Class<? extends Annotation>... annotationTypes) {
String message = "annotationNotPresent=" + Arrays.toString(annotationTypes);
addFilter(message, method -> {
addFilter(message, candidate -> {
if (annotationTypes.length != 0) {
return Arrays.stream(annotationTypes).noneMatch(
annotType -> AnnotatedElementUtils.findMergedAnnotation(method, annotType) != null);
annotType -> AnnotatedElementUtils.findMergedAnnotation(candidate, annotType) != null);
}
else {
return method.getAnnotations().length == 0;
return candidate.getAnnotations().length == 0;
}
});
return this;
@@ -574,8 +574,8 @@ public final class ResolvableMethod {
private List<MethodParameter> applyFilters() {
List<MethodParameter> matches = new ArrayList<>();
for (int i = 0; i < method.getParameterCount(); i++) {
MethodParameter param = new SynthesizingMethodParameter(method, i);
for (int i = 0; i < ResolvableMethod.this.method.getParameterCount(); i++) {
MethodParameter param = new SynthesizingMethodParameter(ResolvableMethod.this.method, i);
param.initParameterNameDiscovery(nameDiscoverer);
if (this.filters.stream().allMatch(p -> p.test(param))) {
matches.add(param);

View File

@@ -48,7 +48,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
@Before
public void setup() {
resolver = new AuthenticationPrincipalArgumentResolver();
this.resolver = new AuthenticationPrincipalArgumentResolver();
}
@After
@@ -58,60 +58,63 @@ public class AuthenticationPrincipalArgumentResolverTests {
@Test
public void supportsParameterNoAnnotation() {
assertThat(resolver.supportsParameter(showUserNoAnnotation())).isFalse();
assertThat(this.resolver.supportsParameter(showUserNoAnnotation())).isFalse();
}
@Test
public void supportsParameterAnnotation() {
assertThat(resolver.supportsParameter(showUserAnnotationObject())).isTrue();
assertThat(this.resolver.supportsParameter(showUserAnnotationObject())).isTrue();
}
@Test
public void supportsParameterCustomAnnotation() {
assertThat(resolver.supportsParameter(showUserCustomAnnotation())).isTrue();
assertThat(this.resolver.supportsParameter(showUserCustomAnnotation())).isTrue();
}
@Test
public void resolveArgumentNullAuthentication() throws Exception {
assertThat(resolver.resolveArgument(showUserAnnotationString(), null, null, null)).isNull();
assertThat(this.resolver.resolveArgument(showUserAnnotationString(), null, null, null)).isNull();
}
@Test
public void resolveArgumentNullPrincipal() throws Exception {
setAuthenticationPrincipal(null);
assertThat(resolver.resolveArgument(showUserAnnotationString(), null, null, null)).isNull();
assertThat(this.resolver.resolveArgument(showUserAnnotationString(), null, null, null)).isNull();
}
@Test
public void resolveArgumentString() throws Exception {
setAuthenticationPrincipal("john");
assertThat(resolver.resolveArgument(showUserAnnotationString(), null, null, null)).isEqualTo(expectedPrincipal);
assertThat(this.resolver.resolveArgument(showUserAnnotationString(), null, null, null))
.isEqualTo(this.expectedPrincipal);
}
@Test
public void resolveArgumentPrincipalStringOnObject() throws Exception {
setAuthenticationPrincipal("john");
assertThat(resolver.resolveArgument(showUserAnnotationObject(), null, null, null)).isEqualTo(expectedPrincipal);
assertThat(this.resolver.resolveArgument(showUserAnnotationObject(), null, null, null))
.isEqualTo(this.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);
assertThat(this.resolver.resolveArgument(showUserAnnotationUserDetails(), null, null, null))
.isEqualTo(this.expectedPrincipal);
}
@Test
public void resolveArgumentCustomUserPrincipal() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
assertThat(resolver.resolveArgument(showUserAnnotationCustomUserPrincipal(), null, null, null))
.isEqualTo(expectedPrincipal);
assertThat(this.resolver.resolveArgument(showUserAnnotationCustomUserPrincipal(), null, null, null))
.isEqualTo(this.expectedPrincipal);
}
@Test
public void resolveArgumentCustomAnnotation() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
assertThat(resolver.resolveArgument(showUserCustomAnnotation(), null, null, null)).isEqualTo(expectedPrincipal);
assertThat(this.resolver.resolveArgument(showUserCustomAnnotation(), null, null, null))
.isEqualTo(this.expectedPrincipal);
}
@Test
@@ -134,25 +137,26 @@ public class AuthenticationPrincipalArgumentResolverTests {
@Test
public void resolveArgumentNullOnInvalidType() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
assertThat(resolver.resolveArgument(showUserAnnotationString(), null, null, null)).isNull();
assertThat(this.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);
this.resolver.resolveArgument(showUserAnnotationErrorOnInvalidType(), null, null, null);
}
@Test(expected = ClassCastException.class)
public void resolveArgumentCustomserErrorOnInvalidType() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
resolver.resolveArgument(showUserAnnotationCurrentUserErrorOnInvalidType(), null, null, null);
this.resolver.resolveArgument(showUserAnnotationCurrentUserErrorOnInvalidType(), null, null, null);
}
@Test
public void resolveArgumentObject() throws Exception {
setAuthenticationPrincipal(new Object());
assertThat(resolver.resolveArgument(showUserAnnotationObject(), null, null, null)).isEqualTo(expectedPrincipal);
assertThat(this.resolver.resolveArgument(showUserAnnotationObject(), null, null, null))
.isEqualTo(this.expectedPrincipal);
}
private MethodParameter showUserNoAnnotation() {
@@ -304,7 +308,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
private void setAuthenticationPrincipal(Object principal) {
this.expectedPrincipal = principal;
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken(expectedPrincipal, "password", "ROLE_USER"));
.setAuthentication(new TestingAuthenticationToken(this.expectedPrincipal, "password", "ROLE_USER"));
}
}

View File

@@ -58,32 +58,34 @@ public class CsrfTokenArgumentResolverTests {
@Before
public void setup() {
token = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "secret");
resolver = new CsrfTokenArgumentResolver();
request = new MockHttpServletRequest();
webRequest = new ServletWebRequest(request);
this.token = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "secret");
this.resolver = new CsrfTokenArgumentResolver();
this.request = new MockHttpServletRequest();
this.webRequest = new ServletWebRequest(this.request);
}
@Test
public void supportsParameterFalse() {
assertThat(resolver.supportsParameter(noToken())).isFalse();
assertThat(this.resolver.supportsParameter(noToken())).isFalse();
}
@Test
public void supportsParameterTrue() {
assertThat(resolver.supportsParameter(token())).isTrue();
assertThat(this.resolver.supportsParameter(token())).isTrue();
}
@Test
public void resolveArgumentNotFound() throws Exception {
assertThat(resolver.resolveArgument(token(), mavContainer, webRequest, binderFactory)).isNull();
assertThat(this.resolver.resolveArgument(token(), this.mavContainer, this.webRequest, this.binderFactory))
.isNull();
}
@Test
public void resolveArgumentFound() throws Exception {
request.setAttribute(CsrfToken.class.getName(), token);
this.request.setAttribute(CsrfToken.class.getName(), this.token);
assertThat(resolver.resolveArgument(token(), mavContainer, webRequest, binderFactory)).isSameAs(token);
assertThat(this.resolver.resolveArgument(token(), this.mavContainer, this.webRequest, this.binderFactory))
.isSameAs(this.token);
}
private MethodParameter noToken() {

View File

@@ -334,7 +334,7 @@ public class CurrentSecurityContextArgumentResolverTests {
@Override
public Authentication getAuthentication() {
return authentication;
return this.authentication;
}
@Override

View File

@@ -76,36 +76,36 @@ public class AuthenticationPrincipalArgumentResolverTests {
@Before
public void setup() {
resolver = new AuthenticationPrincipalArgumentResolver(new ReactiveAdapterRegistry());
this.resolver = new AuthenticationPrincipalArgumentResolver(new ReactiveAdapterRegistry());
this.resolver.setBeanResolver(this.beanResolver);
}
@Test
public void supportsParameterAuthenticationPrincipal() {
assertThat(resolver.supportsParameter(this.authenticationPrincipal.arg(String.class))).isTrue();
assertThat(this.resolver.supportsParameter(this.authenticationPrincipal.arg(String.class))).isTrue();
}
@Test
public void supportsParameterCurrentUser() {
assertThat(resolver.supportsParameter(this.meta.arg(String.class))).isTrue();
assertThat(this.resolver.supportsParameter(this.meta.arg(String.class))).isTrue();
}
@Test
public void resolveArgumentWhenIsAuthenticationThenObtainsPrincipal() {
MethodParameter parameter = this.authenticationPrincipal.arg(String.class);
when(authentication.getPrincipal()).thenReturn("user");
when(this.authentication.getPrincipal()).thenReturn("user");
Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication));
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
assertThat(argument.block()).isEqualTo(authentication.getPrincipal());
assertThat(argument.block()).isEqualTo(this.authentication.getPrincipal());
}
@Test
public void resolveArgumentWhenIsEmptyThenMonoEmpty() {
MethodParameter parameter = this.authenticationPrincipal.arg(String.class);
Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange);
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange);
assertThat(argument).isNotNull();
assertThat(argument.block()).isNull();
@@ -114,34 +114,34 @@ public class AuthenticationPrincipalArgumentResolverTests {
@Test
public void resolveArgumentWhenMonoIsAuthenticationThenObtainsPrincipal() {
MethodParameter parameter = this.authenticationPrincipal.arg(Mono.class, String.class);
when(authentication.getPrincipal()).thenReturn("user");
when(this.authentication.getPrincipal()).thenReturn("user");
Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication));
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
assertThat(argument.cast(Mono.class).block().block()).isEqualTo(authentication.getPrincipal());
assertThat(argument.cast(Mono.class).block().block()).isEqualTo(this.authentication.getPrincipal());
}
@Test
public void resolveArgumentWhenMonoIsAuthenticationAndNoGenericThenObtainsPrincipal() {
MethodParameter parameter = ResolvableMethod.on(getClass()).named("authenticationPrincipalNoGeneric").build()
.arg(Mono.class);
when(authentication.getPrincipal()).thenReturn("user");
when(this.authentication.getPrincipal()).thenReturn("user");
Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication));
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
assertThat(argument.cast(Mono.class).block().block()).isEqualTo(authentication.getPrincipal());
assertThat(argument.cast(Mono.class).block().block()).isEqualTo(this.authentication.getPrincipal());
}
@Test
public void resolveArgumentWhenSpelThenObtainsPrincipal() {
MyUser user = new MyUser(3L);
MethodParameter parameter = this.spel.arg(Long.class);
when(authentication.getPrincipal()).thenReturn(user);
when(this.authentication.getPrincipal()).thenReturn(user);
Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication));
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
assertThat(argument.block()).isEqualTo(user.getId());
}
@@ -150,11 +150,11 @@ public class AuthenticationPrincipalArgumentResolverTests {
public void resolveArgumentWhenBeanThenObtainsPrincipal() throws Exception {
MyUser user = new MyUser(3L);
MethodParameter parameter = this.bean.arg(Long.class);
when(authentication.getPrincipal()).thenReturn(user);
when(this.authentication.getPrincipal()).thenReturn(user);
when(this.beanResolver.resolve(any(), eq("beanName"))).thenReturn(new Bean());
Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication));
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
assertThat(argument.block()).isEqualTo(user.getId());
}
@@ -162,10 +162,10 @@ public class AuthenticationPrincipalArgumentResolverTests {
@Test
public void resolveArgumentWhenMetaThenObtainsPrincipal() {
MethodParameter parameter = this.meta.arg(String.class);
when(authentication.getPrincipal()).thenReturn("user");
when(this.authentication.getPrincipal()).thenReturn("user");
Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication));
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
assertThat(argument.block()).isEqualTo("user");
}
@@ -174,10 +174,10 @@ public class AuthenticationPrincipalArgumentResolverTests {
public void resolveArgumentWhenErrorOnInvalidTypeImplicit() {
MethodParameter parameter = ResolvableMethod.on(getClass()).named("errorOnInvalidTypeWhenImplicit").build()
.arg(Integer.class);
when(authentication.getPrincipal()).thenReturn("user");
when(this.authentication.getPrincipal()).thenReturn("user");
Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication));
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
assertThat(argument.block()).isNull();
}
@@ -186,10 +186,10 @@ public class AuthenticationPrincipalArgumentResolverTests {
public void resolveArgumentWhenErrorOnInvalidTypeExplicitFalse() {
MethodParameter parameter = ResolvableMethod.on(getClass()).named("errorOnInvalidTypeWhenExplicitFalse").build()
.arg(Integer.class);
when(authentication.getPrincipal()).thenReturn("user");
when(this.authentication.getPrincipal()).thenReturn("user");
Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication));
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
assertThat(argument.block()).isNull();
}
@@ -198,10 +198,10 @@ public class AuthenticationPrincipalArgumentResolverTests {
public void resolveArgumentWhenErrorOnInvalidTypeExplicitTrue() {
MethodParameter parameter = ResolvableMethod.on(getClass()).named("errorOnInvalidTypeWhenExplicitTrue").build()
.arg(Integer.class);
when(authentication.getPrincipal()).thenReturn("user");
when(this.authentication.getPrincipal()).thenReturn("user");
Mono<Object> argument = resolver.resolveArgument(parameter, bindingContext, exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication));
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
assertThatThrownBy(() -> argument.block()).isInstanceOf(ClassCastException.class);
}
@@ -248,7 +248,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
}
public Long getId() {
return id;
return this.id;
}
}

View File

@@ -379,7 +379,7 @@ public class CurrentSecurityContextArgumentResolverTests {
@Override
public Authentication getAuthentication() {
return authentication;
return this.authentication;
}
@Override

View File

@@ -111,35 +111,35 @@ public class HttpSessionRequestCacheTests {
}
public String getRedirectUrl() {
return delegate.getRedirectUrl();
return this.delegate.getRedirectUrl();
}
public List<Cookie> getCookies() {
return delegate.getCookies();
return this.delegate.getCookies();
}
public String getMethod() {
return delegate.getMethod();
return this.delegate.getMethod();
}
public List<String> getHeaderValues(String name) {
return delegate.getHeaderValues(name);
return this.delegate.getHeaderValues(name);
}
public Collection<String> getHeaderNames() {
return delegate.getHeaderNames();
return this.delegate.getHeaderNames();
}
public List<Locale> getLocales() {
return delegate.getLocales();
return this.delegate.getLocales();
}
public String[] getParameterValues(String name) {
return delegate.getParameterValues(name);
return this.delegate.getParameterValues(name);
}
public Map<String, String[]> getParameterMap() {
return delegate.getParameterMap();
return this.delegate.getParameterMap();
}
private static final long serialVersionUID = 2426831999233621470L;

View File

@@ -32,67 +32,67 @@ public class SavedCookieTests {
@Before
public void setUp() {
cookie = new Cookie("name", "value");
cookie.setComment("comment");
cookie.setDomain("domain");
cookie.setMaxAge(100);
cookie.setPath("path");
cookie.setSecure(true);
cookie.setVersion(11);
savedCookie = new SavedCookie(cookie);
this.cookie = new Cookie("name", "value");
this.cookie.setComment("comment");
this.cookie.setDomain("domain");
this.cookie.setMaxAge(100);
this.cookie.setPath("path");
this.cookie.setSecure(true);
this.cookie.setVersion(11);
this.savedCookie = new SavedCookie(this.cookie);
}
@Test
public void testGetName() {
assertThat(savedCookie.getName()).isEqualTo(cookie.getName());
assertThat(this.savedCookie.getName()).isEqualTo(this.cookie.getName());
}
@Test
public void testGetValue() {
assertThat(savedCookie.getValue()).isEqualTo(cookie.getValue());
assertThat(this.savedCookie.getValue()).isEqualTo(this.cookie.getValue());
}
@Test
public void testGetComment() {
assertThat(savedCookie.getComment()).isEqualTo(cookie.getComment());
assertThat(this.savedCookie.getComment()).isEqualTo(this.cookie.getComment());
}
@Test
public void testGetDomain() {
assertThat(savedCookie.getDomain()).isEqualTo(cookie.getDomain());
assertThat(this.savedCookie.getDomain()).isEqualTo(this.cookie.getDomain());
}
@Test
public void testGetMaxAge() {
assertThat(savedCookie.getMaxAge()).isEqualTo(cookie.getMaxAge());
assertThat(this.savedCookie.getMaxAge()).isEqualTo(this.cookie.getMaxAge());
}
@Test
public void testGetPath() {
assertThat(savedCookie.getPath()).isEqualTo(cookie.getPath());
assertThat(this.savedCookie.getPath()).isEqualTo(this.cookie.getPath());
}
@Test
public void testGetVersion() {
assertThat(savedCookie.getVersion()).isEqualTo(cookie.getVersion());
assertThat(this.savedCookie.getVersion()).isEqualTo(this.cookie.getVersion());
}
@Test
public void testGetCookie() {
Cookie other = savedCookie.getCookie();
assertThat(other.getComment()).isEqualTo(cookie.getComment());
assertThat(other.getDomain()).isEqualTo(cookie.getDomain());
assertThat(other.getMaxAge()).isEqualTo(cookie.getMaxAge());
assertThat(other.getName()).isEqualTo(cookie.getName());
assertThat(other.getPath()).isEqualTo(cookie.getPath());
assertThat(other.getSecure()).isEqualTo(cookie.getSecure());
assertThat(other.getValue()).isEqualTo(cookie.getValue());
assertThat(other.getVersion()).isEqualTo(cookie.getVersion());
Cookie other = this.savedCookie.getCookie();
assertThat(other.getComment()).isEqualTo(this.cookie.getComment());
assertThat(other.getDomain()).isEqualTo(this.cookie.getDomain());
assertThat(other.getMaxAge()).isEqualTo(this.cookie.getMaxAge());
assertThat(other.getName()).isEqualTo(this.cookie.getName());
assertThat(other.getPath()).isEqualTo(this.cookie.getPath());
assertThat(other.getSecure()).isEqualTo(this.cookie.getSecure());
assertThat(other.getValue()).isEqualTo(this.cookie.getValue());
assertThat(other.getVersion()).isEqualTo(this.cookie.getVersion());
}
@Test
public void testSerializable() {
assertThat(savedCookie instanceof Serializable).isTrue();
assertThat(this.savedCookie instanceof Serializable).isTrue();
}
}

View File

@@ -45,7 +45,7 @@ public class ReactivePreAuthenticatedAuthenticationManagerTests {
private ReactiveUserDetailsService mockUserDetailsService = mock(ReactiveUserDetailsService.class);
private ReactivePreAuthenticatedAuthenticationManager manager = new ReactivePreAuthenticatedAuthenticationManager(
mockUserDetailsService);
this.mockUserDetailsService);
private final User validAccount = new User("valid", "", Collections.emptySet());
@@ -62,45 +62,47 @@ public class ReactivePreAuthenticatedAuthenticationManagerTests {
@Test
public void returnsAuthenticatedTokenForValidAccount() {
when(mockUserDetailsService.findByUsername(anyString())).thenReturn(Mono.just(validAccount));
when(this.mockUserDetailsService.findByUsername(anyString())).thenReturn(Mono.just(this.validAccount));
Authentication authentication = manager.authenticate(tokenForUser(validAccount.getUsername())).block();
Authentication authentication = this.manager.authenticate(tokenForUser(this.validAccount.getUsername()))
.block();
assertThat(authentication.isAuthenticated()).isEqualTo(true);
}
@Test(expected = UsernameNotFoundException.class)
public void returnsNullForNonExistingAccount() {
when(mockUserDetailsService.findByUsername(anyString())).thenReturn(Mono.empty());
when(this.mockUserDetailsService.findByUsername(anyString())).thenReturn(Mono.empty());
manager.authenticate(tokenForUser(nonExistingAccount.getUsername())).block();
this.manager.authenticate(tokenForUser(this.nonExistingAccount.getUsername())).block();
}
@Test(expected = LockedException.class)
public void throwsExceptionForLockedAccount() {
when(mockUserDetailsService.findByUsername(anyString())).thenReturn(Mono.just(lockedAccount));
when(this.mockUserDetailsService.findByUsername(anyString())).thenReturn(Mono.just(this.lockedAccount));
manager.authenticate(tokenForUser(lockedAccount.getUsername())).block();
this.manager.authenticate(tokenForUser(this.lockedAccount.getUsername())).block();
}
@Test(expected = DisabledException.class)
public void throwsExceptionForDisabledAccount() {
when(mockUserDetailsService.findByUsername(anyString())).thenReturn(Mono.just(disabledAccount));
when(this.mockUserDetailsService.findByUsername(anyString())).thenReturn(Mono.just(this.disabledAccount));
manager.authenticate(tokenForUser(disabledAccount.getUsername())).block();
this.manager.authenticate(tokenForUser(this.disabledAccount.getUsername())).block();
}
@Test(expected = AccountExpiredException.class)
public void throwsExceptionForExpiredAccount() {
when(mockUserDetailsService.findByUsername(anyString())).thenReturn(Mono.just(expiredAccount));
when(this.mockUserDetailsService.findByUsername(anyString())).thenReturn(Mono.just(this.expiredAccount));
manager.authenticate(tokenForUser(expiredAccount.getUsername())).block();
this.manager.authenticate(tokenForUser(this.expiredAccount.getUsername())).block();
}
@Test(expected = CredentialsExpiredException.class)
public void throwsExceptionForAccountWithExpiredCredentials() {
when(mockUserDetailsService.findByUsername(anyString())).thenReturn(Mono.just(accountWithExpiredCredentials));
when(this.mockUserDetailsService.findByUsername(anyString()))
.thenReturn(Mono.just(this.accountWithExpiredCredentials));
manager.authenticate(tokenForUser(accountWithExpiredCredentials.getUsername())).block();
this.manager.authenticate(tokenForUser(this.accountWithExpiredCredentials.getUsername())).block();
}
private Authentication tokenForUser(String username) {

View File

@@ -51,27 +51,29 @@ public class ServerX509AuthenticationConverterTests {
@Before
public void setUp() throws Exception {
request = MockServerHttpRequest.get("/");
this.request = MockServerHttpRequest.get("/");
certificate = X509TestUtils.buildTestCertificate();
when(principalExtractor.extractPrincipal(any())).thenReturn("Luke Taylor");
this.certificate = X509TestUtils.buildTestCertificate();
when(this.principalExtractor.extractPrincipal(any())).thenReturn("Luke Taylor");
}
@Test
public void shouldReturnNullForInvalidCertificate() {
Authentication authentication = converter.convert(MockServerWebExchange.from(request.build())).block();
Authentication authentication = this.converter.convert(MockServerWebExchange.from(this.request.build()))
.block();
assertThat(authentication).isNull();
}
@Test
public void shouldReturnAuthenticationForValidCertificate() {
request.sslInfo(new MockSslInfo(certificate));
this.request.sslInfo(new MockSslInfo(this.certificate));
Authentication authentication = converter.convert(MockServerWebExchange.from(request.build())).block();
Authentication authentication = this.converter.convert(MockServerWebExchange.from(this.request.build()))
.block();
assertThat(authentication.getName()).isEqualTo("Luke Taylor");
assertThat(authentication.getCredentials()).isEqualTo(certificate);
assertThat(authentication.getCredentials()).isEqualTo(this.certificate);
}
class MockSslInfo implements SslInfo {

View File

@@ -92,8 +92,9 @@ public class SwitchUserWebFilterTests {
@Before
public void setUp() {
switchUserWebFilter = new SwitchUserWebFilter(userDetailsService, successHandler, failureHandler);
switchUserWebFilter.setSecurityContextRepository(serverSecurityContextRepository);
this.switchUserWebFilter = new SwitchUserWebFilter(this.userDetailsService, this.successHandler,
this.failureHandler);
this.switchUserWebFilter.setSecurityContextRepository(this.serverSecurityContextRepository);
}
@Test
@@ -105,12 +106,12 @@ public class SwitchUserWebFilterTests {
when(chain.filter(exchange)).thenReturn(Mono.empty());
// when
switchUserWebFilter.filter(exchange, chain).block();
this.switchUserWebFilter.filter(exchange, chain).block();
// then
verifyNoInteractions(userDetailsService);
verifyNoInteractions(successHandler);
verifyNoInteractions(failureHandler);
verifyNoInteractions(serverSecurityContextRepository);
verifyNoInteractions(this.userDetailsService);
verifyNoInteractions(this.successHandler);
verifyNoInteractions(this.failureHandler);
verifyNoInteractions(this.serverSecurityContextRepository);
verify(chain).filter(exchange);
}
@@ -130,25 +131,27 @@ public class SwitchUserWebFilterTests {
"credentials");
final SecurityContextImpl securityContext = new SecurityContextImpl(originalAuthentication);
when(userDetailsService.findByUsername(targetUsername)).thenReturn(Mono.just(switchUserDetails));
when(serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class))).thenReturn(Mono.empty());
when(successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class)))
when(this.userDetailsService.findByUsername(targetUsername)).thenReturn(Mono.just(switchUserDetails));
when(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class)))
.thenReturn(Mono.empty());
when(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class)))
.thenReturn(Mono.empty());
// when
switchUserWebFilter.filter(exchange, chain).subscriberContext(withSecurityContext(Mono.just(securityContext)))
.block();
this.switchUserWebFilter.filter(exchange, chain)
.subscriberContext(withSecurityContext(Mono.just(securityContext))).block();
// then
verifyNoInteractions(chain);
verify(userDetailsService).findByUsername(targetUsername);
verify(this.userDetailsService).findByUsername(targetUsername);
final ArgumentCaptor<SecurityContext> securityContextCaptor = ArgumentCaptor.forClass(SecurityContext.class);
verify(serverSecurityContextRepository).save(eq(exchange), securityContextCaptor.capture());
verify(this.serverSecurityContextRepository).save(eq(exchange), securityContextCaptor.capture());
final SecurityContext savedSecurityContext = securityContextCaptor.getValue();
final ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(successHandler).onAuthenticationSuccess(any(WebFilterExchange.class), authenticationCaptor.capture());
verify(this.successHandler).onAuthenticationSuccess(any(WebFilterExchange.class),
authenticationCaptor.capture());
final Authentication switchUserAuthentication = authenticationCaptor.getValue();
@@ -185,19 +188,21 @@ public class SwitchUserWebFilterTests {
final WebFilterChain chain = mock(WebFilterChain.class);
when(serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class))).thenReturn(Mono.empty());
when(successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class)))
when(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class)))
.thenReturn(Mono.empty());
when(userDetailsService.findByUsername(targetUsername))
when(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class)))
.thenReturn(Mono.empty());
when(this.userDetailsService.findByUsername(targetUsername))
.thenReturn(Mono.just(switchUserDetails(targetUsername, true)));
// when
switchUserWebFilter.filter(exchange, chain).subscriberContext(withSecurityContext(Mono.just(securityContext)))
.block();
this.switchUserWebFilter.filter(exchange, chain)
.subscriberContext(withSecurityContext(Mono.just(securityContext))).block();
// then
final ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(successHandler).onAuthenticationSuccess(any(WebFilterExchange.class), authenticationCaptor.capture());
verify(this.successHandler).onAuthenticationSuccess(any(WebFilterExchange.class),
authenticationCaptor.capture());
final Authentication secondSwitchUserAuthentication = authenticationCaptor.getValue();
@@ -220,12 +225,12 @@ public class SwitchUserWebFilterTests {
final WebFilterChain chain = mock(WebFilterChain.class);
final SecurityContextImpl securityContext = new SecurityContextImpl(mock(Authentication.class));
exceptionRule.expect(IllegalArgumentException.class);
exceptionRule.expectMessage("The userName can not be null.");
this.exceptionRule.expect(IllegalArgumentException.class);
this.exceptionRule.expectMessage("The userName can not be null.");
// when
switchUserWebFilter.filter(exchange, chain).subscriberContext(withSecurityContext(Mono.just(securityContext)))
.block();
this.switchUserWebFilter.filter(exchange, chain)
.subscriberContext(withSecurityContext(Mono.just(securityContext))).block();
verifyNoInteractions(chain);
}
@@ -239,22 +244,22 @@ public class SwitchUserWebFilterTests {
final SecurityContextImpl securityContext = new SecurityContextImpl(mock(Authentication.class));
final UserDetails switchUserDetails = switchUserDetails(targetUsername, false);
when(userDetailsService.findByUsername(any(String.class))).thenReturn(Mono.just(switchUserDetails));
when(failureHandler.onAuthenticationFailure(any(WebFilterExchange.class), any(DisabledException.class)))
when(this.userDetailsService.findByUsername(any(String.class))).thenReturn(Mono.just(switchUserDetails));
when(this.failureHandler.onAuthenticationFailure(any(WebFilterExchange.class), any(DisabledException.class)))
.thenReturn(Mono.empty());
// when
switchUserWebFilter.filter(exchange, chain).subscriberContext(withSecurityContext(Mono.just(securityContext)))
.block();
this.switchUserWebFilter.filter(exchange, chain)
.subscriberContext(withSecurityContext(Mono.just(securityContext))).block();
verify(failureHandler).onAuthenticationFailure(any(WebFilterExchange.class), any(DisabledException.class));
verify(this.failureHandler).onAuthenticationFailure(any(WebFilterExchange.class), any(DisabledException.class));
verifyNoInteractions(chain);
}
@Test
public void switchUserWhenFailureHandlerNotDefinedThenReturnError() {
// given
switchUserWebFilter = new SwitchUserWebFilter(userDetailsService, successHandler, null);
this.switchUserWebFilter = new SwitchUserWebFilter(this.userDetailsService, this.successHandler, null);
final String targetUsername = "TEST_USERNAME";
final MockServerWebExchange exchange = MockServerWebExchange
@@ -264,13 +269,13 @@ public class SwitchUserWebFilterTests {
final SecurityContextImpl securityContext = new SecurityContextImpl(mock(Authentication.class));
final UserDetails switchUserDetails = switchUserDetails(targetUsername, false);
when(userDetailsService.findByUsername(any(String.class))).thenReturn(Mono.just(switchUserDetails));
when(this.userDetailsService.findByUsername(any(String.class))).thenReturn(Mono.just(switchUserDetails));
exceptionRule.expect(DisabledException.class);
this.exceptionRule.expect(DisabledException.class);
// when then
switchUserWebFilter.filter(exchange, chain).subscriberContext(withSecurityContext(Mono.just(securityContext)))
.block();
this.switchUserWebFilter.filter(exchange, chain)
.subscriberContext(withSecurityContext(Mono.just(securityContext))).block();
verifyNoInteractions(chain);
}
@@ -291,21 +296,23 @@ public class SwitchUserWebFilterTests {
final WebFilterChain chain = mock(WebFilterChain.class);
final SecurityContextImpl securityContext = new SecurityContextImpl(switchUserAuthentication);
when(serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class))).thenReturn(Mono.empty());
when(successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class)))
when(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class)))
.thenReturn(Mono.empty());
when(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class)))
.thenReturn(Mono.empty());
// when
switchUserWebFilter.filter(exchange, chain).subscriberContext(withSecurityContext(Mono.just(securityContext)))
.block();
this.switchUserWebFilter.filter(exchange, chain)
.subscriberContext(withSecurityContext(Mono.just(securityContext))).block();
// then
final ArgumentCaptor<SecurityContext> securityContextCaptor = ArgumentCaptor.forClass(SecurityContext.class);
verify(serverSecurityContextRepository).save(eq(exchange), securityContextCaptor.capture());
verify(this.serverSecurityContextRepository).save(eq(exchange), securityContextCaptor.capture());
final SecurityContext savedSecurityContext = securityContextCaptor.getValue();
final ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(successHandler).onAuthenticationSuccess(any(WebFilterExchange.class), authenticationCaptor.capture());
verify(this.successHandler).onAuthenticationSuccess(any(WebFilterExchange.class),
authenticationCaptor.capture());
final Authentication originalAuthenticationValue = authenticationCaptor.getValue();
@@ -326,12 +333,12 @@ public class SwitchUserWebFilterTests {
final WebFilterChain chain = mock(WebFilterChain.class);
final SecurityContextImpl securityContext = new SecurityContextImpl(originalAuthentication);
exceptionRule.expect(AuthenticationCredentialsNotFoundException.class);
exceptionRule.expectMessage("Could not find original Authentication object");
this.exceptionRule.expect(AuthenticationCredentialsNotFoundException.class);
this.exceptionRule.expectMessage("Could not find original Authentication object");
// when then
switchUserWebFilter.filter(exchange, chain).subscriberContext(withSecurityContext(Mono.just(securityContext)))
.block();
this.switchUserWebFilter.filter(exchange, chain)
.subscriberContext(withSecurityContext(Mono.just(securityContext))).block();
verifyNoInteractions(chain);
}
@@ -343,11 +350,11 @@ public class SwitchUserWebFilterTests {
final WebFilterChain chain = mock(WebFilterChain.class);
exceptionRule.expect(AuthenticationCredentialsNotFoundException.class);
exceptionRule.expectMessage("No current user associated with this request");
this.exceptionRule.expect(AuthenticationCredentialsNotFoundException.class);
this.exceptionRule.expectMessage("No current user associated with this request");
// when
switchUserWebFilter.filter(exchange, chain).block();
this.switchUserWebFilter.filter(exchange, chain).block();
// then
verifyNoInteractions(chain);
}
@@ -355,77 +362,77 @@ public class SwitchUserWebFilterTests {
@Test
public void constructorUserDetailsServiceRequired() {
// given
exceptionRule.expect(IllegalArgumentException.class);
exceptionRule.expectMessage("userDetailsService must be specified");
this.exceptionRule.expect(IllegalArgumentException.class);
this.exceptionRule.expectMessage("userDetailsService must be specified");
// when
switchUserWebFilter = new SwitchUserWebFilter(null, mock(ServerAuthenticationSuccessHandler.class),
this.switchUserWebFilter = new SwitchUserWebFilter(null, mock(ServerAuthenticationSuccessHandler.class),
mock(ServerAuthenticationFailureHandler.class));
}
@Test
public void constructorServerAuthenticationSuccessHandlerRequired() {
// given
exceptionRule.expect(IllegalArgumentException.class);
exceptionRule.expectMessage("successHandler must be specified");
this.exceptionRule.expect(IllegalArgumentException.class);
this.exceptionRule.expectMessage("successHandler must be specified");
// when
switchUserWebFilter = new SwitchUserWebFilter(mock(ReactiveUserDetailsService.class), null,
this.switchUserWebFilter = new SwitchUserWebFilter(mock(ReactiveUserDetailsService.class), null,
mock(ServerAuthenticationFailureHandler.class));
}
@Test
public void constructorSuccessTargetUrlRequired() {
// given
exceptionRule.expect(IllegalArgumentException.class);
exceptionRule.expectMessage("successTargetUrl must be specified");
this.exceptionRule.expect(IllegalArgumentException.class);
this.exceptionRule.expectMessage("successTargetUrl must be specified");
// when
switchUserWebFilter = new SwitchUserWebFilter(mock(ReactiveUserDetailsService.class), null,
this.switchUserWebFilter = new SwitchUserWebFilter(mock(ReactiveUserDetailsService.class), null,
"failure/target/url");
}
@Test
public void constructorFirstDefaultValues() {
// when
switchUserWebFilter = new SwitchUserWebFilter(mock(ReactiveUserDetailsService.class),
this.switchUserWebFilter = new SwitchUserWebFilter(mock(ReactiveUserDetailsService.class),
mock(ServerAuthenticationSuccessHandler.class), mock(ServerAuthenticationFailureHandler.class));
// then
final Object securityContextRepository = ReflectionTestUtils.getField(switchUserWebFilter,
final Object securityContextRepository = ReflectionTestUtils.getField(this.switchUserWebFilter,
"securityContextRepository");
assertTrue(securityContextRepository instanceof WebSessionServerSecurityContextRepository);
final Object userDetailsChecker = ReflectionTestUtils.getField(switchUserWebFilter, "userDetailsChecker");
final Object userDetailsChecker = ReflectionTestUtils.getField(this.switchUserWebFilter, "userDetailsChecker");
assertTrue(userDetailsChecker instanceof AccountStatusUserDetailsChecker);
}
@Test
public void constructorSecondDefaultValues() {
// when
switchUserWebFilter = new SwitchUserWebFilter(mock(ReactiveUserDetailsService.class), "success/target/url",
this.switchUserWebFilter = new SwitchUserWebFilter(mock(ReactiveUserDetailsService.class), "success/target/url",
"failure/target/url");
// then
final Object successHandler = ReflectionTestUtils.getField(switchUserWebFilter, "successHandler");
final Object successHandler = ReflectionTestUtils.getField(this.switchUserWebFilter, "successHandler");
assertTrue(successHandler instanceof RedirectServerAuthenticationSuccessHandler);
final Object failureHandler = ReflectionTestUtils.getField(switchUserWebFilter, "failureHandler");
final Object failureHandler = ReflectionTestUtils.getField(this.switchUserWebFilter, "failureHandler");
assertTrue(failureHandler instanceof RedirectServerAuthenticationFailureHandler);
final Object securityContextRepository = ReflectionTestUtils.getField(switchUserWebFilter,
final Object securityContextRepository = ReflectionTestUtils.getField(this.switchUserWebFilter,
"securityContextRepository");
assertTrue(securityContextRepository instanceof WebSessionServerSecurityContextRepository);
final Object userDetailsChecker = ReflectionTestUtils.getField(switchUserWebFilter, "userDetailsChecker");
final Object userDetailsChecker = ReflectionTestUtils.getField(this.switchUserWebFilter, "userDetailsChecker");
assertTrue(userDetailsChecker instanceof AccountStatusUserDetailsChecker);
}
@Test
public void setSecurityContextRepositoryWhenNullThenThrowException() {
// given
exceptionRule.expect(IllegalArgumentException.class);
exceptionRule.expectMessage("securityContextRepository cannot be null");
this.exceptionRule.expect(IllegalArgumentException.class);
this.exceptionRule.expectMessage("securityContextRepository cannot be null");
// when
switchUserWebFilter.setSecurityContextRepository(null);
this.switchUserWebFilter.setSecurityContextRepository(null);
// then
fail("Test should fail with exception");
}
@@ -433,16 +440,16 @@ public class SwitchUserWebFilterTests {
@Test
public void setSecurityContextRepositoryWhenDefinedThenChangeDefaultValue() {
// given
final Object oldSecurityContextRepository = ReflectionTestUtils.getField(switchUserWebFilter,
final Object oldSecurityContextRepository = ReflectionTestUtils.getField(this.switchUserWebFilter,
"securityContextRepository");
assertSame(serverSecurityContextRepository, oldSecurityContextRepository);
assertSame(this.serverSecurityContextRepository, oldSecurityContextRepository);
final ServerSecurityContextRepository newSecurityContextRepository = mock(
ServerSecurityContextRepository.class);
// when
switchUserWebFilter.setSecurityContextRepository(newSecurityContextRepository);
this.switchUserWebFilter.setSecurityContextRepository(newSecurityContextRepository);
// then
final Object currentSecurityContextRepository = ReflectionTestUtils.getField(switchUserWebFilter,
final Object currentSecurityContextRepository = ReflectionTestUtils.getField(this.switchUserWebFilter,
"securityContextRepository");
assertSame(newSecurityContextRepository, currentSecurityContextRepository);
}
@@ -450,10 +457,10 @@ public class SwitchUserWebFilterTests {
@Test
public void setExitUserUrlWhenNullThenThrowException() {
// given
exceptionRule.expect(IllegalArgumentException.class);
exceptionRule.expectMessage("exitUserUrl cannot be empty and must be a valid redirect URL");
this.exceptionRule.expect(IllegalArgumentException.class);
this.exceptionRule.expectMessage("exitUserUrl cannot be empty and must be a valid redirect URL");
// when
switchUserWebFilter.setExitUserUrl(null);
this.switchUserWebFilter.setExitUserUrl(null);
// then
fail("Test should fail with exception");
}
@@ -461,10 +468,10 @@ public class SwitchUserWebFilterTests {
@Test
public void setExitUserUrlWhenInvalidUrlThenThrowException() {
// given
exceptionRule.expect(IllegalArgumentException.class);
exceptionRule.expectMessage("exitUserUrl cannot be empty and must be a valid redirect URL");
this.exceptionRule.expect(IllegalArgumentException.class);
this.exceptionRule.expectMessage("exitUserUrl cannot be empty and must be a valid redirect URL");
// when
switchUserWebFilter.setExitUserUrl("wrongUrl");
this.switchUserWebFilter.setExitUserUrl("wrongUrl");
// then
fail("Test should fail with exception");
}
@@ -476,18 +483,18 @@ public class SwitchUserWebFilterTests {
.from(MockServerHttpRequest.post("/logout/impersonate"));
final ServerWebExchangeMatcher oldExitUserMatcher = (ServerWebExchangeMatcher) ReflectionTestUtils
.getField(switchUserWebFilter, "exitUserMatcher");
.getField(this.switchUserWebFilter, "exitUserMatcher");
assertThat(oldExitUserMatcher.matches(exchange).block().isMatch()).isTrue();
// when
switchUserWebFilter.setExitUserUrl("/exit-url");
this.switchUserWebFilter.setExitUserUrl("/exit-url");
// then
final MockServerWebExchange newExchange = MockServerWebExchange.from(MockServerHttpRequest.post("/exit-url"));
final ServerWebExchangeMatcher newExitUserMatcher = (ServerWebExchangeMatcher) ReflectionTestUtils
.getField(switchUserWebFilter, "exitUserMatcher");
.getField(this.switchUserWebFilter, "exitUserMatcher");
assertThat(newExitUserMatcher.matches(newExchange).block().isMatch()).isTrue();
}
@@ -495,10 +502,10 @@ public class SwitchUserWebFilterTests {
@Test
public void setExitUserMatcherWhenNullThenThrowException() {
// given
exceptionRule.expect(IllegalArgumentException.class);
exceptionRule.expectMessage("exitUserMatcher cannot be null");
this.exceptionRule.expect(IllegalArgumentException.class);
this.exceptionRule.expectMessage("exitUserMatcher cannot be null");
// when
switchUserWebFilter.setExitUserMatcher(null);
this.switchUserWebFilter.setExitUserMatcher(null);
// then
fail("Test should fail with exception");
}
@@ -510,7 +517,7 @@ public class SwitchUserWebFilterTests {
.from(MockServerHttpRequest.post("/logout/impersonate"));
final ServerWebExchangeMatcher oldExitUserMatcher = (ServerWebExchangeMatcher) ReflectionTestUtils
.getField(switchUserWebFilter, "exitUserMatcher");
.getField(this.switchUserWebFilter, "exitUserMatcher");
assertThat(oldExitUserMatcher.matches(exchange).block().isMatch()).isTrue();
@@ -518,12 +525,12 @@ public class SwitchUserWebFilterTests {
"/exit-url");
// when
switchUserWebFilter.setExitUserMatcher(newExitUserMatcher);
this.switchUserWebFilter.setExitUserMatcher(newExitUserMatcher);
// then
final ServerWebExchangeMatcher currentExitUserMatcher = (ServerWebExchangeMatcher) ReflectionTestUtils
.getField(switchUserWebFilter, "exitUserMatcher");
.getField(this.switchUserWebFilter, "exitUserMatcher");
assertSame(newExitUserMatcher, currentExitUserMatcher);
}
@@ -531,10 +538,10 @@ public class SwitchUserWebFilterTests {
@Test
public void setSwitchUserUrlWhenNullThenThrowException() {
// given
exceptionRule.expect(IllegalArgumentException.class);
exceptionRule.expectMessage("switchUserUrl cannot be empty and must be a valid redirect URL");
this.exceptionRule.expect(IllegalArgumentException.class);
this.exceptionRule.expectMessage("switchUserUrl cannot be empty and must be a valid redirect URL");
// when
switchUserWebFilter.setSwitchUserUrl(null);
this.switchUserWebFilter.setSwitchUserUrl(null);
// then
fail("Test should fail with exception");
}
@@ -542,10 +549,10 @@ public class SwitchUserWebFilterTests {
@Test
public void setSwitchUserUrlWhenInvalidThenThrowException() {
// given
exceptionRule.expect(IllegalArgumentException.class);
exceptionRule.expectMessage("switchUserUrl cannot be empty and must be a valid redirect URL");
this.exceptionRule.expect(IllegalArgumentException.class);
this.exceptionRule.expectMessage("switchUserUrl cannot be empty and must be a valid redirect URL");
// when
switchUserWebFilter.setSwitchUserUrl("wrongUrl");
this.switchUserWebFilter.setSwitchUserUrl("wrongUrl");
// then
fail("Test should fail with exception");
}
@@ -557,18 +564,18 @@ public class SwitchUserWebFilterTests {
.from(MockServerHttpRequest.post("/login/impersonate"));
final ServerWebExchangeMatcher oldSwitchUserMatcher = (ServerWebExchangeMatcher) ReflectionTestUtils
.getField(switchUserWebFilter, "switchUserMatcher");
.getField(this.switchUserWebFilter, "switchUserMatcher");
assertThat(oldSwitchUserMatcher.matches(exchange).block().isMatch()).isTrue();
// when
switchUserWebFilter.setSwitchUserUrl("/switch-url");
this.switchUserWebFilter.setSwitchUserUrl("/switch-url");
// then
final MockServerWebExchange newExchange = MockServerWebExchange.from(MockServerHttpRequest.post("/switch-url"));
final ServerWebExchangeMatcher newSwitchUserMatcher = (ServerWebExchangeMatcher) ReflectionTestUtils
.getField(switchUserWebFilter, "switchUserMatcher");
.getField(this.switchUserWebFilter, "switchUserMatcher");
assertThat(newSwitchUserMatcher.matches(newExchange).block().isMatch()).isTrue();
}
@@ -576,10 +583,10 @@ public class SwitchUserWebFilterTests {
@Test
public void setSwitchUserMatcherWhenNullThenThrowException() {
// given
exceptionRule.expect(IllegalArgumentException.class);
exceptionRule.expectMessage("switchUserMatcher cannot be null");
this.exceptionRule.expect(IllegalArgumentException.class);
this.exceptionRule.expectMessage("switchUserMatcher cannot be null");
// when
switchUserWebFilter.setSwitchUserMatcher(null);
this.switchUserWebFilter.setSwitchUserMatcher(null);
// then
fail("Test should fail with exception");
}
@@ -591,7 +598,7 @@ public class SwitchUserWebFilterTests {
.from(MockServerHttpRequest.post("/login/impersonate"));
final ServerWebExchangeMatcher oldSwitchUserMatcher = (ServerWebExchangeMatcher) ReflectionTestUtils
.getField(switchUserWebFilter, "switchUserMatcher");
.getField(this.switchUserWebFilter, "switchUserMatcher");
assertThat(oldSwitchUserMatcher.matches(exchange).block().isMatch()).isTrue();
@@ -599,12 +606,12 @@ public class SwitchUserWebFilterTests {
"/switch-url");
// when
switchUserWebFilter.setSwitchUserMatcher(newSwitchUserMatcher);
this.switchUserWebFilter.setSwitchUserMatcher(newSwitchUserMatcher);
// then
final ServerWebExchangeMatcher currentExitUserMatcher = (ServerWebExchangeMatcher) ReflectionTestUtils
.getField(switchUserWebFilter, "switchUserMatcher");
.getField(this.switchUserWebFilter, "switchUserMatcher");
assertSame(newSwitchUserMatcher, currentExitUserMatcher);
}

View File

@@ -68,30 +68,32 @@ public class DelegatingReactiveAuthorizationManagerTests {
@Before
public void setup() {
manager = DelegatingReactiveAuthorizationManager.builder()
.add(new ServerWebExchangeMatcherEntry<>(match1, delegate1))
.add(new ServerWebExchangeMatcherEntry<>(match2, delegate2)).build();
this.manager = DelegatingReactiveAuthorizationManager.builder()
.add(new ServerWebExchangeMatcherEntry<>(this.match1, this.delegate1))
.add(new ServerWebExchangeMatcherEntry<>(this.match2, this.delegate2)).build();
}
@Test
public void checkWhenFirstMatchesThenNoMoreMatchersAndNoMoreDelegatesInvoked() {
when(match1.matches(any())).thenReturn(ServerWebExchangeMatcher.MatchResult.match());
when(delegate1.check(eq(authentication), any(AuthorizationContext.class))).thenReturn(Mono.just(decision));
when(this.match1.matches(any())).thenReturn(ServerWebExchangeMatcher.MatchResult.match());
when(this.delegate1.check(eq(this.authentication), any(AuthorizationContext.class)))
.thenReturn(Mono.just(this.decision));
assertThat(manager.check(authentication, exchange).block()).isEqualTo(decision);
assertThat(this.manager.check(this.authentication, this.exchange).block()).isEqualTo(this.decision);
verifyZeroInteractions(match2, delegate2);
verifyZeroInteractions(this.match2, this.delegate2);
}
@Test
public void checkWhenSecondMatchesThenNoMoreMatchersAndNoMoreDelegatesInvoked() {
when(match1.matches(any())).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
when(match2.matches(any())).thenReturn(ServerWebExchangeMatcher.MatchResult.match());
when(delegate2.check(eq(authentication), any(AuthorizationContext.class))).thenReturn(Mono.just(decision));
when(this.match1.matches(any())).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
when(this.match2.matches(any())).thenReturn(ServerWebExchangeMatcher.MatchResult.match());
when(this.delegate2.check(eq(this.authentication), any(AuthorizationContext.class)))
.thenReturn(Mono.just(this.decision));
assertThat(manager.check(authentication, exchange).block()).isEqualTo(decision);
assertThat(this.manager.check(this.authentication, this.exchange).block()).isEqualTo(this.decision);
verifyZeroInteractions(delegate1);
verifyZeroInteractions(this.delegate1);
}
}

View File

@@ -46,7 +46,7 @@ public class SecurityContextServerWebExchangeWebFilterTests {
public void filterWhenExistingContextAndPrincipalNotNullThenContextPopulated() {
Mono<Void> result = this.filter
.filter(this.exchange, new DefaultWebFilterChain(e -> e.getPrincipal()
.doOnSuccess(contextPrincipal -> assertThat(contextPrincipal).isEqualTo(principal))
.doOnSuccess(contextPrincipal -> assertThat(contextPrincipal).isEqualTo(this.principal))
.flatMap(contextPrincipal -> Mono.subscriberContext())
.doOnSuccess(context -> assertThat(context.<String>get("foo")).isEqualTo("bar")).then()))
.subscriberContext(context -> context.put("foo", "bar"))

View File

@@ -36,60 +36,61 @@ public class CacheControlServerHttpHeadersWriterTests {
ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build());
HttpHeaders headers = exchange.getResponse().getHeaders();
HttpHeaders headers = this.exchange.getResponse().getHeaders();
@Test
public void writeHeadersWhenCacheHeadersThenWritesAllCacheControl() {
writer.writeHttpHeaders(exchange);
this.writer.writeHttpHeaders(this.exchange);
assertThat(headers).hasSize(3);
assertThat(headers.get(HttpHeaders.CACHE_CONTROL))
assertThat(this.headers).hasSize(3);
assertThat(this.headers.get(HttpHeaders.CACHE_CONTROL))
.containsOnly(CacheControlServerHttpHeadersWriter.CACHE_CONTRTOL_VALUE);
assertThat(headers.get(HttpHeaders.EXPIRES)).containsOnly(CacheControlServerHttpHeadersWriter.EXPIRES_VALUE);
assertThat(headers.get(HttpHeaders.PRAGMA)).containsOnly(CacheControlServerHttpHeadersWriter.PRAGMA_VALUE);
assertThat(this.headers.get(HttpHeaders.EXPIRES))
.containsOnly(CacheControlServerHttpHeadersWriter.EXPIRES_VALUE);
assertThat(this.headers.get(HttpHeaders.PRAGMA)).containsOnly(CacheControlServerHttpHeadersWriter.PRAGMA_VALUE);
}
@Test
public void writeHeadersWhenCacheControlThenNoCacheControlHeaders() {
String cacheControl = "max-age=1234";
headers.set(HttpHeaders.CACHE_CONTROL, cacheControl);
this.headers.set(HttpHeaders.CACHE_CONTROL, cacheControl);
writer.writeHttpHeaders(exchange);
this.writer.writeHttpHeaders(this.exchange);
assertThat(headers.get(HttpHeaders.CACHE_CONTROL)).containsOnly(cacheControl);
assertThat(this.headers.get(HttpHeaders.CACHE_CONTROL)).containsOnly(cacheControl);
}
@Test
public void writeHeadersWhenPragmaThenNoCacheControlHeaders() {
String pragma = "1";
headers.set(HttpHeaders.PRAGMA, pragma);
this.headers.set(HttpHeaders.PRAGMA, pragma);
writer.writeHttpHeaders(exchange);
this.writer.writeHttpHeaders(this.exchange);
assertThat(headers).hasSize(1);
assertThat(headers.get(HttpHeaders.PRAGMA)).containsOnly(pragma);
assertThat(this.headers).hasSize(1);
assertThat(this.headers.get(HttpHeaders.PRAGMA)).containsOnly(pragma);
}
@Test
public void writeHeadersWhenExpiresThenNoCacheControlHeaders() {
String expires = "1";
headers.set(HttpHeaders.EXPIRES, expires);
this.headers.set(HttpHeaders.EXPIRES, expires);
writer.writeHttpHeaders(exchange);
this.writer.writeHttpHeaders(this.exchange);
assertThat(headers).hasSize(1);
assertThat(headers.get(HttpHeaders.EXPIRES)).containsOnly(expires);
assertThat(this.headers).hasSize(1);
assertThat(this.headers.get(HttpHeaders.EXPIRES)).containsOnly(expires);
}
@Test
// gh-5534
public void writeHeadersWhenNotModifiedThenNoCacheControlHeaders() {
exchange.getResponse().setStatusCode(HttpStatus.NOT_MODIFIED);
this.exchange.getResponse().setStatusCode(HttpStatus.NOT_MODIFIED);
writer.writeHttpHeaders(exchange);
this.writer.writeHttpHeaders(this.exchange);
assertThat(headers).isEmpty();
assertThat(this.headers).isEmpty();
}
}

View File

@@ -107,7 +107,7 @@ public class ClearSiteDataServerHttpHeadersWriterTests {
}
List<String> getHeader() {
return actual.getHeaders().get(ClearSiteDataServerHttpHeadersWriter.CLEAR_SITE_DATA_HEADER);
return this.actual.getHeaders().get(ClearSiteDataServerHttpHeadersWriter.CLEAR_SITE_DATA_HEADER);
}
}

View File

@@ -56,42 +56,42 @@ public class CompositeServerHttpHeadersWriterTests {
@Before
public void setup() {
writer = new CompositeServerHttpHeadersWriter(Arrays.asList(writer1, writer2));
this.writer = new CompositeServerHttpHeadersWriter(Arrays.asList(this.writer1, this.writer2));
}
@Test
public void writeHttpHeadersWhenErrorNoErrorThenError() {
when(writer1.writeHttpHeaders(exchange)).thenReturn(Mono.error(new RuntimeException()));
when(this.writer1.writeHttpHeaders(this.exchange)).thenReturn(Mono.error(new RuntimeException()));
Mono<Void> result = writer.writeHttpHeaders(exchange);
Mono<Void> result = this.writer.writeHttpHeaders(this.exchange);
StepVerifier.create(result).expectError().verify();
verify(writer1).writeHttpHeaders(exchange);
verify(this.writer1).writeHttpHeaders(this.exchange);
}
@Test
public void writeHttpHeadersWhenErrorErrorThenError() {
when(writer1.writeHttpHeaders(exchange)).thenReturn(Mono.error(new RuntimeException()));
when(this.writer1.writeHttpHeaders(this.exchange)).thenReturn(Mono.error(new RuntimeException()));
Mono<Void> result = writer.writeHttpHeaders(exchange);
Mono<Void> result = this.writer.writeHttpHeaders(this.exchange);
StepVerifier.create(result).expectError().verify();
verify(writer1).writeHttpHeaders(exchange);
verify(this.writer1).writeHttpHeaders(this.exchange);
}
@Test
public void writeHttpHeadersWhenNoErrorThenNoError() {
when(writer1.writeHttpHeaders(exchange)).thenReturn(Mono.empty());
when(writer2.writeHttpHeaders(exchange)).thenReturn(Mono.empty());
when(this.writer1.writeHttpHeaders(this.exchange)).thenReturn(Mono.empty());
when(this.writer2.writeHttpHeaders(this.exchange)).thenReturn(Mono.empty());
Mono<Void> result = writer.writeHttpHeaders(exchange);
Mono<Void> result = this.writer.writeHttpHeaders(this.exchange);
StepVerifier.create(result).expectComplete().verify();
verify(writer1).writeHttpHeaders(exchange);
verify(writer2).writeHttpHeaders(exchange);
verify(this.writer1).writeHttpHeaders(this.exchange);
verify(this.writer2).writeHttpHeaders(this.exchange);
}
@Test

View File

@@ -47,30 +47,30 @@ public class HttpHeaderWriterWebFilterTests {
@Before
public void setup() {
when(writer.writeHttpHeaders(any())).thenReturn(Mono.empty());
filter = new HttpHeaderWriterWebFilter(writer);
when(this.writer.writeHttpHeaders(any())).thenReturn(Mono.empty());
this.filter = new HttpHeaderWriterWebFilter(this.writer);
}
@Test
public void filterWhenCompleteThenWritten() {
WebTestClient rest = WebTestClientBuilder.bindToWebFilters(filter).build();
WebTestClient rest = WebTestClientBuilder.bindToWebFilters(this.filter).build();
rest.get().uri("/foo").exchange();
verify(writer).writeHttpHeaders(any());
verify(this.writer).writeHttpHeaders(any());
}
@Test
public void filterWhenNotCompleteThenNotWritten() {
WebTestHandler handler = WebTestHandler.bindToWebFilters(filter);
WebTestHandler handler = WebTestHandler.bindToWebFilters(this.filter);
WebHandlerResult result = handler.exchange(MockServerHttpRequest.get("/foo"));
verify(writer, never()).writeHttpHeaders(any());
verify(this.writer, never()).writeHttpHeaders(any());
result.getExchange().getResponse().setComplete().block();
verify(writer).writeHttpHeaders(any());
verify(this.writer).writeHttpHeaders(any());
}
}

View File

@@ -37,55 +37,57 @@ public class StaticServerHttpHeadersWriterTests {
ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build());
HttpHeaders headers = exchange.getResponse().getHeaders();
HttpHeaders headers = this.exchange.getResponse().getHeaders();
@Test
public void writeHeadersWhenSingleHeaderThenWritesHeader() {
writer.writeHttpHeaders(exchange);
this.writer.writeHttpHeaders(this.exchange);
assertThat(headers.get(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS))
assertThat(this.headers.get(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS))
.containsOnly(ContentTypeOptionsServerHttpHeadersWriter.NOSNIFF);
}
@Test
public void writeHeadersWhenSingleHeaderAndHeaderWrittenThenSuccess() {
String headerValue = "other";
headers.set(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS, headerValue);
this.headers.set(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS, headerValue);
writer.writeHttpHeaders(exchange);
this.writer.writeHttpHeaders(this.exchange);
assertThat(headers.get(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS)).containsOnly(headerValue);
assertThat(this.headers.get(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS))
.containsOnly(headerValue);
}
@Test
public void writeHeadersWhenMultiHeaderThenWritesAllHeaders() {
writer = StaticServerHttpHeadersWriter.builder()
this.writer = StaticServerHttpHeadersWriter.builder()
.header(HttpHeaders.CACHE_CONTROL, CacheControlServerHttpHeadersWriter.CACHE_CONTRTOL_VALUE)
.header(HttpHeaders.PRAGMA, CacheControlServerHttpHeadersWriter.PRAGMA_VALUE)
.header(HttpHeaders.EXPIRES, CacheControlServerHttpHeadersWriter.EXPIRES_VALUE).build();
writer.writeHttpHeaders(exchange);
this.writer.writeHttpHeaders(this.exchange);
assertThat(headers.get(HttpHeaders.CACHE_CONTROL))
assertThat(this.headers.get(HttpHeaders.CACHE_CONTROL))
.containsOnly(CacheControlServerHttpHeadersWriter.CACHE_CONTRTOL_VALUE);
assertThat(headers.get(HttpHeaders.PRAGMA)).containsOnly(CacheControlServerHttpHeadersWriter.PRAGMA_VALUE);
assertThat(headers.get(HttpHeaders.EXPIRES)).containsOnly(CacheControlServerHttpHeadersWriter.EXPIRES_VALUE);
assertThat(this.headers.get(HttpHeaders.PRAGMA)).containsOnly(CacheControlServerHttpHeadersWriter.PRAGMA_VALUE);
assertThat(this.headers.get(HttpHeaders.EXPIRES))
.containsOnly(CacheControlServerHttpHeadersWriter.EXPIRES_VALUE);
}
@Test
public void writeHeadersWhenMultiHeaderAndSingleWrittenThenNoHeadersOverridden() {
String headerValue = "other";
headers.set(HttpHeaders.CACHE_CONTROL, headerValue);
this.headers.set(HttpHeaders.CACHE_CONTROL, headerValue);
writer = StaticServerHttpHeadersWriter.builder()
this.writer = StaticServerHttpHeadersWriter.builder()
.header(HttpHeaders.CACHE_CONTROL, CacheControlServerHttpHeadersWriter.CACHE_CONTRTOL_VALUE)
.header(HttpHeaders.PRAGMA, CacheControlServerHttpHeadersWriter.PRAGMA_VALUE)
.header(HttpHeaders.EXPIRES, CacheControlServerHttpHeadersWriter.EXPIRES_VALUE).build();
writer.writeHttpHeaders(exchange);
this.writer.writeHttpHeaders(this.exchange);
assertThat(headers).hasSize(1);
assertThat(headers.get(HttpHeaders.CACHE_CONTROL)).containsOnly(headerValue);
assertThat(this.headers).hasSize(1);
assertThat(this.headers.get(HttpHeaders.CACHE_CONTROL)).containsOnly(headerValue);
}
}

View File

@@ -39,11 +39,11 @@ public class StrictTransportSecurityServerHttpHeadersWriterTests {
@Test
public void writeHttpHeadersWhenHttpsThenWrites() {
exchange = exchange(MockServerHttpRequest.get("https://example.com/"));
this.exchange = exchange(MockServerHttpRequest.get("https://example.com/"));
hsts.writeHttpHeaders(exchange);
this.hsts.writeHttpHeaders(this.exchange);
HttpHeaders headers = exchange.getResponse().getHeaders();
HttpHeaders headers = this.exchange.getResponse().getHeaders();
assertThat(headers).hasSize(1);
assertThat(headers).containsEntry(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY,
Arrays.asList("max-age=31536000 ; includeSubDomains"));
@@ -52,12 +52,12 @@ public class StrictTransportSecurityServerHttpHeadersWriterTests {
@Test
public void writeHttpHeadersWhenCustomMaxAgeThenWrites() {
Duration maxAge = Duration.ofDays(1);
hsts.setMaxAge(maxAge);
exchange = exchange(MockServerHttpRequest.get("https://example.com/"));
this.hsts.setMaxAge(maxAge);
this.exchange = exchange(MockServerHttpRequest.get("https://example.com/"));
hsts.writeHttpHeaders(exchange);
this.hsts.writeHttpHeaders(this.exchange);
HttpHeaders headers = exchange.getResponse().getHeaders();
HttpHeaders headers = this.exchange.getResponse().getHeaders();
assertThat(headers).hasSize(1);
assertThat(headers).containsEntry(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY,
Arrays.asList("max-age=" + maxAge.getSeconds() + " ; includeSubDomains"));
@@ -65,12 +65,12 @@ public class StrictTransportSecurityServerHttpHeadersWriterTests {
@Test
public void writeHttpHeadersWhenCustomIncludeSubDomainsThenWrites() {
hsts.setIncludeSubDomains(false);
exchange = exchange(MockServerHttpRequest.get("https://example.com/"));
this.hsts.setIncludeSubDomains(false);
this.exchange = exchange(MockServerHttpRequest.get("https://example.com/"));
hsts.writeHttpHeaders(exchange);
this.hsts.writeHttpHeaders(this.exchange);
HttpHeaders headers = exchange.getResponse().getHeaders();
HttpHeaders headers = this.exchange.getResponse().getHeaders();
assertThat(headers).hasSize(1);
assertThat(headers).containsEntry(StrictTransportSecurityServerHttpHeadersWriter.STRICT_TRANSPORT_SECURITY,
Arrays.asList("max-age=31536000"));
@@ -78,21 +78,21 @@ public class StrictTransportSecurityServerHttpHeadersWriterTests {
@Test
public void writeHttpHeadersWhenNullSchemeThenNoHeaders() {
exchange = exchange(MockServerHttpRequest.get("/"));
this.exchange = exchange(MockServerHttpRequest.get("/"));
hsts.writeHttpHeaders(exchange);
this.hsts.writeHttpHeaders(this.exchange);
HttpHeaders headers = exchange.getResponse().getHeaders();
HttpHeaders headers = this.exchange.getResponse().getHeaders();
assertThat(headers).isEmpty();
}
@Test
public void writeHttpHeadersWhenHttpThenNoHeaders() {
exchange = exchange(MockServerHttpRequest.get("http://localhost/"));
this.exchange = exchange(MockServerHttpRequest.get("http://localhost/"));
hsts.writeHttpHeaders(exchange);
this.hsts.writeHttpHeaders(this.exchange);
HttpHeaders headers = exchange.getResponse().getHeaders();
HttpHeaders headers = this.exchange.getResponse().getHeaders();
assertThat(headers).isEmpty();
}

View File

@@ -34,26 +34,27 @@ public class XContentTypeOptionsServerHttpHeadersWriterTests {
ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build());
HttpHeaders headers = exchange.getResponse().getHeaders();
HttpHeaders headers = this.exchange.getResponse().getHeaders();
@Test
public void writeHeadersWhenNoHeadersThenWriteHeaders() {
writer.writeHttpHeaders(exchange);
this.writer.writeHttpHeaders(this.exchange);
assertThat(headers).hasSize(1);
assertThat(headers.get(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS))
assertThat(this.headers).hasSize(1);
assertThat(this.headers.get(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS))
.containsOnly(ContentTypeOptionsServerHttpHeadersWriter.NOSNIFF);
}
@Test
public void writeHeadersWhenHeaderWrittenThenDoesNotOverrride() {
String headerValue = "value";
headers.set(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS, headerValue);
this.headers.set(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS, headerValue);
writer.writeHttpHeaders(exchange);
this.writer.writeHttpHeaders(this.exchange);
assertThat(headers).hasSize(1);
assertThat(headers.get(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS)).containsOnly(headerValue);
assertThat(this.headers).hasSize(1);
assertThat(this.headers.get(ContentTypeOptionsServerHttpHeadersWriter.X_CONTENT_OPTIONS))
.containsOnly(headerValue);
}
}

View File

@@ -37,36 +37,36 @@ public class XFrameOptionsServerHttpHeadersWriterTests {
@Before
public void setup() {
writer = new XFrameOptionsServerHttpHeadersWriter();
this.writer = new XFrameOptionsServerHttpHeadersWriter();
}
@Test
public void writeHeadersWhenUsingDefaultsThenWritesDeny() {
writer.writeHttpHeaders(exchange);
this.writer.writeHttpHeaders(this.exchange);
HttpHeaders headers = exchange.getResponse().getHeaders();
HttpHeaders headers = this.exchange.getResponse().getHeaders();
assertThat(headers).hasSize(1);
assertThat(headers.get(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS)).containsOnly("DENY");
}
@Test
public void writeHeadersWhenUsingExplicitDenyThenWritesDeny() {
writer.setMode(XFrameOptionsServerHttpHeadersWriter.Mode.DENY);
this.writer.setMode(XFrameOptionsServerHttpHeadersWriter.Mode.DENY);
writer.writeHttpHeaders(exchange);
this.writer.writeHttpHeaders(this.exchange);
HttpHeaders headers = exchange.getResponse().getHeaders();
HttpHeaders headers = this.exchange.getResponse().getHeaders();
assertThat(headers).hasSize(1);
assertThat(headers.get(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS)).containsOnly("DENY");
}
@Test
public void writeHeadersWhenUsingSameOriginThenWritesSameOrigin() {
writer.setMode(XFrameOptionsServerHttpHeadersWriter.Mode.SAMEORIGIN);
this.writer.setMode(XFrameOptionsServerHttpHeadersWriter.Mode.SAMEORIGIN);
writer.writeHttpHeaders(exchange);
this.writer.writeHttpHeaders(this.exchange);
HttpHeaders headers = exchange.getResponse().getHeaders();
HttpHeaders headers = this.exchange.getResponse().getHeaders();
assertThat(headers).hasSize(1);
assertThat(headers.get(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS)).containsOnly("SAMEORIGIN");
}
@@ -74,11 +74,11 @@ public class XFrameOptionsServerHttpHeadersWriterTests {
@Test
public void writeHeadersWhenAlreadyWrittenThenWritesHeader() {
String headerValue = "other";
exchange.getResponse().getHeaders().set(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS, headerValue);
this.exchange.getResponse().getHeaders().set(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS, headerValue);
writer.writeHttpHeaders(exchange);
this.writer.writeHttpHeaders(this.exchange);
HttpHeaders headers = exchange.getResponse().getHeaders();
HttpHeaders headers = this.exchange.getResponse().getHeaders();
assertThat(headers).hasSize(1);
assertThat(headers.get(XFrameOptionsServerHttpHeadersWriter.X_FRAME_OPTIONS)).containsOnly(headerValue);
}

View File

@@ -32,47 +32,48 @@ public class XXssProtectionServerHttpHeadersWriterTests {
ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build());
HttpHeaders headers = exchange.getResponse().getHeaders();
HttpHeaders headers = this.exchange.getResponse().getHeaders();
XXssProtectionServerHttpHeadersWriter writer = new XXssProtectionServerHttpHeadersWriter();
@Test
public void writeHeadersWhenNoHeadersThenWriteHeaders() {
writer.writeHttpHeaders(exchange);
this.writer.writeHttpHeaders(this.exchange);
assertThat(headers).hasSize(1);
assertThat(headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly("1 ; mode=block");
assertThat(this.headers).hasSize(1);
assertThat(this.headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION))
.containsOnly("1 ; mode=block");
}
@Test
public void writeHeadersWhenBlockFalseThenWriteHeaders() {
writer.setBlock(false);
this.writer.setBlock(false);
writer.writeHttpHeaders(exchange);
this.writer.writeHttpHeaders(this.exchange);
assertThat(headers).hasSize(1);
assertThat(headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly("1");
assertThat(this.headers).hasSize(1);
assertThat(this.headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly("1");
}
@Test
public void writeHeadersWhenEnabledFalseThenWriteHeaders() {
writer.setEnabled(false);
this.writer.setEnabled(false);
writer.writeHttpHeaders(exchange);
this.writer.writeHttpHeaders(this.exchange);
assertThat(headers).hasSize(1);
assertThat(headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly("0");
assertThat(this.headers).hasSize(1);
assertThat(this.headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly("0");
}
@Test
public void writeHeadersWhenHeaderWrittenThenDoesNotOverrride() {
String headerValue = "value";
headers.set(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION, headerValue);
this.headers.set(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION, headerValue);
writer.writeHttpHeaders(exchange);
this.writer.writeHttpHeaders(this.exchange);
assertThat(headers).hasSize(1);
assertThat(headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly(headerValue);
assertThat(this.headers).hasSize(1);
assertThat(this.headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly(headerValue);
}
}

View File

@@ -47,13 +47,13 @@ public class DefaultCsrfServerTokenMixinTests extends AbstractMixinTests {
@Test
public void defaultCsrfTokenSerializedTest() throws JsonProcessingException, JSONException {
DefaultCsrfToken token = new DefaultCsrfToken("csrf-header", "_csrf", "1");
String serializedJson = mapper.writeValueAsString(token);
String serializedJson = this.mapper.writeValueAsString(token);
JSONAssert.assertEquals(CSRF_JSON, serializedJson, true);
}
@Test
public void defaultCsrfTokenDeserializeTest() throws IOException {
DefaultCsrfToken token = mapper.readValue(CSRF_JSON, DefaultCsrfToken.class);
DefaultCsrfToken token = this.mapper.readValue(CSRF_JSON, DefaultCsrfToken.class);
assertThat(token).isNotNull();
assertThat(token.getHeaderName()).isEqualTo("csrf-header");
assertThat(token.getParameterName()).isEqualTo("_csrf");
@@ -63,13 +63,13 @@ public class DefaultCsrfServerTokenMixinTests extends AbstractMixinTests {
@Test(expected = JsonMappingException.class)
public void defaultCsrfTokenDeserializeWithoutClassTest() throws IOException {
String tokenJson = "{\"headerName\": \"csrf-header\", \"parameterName\": \"_csrf\", \"token\": \"1\"}";
mapper.readValue(tokenJson, DefaultCsrfToken.class);
this.mapper.readValue(tokenJson, DefaultCsrfToken.class);
}
@Test(expected = JsonMappingException.class)
public void defaultCsrfTokenDeserializeNullValuesTest() throws IOException {
String tokenJson = "{\"@class\": \"org.springframework.security.web.server.csrf.DefaultCsrfToken\", \"headerName\": \"\", \"parameterName\": null, \"token\": \"1\"}";
mapper.readValue(tokenJson, DefaultCsrfToken.class);
this.mapper.readValue(tokenJson, DefaultCsrfToken.class);
}
}

View File

@@ -60,7 +60,7 @@ public class ServerRequestCacheWebFilterTests {
@Before
public void setup() {
this.requestCacheFilter = new ServerRequestCacheWebFilter();
this.requestCacheFilter.setRequestCache(requestCache);
this.requestCacheFilter.setRequestCache(this.requestCache);
when(this.chain.filter(any(ServerWebExchange.class))).thenReturn(Mono.empty());
}
@@ -73,8 +73,8 @@ public class ServerRequestCacheWebFilterTests {
this.requestCacheFilter.filter(exchange, this.chain).block();
verify(chain).filter(exchangeCaptor.capture());
ServerWebExchange updatedExchange = exchangeCaptor.getValue();
verify(this.chain).filter(this.exchangeCaptor.capture());
ServerWebExchange updatedExchange = this.exchangeCaptor.getValue();
assertThat(updatedExchange.getRequest()).isEqualTo(savedRequest);
}
@@ -86,8 +86,8 @@ public class ServerRequestCacheWebFilterTests {
this.requestCacheFilter.filter(exchange, this.chain).block();
verify(chain).filter(exchangeCaptor.capture());
ServerWebExchange updatedExchange = exchangeCaptor.getValue();
verify(this.chain).filter(this.exchangeCaptor.capture());
ServerWebExchange updatedExchange = this.exchangeCaptor.getValue();
assertThat(updatedExchange.getRequest()).isEqualTo(initialRequest);
}

View File

@@ -52,66 +52,66 @@ public class AndServerWebExchangeMatcherTests {
@Before
public void setUp() {
matcher = new AndServerWebExchangeMatcher(matcher1, matcher2);
this.matcher = new AndServerWebExchangeMatcher(this.matcher1, this.matcher2);
}
@Test
public void matchesWhenTrueTrueThenTrue() {
Map<String, Object> params1 = Collections.singletonMap("foo", "bar");
Map<String, Object> params2 = Collections.singletonMap("x", "y");
when(matcher1.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params1));
when(matcher2.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params2));
when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params1));
when(this.matcher2.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params2));
ServerWebExchangeMatcher.MatchResult matches = matcher.matches(exchange).block();
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isTrue();
assertThat(matches.getVariables()).hasSize(2);
assertThat(matches.getVariables()).containsAllEntriesOf(params1);
assertThat(matches.getVariables()).containsAllEntriesOf(params2);
verify(matcher1).matches(exchange);
verify(matcher2).matches(exchange);
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2).matches(this.exchange);
}
@Test
public void matchesWhenFalseFalseThenFalseAndMatcher2NotInvoked() {
when(matcher1.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = matcher.matches(exchange).block();
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isFalse();
assertThat(matches.getVariables()).isEmpty();
verify(matcher1).matches(exchange);
verify(matcher2, never()).matches(exchange);
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2, never()).matches(this.exchange);
}
@Test
public void matchesWhenTrueFalseThenFalse() {
Map<String, Object> params = Collections.singletonMap("foo", "bar");
when(matcher1.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params));
when(matcher2.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params));
when(this.matcher2.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = matcher.matches(exchange).block();
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isFalse();
assertThat(matches.getVariables()).isEmpty();
verify(matcher1).matches(exchange);
verify(matcher2).matches(exchange);
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2).matches(this.exchange);
}
@Test
public void matchesWhenFalseTrueThenFalse() {
when(matcher1.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = matcher.matches(exchange).block();
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isFalse();
assertThat(matches.getVariables()).isEmpty();
verify(matcher1).matches(exchange);
verify(matcher2, never()).matches(exchange);
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2, never()).matches(this.exchange);
}
}

View File

@@ -45,31 +45,31 @@ public class NegatedServerWebExchangeMatcherTests {
@Before
public void setUp() {
matcher = new NegatedServerWebExchangeMatcher(matcher1);
this.matcher = new NegatedServerWebExchangeMatcher(this.matcher1);
}
@Test
public void matchesWhenFalseThenTrue() {
when(matcher1.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = matcher.matches(exchange).block();
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isTrue();
assertThat(matches.getVariables()).isEmpty();
verify(matcher1).matches(exchange);
verify(this.matcher1).matches(this.exchange);
}
@Test
public void matchesWhenTrueThenFalse() {
when(matcher1.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match());
when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match());
ServerWebExchangeMatcher.MatchResult matches = matcher.matches(exchange).block();
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isFalse();
assertThat(matches.getVariables()).isEmpty();
verify(matcher1).matches(exchange);
verify(this.matcher1).matches(this.exchange);
}
}

View File

@@ -52,50 +52,50 @@ public class OrServerWebExchangeMatcherTests {
@Before
public void setUp() {
matcher = new OrServerWebExchangeMatcher(matcher1, matcher2);
this.matcher = new OrServerWebExchangeMatcher(this.matcher1, this.matcher2);
}
@Test
public void matchesWhenFalseFalseThenFalse() {
when(matcher1.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
when(matcher2.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
when(this.matcher2.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
ServerWebExchangeMatcher.MatchResult matches = matcher.matches(exchange).block();
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isFalse();
assertThat(matches.getVariables()).isEmpty();
verify(matcher1).matches(exchange);
verify(matcher2).matches(exchange);
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2).matches(this.exchange);
}
@Test
public void matchesWhenTrueFalseThenTrueAndMatcher2NotInvoked() {
Map<String, Object> params = Collections.singletonMap("foo", "bar");
when(matcher1.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params));
when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params));
ServerWebExchangeMatcher.MatchResult matches = matcher.matches(exchange).block();
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isTrue();
assertThat(matches.getVariables()).isEqualTo(params);
verify(matcher1).matches(exchange);
verify(matcher2, never()).matches(exchange);
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2, never()).matches(this.exchange);
}
@Test
public void matchesWhenFalseTrueThenTrue() {
Map<String, Object> params = Collections.singletonMap("foo", "bar");
when(matcher1.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
when(matcher2.matches(exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params));
when(this.matcher1.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.notMatch());
when(this.matcher2.matches(this.exchange)).thenReturn(ServerWebExchangeMatcher.MatchResult.match(params));
ServerWebExchangeMatcher.MatchResult matches = matcher.matches(exchange).block();
ServerWebExchangeMatcher.MatchResult matches = this.matcher.matches(this.exchange).block();
assertThat(matches.isMatch()).isTrue();
assertThat(matches.getVariables()).isEqualTo(params);
verify(matcher1).matches(exchange);
verify(matcher2).matches(exchange);
verify(this.matcher1).matches(this.exchange);
verify(this.matcher2).matches(this.exchange);
}
}

View File

@@ -59,10 +59,10 @@ public class PathMatcherServerWebExchangeMatcherTests {
MockServerHttpRequest request = MockServerHttpRequest.post("/path").build();
MockServerHttpResponse response = new MockServerHttpResponse();
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
exchange = MockServerWebExchange.from(request);
path = "/path";
this.exchange = MockServerWebExchange.from(request);
this.path = "/path";
matcher = new PathPatternParserServerWebExchangeMatcher(pattern);
this.matcher = new PathPatternParserServerWebExchangeMatcher(this.pattern);
}
@Test(expected = IllegalArgumentException.class)
@@ -77,39 +77,40 @@ public class PathMatcherServerWebExchangeMatcherTests {
@Test
public void matchesWhenPathMatcherTrueThenReturnTrue() {
when(pattern.matches(any())).thenReturn(true);
when(pattern.matchAndExtract(any())).thenReturn(pathMatchInfo);
when(pathMatchInfo.getUriVariables()).thenReturn(new HashMap<>());
when(this.pattern.matches(any())).thenReturn(true);
when(this.pattern.matchAndExtract(any())).thenReturn(this.pathMatchInfo);
when(this.pathMatchInfo.getUriVariables()).thenReturn(new HashMap<>());
assertThat(matcher.matches(exchange).block().isMatch()).isTrue();
assertThat(this.matcher.matches(this.exchange).block().isMatch()).isTrue();
}
@Test
public void matchesWhenPathMatcherFalseThenReturnFalse() {
when(pattern.matches(any())).thenReturn(false);
when(this.pattern.matches(any())).thenReturn(false);
assertThat(matcher.matches(exchange).block().isMatch()).isFalse();
assertThat(this.matcher.matches(this.exchange).block().isMatch()).isFalse();
}
@Test
public void matchesWhenPathMatcherTrueAndMethodTrueThenReturnTrue() {
matcher = new PathPatternParserServerWebExchangeMatcher(pattern, exchange.getRequest().getMethod());
when(pattern.matches(any())).thenReturn(true);
when(pattern.matchAndExtract(any())).thenReturn(pathMatchInfo);
when(pathMatchInfo.getUriVariables()).thenReturn(new HashMap<>());
this.matcher = new PathPatternParserServerWebExchangeMatcher(this.pattern,
this.exchange.getRequest().getMethod());
when(this.pattern.matches(any())).thenReturn(true);
when(this.pattern.matchAndExtract(any())).thenReturn(this.pathMatchInfo);
when(this.pathMatchInfo.getUriVariables()).thenReturn(new HashMap<>());
assertThat(matcher.matches(exchange).block().isMatch()).isTrue();
assertThat(this.matcher.matches(this.exchange).block().isMatch()).isTrue();
}
@Test
public void matchesWhenPathMatcherTrueAndMethodFalseThenReturnFalse() {
HttpMethod method = HttpMethod.OPTIONS;
assertThat(exchange.getRequest().getMethod()).isNotEqualTo(method);
matcher = new PathPatternParserServerWebExchangeMatcher(pattern, method);
assertThat(this.exchange.getRequest().getMethod()).isNotEqualTo(method);
this.matcher = new PathPatternParserServerWebExchangeMatcher(this.pattern, method);
assertThat(matcher.matches(exchange).block().isMatch()).isFalse();
assertThat(this.matcher.matches(this.exchange).block().isMatch()).isFalse();
verifyZeroInteractions(pattern);
verifyZeroInteractions(this.pattern);
}
}

View File

@@ -39,29 +39,30 @@ public class ServerWebExchangeMatchersTests {
@Test
public void pathMatchersWhenSingleAndSamePatternThenMatches() {
assertThat(pathMatchers("/").matches(exchange).block().isMatch()).isTrue();
assertThat(pathMatchers("/").matches(this.exchange).block().isMatch()).isTrue();
}
@Test
public void pathMatchersWhenSingleAndSamePatternAndMethodThenMatches() {
assertThat(ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, "/").matches(exchange).block().isMatch())
assertThat(ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, "/").matches(this.exchange).block().isMatch())
.isTrue();
}
@Test
public void pathMatchersWhenSingleAndSamePatternAndDiffMethodThenDoesNotMatch() {
assertThat(ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, "/").matches(exchange).block().isMatch())
.isFalse();
assertThat(
ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, "/").matches(this.exchange).block().isMatch())
.isFalse();
}
@Test
public void pathMatchersWhenSingleAndDifferentPatternThenDoesNotMatch() {
assertThat(pathMatchers("/foobar").matches(exchange).block().isMatch()).isFalse();
assertThat(pathMatchers("/foobar").matches(this.exchange).block().isMatch()).isFalse();
}
@Test
public void pathMatchersWhenMultiThenMatches() {
assertThat(pathMatchers("/foobar", "/").matches(exchange).block().isMatch()).isTrue();
assertThat(pathMatchers("/foobar", "/").matches(this.exchange).block().isMatch()).isTrue();
}
@Test

View File

@@ -46,13 +46,13 @@ public class CsrfRequestDataValueProcessorTests {
@Before
public void setup() {
request = new MockHttpServletRequest();
processor = new CsrfRequestDataValueProcessor();
this.request = new MockHttpServletRequest();
this.processor = new CsrfRequestDataValueProcessor();
token = new DefaultCsrfToken("1", "a", "b");
request.setAttribute(CsrfToken.class.getName(), token);
this.token = new DefaultCsrfToken("1", "a", "b");
this.request.setAttribute(CsrfToken.class.getName(), this.token);
expected.put(token.getParameterName(), token.getToken());
this.expected.put(this.token.getParameterName(), this.token.getToken());
}
@Test
@@ -68,72 +68,72 @@ public class CsrfRequestDataValueProcessorTests {
@Test
public void getExtraHiddenFieldsNoCsrfToken() {
request = new MockHttpServletRequest();
assertThat(processor.getExtraHiddenFields(request)).isEmpty();
this.request = new MockHttpServletRequest();
assertThat(this.processor.getExtraHiddenFields(this.request)).isEmpty();
}
@Test
public void getExtraHiddenFieldsHasCsrfTokenNoMethodSet() {
assertThat(processor.getExtraHiddenFields(request)).isEqualTo(expected);
assertThat(this.processor.getExtraHiddenFields(this.request)).isEqualTo(this.expected);
}
@Test
public void getExtraHiddenFieldsHasCsrfToken_GET() {
processor.processAction(request, "action", "GET");
assertThat(processor.getExtraHiddenFields(request)).isEmpty();
this.processor.processAction(this.request, "action", "GET");
assertThat(this.processor.getExtraHiddenFields(this.request)).isEmpty();
}
@Test
public void getExtraHiddenFieldsHasCsrfToken_get() {
processor.processAction(request, "action", "get");
assertThat(processor.getExtraHiddenFields(request)).isEmpty();
this.processor.processAction(this.request, "action", "get");
assertThat(this.processor.getExtraHiddenFields(this.request)).isEmpty();
}
@Test
public void getExtraHiddenFieldsHasCsrfToken_POST() {
processor.processAction(request, "action", "POST");
assertThat(processor.getExtraHiddenFields(request)).isEqualTo(expected);
this.processor.processAction(this.request, "action", "POST");
assertThat(this.processor.getExtraHiddenFields(this.request)).isEqualTo(this.expected);
}
@Test
public void getExtraHiddenFieldsHasCsrfToken_post() {
processor.processAction(request, "action", "post");
assertThat(processor.getExtraHiddenFields(request)).isEqualTo(expected);
this.processor.processAction(this.request, "action", "post");
assertThat(this.processor.getExtraHiddenFields(this.request)).isEqualTo(this.expected);
}
@Test
public void processAction() {
String action = "action";
assertThat(processor.processAction(request, action)).isEqualTo(action);
assertThat(this.processor.processAction(this.request, action)).isEqualTo(action);
}
@Test
public void processActionWithMethodArg() {
String action = "action";
assertThat(processor.processAction(request, action, null)).isEqualTo(action);
assertThat(this.processor.processAction(this.request, action, null)).isEqualTo(action);
}
@Test
public void processFormFieldValue() {
String value = "action";
assertThat(processor.processFormFieldValue(request, "name", value, "hidden")).isEqualTo(value);
assertThat(this.processor.processFormFieldValue(this.request, "name", value, "hidden")).isEqualTo(value);
}
@Test
public void processUrl() {
String url = "url";
assertThat(processor.processUrl(request, url)).isEqualTo(url);
assertThat(this.processor.processUrl(this.request, url)).isEqualTo(url);
}
@Test
public void createGetExtraHiddenFieldsHasCsrfToken() {
CsrfToken token = new DefaultCsrfToken("1", "a", "b");
request.setAttribute(CsrfToken.class.getName(), token);
this.request.setAttribute(CsrfToken.class.getName(), token);
Map<String, String> expected = new HashMap<>();
expected.put(token.getParameterName(), token.getToken());
RequestDataValueProcessor processor = new CsrfRequestDataValueProcessor();
assertThat(processor.getExtraHiddenFields(request)).isEqualTo(expected);
assertThat(processor.getExtraHiddenFields(this.request)).isEqualTo(expected);
}
}

View File

@@ -39,34 +39,34 @@ public class HttpSessionDestroyedEventTests {
@Before
public void setUp() {
session = new MockHttpSession();
session.setAttribute("notcontext", "notcontext");
session.setAttribute("null", null);
session.setAttribute("context", new SecurityContextImpl());
destroyedEvent = new HttpSessionDestroyedEvent(session);
this.session = new MockHttpSession();
this.session.setAttribute("notcontext", "notcontext");
this.session.setAttribute("null", null);
this.session.setAttribute("context", new SecurityContextImpl());
this.destroyedEvent = new HttpSessionDestroyedEvent(this.session);
}
// SEC-1870
@Test
public void getSecurityContexts() {
List<SecurityContext> securityContexts = destroyedEvent.getSecurityContexts();
List<SecurityContext> securityContexts = this.destroyedEvent.getSecurityContexts();
assertThat(securityContexts).hasSize(1);
assertThat(securityContexts.get(0)).isSameAs(session.getAttribute("context"));
assertThat(securityContexts.get(0)).isSameAs(this.session.getAttribute("context"));
}
@Test
public void getSecurityContextsMulti() {
session.setAttribute("another", new SecurityContextImpl());
List<SecurityContext> securityContexts = destroyedEvent.getSecurityContexts();
this.session.setAttribute("another", new SecurityContextImpl());
List<SecurityContext> securityContexts = this.destroyedEvent.getSecurityContexts();
assertThat(securityContexts).hasSize(2);
}
@Test
public void getSecurityContextsDiffImpl() {
session.setAttribute("context", mock(SecurityContext.class));
List<SecurityContext> securityContexts = destroyedEvent.getSecurityContexts();
this.session.setAttribute("context", mock(SecurityContext.class));
List<SecurityContext> securityContexts = this.destroyedEvent.getSecurityContexts();
assertThat(securityContexts).hasSize(1);
assertThat(securityContexts.get(0)).isSameAs(session.getAttribute("context"));
assertThat(securityContexts.get(0)).isSameAs(this.session.getAttribute("context"));
}
}

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