Merge branch '6.0.x' into 6.1.x

Closes gh-13883
This commit is contained in:
Marcus Da Coregio
2023-09-29 11:46:48 -03:00
1173 changed files with 10937 additions and 8789 deletions

View File

@@ -61,7 +61,7 @@ public class DefaultRedirectStrategyTests {
request.setContextPath("/context");
MockHttpServletResponse response = new MockHttpServletResponse();
assertThatIllegalArgumentException()
.isThrownBy(() -> rds.sendRedirect(request, response, "https://redirectme.somewhere.else"));
.isThrownBy(() -> rds.sendRedirect(request, response, "https://redirectme.somewhere.else"));
}
}

View File

@@ -201,10 +201,10 @@ public class FilterChainProxyTests {
given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(true);
willAnswer((Answer<Object>) (inv) -> {
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("username", "password"));
.setAuthentication(new TestingAuthenticationToken("username", "password"));
return null;
}).given(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(FilterChain.class));
}).given(this.filter)
.doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), any(FilterChain.class));
this.fcp.doFilter(this.request, this.response, this.chain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -223,12 +223,12 @@ public class FilterChainProxyTests {
given(this.matcher.matches(any(HttpServletRequest.class))).willReturn(true);
willAnswer((Answer<Object>) (inv) -> {
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("username", "password"));
.setAuthentication(new TestingAuthenticationToken("username", "password"));
throw new ServletException("oops");
}).given(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(FilterChain.class));
}).given(this.filter)
.doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), any(FilterChain.class));
assertThatExceptionOfType(ServletException.class)
.isThrownBy(() -> this.fcp.doFilter(this.request, this.response, this.chain));
.isThrownBy(() -> this.fcp.doFilter(this.request, this.response, this.chain));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -243,13 +243,13 @@ public class FilterChainProxyTests {
willAnswer((Answer<Object>) (inv1) -> {
innerChain.doFilter(this.request, this.response);
return null;
}).given(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(FilterChain.class));
}).given(this.filter)
.doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), any(FilterChain.class));
this.fcp.doFilter(this.request, this.response, innerChain);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isSameAs(expected);
return null;
}).given(this.filter).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class),
any(FilterChain.class));
}).given(this.filter)
.doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class), any(FilterChain.class));
this.fcp.doFilter(this.request, this.response, this.chain);
verify(innerChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
@@ -297,7 +297,8 @@ public class FilterChainProxyTests {
FilterChainProxy fcp = new FilterChainProxy(sec);
fcp.setFilterChainDecorator(new ObservationFilterChainDecorator(registry));
Filter filter = ObservationFilterChainDecorator.FilterObservation
.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
.create(Observation.createNotStarted("wrap", registry))
.wrap(fcp);
filter.doFilter(this.request, this.response, this.chain);
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(4)).onStart(captor.capture());
@@ -323,7 +324,8 @@ public class FilterChainProxyTests {
FilterChainProxy fcp = new FilterChainProxy(sec);
fcp.setFilterChainDecorator(new ObservationFilterChainDecorator(registry));
Filter filter = ObservationFilterChainDecorator.FilterObservation
.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
.create(Observation.createNotStarted("wrap", registry))
.wrap(fcp);
filter.doFilter(this.request, this.response, this.chain);
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(4)).onStart(captor.capture());
@@ -345,7 +347,8 @@ public class FilterChainProxyTests {
FilterChainProxy fcp = new FilterChainProxy(sec);
fcp.setFilterChainDecorator(new ObservationFilterChainDecorator(registry));
Filter filter = ObservationFilterChainDecorator.FilterObservation
.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
.create(Observation.createNotStarted("wrap", registry))
.wrap(fcp);
filter.doFilter(this.request, this.response, this.chain);
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(2)).onStart(captor.capture());
@@ -367,9 +370,10 @@ public class FilterChainProxyTests {
FilterChainProxy fcp = new FilterChainProxy(sec);
fcp.setFilterChainDecorator(new ObservationFilterChainDecorator(registry));
Filter filter = ObservationFilterChainDecorator.FilterObservation
.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
.create(Observation.createNotStarted("wrap", registry))
.wrap(fcp);
assertThatExceptionOfType(IllegalStateException.class)
.isThrownBy(() -> filter.doFilter(this.request, this.response, this.chain));
.isThrownBy(() -> filter.doFilter(this.request, this.response, this.chain));
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(2)).onStart(captor.capture());
verify(handler, times(2)).onStop(any());
@@ -394,9 +398,10 @@ public class FilterChainProxyTests {
FilterChainProxy fcp = new FilterChainProxy(sec);
fcp.setFilterChainDecorator(new ObservationFilterChainDecorator(registry));
Filter filter = ObservationFilterChainDecorator.FilterObservation
.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
.create(Observation.createNotStarted("wrap", registry))
.wrap(fcp);
assertThatExceptionOfType(IllegalStateException.class)
.isThrownBy(() -> filter.doFilter(this.request, this.response, this.chain));
.isThrownBy(() -> filter.doFilter(this.request, this.response, this.chain));
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(2)).onStart(captor.capture());
verify(handler, times(2)).onStop(any());
@@ -419,7 +424,8 @@ public class FilterChainProxyTests {
FilterChainProxy fcp = new FilterChainProxy(sec);
fcp.setFilterChainDecorator(new ObservationFilterChainDecorator(registry));
Filter filter = ObservationFilterChainDecorator.FilterObservation
.create(Observation.createNotStarted("wrap", registry)).wrap(fcp);
.create(Observation.createNotStarted("wrap", registry))
.wrap(fcp);
filter.doFilter(this.request, this.response, this.chain);
ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(3)).onStart(captor.capture());
@@ -434,7 +440,7 @@ public class FilterChainProxyTests {
assertThat(context).isInstanceOf(ObservationFilterChainDecorator.FilterChainObservationContext.class);
ObservationFilterChainDecorator.FilterChainObservationContext filterChainObservationContext = (ObservationFilterChainDecorator.FilterChainObservationContext) context;
assertThat(context.getName())
.isEqualTo(ObservationFilterChainDecorator.FilterChainObservationConvention.CHAIN_OBSERVATION_NAME);
.isEqualTo(ObservationFilterChainDecorator.FilterChainObservationConvention.CHAIN_OBSERVATION_NAME);
assertThat(context.getContextualName()).endsWith(filterSection);
assertThat(filterChainObservationContext.getChainPosition()).isEqualTo(chainPosition);
}

View File

@@ -77,14 +77,14 @@ public class FilterInvocationTests {
public void testRejectsNullServletRequest() {
MockHttpServletResponse response = new MockHttpServletResponse();
assertThatIllegalArgumentException()
.isThrownBy(() -> new FilterInvocation(null, response, mock(FilterChain.class)));
.isThrownBy(() -> new FilterInvocation(null, response, mock(FilterChain.class)));
}
@Test
public void testRejectsNullServletResponse() {
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
assertThatIllegalArgumentException()
.isThrownBy(() -> new FilterInvocation(request, null, mock(FilterChain.class)));
.isThrownBy(() -> new FilterInvocation(request, null, mock(FilterChain.class)));
}
@Test
@@ -123,7 +123,7 @@ public class FilterInvocationTests {
@Test
public void dummyChainRejectsInvocation() throws Exception {
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> FilterInvocation.DUMMY_CHAIN
.doFilter(mock(HttpServletRequest.class), mock(HttpServletResponse.class)));
.doFilter(mock(HttpServletRequest.class), mock(HttpServletResponse.class)));
}
@Test

View File

@@ -147,7 +147,7 @@ public class ObservationFilterChainDecoratorTests {
ArgumentCaptor<Observation.Context> context = ArgumentCaptor.forClass(Observation.Context.class);
verify(handler, times(3)).onScopeClosed(context.capture());
assertThat(context.getValue().getLowCardinalityKeyValue("spring.security.reached.filter.name").getValue())
.isEqualTo(expectedFilterNameTag);
.isEqualTo(expectedFilterNameTag);
}
static Stream<Arguments> decorateFiltersWhenCompletesThenHasSpringSecurityReachedFilterNameTag() {

View File

@@ -77,28 +77,28 @@ public class RequestMatcherRedirectFilterTests {
@Test
public void constructWhenRequestMatcherNull() {
assertThatIllegalArgumentException().isThrownBy(() -> new RequestMatcherRedirectFilter(null, "/test"))
.withMessage("requestMatcher cannot be null");
.withMessage("requestMatcher cannot be null");
}
@Test
public void constructWhenRedirectUrlNull() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new RequestMatcherRedirectFilter(new AntPathRequestMatcher("/**"), null))
.withMessage("redirectUrl cannot be empty");
.isThrownBy(() -> new RequestMatcherRedirectFilter(new AntPathRequestMatcher("/**"), null))
.withMessage("redirectUrl cannot be empty");
}
@Test
public void constructWhenRedirectUrlEmpty() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new RequestMatcherRedirectFilter(new AntPathRequestMatcher("/**"), ""))
.withMessage("redirectUrl cannot be empty");
.isThrownBy(() -> new RequestMatcherRedirectFilter(new AntPathRequestMatcher("/**"), ""))
.withMessage("redirectUrl cannot be empty");
}
@Test
public void constructWhenRedirectUrlBlank() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new RequestMatcherRedirectFilter(new AntPathRequestMatcher("/**"), " "))
.withMessage("redirectUrl cannot be empty");
.isThrownBy(() -> new RequestMatcherRedirectFilter(new AntPathRequestMatcher("/**"), " "))
.withMessage("redirectUrl cannot be empty");
}
}

View File

@@ -48,8 +48,8 @@ class AuthorizationManagerWebInvocationPrivilegeEvaluatorTests {
@Test
void constructorWhenAuthorizationManagerNullThenIllegalArgument() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new AuthorizationManagerWebInvocationPrivilegeEvaluator(null))
.withMessage("authorizationManager cannot be null");
.isThrownBy(() -> new AuthorizationManagerWebInvocationPrivilegeEvaluator(null))
.withMessage("authorizationManager cannot be null");
}
@Test

View File

@@ -114,7 +114,7 @@ public class DefaultWebInvocationPrivilegeEvaluatorTests {
Authentication token = new TestingAuthenticationToken("test", "Password", "MOCK_INDEX");
MockServletContext servletContext = new MockServletContext();
ArgumentCaptor<FilterInvocation> filterInvocationArgumentCaptor = ArgumentCaptor
.forClass(FilterInvocation.class);
.forClass(FilterInvocation.class);
DefaultWebInvocationPrivilegeEvaluator wipe = new DefaultWebInvocationPrivilegeEvaluator(this.interceptor);
wipe.setServletContext(servletContext);
wipe.isAllowed("/foo/index.jsp", token);

View File

@@ -92,12 +92,13 @@ public class ExceptionTranslationFilterTests {
request.setRequestURI("/mycontext/secure/page.html");
// Setup the FilterChain to thrown an access denied exception
FilterChain fc = mock(FilterChain.class);
willThrow(new AccessDeniedException("")).given(fc).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
willThrow(new AccessDeniedException("")).given(fc)
.doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
// Setup SecurityContextHolder, as filter needs to check if user is
// anonymous
SecurityContextHolder.getContext().setAuthentication(
new AnonymousAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("IGNORED")));
SecurityContextHolder.getContext()
.setAuthentication(new AnonymousAuthenticationToken("ignored", "ignored",
AuthorityUtils.createAuthorityList("IGNORED")));
// Test
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint);
filter.setAuthenticationTrustResolver(new AuthenticationTrustResolverImpl());
@@ -119,8 +120,8 @@ public class ExceptionTranslationFilterTests {
request.setRequestURI("/mycontext/secure/page.html");
// Setup the FilterChain to thrown an access denied exception
FilterChain fc = mock(FilterChain.class);
willThrow(new AccessDeniedException("")).given(fc).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
willThrow(new AccessDeniedException("")).given(fc)
.doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
// Setup SecurityContextHolder, as filter needs to check if user is remembered
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(
@@ -142,8 +143,8 @@ public class ExceptionTranslationFilterTests {
request.setServletPath("/secure/page.html");
// Setup the FilterChain to thrown an access denied exception
FilterChain fc = mock(FilterChain.class);
willThrow(new AccessDeniedException("")).given(fc).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
willThrow(new AccessDeniedException("")).given(fc)
.doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
// Setup SecurityContextHolder, as filter needs to check if user is
// anonymous
SecurityContextHolder.clearContext();
@@ -157,7 +158,7 @@ public class ExceptionTranslationFilterTests {
filter.doFilter(request, response, fc);
assertThat(response.getStatus()).isEqualTo(403);
assertThat(request.getAttribute(WebAttributes.ACCESS_DENIED_403))
.isExactlyInstanceOf(AccessDeniedException.class);
.isExactlyInstanceOf(AccessDeniedException.class);
}
@Test
@@ -167,12 +168,13 @@ public class ExceptionTranslationFilterTests {
request.setServletPath("/secure/page.html");
// Setup the FilterChain to thrown an access denied exception
FilterChain fc = mock(FilterChain.class);
willThrow(new AccessDeniedException("")).given(fc).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
willThrow(new AccessDeniedException("")).given(fc)
.doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
// Setup SecurityContextHolder, as filter needs to check if user is
// anonymous
SecurityContextHolder.getContext().setAuthentication(
new AnonymousAuthenticationToken("ignored", "ignored", AuthorityUtils.createAuthorityList("IGNORED")));
SecurityContextHolder.getContext()
.setAuthentication(new AnonymousAuthenticationToken("ignored", "ignored",
AuthorityUtils.createAuthorityList("IGNORED")));
// Test
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(
(req, res, ae) -> res.sendError(403, ae.getMessage()));
@@ -182,7 +184,7 @@ public class ExceptionTranslationFilterTests {
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, fc);
assertThat(response.getErrorMessage())
.isEqualTo("Vollst\u00e4ndige Authentifikation wird ben\u00f6tigt um auf diese Resource zuzugreifen");
.isEqualTo("Vollst\u00e4ndige Authentifikation wird ben\u00f6tigt um auf diese Resource zuzugreifen");
}
@Test
@@ -197,8 +199,8 @@ public class ExceptionTranslationFilterTests {
request.setRequestURI("/mycontext/secure/page.html");
// Setup the FilterChain to thrown an authentication failure exception
FilterChain fc = mock(FilterChain.class);
willThrow(new BadCredentialsException("")).given(fc).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
willThrow(new BadCredentialsException("")).given(fc)
.doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
// Test
RequestCache requestCache = new HttpSessionRequestCache();
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint, requestCache);
@@ -222,8 +224,8 @@ public class ExceptionTranslationFilterTests {
request.setRequestURI("/mycontext/secure/page.html");
// Setup the FilterChain to thrown an authentication failure exception
FilterChain fc = mock(FilterChain.class);
willThrow(new BadCredentialsException("")).given(fc).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
willThrow(new BadCredentialsException("")).given(fc)
.doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
// Test
HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint, requestCache);
@@ -242,7 +244,7 @@ public class ExceptionTranslationFilterTests {
@Test
public void startupDetectsMissingRequestCache() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new ExceptionTranslationFilter(this.mockEntryPoint, null));
.isThrownBy(() -> new ExceptionTranslationFilter(this.mockEntryPoint, null));
}
@Test
@@ -266,8 +268,8 @@ public class ExceptionTranslationFilterTests {
FilterChain fc = mock(FilterChain.class);
willThrow(exception).given(fc).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
assertThatExceptionOfType(Exception.class)
.isThrownBy(() -> filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), fc))
.isSameAs(exception);
.isThrownBy(() -> filter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), fc))
.isSameAs(exception);
}
}
@@ -283,7 +285,7 @@ public class ExceptionTranslationFilterTests {
MockHttpServletResponse response = new MockHttpServletResponse();
ExceptionTranslationFilter filter = new ExceptionTranslationFilter(this.mockEntryPoint);
assertThatExceptionOfType(ServletException.class).isThrownBy(() -> filter.doFilter(request, response, chain))
.withCauseInstanceOf(AccessDeniedException.class);
.withCauseInstanceOf(AccessDeniedException.class);
verifyNoMoreInteractions(this.mockEntryPoint);
}
@@ -304,6 +306,6 @@ public class ExceptionTranslationFilterTests {
}
private AuthenticationEntryPoint mockEntryPoint = (request, response, authException) -> response
.sendRedirect(request.getContextPath() + "/login.jsp");
.sendRedirect(request.getContextPath() + "/login.jsp");
}

View File

@@ -182,18 +182,20 @@ class RequestMatcherDelegatingWebInvocationPrivilegeEvaluatorTests {
void constructorWhenPrivilegeEvaluatorsNullThenException() {
RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>> entry = new RequestMatcherEntry<>(this.alwaysMatch,
null);
assertThatIllegalArgumentException().isThrownBy(
() -> new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator(Collections.singletonList(entry)))
.withMessageContaining("webInvocationPrivilegeEvaluators cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(
() -> new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator(Collections.singletonList(entry)))
.withMessageContaining("webInvocationPrivilegeEvaluators cannot be null");
}
@Test
void constructorWhenRequestMatcherNullThenException() {
RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>> entry = new RequestMatcherEntry<>(null,
Collections.singletonList(mock(WebInvocationPrivilegeEvaluator.class)));
assertThatIllegalArgumentException().isThrownBy(
() -> new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator(Collections.singletonList(entry)))
.withMessageContaining("requestMatcher cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(
() -> new RequestMatcherDelegatingWebInvocationPrivilegeEvaluator(Collections.singletonList(entry)))
.withMessageContaining("requestMatcher cannot be null");
}
}

View File

@@ -152,7 +152,7 @@ public class ChannelDecisionManagerImplTests {
public void testStartupFailsWithEmptyChannelProcessorsList() throws Exception {
ChannelDecisionManagerImpl cdm = new ChannelDecisionManagerImpl();
assertThatIllegalArgumentException().isThrownBy(cdm::afterPropertiesSet)
.withMessage("A list of ChannelProcessors is required");
.withMessage("A list of ChannelProcessors is required");
}
private class MockChannelProcessor implements ChannelProcessor {

View File

@@ -92,7 +92,7 @@ public class InsecureChannelProcessorTests {
InsecureChannelProcessor processor = new InsecureChannelProcessor();
processor.setEntryPoint(null);
assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet)
.withMessage("entryPoint required");
.withMessage("entryPoint required");
}
@Test
@@ -100,10 +100,10 @@ public class InsecureChannelProcessorTests {
InsecureChannelProcessor processor = new InsecureChannelProcessor();
processor.setInsecureKeyword(null);
assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet)
.withMessage("insecureKeyword required");
.withMessage("insecureKeyword required");
processor.setInsecureKeyword("");
assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet)
.withMessage("insecureKeyword required");
.withMessage("insecureKeyword required");
}
@Test

View File

@@ -127,7 +127,7 @@ public class RetryWithHttpEntryPointTests {
ep.setPortMapper(portMapper);
ep.commence(request, response);
assertThat(response.getRedirectedUrl())
.isEqualTo("http://localhost:8888/bigWebApp/hello/pathInfo.html?open=true");
.isEqualTo("http://localhost:8888/bigWebApp/hello/pathInfo.html?open=true");
}
}

View File

@@ -70,7 +70,7 @@ public class RetryWithHttpsEntryPointTests {
ep.setPortResolver(new MockPortResolver(80, 443));
ep.commence(request, response);
assertThat(response.getRedirectedUrl())
.isEqualTo("https://www.example.com/bigWebApp/hello/pathInfo.html?open=true");
.isEqualTo("https://www.example.com/bigWebApp/hello/pathInfo.html?open=true");
}
@Test
@@ -119,7 +119,7 @@ public class RetryWithHttpsEntryPointTests {
ep.setPortMapper(portMapper);
ep.commence(request, response);
assertThat(response.getRedirectedUrl())
.isEqualTo("https://www.example.com:9999/bigWebApp/hello/pathInfo.html?open=true");
.isEqualTo("https://www.example.com:9999/bigWebApp/hello/pathInfo.html?open=true");
}
}

View File

@@ -92,7 +92,7 @@ public class SecureChannelProcessorTests {
SecureChannelProcessor processor = new SecureChannelProcessor();
processor.setEntryPoint(null);
assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet)
.withMessage("entryPoint required");
.withMessage("entryPoint required");
}
@Test
@@ -100,10 +100,10 @@ public class SecureChannelProcessorTests {
SecureChannelProcessor processor = new SecureChannelProcessor();
processor.setSecureKeyword(null);
assertThatIllegalArgumentException().isThrownBy(processor::afterPropertiesSet)
.withMessage("secureKeyword required");
.withMessage("secureKeyword required");
processor.setSecureKeyword("");
assertThatIllegalArgumentException().isThrownBy(() -> processor.afterPropertiesSet())
.withMessage("secureKeyword required");
.withMessage("secureKeyword required");
}
@Test

View File

@@ -105,8 +105,9 @@ public class DefaultHttpSecurityExpressionHandlerTests {
EvaluationContext context = this.handler.createEvaluationContext(mockAuthenticationSupplier, this.context);
verifyNoInteractions(mockAuthenticationSupplier);
assertThat(context.getRootObject()).extracting(TypedValue::getValue)
.asInstanceOf(InstanceOfAssertFactories.type(WebSecurityExpressionRoot.class))
.extracting(SecurityExpressionRoot::getAuthentication).isEqualTo(this.authentication);
.asInstanceOf(InstanceOfAssertFactories.type(WebSecurityExpressionRoot.class))
.extracting(SecurityExpressionRoot::getAuthentication)
.isEqualTo(this.authentication);
verify(mockAuthenticationSupplier).get();
}

View File

@@ -56,8 +56,8 @@ public class ExpressionBasedFilterInvocationSecurityMetadataSourceTests {
LinkedHashMap<RequestMatcher, Collection<ConfigAttribute>> requestMap = new LinkedHashMap<>();
requestMap.put(AnyRequestMatcher.INSTANCE, SecurityConfig.createList("hasRole('X'"));
assertThatIllegalArgumentException()
.isThrownBy(() -> new ExpressionBasedFilterInvocationSecurityMetadataSource(requestMap,
new DefaultWebSecurityExpressionHandler()));
.isThrownBy(() -> new ExpressionBasedFilterInvocationSecurityMetadataSource(requestMap,
new DefaultWebSecurityExpressionHandler()));
}
}

View File

@@ -41,19 +41,19 @@ class WebExpressionAuthorizationManagerTests {
@Test
void instantiateWhenExpressionStringNullThenIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new WebExpressionAuthorizationManager(null))
.withMessage("expressionString cannot be empty");
.withMessage("expressionString cannot be empty");
}
@Test
void instantiateWhenExpressionStringEmptyThenIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new WebExpressionAuthorizationManager(""))
.withMessage("expressionString cannot be empty");
.withMessage("expressionString cannot be empty");
}
@Test
void instantiateWhenExpressionStringBlankThenIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new WebExpressionAuthorizationManager(" "))
.withMessage("expressionString cannot be empty");
.withMessage("expressionString cannot be empty");
}
@Test
@@ -66,7 +66,7 @@ class WebExpressionAuthorizationManagerTests {
void setExpressionHandlerWhenNullThenIllegalArgumentException() {
WebExpressionAuthorizationManager manager = new WebExpressionAuthorizationManager("hasRole('ADMIN')");
assertThatIllegalArgumentException().isThrownBy(() -> manager.setExpressionHandler(null))
.withMessage("expressionHandler cannot be null");
.withMessage("expressionHandler cannot be null");
}
@Test

View File

@@ -51,7 +51,7 @@ public class WebExpressionVoterTests {
WebExpressionVoter voter = new WebExpressionVoter();
assertThat(voter.supports(
new WebExpressionConfigAttribute(mock(Expression.class), mock(EvaluationContextPostProcessor.class))))
.isTrue();
.isTrue();
assertThat(voter.supports(FilterInvocation.class)).isTrue();
assertThat(voter.supports(MethodInvocation.class)).isFalse();
}
@@ -61,7 +61,7 @@ public class WebExpressionVoterTests {
WebExpressionVoter voter = new WebExpressionVoter();
assertThat(
voter.vote(this.user, new FilterInvocation("/path", "GET"), SecurityConfig.createList("A", "B", "C")))
.isEqualTo(AccessDecisionVoter.ACCESS_ABSTAIN);
.isEqualTo(AccessDecisionVoter.ACCESS_ABSTAIN);
}
@Test
@@ -70,7 +70,7 @@ public class WebExpressionVoterTests {
Expression ex = mock(Expression.class);
EvaluationContextPostProcessor postProcessor = mock(EvaluationContextPostProcessor.class);
given(postProcessor.postProcess(any(EvaluationContext.class), any(FilterInvocation.class)))
.willAnswer((invocation) -> invocation.getArgument(0));
.willAnswer((invocation) -> invocation.getArgument(0));
WebExpressionConfigAttribute weca = new WebExpressionConfigAttribute(ex, postProcessor);
EvaluationContext ctx = mock(EvaluationContext.class);
SecurityExpressionHandler eh = mock(SecurityExpressionHandler.class);

View File

@@ -92,7 +92,7 @@ public class AuthorizationFilterTests {
public void filterWhenAuthorizationManagerVerifyPassesThenNextFilter() throws Exception {
AuthorizationManager<HttpServletRequest> mockAuthorizationManager = mock(AuthorizationManager.class);
given(mockAuthorizationManager.check(any(Supplier.class), any(HttpServletRequest.class)))
.willReturn(new AuthorizationDecision(true));
.willReturn(new AuthorizationDecision(true));
AuthorizationFilter filter = new AuthorizationFilter(mockAuthorizationManager);
TestingAuthenticationToken authenticationToken = new TestingAuthenticationToken("user", "password");
@@ -129,12 +129,12 @@ public class AuthorizationFilterTests {
MockHttpServletResponse mockResponse = new MockHttpServletResponse();
FilterChain mockFilterChain = mock(FilterChain.class);
willThrow(new AccessDeniedException("Access Denied")).given(mockAuthorizationManager).check(any(),
eq(mockRequest));
willThrow(new AccessDeniedException("Access Denied")).given(mockAuthorizationManager)
.check(any(), eq(mockRequest));
assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> filter.doFilter(mockRequest, mockResponse, mockFilterChain))
.withMessage("Access Denied");
.isThrownBy(() -> filter.doFilter(mockRequest, mockResponse, mockFilterChain))
.withMessage("Access Denied");
ArgumentCaptor<Supplier<Authentication>> authenticationCaptor = ArgumentCaptor.forClass(Supplier.class);
verify(mockAuthorizationManager).check(authenticationCaptor.capture(), eq(mockRequest));
@@ -152,8 +152,8 @@ public class AuthorizationFilterTests {
FilterChain mockFilterChain = mock(FilterChain.class);
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> filter.doFilter(mockRequest, mockResponse, mockFilterChain))
.withMessage("An Authentication object was not found in the SecurityContext");
.isThrownBy(() -> filter.doFilter(mockRequest, mockResponse, mockFilterChain))
.withMessage("An Authentication object was not found in the SecurityContext");
verifyNoInteractions(mockFilterChain);
}
@@ -170,7 +170,7 @@ public class AuthorizationFilterTests {
AuthorizationManager<HttpServletRequest> authorizationManager = mock(AuthorizationManager.class);
AuthorizationFilter authorizationFilter = new AuthorizationFilter(authorizationManager);
assertThatIllegalArgumentException().isThrownBy(() -> authorizationFilter.setAuthorizationEventPublisher(null))
.withMessage("eventPublisher cannot be null");
.withMessage("eventPublisher cannot be null");
}
@Test

View File

@@ -131,8 +131,8 @@ public class FilterSecurityInterceptorTests {
SecurityContextHolder.getContext().setAuthentication(token);
FilterInvocation fi = createinvocation();
FilterChain chain = fi.getChain();
willThrow(new RuntimeException()).given(chain).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
willThrow(new RuntimeException()).given(chain)
.doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK"));
AfterInvocationManager aim = mock(AfterInvocationManager.class);
this.interceptor.setAfterInvocationManager(aim);
@@ -150,12 +150,12 @@ public class FilterSecurityInterceptorTests {
ctx.setAuthentication(token);
RunAsManager runAsManager = mock(RunAsManager.class);
given(runAsManager.buildRunAs(eq(token), any(), anyCollection()))
.willReturn(new RunAsUserToken("key", "someone", "creds", token.getAuthorities(), token.getClass()));
.willReturn(new RunAsUserToken("key", "someone", "creds", token.getAuthorities(), token.getClass()));
this.interceptor.setRunAsManager(runAsManager);
FilterInvocation fi = createinvocation();
FilterChain chain = fi.getChain();
willThrow(new RuntimeException()).given(chain).doFilter(any(HttpServletRequest.class),
any(HttpServletResponse.class));
willThrow(new RuntimeException()).given(chain)
.doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
given(this.ods.getAttributes(fi)).willReturn(SecurityConfig.createList("MOCK_OK"));
AfterInvocationManager aim = mock(AfterInvocationManager.class);
this.interceptor.setAfterInvocationManager(aim);

View File

@@ -65,7 +65,7 @@ public class RequestKeyTests {
@Test
public void keysWithNullUrlFailsAssertion() {
assertThatIllegalArgumentException().isThrownBy(() -> new RequestKey(null, null))
.withMessage("url cannot be null");
.withMessage("url cannot be null");
}
}

View File

@@ -43,31 +43,34 @@ public class RequestMatcherDelegatingAuthorizationManagerTests {
@Test
public void buildWhenMappingsEmptyThenException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> RequestMatcherDelegatingAuthorizationManager.builder().build())
.withMessage("mappings cannot be empty");
.isThrownBy(() -> RequestMatcherDelegatingAuthorizationManager.builder().build())
.withMessage("mappings cannot be empty");
}
@Test
public void addWhenMatcherNullThenException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> RequestMatcherDelegatingAuthorizationManager.builder()
.add(null, (a, o) -> new AuthorizationDecision(true)).build())
.withMessage("matcher cannot be null");
.isThrownBy(() -> RequestMatcherDelegatingAuthorizationManager.builder()
.add(null, (a, o) -> new AuthorizationDecision(true))
.build())
.withMessage("matcher cannot be null");
}
@Test
public void addWhenManagerNullThenException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> RequestMatcherDelegatingAuthorizationManager.builder()
.add(new MvcRequestMatcher(null, "/grant"), null).build())
.withMessage("manager cannot be null");
.isThrownBy(() -> RequestMatcherDelegatingAuthorizationManager.builder()
.add(new MvcRequestMatcher(null, "/grant"), null)
.build())
.withMessage("manager cannot be null");
}
@Test
public void checkWhenMultipleMappingsConfiguredThenDelegatesMatchingManager() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.add(new MvcRequestMatcher(null, "/grant"), (a, o) -> new AuthorizationDecision(true))
.add(new MvcRequestMatcher(null, "/deny"), (a, o) -> new AuthorizationDecision(false)).build();
.add(new MvcRequestMatcher(null, "/grant"), (a, o) -> new AuthorizationDecision(true))
.add(new MvcRequestMatcher(null, "/deny"), (a, o) -> new AuthorizationDecision(false))
.build();
Supplier<Authentication> authentication = () -> new TestingAuthenticationToken("user", "password", "ROLE_USER");
@@ -88,14 +91,15 @@ public class RequestMatcherDelegatingAuthorizationManagerTests {
@Test
public void checkWhenMultipleMappingsConfiguredWithConsumerThenDelegatesMatchingManager() {
RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder()
.mappings((m) -> {
m.add(new RequestMatcherEntry<>(new MvcRequestMatcher(null, "/grant"),
(a, o) -> new AuthorizationDecision(true)));
m.add(new RequestMatcherEntry<>(AnyRequestMatcher.INSTANCE,
AuthorityAuthorizationManager.hasRole("ADMIN")));
m.add(new RequestMatcherEntry<>(new MvcRequestMatcher(null, "/afterAny"),
(a, o) -> new AuthorizationDecision(true)));
}).build();
.mappings((m) -> {
m.add(new RequestMatcherEntry<>(new MvcRequestMatcher(null, "/grant"),
(a, o) -> new AuthorizationDecision(true)));
m.add(new RequestMatcherEntry<>(AnyRequestMatcher.INSTANCE,
AuthorityAuthorizationManager.hasRole("ADMIN")));
m.add(new RequestMatcherEntry<>(new MvcRequestMatcher(null, "/afterAny"),
(a, o) -> new AuthorizationDecision(true)));
})
.build();
Supplier<Authentication> authentication = () -> new TestingAuthenticationToken("user", "password", "ROLE_USER");
@@ -116,8 +120,8 @@ public class RequestMatcherDelegatingAuthorizationManagerTests {
@Test
public void addWhenMappingsConsumerNullThenException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> RequestMatcherDelegatingAuthorizationManager.builder().mappings(null).build())
.withMessage("mappingsConsumer cannot be null");
.isThrownBy(() -> RequestMatcherDelegatingAuthorizationManager.builder().mappings(null).build())
.withMessage("mappingsConsumer cannot be null");
}
}

View File

@@ -40,15 +40,17 @@ class WebMvcSecurityRuntimeHintsTests {
@BeforeEach
void setup() {
SpringFactoriesLoader.forResourceLocation("META-INF/spring/aot.factories").load(RuntimeHintsRegistrar.class)
.forEach((registrar) -> registrar.registerHints(this.hints, ClassUtils.getDefaultClassLoader()));
SpringFactoriesLoader.forResourceLocation("META-INF/spring/aot.factories")
.load(RuntimeHintsRegistrar.class)
.forEach((registrar) -> registrar.registerHints(this.hints, ClassUtils.getDefaultClassLoader()));
}
@Test
void webSecurityExpressionRootHasHints() {
assertThat(RuntimeHintsPredicates.reflection().onType(WebSecurityExpressionRoot.class)
.withMemberCategories(MemberCategory.INVOKE_DECLARED_METHODS, MemberCategory.DECLARED_FIELDS))
.accepts(this.hints);
assertThat(RuntimeHintsPredicates.reflection()
.onType(WebSecurityExpressionRoot.class)
.withMemberCategories(MemberCategory.INVOKE_DECLARED_METHODS, MemberCategory.DECLARED_FIELDS))
.accepts(this.hints);
}
}

View File

@@ -190,7 +190,7 @@ public class AbstractAuthenticationProcessingFilterTests {
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).isEqualTo("test");
assertThat(request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME))
.isNotNull();
.isNotNull();
// Should still have the same session
assertThat(request.getSession()).isEqualTo(sessionPreAuth);
}
@@ -219,7 +219,7 @@ public class AbstractAuthenticationProcessingFilterTests {
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).isEqualTo("test");
assertThat(request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME))
.isNotNull();
.isNotNull();
// Should still have the same session
assertThat(request.getSession()).isEqualTo(sessionPreAuth);
}
@@ -250,7 +250,7 @@ public class AbstractAuthenticationProcessingFilterTests {
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).isEqualTo("test");
assertThat(request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME))
.isNotNull();
.isNotNull();
// Should still have the same session
assertThat(request.getSession()).isEqualTo(sessionPreAuth);
}
@@ -263,7 +263,7 @@ public class AbstractAuthenticationProcessingFilterTests {
filter.setAuthenticationSuccessHandler(this.successHandler);
filter.setFilterProcessesUrl("/login");
assertThatIllegalArgumentException().isThrownBy(filter::afterPropertiesSet)
.withMessage("authenticationManager must be specified");
.withMessage("authenticationManager must be specified");
}
@Test
@@ -273,7 +273,7 @@ public class AbstractAuthenticationProcessingFilterTests {
filter.setAuthenticationManager(mock(AuthenticationManager.class));
filter.setAuthenticationSuccessHandler(this.successHandler);
assertThatIllegalArgumentException().isThrownBy(() -> filter.setFilterProcessesUrl(null))
.withMessage("Pattern cannot be null or empty");
.withMessage("Pattern cannot be null or empty");
}
@Test
@@ -331,7 +331,7 @@ public class AbstractAuthenticationProcessingFilterTests {
any(Authentication.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME))
.isNotNull();
.isNotNull();
}
@Test

View File

@@ -41,8 +41,8 @@ public class AuthenticationEntryPointFailureHandlerTests {
void handleWhenDefaultsThenAuthenticationServiceExceptionRethrown() {
AuthenticationEntryPoint entryPoint = mock(AuthenticationEntryPoint.class);
AuthenticationEntryPointFailureHandler handler = new AuthenticationEntryPointFailureHandler(entryPoint);
assertThatExceptionOfType(AuthenticationServiceException.class).isThrownBy(
() -> handler.onAuthenticationFailure(null, null, new AuthenticationServiceException("fail")));
assertThatExceptionOfType(AuthenticationServiceException.class)
.isThrownBy(() -> handler.onAuthenticationFailure(null, null, new AuthenticationServiceException("fail")));
}
}

View File

@@ -130,7 +130,7 @@ public class AuthenticationFilterTests {
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME))
.isNotNull();
.isNotNull();
}
@Test
@@ -169,7 +169,7 @@ public class AuthenticationFilterTests {
verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME))
.isNotNull();
.isNotNull();
}
@Test
@@ -234,7 +234,7 @@ public class AuthenticationFilterTests {
verifyNoMoreInteractions(this.failureHandler);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME))
.isNotNull();
.isNotNull();
}
@Test

View File

@@ -111,8 +111,8 @@ public class DefaultLoginPageGeneratingFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/login");
filter.doFilter(request, response, this.chain);
assertThat(response
.getContentLength() == response.getContentAsString().getBytes(response.getCharacterEncoding()).length)
.isTrue();
.getContentLength() == response.getContentAsString().getBytes(response.getCharacterEncoding()).length)
.isTrue();
}
@Test
@@ -154,7 +154,7 @@ public class DefaultLoginPageGeneratingFilterTests {
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(new MockHttpServletRequest("GET", "/login"), response, this.chain);
assertThat(response.getContentAsString())
.contains("<a href=\"/oauth2/authorization/google\">Google &lt; &gt; &quot; &#39; &amp;</a>");
.contains("<a href=\"/oauth2/authorization/google\">Google &lt; &gt; &quot; &#39; &amp;</a>");
}
@Test
@@ -168,7 +168,7 @@ public class DefaultLoginPageGeneratingFilterTests {
filter.doFilter(new MockHttpServletRequest("GET", "/login"), response, this.chain);
assertThat(response.getContentAsString()).contains("Login with SAML 2.0");
assertThat(response.getContentAsString())
.contains("<a href=\"/saml/sso/google\">Google &lt; &gt; &quot; &#39; &amp;</a>");
.contains("<a href=\"/saml/sso/google\">Google &lt; &gt; &quot; &#39; &amp;</a>");
}
}

View File

@@ -106,23 +106,23 @@ public class DelegatingAuthenticationFailureHandlerTests {
@Test
public void handlersIsNull() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingAuthenticationFailureHandler(null, this.defaultHandler))
.withMessage("handlers cannot be null or empty");
.isThrownBy(() -> new DelegatingAuthenticationFailureHandler(null, this.defaultHandler))
.withMessage("handlers cannot be null or empty");
}
@Test
public void handlersIsEmpty() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingAuthenticationFailureHandler(this.handlers, this.defaultHandler))
.withMessage("handlers cannot be null or empty");
.isThrownBy(() -> new DelegatingAuthenticationFailureHandler(this.handlers, this.defaultHandler))
.withMessage("handlers cannot be null or empty");
}
@Test
public void defaultHandlerIsNull() {
this.handlers.put(BadCredentialsException.class, this.handler1);
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingAuthenticationFailureHandler(this.handlers, null))
.withMessage("defaultHandler cannot be null");
.isThrownBy(() -> new DelegatingAuthenticationFailureHandler(this.handlers, null))
.withMessage("defaultHandler cannot be null");
}
}

View File

@@ -43,8 +43,10 @@ public class RequestMatcherDelegatingAuthenticationManagerResolverTests {
@Test
public void resolveWhenMatchesThenReturnsAuthenticationManager() {
RequestMatcherDelegatingAuthenticationManagerResolver resolver = RequestMatcherDelegatingAuthenticationManagerResolver
.builder().add(new AntPathRequestMatcher("/one/**"), this.one)
.add(new AntPathRequestMatcher("/two/**"), this.two).build();
.builder()
.add(new AntPathRequestMatcher("/one/**"), this.one)
.add(new AntPathRequestMatcher("/two/**"), this.two)
.build();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/one/location");
request.setServletPath("/one/location");
@@ -54,15 +56,17 @@ public class RequestMatcherDelegatingAuthenticationManagerResolverTests {
@Test
public void resolveWhenDoesNotMatchThenReturnsDefaultAuthenticationManager() {
RequestMatcherDelegatingAuthenticationManagerResolver resolver = RequestMatcherDelegatingAuthenticationManagerResolver
.builder().add(new AntPathRequestMatcher("/one/**"), this.one)
.add(new AntPathRequestMatcher("/two/**"), this.two).build();
.builder()
.add(new AntPathRequestMatcher("/one/**"), this.one)
.add(new AntPathRequestMatcher("/two/**"), this.two)
.build();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/wrong/location");
AuthenticationManager authenticationManager = resolver.resolve(request);
Authentication authentication = new TestingAuthenticationToken("principal", "creds");
assertThatExceptionOfType(AuthenticationServiceException.class)
.isThrownBy(() -> authenticationManager.authenticate(authentication));
.isThrownBy(() -> authenticationManager.authenticate(authentication));
}
}

View File

@@ -123,7 +123,7 @@ public class SimpleUrlAuthenticationSuccessHandlerTests {
new BadCredentialsException("Invalid credentials"));
assertThat(session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION)).isNotNull();
assertThat(session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION))
.isInstanceOf(AuthenticationException.class);
.isInstanceOf(AuthenticationException.class);
ash.onAuthenticationSuccess(request, response, mock(Authentication.class));
assertThat(session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION)).isNull();
}

View File

@@ -123,7 +123,7 @@ public class UsernamePasswordAuthenticationFilterTests {
given(am.authenticate(any(Authentication.class))).willThrow(new BadCredentialsException(""));
filter.setAuthenticationManager(am);
assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(() -> filter.attemptAuthentication(request, new MockHttpServletResponse()));
.isThrownBy(() -> filter.attemptAuthentication(request, new MockHttpServletResponse()));
}
@Test
@@ -159,7 +159,7 @@ public class UsernamePasswordAuthenticationFilterTests {
private AuthenticationManager createAuthenticationManager() {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(Authentication.class)))
.willAnswer((Answer<Authentication>) (invocation) -> (Authentication) invocation.getArguments()[0]);
.willAnswer((Answer<Authentication>) (invocation) -> (Authentication) invocation.getArguments()[0]);
return am;
}

View File

@@ -45,7 +45,7 @@ public class CompositeLogoutHandlerTests {
@Test
public void buildEmptyCompositeLogoutHandlerThrowsException() {
assertThatIllegalArgumentException().isThrownBy(() -> new CompositeLogoutHandler())
.withMessage("LogoutHandlers are required");
.withMessage("LogoutHandlers are required");
}
@Test
@@ -77,17 +77,17 @@ public class CompositeLogoutHandlerTests {
public void callLogoutHandlersThrowException() {
LogoutHandler firstLogoutHandler = mock(LogoutHandler.class);
LogoutHandler secondLogoutHandler = mock(LogoutHandler.class);
willThrow(new IllegalArgumentException()).given(firstLogoutHandler).logout(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(Authentication.class));
willThrow(new IllegalArgumentException()).given(firstLogoutHandler)
.logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class));
List<LogoutHandler> logoutHandlers = Arrays.asList(firstLogoutHandler, secondLogoutHandler);
LogoutHandler handler = new CompositeLogoutHandler(logoutHandlers);
assertThatIllegalArgumentException().isThrownBy(() -> handler.logout(mock(HttpServletRequest.class),
mock(HttpServletResponse.class), mock(Authentication.class)));
InOrder logoutHandlersInOrder = inOrder(firstLogoutHandler, secondLogoutHandler);
logoutHandlersInOrder.verify(firstLogoutHandler, times(1)).logout(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(Authentication.class));
logoutHandlersInOrder.verify(secondLogoutHandler, never()).logout(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(Authentication.class));
logoutHandlersInOrder.verify(firstLogoutHandler, times(1))
.logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class));
logoutHandlersInOrder.verify(secondLogoutHandler, never())
.logout(any(HttpServletRequest.class), any(HttpServletResponse.class), any(Authentication.class));
}
}

View File

@@ -37,14 +37,14 @@ public class ForwardLogoutSuccessHandlerTests {
public void invalidTargetUrl() {
String targetUrl = "not.valid";
assertThatIllegalArgumentException().isThrownBy(() -> new ForwardLogoutSuccessHandler(targetUrl))
.withMessage("'" + targetUrl + "' is not a valid target URL");
.withMessage("'" + targetUrl + "' is not a valid target URL");
}
@Test
public void emptyTargetUrl() {
String targetUrl = " ";
assertThatIllegalArgumentException().isThrownBy(() -> new ForwardLogoutSuccessHandler(targetUrl))
.withMessage("'" + targetUrl + "' is not a valid target URL");
.withMessage("'" + targetUrl + "' is not a valid target URL");
}
@Test

View File

@@ -48,7 +48,7 @@ public class HeaderWriterLogoutHandlerTests {
@Test
public void constructorWhenHeaderWriterIsNullThenThrowsException() {
assertThatIllegalArgumentException().isThrownBy(() -> new HeaderWriterLogoutHandler(null))
.withMessage("headerWriter cannot be null");
.withMessage("headerWriter cannot be null");
}
@Test

View File

@@ -60,7 +60,7 @@ public class HttpStatusReturningLogoutSuccessHandlerTests {
@Test
public void testThatSettNullHttpStatusThrowsException() {
assertThatIllegalArgumentException().isThrownBy(() -> new HttpStatusReturningLogoutSuccessHandler(null))
.withMessage("The provided HttpStatus must not be null.");
.withMessage("The provided HttpStatus must not be null.");
}
}

View File

@@ -103,15 +103,15 @@ public class SecurityContextLogoutHandlerTests {
@Test
public void constructorWhenDefaultSecurityContextRepositoryThenHttpSessionSecurityContextRepository() {
SecurityContextRepository securityContextRepository = (SecurityContextRepository) ReflectionTestUtils
.getField(this.handler, "securityContextRepository");
.getField(this.handler, "securityContextRepository");
assertThat(securityContextRepository).isInstanceOf(HttpSessionSecurityContextRepository.class);
}
@Test
public void setSecurityContextRepositoryWhenNullThenException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.handler.setSecurityContextRepository(null))
.withMessage("securityContextRepository cannot be null");
.isThrownBy(() -> this.handler.setSecurityContextRepository(null))
.withMessage("securityContextRepository cannot be null");
}
}

View File

@@ -103,7 +103,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
this.filter.setAuthenticationManager(am);
this.filter.afterPropertiesSet();
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.filter
.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), mock(FilterChain.class)));
.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), mock(FilterChain.class)));
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@@ -137,7 +137,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
@Test
public void nullPreAuthenticationClearsPreviousUser() throws Exception {
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("oldUser", "pass", "ROLE_USER"));
.setAuthentication(new TestingAuthenticationToken("oldUser", "pass", "ROLE_USER"));
ConcretePreAuthenticatedProcessingFilter filter = new ConcretePreAuthenticatedProcessingFilter();
filter.principal = null;
filter.setCheckForPrincipalChanges(true);
@@ -159,7 +159,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
public void requiresAuthenticationFalsePrincipalString() throws Exception {
Object principal = "sameprincipal";
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken(principal, "something", "ROLE_USER"));
.setAuthentication(new TestingAuthenticationToken(principal, "something", "ROLE_USER"));
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
@@ -248,7 +248,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
filter.setCheckForPrincipalChanges(true);
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(PreAuthenticatedAuthenticationToken.class)))
.willThrow(new PreAuthenticatedCredentialsNotFoundException("invalid"));
.willThrow(new PreAuthenticatedCredentialsNotFoundException("invalid"));
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();
filter.doFilter(request, response, chain);
@@ -262,7 +262,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
public void requiresAuthenticationFalsePrincipalNotString() throws Exception {
Object principal = new Object();
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken(principal, "something", "ROLE_USER"));
.setAuthentication(new TestingAuthenticationToken(principal, "something", "ROLE_USER"));
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
@@ -280,7 +280,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
public void requiresAuthenticationFalsePrincipalUser() throws Exception {
User currentPrincipal = new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER"));
UsernamePasswordAuthenticationToken currentAuthentication = UsernamePasswordAuthenticationToken
.authenticated(currentPrincipal, currentPrincipal.getPassword(), currentPrincipal.getAuthorities());
.authenticated(currentPrincipal, currentPrincipal.getPassword(), currentPrincipal.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(currentAuthentication);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -319,7 +319,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
public void requiresAuthenticationOverridePrincipalChangedTrue() throws Exception {
Object principal = new Object();
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken(principal, "something", "ROLE_USER"));
.setAuthentication(new TestingAuthenticationToken(principal, "something", "ROLE_USER"));
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
@@ -342,7 +342,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
public void requiresAuthenticationOverridePrincipalChangedFalse() throws Exception {
Object principal = new Object();
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken(principal, "something", "ROLE_USER"));
.setAuthentication(new TestingAuthenticationToken(principal, "something", "ROLE_USER"));
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
@@ -404,7 +404,7 @@ public class AbstractPreAuthenticatedProcessingFilterTests {
}
else {
given(am.authenticate(any(Authentication.class)))
.willAnswer((Answer<Authentication>) (invocation) -> (Authentication) invocation.getArguments()[0]);
.willAnswer((Answer<Authentication>) (invocation) -> (Authentication) invocation.getArguments()[0]);
}
filter.setAuthenticationManager(am);
filter.afterPropertiesSet();

View File

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

View File

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

View File

@@ -51,9 +51,10 @@ public class PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetailsTests {
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails(
getRequest("testUser", new String[] {}), this.gas);
List<GrantedAuthority> returnedGas = details.getGrantedAuthorities();
assertThat(this.gas.containsAll(returnedGas) && returnedGas.containsAll(this.gas)).withFailMessage(
"Collections do not contain same elements; expected: " + this.gas + ", returned: " + returnedGas)
.isTrue();
assertThat(this.gas.containsAll(returnedGas) && returnedGas.containsAll(this.gas))
.withFailMessage(
"Collections do not contain same elements; expected: " + this.gas + ", returned: " + returnedGas)
.isTrue();
}
private HttpServletRequest getRequest(final String userName, final String[] aRoles) {

View File

@@ -52,7 +52,7 @@ public class RequestAttributeAuthenticationFilterTests {
MockFilterChain chain = new MockFilterChain();
RequestAttributeAuthenticationFilter filter = new RequestAttributeAuthenticationFilter();
assertThatExceptionOfType(PreAuthenticatedCredentialsNotFoundException.class)
.isThrownBy(() -> filter.doFilter(request, response, chain));
.isThrownBy(() -> filter.doFilter(request, response, chain));
}
@Test
@@ -129,7 +129,7 @@ public class RequestAttributeAuthenticationFilterTests {
RequestAttributeAuthenticationFilter filter = new RequestAttributeAuthenticationFilter();
filter.setAuthenticationManager(createAuthenticationManager());
assertThatExceptionOfType(PreAuthenticatedCredentialsNotFoundException.class)
.isThrownBy(() -> filter.doFilter(request, response, chain));
.isThrownBy(() -> filter.doFilter(request, response, chain));
}
@Test
@@ -149,7 +149,7 @@ public class RequestAttributeAuthenticationFilterTests {
private AuthenticationManager createAuthenticationManager() {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(Authentication.class)))
.willAnswer((Answer<Authentication>) (invocation) -> (Authentication) invocation.getArguments()[0]);
.willAnswer((Answer<Authentication>) (invocation) -> (Authentication) invocation.getArguments()[0]);
return am;
}

View File

@@ -54,7 +54,7 @@ public class RequestHeaderAuthenticationFilterTests {
MockFilterChain chain = new MockFilterChain();
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
assertThatExceptionOfType(PreAuthenticatedCredentialsNotFoundException.class)
.isThrownBy(() -> filter.doFilter(request, response, chain));
.isThrownBy(() -> filter.doFilter(request, response, chain));
}
@Test
@@ -130,7 +130,7 @@ public class RequestHeaderAuthenticationFilterTests {
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
filter.setAuthenticationManager(createAuthenticationManager());
assertThatExceptionOfType(PreAuthenticatedCredentialsNotFoundException.class)
.isThrownBy(() -> filter.doFilter(request, response, chain));
.isThrownBy(() -> filter.doFilter(request, response, chain));
}
@Test
@@ -150,7 +150,7 @@ public class RequestHeaderAuthenticationFilterTests {
private AuthenticationManager createAuthenticationManager() {
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(Authentication.class)))
.willAnswer((Answer<Authentication>) (invocation) -> (Authentication) invocation.getArguments()[0]);
.willAnswer((Answer<Authentication>) (invocation) -> (Authentication) invocation.getArguments()[0]);
return am;
}

View File

@@ -111,7 +111,7 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests {
assertThat(o instanceof PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails).withFailMessage(
"Returned object not of type PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails, actual type: "
+ o.getClass())
.isTrue();
.isTrue();
PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails details = (PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails) o;
List<GrantedAuthority> gas = details.getGrantedAuthorities();
assertThat(gas).as("Granted authorities should not be null").isNotNull();
@@ -122,7 +122,8 @@ public class J2eeBasedPreAuthenticatedWebAuthenticationDetailsSourceTests {
gasRolesSet.add(grantedAuthority.getAuthority());
}
assertThat(expectedRolesColl.containsAll(gasRolesSet) && gasRolesSet.containsAll(expectedRolesColl))
.withFailMessage("Granted Authorities do not match expected roles").isTrue();
.withFailMessage("Granted Authorities do not match expected roles")
.isTrue();
}
private J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource getJ2eeBasedPreAuthenticatedWebAuthenticationDetailsSource(

View File

@@ -37,13 +37,13 @@ public class J2eePreAuthenticatedProcessingFilterTests {
public final void testGetPreAuthenticatedPrincipal() {
String user = "testUser";
assertThat(user).isEqualTo(new J2eePreAuthenticatedProcessingFilter()
.getPreAuthenticatedPrincipal(getRequest(user, new String[] {})));
.getPreAuthenticatedPrincipal(getRequest(user, new String[] {})));
}
@Test
public final void testGetPreAuthenticatedCredentials() {
assertThat("N/A").isEqualTo(new J2eePreAuthenticatedProcessingFilter()
.getPreAuthenticatedCredentials(getRequest("testUser", new String[] {})));
.getPreAuthenticatedCredentials(getRequest("testUser", new String[] {})));
}
private HttpServletRequest getRequest(final String aUserName, final String[] aRoles) {

View File

@@ -53,7 +53,7 @@ public class WebSpherePreAuthenticatedProcessingFilterTests {
assertThat(filter.getPreAuthenticatedCredentials(new MockHttpServletRequest())).isEqualTo("N/A");
AuthenticationManager am = mock(AuthenticationManager.class);
given(am.authenticate(any(Authentication.class)))
.willAnswer((Answer<Authentication>) (invocation) -> (Authentication) invocation.getArguments()[0]);
.willAnswer((Answer<Authentication>) (invocation) -> (Authentication) invocation.getArguments()[0]);
filter.setAuthenticationManager(am);
WebSpherePreAuthenticatedWebAuthenticationDetailsSource ads = new WebSpherePreAuthenticatedWebAuthenticationDetailsSource(
helper);

View File

@@ -65,7 +65,7 @@ public class SubjectDnX509PrincipalExtractorTests {
public void matchOnShoeSizeThrowsBadCredentials() throws Exception {
this.extractor.setSubjectDnRegex("shoeSize=(.*?),");
assertThatExceptionOfType(BadCredentialsException.class)
.isThrownBy(() -> this.extractor.extractPrincipal(X509TestUtils.buildTestCertificate()));
.isThrownBy(() -> this.extractor.extractPrincipal(X509TestUtils.buildTestCertificate()));
}
@Test

View File

@@ -63,7 +63,7 @@ public class AbstractRememberMeServicesTests {
@Test
public void nonBase64CookieShouldBeDetected() {
assertThatExceptionOfType(InvalidCookieException.class)
.isThrownBy(() -> new MockRememberMeServices(this.uds).decodeCookie("nonBase64CookieValue%"));
.isThrownBy(() -> new MockRememberMeServices(this.uds).decodeCookie("nonBase64CookieValue%"));
}
@Test

View File

@@ -145,7 +145,7 @@ public class JdbcTokenRepositoryImplTests {
// 'joesseries'");
this.repo.removeUserTokens("joeuser");
List<Map<String, Object>> results = this.template
.queryForList("select * from persistent_logins where username = 'joeuser'");
.queryForList("select * from persistent_logins where username = 'joeuser'");
assertThat(results).isEmpty();
}
@@ -156,7 +156,7 @@ public class JdbcTokenRepositoryImplTests {
+ "('joesseries', 'joeuser', 'atoken', '" + ts.toString() + "')");
this.repo.updateToken("joesseries", "newtoken", new Date());
Map<String, Object> results = this.template
.queryForMap("select * from persistent_logins where series = 'joesseries'");
.queryForMap("select * from persistent_logins where series = 'joesseries'");
assertThat(results.get("username")).isEqualTo("joeuser");
assertThat(results.get("series")).isEqualTo("joesseries");
assertThat(results.get("token")).isEqualTo("newtoken");

View File

@@ -54,16 +54,16 @@ public class PersistentTokenBasedRememberMeServicesTests {
@Test
public void loginIsRejectedWithWrongNumberOfCookieTokens() {
assertThatExceptionOfType(InvalidCookieException.class)
.isThrownBy(() -> this.services.processAutoLoginCookie(new String[] { "series", "token", "extra" },
new MockHttpServletRequest(), new MockHttpServletResponse()));
.isThrownBy(() -> this.services.processAutoLoginCookie(new String[] { "series", "token", "extra" },
new MockHttpServletRequest(), new MockHttpServletResponse()));
}
@Test
public void loginIsRejectedWhenNoTokenMatchingSeriesIsFound() {
this.services = create(null);
assertThatExceptionOfType(RememberMeAuthenticationException.class)
.isThrownBy(() -> this.services.processAutoLoginCookie(new String[] { "series", "token" },
new MockHttpServletRequest(), new MockHttpServletResponse()));
.isThrownBy(() -> this.services.processAutoLoginCookie(new String[] { "series", "token" },
new MockHttpServletRequest(), new MockHttpServletResponse()));
}
@Test
@@ -72,16 +72,16 @@ public class PersistentTokenBasedRememberMeServicesTests {
new Date(System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(1) - 100)));
this.services.setTokenValiditySeconds(1);
assertThatExceptionOfType(RememberMeAuthenticationException.class)
.isThrownBy(() -> this.services.processAutoLoginCookie(new String[] { "series", "token" },
new MockHttpServletRequest(), new MockHttpServletResponse()));
.isThrownBy(() -> this.services.processAutoLoginCookie(new String[] { "series", "token" },
new MockHttpServletRequest(), new MockHttpServletResponse()));
}
@Test
public void cookieTheftIsDetectedWhenSeriesAndTokenDontMatch() {
this.services = create(new PersistentRememberMeToken("joe", "series", "wrongtoken", new Date()));
assertThatExceptionOfType(CookieTheftException.class)
.isThrownBy(() -> this.services.processAutoLoginCookie(new String[] { "series", "token" },
new MockHttpServletRequest(), new MockHttpServletResponse()));
.isThrownBy(() -> this.services.processAutoLoginCookie(new String[] { "series", "token" },
new MockHttpServletRequest(), new MockHttpServletResponse()));
}
@Test

View File

@@ -68,13 +68,13 @@ public class RememberMeAuthenticationFilterTests {
@Test
public void testDetectsAuthenticationManagerProperty() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new RememberMeAuthenticationFilter(null, new NullRememberMeServices()));
.isThrownBy(() -> new RememberMeAuthenticationFilter(null, new NullRememberMeServices()));
}
@Test
public void testDetectsRememberMeServicesProperty() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new RememberMeAuthenticationFilter(mock(AuthenticationManager.class), null));
.isThrownBy(() -> new RememberMeAuthenticationFilter(mock(AuthenticationManager.class), null));
}
@Test

View File

@@ -446,7 +446,8 @@ public class TokenBasedRememberMeServicesTests {
assertThat(cookie).isNotNull();
// Check the expiry time is within 50ms of two weeks from current time
assertThat(determineExpiryTimeFromBased64EncodedToken(cookie.getValue())
- System.currentTimeMillis() > AbstractRememberMeServices.TWO_WEEKS_S - 50).isTrue();
- System.currentTimeMillis() > AbstractRememberMeServices.TWO_WEEKS_S - 50)
.isTrue();
assertThat(cookie.getMaxAge()).isEqualTo(-1);
assertThat(CodecTestUtils.isBase64(cookie.getValue().getBytes())).isTrue();
}
@@ -454,15 +455,15 @@ public class TokenBasedRememberMeServicesTests {
@Test
public void constructorWhenEncodingAlgorithmNullThenException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> new TokenBasedRememberMeServices("key", this.uds, null))
.withMessage("encodingAlgorithm cannot be null");
.isThrownBy(() -> new TokenBasedRememberMeServices("key", this.uds, null))
.withMessage("encodingAlgorithm cannot be null");
}
@Test
public void constructorWhenNoEncodingAlgorithmSpecifiedThenSha256() {
TokenBasedRememberMeServices rememberMeServices = new TokenBasedRememberMeServices("key", this.uds);
RememberMeTokenAlgorithm encodingAlgorithm = (RememberMeTokenAlgorithm) ReflectionTestUtils
.getField(rememberMeServices, "encodingAlgorithm");
.getField(rememberMeServices, "encodingAlgorithm");
assertThat(encodingAlgorithm).isSameAs(RememberMeTokenAlgorithm.SHA256);
}

View File

@@ -85,11 +85,11 @@ public class CompositeSessionAuthenticationStrategyTests {
@Test
public void delegateShortCircuits() {
willThrow(new SessionAuthenticationException("oops")).given(this.strategy1)
.onAuthentication(this.authentication, this.request, this.response);
.onAuthentication(this.authentication, this.request, this.response);
CompositeSessionAuthenticationStrategy strategy = new CompositeSessionAuthenticationStrategy(
Arrays.asList(this.strategy1, this.strategy2));
assertThatExceptionOfType(SessionAuthenticationException.class)
.isThrownBy(() -> strategy.onAuthentication(this.authentication, this.request, this.response));
.isThrownBy(() -> strategy.onAuthentication(this.authentication, this.request, this.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

@@ -80,7 +80,7 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
@Test
public void noRegisteredSession() {
given(this.sessionRegistry.getAllSessions(any(), anyBoolean()))
.willReturn(Collections.<SessionInformation>emptyList());
.willReturn(Collections.<SessionInformation>emptyList());
this.strategy.setMaximumSessions(1);
this.strategy.setExceptionIfMaximumExceeded(true);
this.strategy.onAuthentication(this.authentication, this.request, this.response);
@@ -92,7 +92,7 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
MockHttpSession session = new MockHttpSession(new MockServletContext(), this.sessionInformation.getSessionId());
this.request.setSession(session);
given(this.sessionRegistry.getAllSessions(any(), anyBoolean()))
.willReturn(Collections.<SessionInformation>singletonList(this.sessionInformation));
.willReturn(Collections.<SessionInformation>singletonList(this.sessionInformation));
this.strategy.setMaximumSessions(1);
this.strategy.setExceptionIfMaximumExceeded(true);
this.strategy.onAuthentication(this.authentication, this.request, this.response);
@@ -102,17 +102,17 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
@Test
public void maxSessionsWithException() {
given(this.sessionRegistry.getAllSessions(any(), anyBoolean()))
.willReturn(Collections.<SessionInformation>singletonList(this.sessionInformation));
.willReturn(Collections.<SessionInformation>singletonList(this.sessionInformation));
this.strategy.setMaximumSessions(1);
this.strategy.setExceptionIfMaximumExceeded(true);
assertThatExceptionOfType(SessionAuthenticationException.class)
.isThrownBy(() -> this.strategy.onAuthentication(this.authentication, this.request, this.response));
.isThrownBy(() -> this.strategy.onAuthentication(this.authentication, this.request, this.response));
}
@Test
public void maxSessionsExpireExistingUser() {
given(this.sessionRegistry.getAllSessions(any(), anyBoolean()))
.willReturn(Collections.<SessionInformation>singletonList(this.sessionInformation));
.willReturn(Collections.<SessionInformation>singletonList(this.sessionInformation));
this.strategy.setMaximumSessions(1);
this.strategy.onAuthentication(this.authentication, this.request, this.response);
assertThat(this.sessionInformation.isExpired()).isTrue();
@@ -123,7 +123,7 @@ public class ConcurrentSessionControlAuthenticationStrategyTests {
SessionInformation moreRecentSessionInfo = new SessionInformation(this.authentication.getPrincipal(), "unique",
new Date(1374766999999L));
given(this.sessionRegistry.getAllSessions(any(), anyBoolean()))
.willReturn(Arrays.<SessionInformation>asList(moreRecentSessionInfo, this.sessionInformation));
.willReturn(Arrays.<SessionInformation>asList(moreRecentSessionInfo, this.sessionInformation));
this.strategy.setMaximumSessions(2);
this.strategy.onAuthentication(this.authentication, this.request, this.response);
assertThat(this.sessionInformation.isExpired()).isTrue();

View File

@@ -331,7 +331,7 @@ public class SwitchUserFilterTests {
FilterChain chain = mock(FilterChain.class);
MockHttpServletResponse response = new MockHttpServletResponse();
assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(() -> filter.doFilter(request, response, chain));
.isThrownBy(() -> filter.doFilter(request, response, chain));
verify(chain, never()).doFilter(request, response);
}
@@ -466,7 +466,7 @@ public class SwitchUserFilterTests {
@Test
public void switchAuthorityRoleCannotBeNull() {
assertThatIllegalArgumentException().isThrownBy(() -> switchToUserWithAuthorityRole("dano", null))
.withMessage("switchAuthorityRole cannot be null");
.withMessage("switchAuthorityRole cannot be null");
}
// gh-3697
@@ -513,7 +513,7 @@ public class SwitchUserFilterTests {
void filterWhenDefaultSecurityContextRepositoryThenHttpSessionRepository() {
SwitchUserFilter switchUserFilter = new SwitchUserFilter();
assertThat(ReflectionTestUtils.getField(switchUserFilter, "securityContextRepository"))
.isInstanceOf(HttpSessionSecurityContextRepository.class);
.isInstanceOf(HttpSessionSecurityContextRepository.class);
}
@Test

View File

@@ -29,13 +29,13 @@ public class SwitchUserGrantedAuthorityTests {
@Test
public void authorityWithNullRoleFailsAssertion() {
assertThatIllegalArgumentException().isThrownBy(() -> new SwitchUserGrantedAuthority(null, null))
.withMessage("role cannot be null");
.withMessage("role cannot be null");
}
@Test
public void authorityWithNullSourceFailsAssertion() {
assertThatIllegalArgumentException().isThrownBy(() -> new SwitchUserGrantedAuthority("role", null))
.withMessage("source cannot be null");
.withMessage("source cannot be null");
}
}

View File

@@ -38,34 +38,36 @@ public class DefaultLogoutPageGeneratingFilterTests {
@Test
public void doFilterWhenNoHiddenInputsThenPageRendered() throws Exception {
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new Object()).addFilter(this.filter).build();
mockMvc.perform(get("/logout")).andExpect(content().string("<!DOCTYPE html>\n" + "<html lang=\"en\">\n"
+ " <head>\n" + " <meta charset=\"utf-8\">\n"
+ " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n"
+ " <meta name=\"description\" content=\"\">\n" + " <meta name=\"author\" content=\"\">\n"
+ " <title>Confirm Log Out?</title>\n"
+ " <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M\" crossorigin=\"anonymous\">\n"
+ " <link href=\"https://getbootstrap.com/docs/4.0/examples/signin/signin.css\" rel=\"stylesheet\" crossorigin=\"anonymous\"/>\n"
+ " </head>\n" + " <body>\n" + " <div class=\"container\">\n"
+ " <form class=\"form-signin\" method=\"post\" action=\"/logout\">\n"
+ " <h2 class=\"form-signin-heading\">Are you sure you want to log out?</h2>\n"
+ " <button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\">Log Out</button>\n"
+ " </form>\n" + " </div>\n" + " </body>\n" + "</html>"))
.andExpect(content().contentType("text/html;charset=UTF-8"));
mockMvc.perform(get("/logout"))
.andExpect(content().string("<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + " <head>\n"
+ " <meta charset=\"utf-8\">\n"
+ " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n"
+ " <meta name=\"description\" content=\"\">\n" + " <meta name=\"author\" content=\"\">\n"
+ " <title>Confirm Log Out?</title>\n"
+ " <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M\" crossorigin=\"anonymous\">\n"
+ " <link href=\"https://getbootstrap.com/docs/4.0/examples/signin/signin.css\" rel=\"stylesheet\" crossorigin=\"anonymous\"/>\n"
+ " </head>\n" + " <body>\n" + " <div class=\"container\">\n"
+ " <form class=\"form-signin\" method=\"post\" action=\"/logout\">\n"
+ " <h2 class=\"form-signin-heading\">Are you sure you want to log out?</h2>\n"
+ " <button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\">Log Out</button>\n"
+ " </form>\n" + " </div>\n" + " </body>\n" + "</html>"))
.andExpect(content().contentType("text/html;charset=UTF-8"));
}
@Test
public void doFilterWhenHiddenInputsSetThenHiddenInputsRendered() throws Exception {
this.filter.setResolveHiddenInputs((r) -> Collections.singletonMap("_csrf", "csrf-token-1"));
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new Object()).addFilters(this.filter).build();
mockMvc.perform(get("/logout")).andExpect(
content().string(containsString("<input name=\"_csrf\" type=\"hidden\" value=\"csrf-token-1\" />")));
mockMvc.perform(get("/logout"))
.andExpect(content()
.string(containsString("<input name=\"_csrf\" type=\"hidden\" value=\"csrf-token-1\" />")));
}
@Test
public void doFilterWhenRequestContextThenActionContainsRequestContext() throws Exception {
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new Object()).addFilters(this.filter).build();
mockMvc.perform(get("/context/logout").contextPath("/context"))
.andExpect(content().string(containsString("action=\"/context/logout\"")));
.andExpect(content().string(containsString("action=\"/context/logout\"")));
}
}

View File

@@ -41,7 +41,7 @@ public class BasicAuthenticationEntryPointTests {
public void testDetectsMissingRealmName() {
BasicAuthenticationEntryPoint ep = new BasicAuthenticationEntryPoint();
assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet)
.withMessage("realmName must be specified");
.withMessage("realmName must be specified");
}
@Test

View File

@@ -346,7 +346,7 @@ public class BasicAuthenticationFilterTests {
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("rod");
assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("äöü");
assertThat(request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME))
.isNotNull();
.isNotNull();
}
@Test

View File

@@ -41,9 +41,9 @@ public class DigestAuthUtilsTests {
assertThat(headerMap.get("username")).isEqualTo("rod");
assertThat(headerMap.get("realm")).isEqualTo("Contacts Realm");
assertThat(headerMap.get("nonce"))
.isEqualTo("MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==");
.isEqualTo("MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==");
assertThat(headerMap.get("uri"))
.isEqualTo("/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4");
.isEqualTo("/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4");
assertThat(headerMap.get("response")).isEqualTo("38644211cf9ac3da63ab639807e2baff");
assertThat(headerMap.get("qop")).isEqualTo("auth");
assertThat(headerMap.get("nc")).isEqualTo("00000004");
@@ -59,9 +59,9 @@ public class DigestAuthUtilsTests {
assertThat(headerMap.get("username")).isEqualTo("\"rod\"");
assertThat(headerMap.get("realm")).isEqualTo("\"Contacts Realm\"");
assertThat(headerMap.get("nonce"))
.isEqualTo("\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\"");
.isEqualTo("\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\"");
assertThat(headerMap.get("uri"))
.isEqualTo("\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\"");
.isEqualTo("\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\"");
assertThat(headerMap.get("response")).isEqualTo("\"38644211cf9ac3da63ab639807e2baff\"");
assertThat(headerMap.get("qop")).isEqualTo("auth");
assertThat(headerMap.get("nc")).isEqualTo("00000004");
@@ -95,7 +95,7 @@ public class DigestAuthUtilsTests {
assertThatIllegalArgumentException().isThrownBy(() -> DigestAuthUtils.split("sdch=dfgf", null));
assertThatIllegalArgumentException().isThrownBy(() -> DigestAuthUtils.split("fvfv=dcdc", ""));
assertThatIllegalArgumentException()
.isThrownBy(() -> DigestAuthUtils.split("dfdc=dcdc", "BIGGER_THAN_ONE_CHARACTER"));
.isThrownBy(() -> DigestAuthUtils.split("dfdc=dcdc", "BIGGER_THAN_ONE_CHARACTER"));
}
@Test

View File

@@ -61,7 +61,7 @@ public class DigestAuthenticationEntryPointTests {
ep.setKey("dcdc");
ep.setNonceValiditySeconds(12);
assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet)
.withMessage("realmName must be specified");
.withMessage("realmName must be specified");
}
@Test

View File

@@ -258,9 +258,9 @@ public class DigestAuthenticationFilterTests {
executeFilterInContainerSimulator(this.filter, this.request, true);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername())
.isEqualTo(USERNAME);
.isEqualTo(USERNAME);
assertThat(this.request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME))
.isNotNull();
.isNotNull();
}
@Test
@@ -272,10 +272,10 @@ public class DigestAuthenticationFilterTests {
executeFilterInContainerSimulator(this.filter, this.request, true);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername())
.isEqualTo(USERNAME);
.isEqualTo(USERNAME);
assertThat(SecurityContextHolder.getContext().getAuthentication().isAuthenticated()).isFalse();
assertThat(this.request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME))
.isNotNull();
.isNotNull();
}
@Test
@@ -288,12 +288,12 @@ public class DigestAuthenticationFilterTests {
executeFilterInContainerSimulator(this.filter, this.request, true);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername())
.isEqualTo(USERNAME);
.isEqualTo(USERNAME);
assertThat(SecurityContextHolder.getContext().getAuthentication().isAuthenticated()).isTrue();
assertThat(SecurityContextHolder.getContext().getAuthentication().getAuthorities())
.isEqualTo(AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
.isEqualTo(AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
assertThat(this.request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME))
.isNotNull();
.isNotNull();
}
@Test
@@ -426,10 +426,10 @@ public class DigestAuthenticationFilterTests {
MockHttpServletResponse response = executeFilterInContainerSimulator(this.filter, this.request, true);
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull();
assertThat(((UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername())
.isEqualTo(USERNAME);
.isEqualTo(USERNAME);
assertThat(SecurityContextHolder.getContext().getAuthentication().isAuthenticated()).isTrue();
assertThat(SecurityContextHolder.getContext().getAuthentication().getAuthorities())
.isEqualTo(AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
.isEqualTo(AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"));
verify(securityContextRepository).saveContext(contextArg.capture(), eq(this.request), eq(response));
assertThat(contextArg.getValue().getAuthentication().getName()).isEqualTo(USERNAME);
}

View File

@@ -89,35 +89,35 @@ public class AuthenticationPrincipalArgumentResolverTests {
public void resolveArgumentString() throws Exception {
setAuthenticationPrincipal("john");
assertThat(this.resolver.resolveArgument(showUserAnnotationString(), null, null, null))
.isEqualTo(this.expectedPrincipal);
.isEqualTo(this.expectedPrincipal);
}
@Test
public void resolveArgumentPrincipalStringOnObject() throws Exception {
setAuthenticationPrincipal("john");
assertThat(this.resolver.resolveArgument(showUserAnnotationObject(), null, null, null))
.isEqualTo(this.expectedPrincipal);
.isEqualTo(this.expectedPrincipal);
}
@Test
public void resolveArgumentUserDetails() throws Exception {
setAuthenticationPrincipal(new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER")));
assertThat(this.resolver.resolveArgument(showUserAnnotationUserDetails(), null, null, null))
.isEqualTo(this.expectedPrincipal);
.isEqualTo(this.expectedPrincipal);
}
@Test
public void resolveArgumentCustomUserPrincipal() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
assertThat(this.resolver.resolveArgument(showUserAnnotationCustomUserPrincipal(), null, null, null))
.isEqualTo(this.expectedPrincipal);
.isEqualTo(this.expectedPrincipal);
}
@Test
public void resolveArgumentCustomAnnotation() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
assertThat(this.resolver.resolveArgument(showUserCustomAnnotation(), null, null, null))
.isEqualTo(this.expectedPrincipal);
.isEqualTo(this.expectedPrincipal);
}
@Test
@@ -129,22 +129,22 @@ public class AuthenticationPrincipalArgumentResolverTests {
@Test
public void resolveArgumentErrorOnInvalidType() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
assertThatExceptionOfType(ClassCastException.class).isThrownBy(
() -> this.resolver.resolveArgument(showUserAnnotationErrorOnInvalidType(), null, null, null));
assertThatExceptionOfType(ClassCastException.class)
.isThrownBy(() -> this.resolver.resolveArgument(showUserAnnotationErrorOnInvalidType(), null, null, null));
}
@Test
public void resolveArgumentCustomserErrorOnInvalidType() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> this.resolver
.resolveArgument(showUserAnnotationCurrentUserErrorOnInvalidType(), null, null, null));
.resolveArgument(showUserAnnotationCurrentUserErrorOnInvalidType(), null, null, null));
}
@Test
public void resolveArgumentObject() throws Exception {
setAuthenticationPrincipal(new Object());
assertThat(this.resolver.resolveArgument(showUserAnnotationObject(), null, null, null))
.isEqualTo(this.expectedPrincipal);
.isEqualTo(this.expectedPrincipal);
}
private MethodParameter showUserNoAnnotation() {
@@ -187,7 +187,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
private void setAuthenticationPrincipal(Object principal) {
this.expectedPrincipal = principal;
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken(this.expectedPrincipal, "password", "ROLE_USER"));
.setAuthentication(new TestingAuthenticationToken(this.expectedPrincipal, "password", "ROLE_USER"));
}
@Target({ ElementType.PARAMETER })

View File

@@ -76,7 +76,7 @@ public class ConcurrentSessionFilterTests {
@SuppressWarnings("deprecation")
public void constructorSessionRegistryExpiresUrlWhenInvalidUrlThenExceptionThrown() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new ConcurrentSessionFilter(new SessionRegistryImpl(), "oops"));
.isThrownBy(() -> new ConcurrentSessionFilter(new SessionRegistryImpl(), "oops"));
}
@Test
@@ -129,8 +129,8 @@ public class ConcurrentSessionFilterTests {
filter.doFilter(request, response, fc);
verifyNoMoreInteractions(fc);
assertThat(response.getContentAsString())
.isEqualTo("This session has been expired (possibly due to multiple concurrent logins being "
+ "attempted as the same user).");
.isEqualTo("This session has been expired (possibly due to multiple concurrent logins being "
+ "attempted as the same user).");
}
@Test

View File

@@ -135,7 +135,7 @@ public class AbstractSecurityWebApplicationInitializerTests {
}.onStartup(context);
DelegatingFilterProxy proxy = proxyCaptor.getValue();
assertThat(proxy.getContextAttribute())
.isEqualTo("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher");
.isEqualTo("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher");
assertThat(proxy).hasFieldOrPropertyWithValue("targetBeanName", "springSecurityFilterChain");
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(registration).setAsyncSupported(true);
@@ -146,8 +146,9 @@ public class AbstractSecurityWebApplicationInitializerTests {
public void onStartupWhenSpringSecurityFilterChainAlreadyRegisteredThenException() {
ServletContext context = mock(ServletContext.class);
assertThatIllegalStateException().isThrownBy(() -> new AbstractSecurityWebApplicationInitializer() {
}.onStartup(context)).withMessage("Duplicate Filter registration for 'springSecurityFilterChain'. "
+ "Check to ensure the Filter is only configured once.");
}.onStartup(context))
.withMessage("Duplicate Filter registration for 'springSecurityFilterChain'. "
+ "Check to ensure the Filter is only configured once.");
}
@Test
@@ -188,8 +189,9 @@ public class AbstractSecurityWebApplicationInitializerTests {
insertFilters(context, filter1);
}
}.onStartup(context)).withMessage(
"Duplicate Filter registration for 'object'. Check to ensure the Filter is only configured once.");
}.onStartup(context))
.withMessage(
"Duplicate Filter registration for 'object'. Check to ensure the Filter is only configured once.");
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(context).addFilter(anyString(), eq(filter1));
@@ -268,8 +270,9 @@ public class AbstractSecurityWebApplicationInitializerTests {
appendFilters(context, filter1);
}
}.onStartup(context)).withMessage(
"Duplicate Filter registration for 'object'. " + "Check to ensure the Filter is only configured once.");
}.onStartup(context))
.withMessage("Duplicate Filter registration for 'object'. "
+ "Check to ensure the Filter is only configured once.");
assertProxyDefaults(proxyCaptor.getValue());
verify(registration).addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
verify(context).addFilter(anyString(), eq(filter1));
@@ -318,8 +321,8 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
ArgumentCaptor<Set<SessionTrackingMode>> modesCaptor = ArgumentCaptor
.forClass(new HashSet<SessionTrackingMode>() {
}.getClass());
.forClass(new HashSet<SessionTrackingMode>() {
}.getClass());
willDoNothing().given(context).setSessionTrackingModes(modesCaptor.capture());
new AbstractSecurityWebApplicationInitializer() {
}.onStartup(context);
@@ -336,8 +339,8 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
ArgumentCaptor<Set<SessionTrackingMode>> modesCaptor = ArgumentCaptor
.forClass(new HashSet<SessionTrackingMode>() {
}.getClass());
.forClass(new HashSet<SessionTrackingMode>() {
}.getClass());
willDoNothing().given(context).setSessionTrackingModes(modesCaptor.capture());
new AbstractSecurityWebApplicationInitializer() {
@Override
@@ -354,7 +357,7 @@ public class AbstractSecurityWebApplicationInitializerTests {
@Test
public void defaultFilterNameEqualsSpringSecurityFilterChain() {
assertThat(AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME)
.isEqualTo("springSecurityFilterChain");
.isEqualTo("springSecurityFilterChain");
}
private static void verifyNoAddListener(ServletContext context) {

View File

@@ -204,7 +204,7 @@ public class HttpSessionSecurityContextRepositoryTests {
assertThat(repo.loadContext(holder)).isSameAs(ctx);
// Modify context contents. Same user, different role
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("someone", "passwd", "ROLE_B"));
.setAuthentication(new TestingAuthenticationToken("someone", "passwd", "ROLE_B"));
repo.saveContext(ctx, holder.getRequest(), holder.getResponse());
// Must be called even though the value in the local VM is already the same
verify(session).setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, ctx);
@@ -249,7 +249,7 @@ public class HttpSessionSecurityContextRepositoryTests {
assertThat(
mockRequest.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY))
.isEqualTo(originalContext);
.isEqualTo(originalContext);
}
@Test
@@ -257,8 +257,9 @@ public class HttpSessionSecurityContextRepositoryTests {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
MockHttpServletRequest request = new MockHttpServletRequest();
SecurityContextHolder.getContext().setAuthentication(this.testToken);
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
"NotASecurityContextInstance");
request.getSession()
.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
"NotASecurityContextInstance");
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContext context = repo.loadContext(holder);
@@ -279,7 +280,7 @@ public class HttpSessionSecurityContextRepositoryTests {
repo.saveContext(context, holder.getRequest(), holder.getResponse());
assertThat(request.getSession(false)).isNotNull();
assertThat(request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY))
.isEqualTo(context);
.isEqualTo(context);
}
@Test
@@ -460,8 +461,9 @@ public class HttpSessionSecurityContextRepositoryTests {
MockHttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(
new AnonymousAuthenticationToken("key", "anon", AuthorityUtils.createAuthorityList("ANON")));
SecurityContextHolder.getContext()
.setAuthentication(
new AnonymousAuthenticationToken("key", "anon", AuthorityUtils.createAuthorityList("ANON")));
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
assertThat(request.getSession(false)).isNull();
}
@@ -473,15 +475,15 @@ public class HttpSessionSecurityContextRepositoryTests {
MockHttpServletRequest request = new MockHttpServletRequest();
SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext();
ctxInSession.setAuthentication(this.testToken);
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
ctxInSession);
request.getSession()
.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, ctxInSession);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse());
repo.loadContext(holder);
SecurityContextHolder.getContext()
.setAuthentication(new AnonymousAuthenticationToken("x", "x", this.testToken.getAuthorities()));
.setAuthentication(new AnonymousAuthenticationToken("x", "x", this.testToken.getAuthorities()));
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
assertThat(request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY))
.isNull();
.isNull();
}
@Test
@@ -508,10 +510,11 @@ public class HttpSessionSecurityContextRepositoryTests {
repo.loadContext(holder);
SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext();
ctxInSession.setAuthentication(this.testToken);
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
ctxInSession);
SecurityContextHolder.getContext().setAuthentication(
new AnonymousAuthenticationToken("x", "x", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
request.getSession()
.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, ctxInSession);
SecurityContextHolder.getContext()
.setAuthentication(
new AnonymousAuthenticationToken("x", "x", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
assertThat(ctxInSession).isSameAs(
request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY));
@@ -524,14 +527,14 @@ public class HttpSessionSecurityContextRepositoryTests {
MockHttpServletRequest request = new MockHttpServletRequest();
SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext();
ctxInSession.setAuthentication(this.testToken);
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
ctxInSession);
request.getSession()
.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, ctxInSession);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse());
repo.loadContext(holder);
ctxInSession.setAuthentication(null);
repo.saveContext(ctxInSession, holder.getRequest(), holder.getResponse());
assertThat(request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY))
.isNull();
.isNull();
}
@Test
@@ -598,7 +601,7 @@ public class HttpSessionSecurityContextRepositoryTests {
new HttpServletResponseWrapper(holder.getResponse()));
assertThat(request.getSession(false)).isNotNull();
assertThat(request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY))
.isEqualTo(context);
.isEqualTo(context);
}
@Test
@@ -611,7 +614,7 @@ public class HttpSessionSecurityContextRepositoryTests {
repo.saveContext(context, request, response);
assertThat(request.getSession(false)).isNotNull();
assertThat(request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY))
.isEqualTo(context);
.isEqualTo(context);
}
@Test
@@ -759,7 +762,7 @@ public class HttpSessionSecurityContextRepositoryTests {
session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, emptyContext);
repo.saveContext(emptyContext, request, response);
Object attributeAfterSave = session
.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
assertThat(attributeAfterSave).isNull();
}
@@ -781,7 +784,7 @@ public class HttpSessionSecurityContextRepositoryTests {
SecurityContext context = createSecurityContext(PasswordEncodedUser.user());
repo.saveContext(context, request, response);
Object savedContext = request.getSession()
.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
assertThat(savedContext).isEqualTo(context);
}

View File

@@ -61,15 +61,15 @@ class RequestAttributeSecurityContextRepositoryTests {
void saveContextAndLoadContextThenFound() {
this.repository.saveContext(this.expectedSecurityContext, this.request, this.response);
SecurityContext securityContext = this.repository
.loadContext(new HttpRequestResponseHolder(this.request, this.response));
.loadContext(new HttpRequestResponseHolder(this.request, this.response));
assertThat(securityContext).isEqualTo(this.expectedSecurityContext);
}
@Test
void saveContextWhenLoadContextAndNewRequestThenNotFound() {
this.repository.saveContext(this.expectedSecurityContext, this.request, this.response);
SecurityContext securityContext = this.repository.loadContext(
new HttpRequestResponseHolder(new MockHttpServletRequest(), new MockHttpServletResponse()));
SecurityContext securityContext = this.repository
.loadContext(new HttpRequestResponseHolder(new MockHttpServletRequest(), new MockHttpServletResponse()));
assertThat(securityContext).isEqualTo(SecurityContextHolder.createEmptyContext());
}
@@ -93,7 +93,7 @@ class RequestAttributeSecurityContextRepositoryTests {
@Test
void loadContextWhenNotPresentThenEmptyContext() {
SecurityContext context = this.repository
.loadContext(new HttpRequestResponseHolder(this.request, this.response));
.loadContext(new HttpRequestResponseHolder(this.request, this.response));
assertThat(context).isEqualTo(SecurityContextHolder.createEmptyContext());
}

View File

@@ -87,9 +87,9 @@ class SecurityContextHolderFilterTests {
Authentication authentication = TestAuthentication.authenticatedUser();
SecurityContext expectedContext = new SecurityContextImpl(authentication);
given(this.repository.loadDeferredContext(this.requestArg.capture()))
.willReturn(new SupplierDeferredSecurityContext(() -> expectedContext, this.strategy));
.willReturn(new SupplierDeferredSecurityContext(() -> expectedContext, this.strategy));
FilterChain filterChain = (request, response) -> assertThat(SecurityContextHolder.getContext())
.isEqualTo(expectedContext);
.isEqualTo(expectedContext);
this.filter.doFilter(this.request, this.response, filterChain);
@@ -101,7 +101,7 @@ class SecurityContextHolderFilterTests {
Authentication authentication = TestAuthentication.authenticatedUser();
SecurityContext expectedContext = new SecurityContextImpl(authentication);
given(this.repository.loadDeferredContext(this.requestArg.capture()))
.willReturn(new SupplierDeferredSecurityContext(() -> expectedContext, this.strategy));
.willReturn(new SupplierDeferredSecurityContext(() -> expectedContext, this.strategy));
FilterChain filterChain = (request, response) -> {
};
@@ -124,8 +124,8 @@ class SecurityContextHolderFilterTests {
@Test
void doFilterWhenNotAppliedThenSetsAndRemovesAttribute() throws Exception {
given(this.repository.loadDeferredContext(this.requestArg.capture())).willReturn(
new SupplierDeferredSecurityContext(SecurityContextHolder::createEmptyContext, this.strategy));
given(this.repository.loadDeferredContext(this.requestArg.capture()))
.willReturn(new SupplierDeferredSecurityContext(SecurityContextHolder::createEmptyContext, this.strategy));
this.filter.doFilter(this.request, this.response, new MockFilterChain());
@@ -142,9 +142,9 @@ class SecurityContextHolderFilterTests {
Authentication authentication = TestAuthentication.authenticatedUser();
SecurityContext expectedContext = new SecurityContextImpl(authentication);
given(this.repository.loadDeferredContext(this.requestArg.capture()))
.willReturn(new SupplierDeferredSecurityContext(() -> expectedContext, this.strategy));
.willReturn(new SupplierDeferredSecurityContext(() -> expectedContext, this.strategy));
FilterChain filterChain = (request, response) -> assertThat(SecurityContextHolder.getContext())
.isEqualTo(expectedContext);
.isEqualTo(expectedContext);
this.filter.doFilter(this.request, this.response, filterChain);
}

View File

@@ -93,7 +93,7 @@ public class WebAsyncManagerIntegrationFilterTests {
@Override
public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) {
assertThat(SecurityContextHolder.getContext())
.isNotSameAs(WebAsyncManagerIntegrationFilterTests.this.securityContext);
.isNotSameAs(WebAsyncManagerIntegrationFilterTests.this.securityContext);
}
});
this.filter.doFilterInternal(this.request, this.response, this.filterChain);
@@ -110,7 +110,7 @@ public class WebAsyncManagerIntegrationFilterTests {
@Override
public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) {
assertThat(SecurityContextHolder.getContext())
.isNotSameAs(WebAsyncManagerIntegrationFilterTests.this.securityContext);
.isNotSameAs(WebAsyncManagerIntegrationFilterTests.this.securityContext);
}
});
this.filter.doFilterInternal(this.request, this.response, this.filterChain);

View File

@@ -323,7 +323,7 @@ class CookieCsrfTokenRepositoryTests {
void loadToken() {
CsrfToken generateToken = this.repository.generateToken(this.request);
this.request
.setCookies(new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, generateToken.getToken()));
.setCookies(new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, generateToken.getToken()));
CsrfToken loadToken = this.repository.loadToken(this.request);
assertThat(loadToken).isNotNull();
assertThat(loadToken.getHeaderName()).isEqualTo(generateToken.getHeaderName());
@@ -368,7 +368,7 @@ class CookieCsrfTokenRepositoryTests {
void loadDeferredTokenWhenExistsAndNullSavedThenGeneratedAndSaved() {
CsrfToken generatedToken = this.repository.generateToken(this.request);
this.request
.setCookies(new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, generatedToken.getToken()));
.setCookies(new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, generatedToken.getToken()));
this.repository.saveToken(null, this.request, this.response);
DeferredCsrfToken deferredCsrfToken = this.repository.loadDeferredToken(this.request, this.response);
CsrfToken csrfToken = deferredCsrfToken.get();
@@ -381,7 +381,7 @@ class CookieCsrfTokenRepositoryTests {
void loadDeferredTokenWhenExistsAndNullSavedAndNonNullSavedThenLoaded() {
CsrfToken generatedToken = this.repository.generateToken(this.request);
this.request
.setCookies(new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, generatedToken.getToken()));
.setCookies(new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, generatedToken.getToken()));
this.repository.saveToken(null, this.request, this.response);
this.repository.saveToken(generatedToken, this.request, this.response);
DeferredCsrfToken deferredCsrfToken = this.repository.loadDeferredToken(this.request, this.response);
@@ -394,7 +394,7 @@ class CookieCsrfTokenRepositoryTests {
void loadDeferredTokenWhenExistsThenLoaded() {
CsrfToken generatedToken = this.repository.generateToken(this.request);
this.request
.setCookies(new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, generatedToken.getToken()));
.setCookies(new Cookie(CookieCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, generatedToken.getToken()));
DeferredCsrfToken deferredCsrfToken = this.repository.loadDeferredToken(this.request, this.response);
CsrfToken csrfToken = deferredCsrfToken.get();
assertThatCsrfToken(csrfToken).isEqualTo(generatedToken);

View File

@@ -77,14 +77,14 @@ public class CsrfAuthenticationStrategyTests {
@Test
public void setRequestHandlerWhenNullThenIllegalStateException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.strategy.setRequestHandler(null))
.withMessage("requestHandler cannot be null");
.withMessage("requestHandler cannot be null");
}
@Test
public void onAuthenticationWhenCustomRequestHandlerThenUsed() {
given(this.csrfTokenRepository.loadToken(this.request)).willReturn(this.existingToken);
given(this.csrfTokenRepository.loadDeferredToken(this.request, this.response))
.willReturn(new TestDeferredCsrfToken(this.existingToken, false));
.willReturn(new TestDeferredCsrfToken(this.existingToken, false));
CsrfTokenRequestHandler requestHandler = mock(CsrfTokenRequestHandler.class);
this.strategy.setRequestHandler(requestHandler);
@@ -100,7 +100,7 @@ public class CsrfAuthenticationStrategyTests {
public void logoutRemovesCsrfTokenAndLoadsNewDeferredCsrfToken() {
given(this.csrfTokenRepository.loadToken(this.request)).willReturn(this.existingToken);
given(this.csrfTokenRepository.loadDeferredToken(this.request, this.response))
.willReturn(new TestDeferredCsrfToken(this.generatedToken, false));
.willReturn(new TestDeferredCsrfToken(this.generatedToken, false));
this.strategy.onAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"), this.request,
this.response);
verify(this.csrfTokenRepository).loadToken(this.request);

View File

@@ -291,7 +291,7 @@ public class CsrfFilterTests {
for (String method : Arrays.asList("GET", "TRACE", "OPTIONS", "HEAD")) {
resetRequestResponse();
given(this.tokenRepository.loadDeferredToken(this.request, this.response))
.willReturn(new TestDeferredCsrfToken(this.token, false));
.willReturn(new TestDeferredCsrfToken(this.token, false));
this.request.setMethod(method);
this.filter.doFilter(this.request, this.response, this.filterChain);
verify(this.filterChain).doFilter(this.request, this.response);
@@ -312,7 +312,7 @@ public class CsrfFilterTests {
for (String method : Arrays.asList("get", "TrAcE", "oPTIOnS", "hEaD")) {
resetRequestResponse();
given(this.tokenRepository.loadDeferredToken(this.request, this.response))
.willReturn(new TestDeferredCsrfToken(this.token, false));
.willReturn(new TestDeferredCsrfToken(this.token, false));
this.request.setMethod(method);
this.filter.doFilter(this.request, this.response, this.filterChain);
verify(this.deniedHandler).handle(eq(this.request), eq(this.response),
@@ -328,7 +328,7 @@ public class CsrfFilterTests {
for (String method : Arrays.asList("POST", "PUT", "PATCH", "DELETE", "INVALID")) {
resetRequestResponse();
given(this.tokenRepository.loadDeferredToken(this.request, this.response))
.willReturn(new TestDeferredCsrfToken(this.token, false));
.willReturn(new TestDeferredCsrfToken(this.token, false));
this.request.setMethod(method);
this.filter.doFilter(this.request, this.response, this.filterChain);
verify(this.deniedHandler).handle(eq(this.request), eq(this.response),

View File

@@ -54,8 +54,8 @@ public class CsrfTokenRequestAttributeHandlerTests {
@Test
public void handleWhenRequestIsNullThenThrowsIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.handler.handle(null, this.response, () -> this.token))
.withMessage("request cannot be null");
.isThrownBy(() -> this.handler.handle(null, this.response, () -> this.token))
.withMessage("request cannot be null");
}
@Test
@@ -70,7 +70,7 @@ public class CsrfTokenRequestAttributeHandlerTests {
@Test
public void handleWhenCsrfTokenSupplierIsNullThenThrowsIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.handler.handle(this.request, this.response, null))
.withMessage("deferredCsrfToken cannot be null");
.withMessage("deferredCsrfToken cannot be null");
}
@Test
@@ -101,13 +101,13 @@ public class CsrfTokenRequestAttributeHandlerTests {
@Test
public void resolveCsrfTokenValueWhenRequestIsNullThenThrowsIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.handler.resolveCsrfTokenValue(null, this.token))
.withMessage("request cannot be null");
.withMessage("request cannot be null");
}
@Test
public void resolveCsrfTokenValueWhenCsrfTokenIsNullThenThrowsIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.handler.resolveCsrfTokenValue(this.request, null))
.withMessage("csrfToken cannot be null");
.withMessage("csrfToken cannot be null");
}
@Test

View File

@@ -35,37 +35,37 @@ public class DefaultCsrfTokenTests {
@Test
public void constructorNullHeaderName() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DefaultCsrfToken(null, this.parameterName, this.tokenValue));
.isThrownBy(() -> new DefaultCsrfToken(null, this.parameterName, this.tokenValue));
}
@Test
public void constructorEmptyHeaderName() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DefaultCsrfToken("", this.parameterName, this.tokenValue));
.isThrownBy(() -> new DefaultCsrfToken("", this.parameterName, this.tokenValue));
}
@Test
public void constructorNullParameterName() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DefaultCsrfToken(this.headerName, null, this.tokenValue));
.isThrownBy(() -> new DefaultCsrfToken(this.headerName, null, this.tokenValue));
}
@Test
public void constructorEmptyParameterName() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DefaultCsrfToken(this.headerName, "", this.tokenValue));
.isThrownBy(() -> new DefaultCsrfToken(this.headerName, "", this.tokenValue));
}
@Test
public void constructorNullTokenValue() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DefaultCsrfToken(this.headerName, this.parameterName, null));
.isThrownBy(() -> new DefaultCsrfToken(this.headerName, this.parameterName, null));
}
@Test
public void constructorEmptyTokenValue() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DefaultCsrfToken(this.headerName, this.parameterName, ""));
.isThrownBy(() -> new DefaultCsrfToken(this.headerName, this.parameterName, ""));
}
}

View File

@@ -66,7 +66,7 @@ public class LazyCsrfTokenRepositoryTests {
@Test
public void generateTokenNullResponseAttribute() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.repository.generateToken(mock(HttpServletRequest.class)));
.isThrownBy(() -> this.repository.generateToken(mock(HttpServletRequest.class)));
}
@Test

View File

@@ -30,9 +30,10 @@ public class CompositeRequestRejectedHandlerTests {
RequestRejectedException requestRejectedException = new RequestRejectedException("rejected");
CompositeRequestRejectedHandler handler = new CompositeRequestRejectedHandler(
new DefaultRequestRejectedHandler());
assertThatExceptionOfType(RequestRejectedException.class).isThrownBy(() -> handler
.handle(mock(HttpServletRequest.class), mock(HttpServletResponse.class), requestRejectedException))
.withMessage("rejected");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> handler.handle(mock(HttpServletRequest.class), mock(HttpServletResponse.class),
requestRejectedException))
.withMessage("rejected");
}
@Test

View File

@@ -37,10 +37,10 @@ public class DefaultHttpFirewallTests {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServletPath(path);
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> fw.getFirewalledRequest(request));
.isThrownBy(() -> fw.getFirewalledRequest(request));
request.setPathInfo(path);
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> fw.getFirewalledRequest(request));
.isThrownBy(() -> fw.getFirewalledRequest(request));
}
}

View File

@@ -29,9 +29,10 @@ public class DefaultRequestRejectedHandlerTests {
public void defaultRequestRejectedHandlerRethrowsTheException() throws Exception {
RequestRejectedException requestRejectedException = new RequestRejectedException("rejected");
DefaultRequestRejectedHandler sut = new DefaultRequestRejectedHandler();
assertThatExceptionOfType(RequestRejectedException.class).isThrownBy(() -> sut
.handle(mock(HttpServletRequest.class), mock(HttpServletResponse.class), requestRejectedException))
.withMessage("rejected");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> sut.handle(mock(HttpServletRequest.class), mock(HttpServletResponse.class),
requestRejectedException))
.withMessage("rejected");
}
}

View File

@@ -59,7 +59,7 @@ public class FirewalledResponseTests {
@Test
public void sendRedirectWhenHasCrlfThenThrowsException() throws Exception {
assertThatIllegalArgumentException().isThrownBy(() -> this.fwResponse.sendRedirect("/theURL\r\nsomething"))
.withMessageContaining(CRLF_MESSAGE);
.withMessageContaining(CRLF_MESSAGE);
}
@Test
@@ -77,15 +77,15 @@ public class FirewalledResponseTests {
@Test
public void addHeaderWhenHeaderValueHasCrlfThenException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.fwResponse.addHeader("foo", "abc\r\nContent-Length:100"))
.withMessageContaining(CRLF_MESSAGE);
.isThrownBy(() -> this.fwResponse.addHeader("foo", "abc\r\nContent-Length:100"))
.withMessageContaining(CRLF_MESSAGE);
}
@Test
public void addHeaderWhenHeaderNameHasCrlfThenException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.fwResponse.addHeader("abc\r\nContent-Length:100", "bar"))
.withMessageContaining(CRLF_MESSAGE);
.isThrownBy(() -> this.fwResponse.addHeader("abc\r\nContent-Length:100", "bar"))
.withMessageContaining(CRLF_MESSAGE);
}
@Test
@@ -114,14 +114,14 @@ public class FirewalledResponseTests {
}
};
assertThatIllegalArgumentException().isThrownBy(() -> this.fwResponse.addCookie(cookie))
.withMessageContaining(CRLF_MESSAGE);
.withMessageContaining(CRLF_MESSAGE);
}
@Test
public void addCookieWhenCookieValueContainsCrlfThenException() {
Cookie cookie = new Cookie("foo", "foo\r\nbar");
assertThatIllegalArgumentException().isThrownBy(() -> this.fwResponse.addCookie(cookie))
.withMessageContaining(CRLF_MESSAGE);
.withMessageContaining(CRLF_MESSAGE);
}
@Test
@@ -129,7 +129,7 @@ public class FirewalledResponseTests {
Cookie cookie = new Cookie("foo", "bar");
cookie.setPath("/foo\r\nbar");
assertThatIllegalArgumentException().isThrownBy(() -> this.fwResponse.addCookie(cookie))
.withMessageContaining(CRLF_MESSAGE);
.withMessageContaining(CRLF_MESSAGE);
}
@Test
@@ -137,7 +137,7 @@ public class FirewalledResponseTests {
Cookie cookie = new Cookie("foo", "bar");
cookie.setDomain("foo\r\nbar");
assertThatIllegalArgumentException().isThrownBy(() -> this.fwResponse.addCookie(cookie))
.withMessageContaining(CRLF_MESSAGE);
.withMessageContaining(CRLF_MESSAGE);
}
@Test

View File

@@ -45,7 +45,7 @@ public class StrictHttpFirewallTests {
public void getFirewalledRequestWhenInvalidMethodThenThrowsRequestRejectedException() {
this.request.setMethod("INVALID");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
// blocks XST attacks
@@ -53,7 +53,7 @@ public class StrictHttpFirewallTests {
public void getFirewalledRequestWhenTraceMethodThenThrowsRequestRejectedException() {
this.request.setMethod(HttpMethod.TRACE.name());
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
@@ -61,7 +61,7 @@ public class StrictHttpFirewallTests {
public void getFirewalledRequestWhenTrackMethodThenThrowsRequestRejectedException() {
this.request.setMethod("TRACK");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
@@ -69,7 +69,7 @@ public class StrictHttpFirewallTests {
public void getFirewalledRequestWhenLowercaseGetThenThrowsRequestRejectedException() {
this.request.setMethod("get");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
@@ -94,7 +94,7 @@ public class StrictHttpFirewallTests {
this.request = new MockHttpServletRequest("GET", "");
this.request.setRequestURI(path);
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
}
@@ -104,7 +104,7 @@ public class StrictHttpFirewallTests {
this.request = new MockHttpServletRequest("GET", "");
this.request.setContextPath(path);
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
}
@@ -114,7 +114,7 @@ public class StrictHttpFirewallTests {
this.request = new MockHttpServletRequest("GET", "");
this.request.setServletPath(path);
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
}
@@ -124,7 +124,7 @@ public class StrictHttpFirewallTests {
this.request = new MockHttpServletRequest("GET", "");
this.request.setPathInfo(path);
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
}
@@ -132,84 +132,84 @@ public class StrictHttpFirewallTests {
public void getFirewalledRequestWhenSemicolonInContextPathThenThrowsRequestRejectedException() {
this.request.setContextPath(";/context");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
public void getFirewalledRequestWhenSemicolonInServletPathThenThrowsRequestRejectedException() {
this.request.setServletPath("/spring;/");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
public void getFirewalledRequestWhenSemicolonInPathInfoThenThrowsRequestRejectedException() {
this.request.setPathInfo("/path;/");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
public void getFirewalledRequestWhenSemicolonInRequestUriThenThrowsRequestRejectedException() {
this.request.setRequestURI("/path;/");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
public void getFirewalledRequestWhenEncodedSemicolonInContextPathThenThrowsRequestRejectedException() {
this.request.setContextPath("%3B/context");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
public void getFirewalledRequestWhenEncodedSemicolonInServletPathThenThrowsRequestRejectedException() {
this.request.setServletPath("/spring%3B/");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
public void getFirewalledRequestWhenEncodedSemicolonInPathInfoThenThrowsRequestRejectedException() {
this.request.setPathInfo("/path%3B/");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
public void getFirewalledRequestWhenEncodedSemicolonInRequestUriThenThrowsRequestRejectedException() {
this.request.setRequestURI("/path%3B/");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
public void getFirewalledRequestWhenLowercaseEncodedSemicolonInContextPathThenThrowsRequestRejectedException() {
this.request.setContextPath("%3b/context");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
public void getFirewalledRequestWhenLowercaseEncodedSemicolonInServletPathThenThrowsRequestRejectedException() {
this.request.setServletPath("/spring%3b/");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
public void getFirewalledRequestWhenLowercaseEncodedSemicolonInPathInfoThenThrowsRequestRejectedException() {
this.request.setPathInfo("/path%3b/");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
public void getFirewalledRequestWhenLowercaseEncodedSemicolonInRequestUriThenThrowsRequestRejectedException() {
this.request.setRequestURI("/path%3b/");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
@@ -306,14 +306,14 @@ public class StrictHttpFirewallTests {
public void getFirewalledRequestWhenEncodedPeriodInThenThrowsRequestRejectedException() {
this.request.setRequestURI("/%2E/");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
public void getFirewalledRequestWhenLowercaseEncodedPeriodInThenThrowsRequestRejectedException() {
this.request.setRequestURI("/%2e/");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
@@ -327,7 +327,7 @@ public class StrictHttpFirewallTests {
public void getFirewalledRequestWhenExceedsLowerboundAsciiThenException() {
this.request.setRequestURI("/\u0019");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
@@ -352,91 +352,91 @@ public class StrictHttpFirewallTests {
public void getFirewalledRequestWhenExceedsUpperboundAsciiThenException() {
this.request.setRequestURI("/\u007f");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
public void getFirewalledRequestWhenContainsNullThenException() {
this.request.setRequestURI("/\0");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
public void getFirewalledRequestWhenContainsEncodedNullThenException() {
this.request.setRequestURI("/something%00/");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
public void getFirewalledRequestWhenContainsLowercaseEncodedLineFeedThenException() {
this.request.setRequestURI("/something%0a/");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
public void getFirewalledRequestWhenContainsUppercaseEncodedLineFeedThenException() {
this.request.setRequestURI("/something%0A/");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
public void getFirewalledRequestWhenContainsLineFeedThenException() {
this.request.setRequestURI("/something\n/");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
public void getFirewalledRequestWhenServletPathContainsLineFeedThenException() {
this.request.setServletPath("/something\n/");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
public void getFirewalledRequestWhenContainsLowercaseEncodedCarriageReturnThenException() {
this.request.setRequestURI("/something%0d/");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
public void getFirewalledRequestWhenContainsUppercaseEncodedCarriageReturnThenException() {
this.request.setRequestURI("/something%0D/");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
public void getFirewalledRequestWhenContainsCarriageReturnThenException() {
this.request.setRequestURI("/something\r/");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
public void getFirewalledRequestWhenServletPathContainsCarriageReturnThenException() {
this.request.setServletPath("/something\r/");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
public void getFirewalledRequestWhenServletPathContainsLineSeparatorThenException() {
this.request.setServletPath("/something\u2028/");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
public void getFirewalledRequestWhenServletPathContainsParagraphSeparatorThenException() {
this.request.setServletPath("/something\u2029/");
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
@@ -460,7 +460,7 @@ public class StrictHttpFirewallTests {
// Expected an error because the line feed is decoded in an encoded part of the
// URL
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
@@ -491,7 +491,7 @@ public class StrictHttpFirewallTests {
// Expected an error because the carriage return is decoded in an encoded part of
// the URL
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
@@ -527,7 +527,7 @@ public class StrictHttpFirewallTests {
this.request.setServletPath("");
this.request.setPathInfo("/a/b;/1/c"); // URL decoded requestURI
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
@@ -537,7 +537,7 @@ public class StrictHttpFirewallTests {
this.request.setServletPath("");
this.request.setPathInfo("/a/b;/1/c"); // URL decoded requestURI
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
@@ -713,7 +713,7 @@ public class StrictHttpFirewallTests {
this.request.addHeader("Host", "example.org");
this.firewall.setAllowedHostnames((hostname) -> hostname.equals("myexample.org"));
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
.isThrownBy(() -> this.firewall.getFirewalledRequest(this.request));
}
@Test
@@ -771,7 +771,7 @@ public class StrictHttpFirewallTests {
this.request.addHeader("Bad\0Name", "some value");
HttpServletRequest request = this.firewall.getFirewalledRequest(this.request);
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> request.getHeaderNames().nextElement());
.isThrownBy(() -> request.getHeaderNames().nextElement());
}
@Test
@@ -793,7 +793,7 @@ public class StrictHttpFirewallTests {
this.request.addHeader("Something", "bad\0value");
HttpServletRequest request = this.firewall.getFirewalledRequest(this.request);
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> request.getHeaders("Something").nextElement());
.isThrownBy(() -> request.getHeaders("Something").nextElement());
}
@Test
@@ -830,7 +830,7 @@ public class StrictHttpFirewallTests {
this.request.addParameter("Something", "bad value");
HttpServletRequest request = this.firewall.getFirewalledRequest(this.request);
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> request.getParameterValues("Something"));
.isThrownBy(() -> request.getParameterValues("Something"));
}
@Test
@@ -839,7 +839,7 @@ public class StrictHttpFirewallTests {
this.request.addParameter("bad name", "good value");
HttpServletRequest request = this.firewall.getFirewalledRequest(this.request);
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> request.getParameterValues("bad name"));
.isThrownBy(() -> request.getParameterValues("bad name"));
}
// gh-9598

View File

@@ -77,7 +77,7 @@ public class HeaderWriterFilterTests {
verify(this.writer1).writeHeaders(request, response);
verify(this.writer2).writeHeaders(request, response);
HeaderWriterFilter.HeaderWriterRequest wrappedRequest = (HeaderWriterFilter.HeaderWriterRequest) filterChain
.getRequest();
.getRequest();
assertThat(wrappedRequest.getRequest()).isEqualTo(request); // verify the
// filterChain
// continued
@@ -120,7 +120,7 @@ public class HeaderWriterFilterTests {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, (request1, response1) -> verify(HeaderWriterFilterTests.this.writer1)
.writeHeaders(any(HttpServletRequest.class), any(HttpServletResponse.class)));
.writeHeaders(any(HttpServletRequest.class), any(HttpServletResponse.class)));
verifyNoMoreInteractions(this.writer1);
}

View File

@@ -49,7 +49,7 @@ public class CacheControlHeadersWriterTests {
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames().size()).isEqualTo(3);
assertThat(this.response.getHeaderValues("Cache-Control"))
.containsOnly("no-cache, no-store, max-age=0, must-revalidate");
.containsOnly("no-cache, no-store, max-age=0, must-revalidate");
assertThat(this.response.getHeaderValues("Pragma")).containsOnly("no-cache");
assertThat(this.response.getHeaderValues("Expires")).containsOnly("0");
}

View File

@@ -49,7 +49,7 @@ public class ClearSiteDataHeaderWriterTests {
@Test
public void createInstanceWhenMissingSourceThenThrowsException() {
assertThatExceptionOfType(Exception.class).isThrownBy(() -> new ClearSiteDataHeaderWriter())
.withMessage("directives cannot be empty or null");
.withMessage("directives cannot be empty or null");
}
@Test
@@ -73,7 +73,7 @@ public class ClearSiteDataHeaderWriterTests {
Directive.STORAGE, Directive.EXECUTION_CONTEXTS);
headerWriter.writeHeaders(this.request, this.response);
assertThat(this.response.getHeader(HEADER_NAME))
.isEqualTo("\"cache\", \"cookies\", \"storage\", \"executionContexts\"");
.isEqualTo("\"cache\", \"cookies\", \"storage\", \"executionContexts\"");
}
}

View File

@@ -45,7 +45,7 @@ class CrossOriginEmbedderPolicyHeaderWriterTests {
@Test
void setEmbedderPolicyWhenNullEmbedderPolicyThenThrowsIllegalArgument() {
assertThatIllegalArgumentException().isThrownBy(() -> this.writer.setPolicy(null))
.withMessage("embedderPolicy cannot be null");
.withMessage("embedderPolicy cannot be null");
}
@Test

View File

@@ -45,7 +45,7 @@ class CrossOriginOpenerPolicyHeaderWriterTests {
@Test
void setOpenerPolicyWhenNullOpenerPolicyThenThrowsIllegalArgument() {
assertThatIllegalArgumentException().isThrownBy(() -> this.writer.setPolicy(null))
.withMessage("openerPolicy cannot be null");
.withMessage("openerPolicy cannot be null");
}
@Test

View File

@@ -45,7 +45,7 @@ class CrossOriginResourcePolicyHeaderWriterTests {
@Test
void setResourcePolicyWhenNullThenThrowsIllegalArgument() {
assertThatIllegalArgumentException().isThrownBy(() -> this.writer.setPolicy(null))
.withMessage("resourcePolicy cannot be null");
.withMessage("resourcePolicy cannot be null");
}
@Test

View File

@@ -61,13 +61,13 @@ public class DelegatingRequestMatcherHeaderWriterTests {
@Test
public void constructorNullRequestMatcher() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingRequestMatcherHeaderWriter(null, this.delegate));
.isThrownBy(() -> new DelegatingRequestMatcherHeaderWriter(null, this.delegate));
}
@Test
public void constructorNullDelegate() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingRequestMatcherHeaderWriter(this.matcher, null));
.isThrownBy(() -> new DelegatingRequestMatcherHeaderWriter(this.matcher, null));
}
@Test

View File

@@ -60,13 +60,13 @@ public class FeaturePolicyHeaderWriterTests {
@Test
public void createWriterWithNullDirectivesShouldThrowException() {
assertThatIllegalArgumentException().isThrownBy(() -> new FeaturePolicyHeaderWriter(null))
.withMessage("policyDirectives must not be null or empty");
.withMessage("policyDirectives must not be null or empty");
}
@Test
public void createWriterWithEmptyDirectivesShouldThrowException() {
assertThatIllegalArgumentException().isThrownBy(() -> new FeaturePolicyHeaderWriter(""))
.withMessage("policyDirectives must not be null or empty");
.withMessage("policyDirectives must not be null or empty");
}
@Test

View File

@@ -70,7 +70,7 @@ public class HpkpHeaderWriterTests {
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Public-Key-Pins-Report-Only"))
.isEqualTo("max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\"");
.isEqualTo("max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\"");
}
@Test
@@ -80,7 +80,7 @@ public class HpkpHeaderWriterTests {
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Public-Key-Pins-Report-Only"))
.isEqualTo("max-age=2592000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\"");
.isEqualTo("max-age=2592000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\"");
}
@Test
@@ -109,7 +109,7 @@ public class HpkpHeaderWriterTests {
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Public-Key-Pins-Report-Only"))
.isEqualTo("max-age=2592000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\"");
.isEqualTo("max-age=2592000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\"");
}
@Test
@@ -127,7 +127,7 @@ public class HpkpHeaderWriterTests {
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Public-Key-Pins"))
.isEqualTo("max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\"");
.isEqualTo("max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\"");
}
@Test
@@ -175,7 +175,7 @@ public class HpkpHeaderWriterTests {
@Test
public void addSha256PinsWithNullPin() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.writer.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=", null));
.isThrownBy(() -> this.writer.addSha256Pins("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=", null));
}
@Test

View File

@@ -73,7 +73,7 @@ public class HstsHeaderWriterTests {
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Strict-Transport-Security"))
.isEqualTo("max-age=15768000 ; includeSubDomains");
.isEqualTo("max-age=15768000 ; includeSubDomains");
}
@Test
@@ -89,7 +89,7 @@ public class HstsHeaderWriterTests {
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Strict-Transport-Security"))
.isEqualTo("max-age=31536000 ; includeSubDomains");
.isEqualTo("max-age=31536000 ; includeSubDomains");
}
@Test
@@ -122,7 +122,7 @@ public class HstsHeaderWriterTests {
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader("Strict-Transport-Security"))
.isEqualTo("max-age=31536000 ; includeSubDomains");
.isEqualTo("max-age=31536000 ; includeSubDomains");
}
@Test

View File

@@ -59,13 +59,13 @@ public class PermissionsPolicyHeaderWriterTests {
@Test
public void createWriterWithNullPolicyShouldThrowException() {
assertThatIllegalArgumentException().isThrownBy(() -> new PermissionsPolicyHeaderWriter(null))
.withMessage("policy can not be null or empty");
.withMessage("policy can not be null or empty");
}
@Test
public void createWriterWithEmptyPolicyShouldThrowException() {
assertThatIllegalArgumentException().isThrownBy(() -> new PermissionsPolicyHeaderWriter(""))
.withMessage("policy can not be null or empty");
.withMessage("policy can not be null or empty");
}
@Test

View File

@@ -90,7 +90,7 @@ public class XXssProtectionHeaderWriterTests {
@Test
public void setHeaderValueNullThenThrowsIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.writer.setHeaderValue(null))
.withMessage("headerValue cannot be null");
.withMessage("headerValue cannot be null");
}
}

View File

@@ -60,7 +60,7 @@ public class FrameOptionsHeaderWriterTests {
@Test
public void constructorAllowFromNoAllowFromStrategy() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new XFrameOptionsHeaderWriter(XFrameOptionsMode.ALLOW_FROM));
.isThrownBy(() -> new XFrameOptionsHeaderWriter(XFrameOptionsMode.ALLOW_FROM));
}
@Test
@@ -83,7 +83,7 @@ public class FrameOptionsHeaderWriterTests {
this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames()).hasSize(1);
assertThat(this.response.getHeader(XFrameOptionsHeaderWriter.XFRAME_OPTIONS_HEADER))
.isEqualTo("ALLOW-FROM " + allowFromValue);
.isEqualTo("ALLOW-FROM " + allowFromValue);
}
@Test

View File

@@ -63,14 +63,14 @@ public class DefaultCsrfTokenMixinTests extends AbstractMixinTests {
public void defaultCsrfTokenDeserializeWithoutClassTest() throws IOException {
String tokenJson = "{\"headerName\": \"csrf-header\", \"parameterName\": \"_csrf\", \"token\": \"1\"}";
assertThatExceptionOfType(JsonMappingException.class)
.isThrownBy(() -> this.mapper.readValue(tokenJson, DefaultCsrfToken.class));
.isThrownBy(() -> this.mapper.readValue(tokenJson, DefaultCsrfToken.class));
}
@Test
public void defaultCsrfTokenDeserializeNullValuesTest() throws IOException {
String tokenJson = "{\"@class\": \"org.springframework.security.web.csrf.DefaultCsrfToken\", \"headerName\": \"\", \"parameterName\": null, \"token\": \"1\"}";
assertThatExceptionOfType(JsonMappingException.class)
.isThrownBy(() -> this.mapper.readValue(tokenJson, DefaultCsrfToken.class));
.isThrownBy(() -> this.mapper.readValue(tokenJson, DefaultCsrfToken.class));
}
}

View File

@@ -95,11 +95,17 @@ public class DefaultSavedRequestMixinTests extends AbstractMixinTests {
@Test
public void matchRequestBuildWithConstructorAndBuilder() {
DefaultSavedRequest request = new DefaultSavedRequest.Builder()
.setCookies(Collections.singletonList(new SavedCookie(new Cookie("SESSION", "123456789"))))
.setHeaders(Collections.singletonMap("x-auth-token", Collections.singletonList("12"))).setScheme("http")
.setRequestURL("http://localhost").setServerName("localhost").setRequestURI("")
.setLocales(Collections.singletonList(new Locale("en"))).setContextPath("").setMethod("")
.setServletPath("").build();
.setCookies(Collections.singletonList(new SavedCookie(new Cookie("SESSION", "123456789"))))
.setHeaders(Collections.singletonMap("x-auth-token", Collections.singletonList("12")))
.setScheme("http")
.setRequestURL("http://localhost")
.setServerName("localhost")
.setRequestURI("")
.setLocales(Collections.singletonList(new Locale("en")))
.setContextPath("")
.setMethod("")
.setServletPath("")
.build();
MockHttpServletRequest mockRequest = new MockHttpServletRequest();
mockRequest.setCookies(new Cookie("SESSION", "123456789"));
mockRequest.addHeader("x-auth-token", "12");
@@ -119,18 +125,24 @@ public class DefaultSavedRequestMixinTests extends AbstractMixinTests {
}
};
String actualString = this.mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(new DefaultSavedRequest(requestToWrite, new PortResolverImpl()));
.writeValueAsString(new DefaultSavedRequest(requestToWrite, new PortResolverImpl()));
JSONAssert.assertEquals(REQUEST_JSON, actualString, true);
}
@Test
public void serializeDefaultRequestBuildWithBuilderTest() throws IOException, JSONException {
DefaultSavedRequest request = new DefaultSavedRequest.Builder()
.setCookies(Collections.singletonList(new SavedCookie(new Cookie("SESSION", "123456789"))))
.setHeaders(Collections.singletonMap("x-auth-token", Collections.singletonList("12"))).setScheme("http")
.setRequestURL("http://localhost").setServerName("localhost").setRequestURI("")
.setLocales(Collections.singletonList(new Locale("en"))).setContextPath("").setMethod("")
.setServletPath("").build();
.setCookies(Collections.singletonList(new SavedCookie(new Cookie("SESSION", "123456789"))))
.setHeaders(Collections.singletonMap("x-auth-token", Collections.singletonList("12")))
.setScheme("http")
.setRequestURL("http://localhost")
.setServerName("localhost")
.setRequestURI("")
.setLocales(Collections.singletonList(new Locale("en")))
.setContextPath("")
.setMethod("")
.setServletPath("")
.build();
String actualString = this.mapper.writerWithDefaultPrettyPrinter().writeValueAsString(request);
JSONAssert.assertEquals(REQUEST_JSON, actualString, true);
}
@@ -148,7 +160,7 @@ public class DefaultSavedRequestMixinTests extends AbstractMixinTests {
@Test
public void deserializeWhenMatchingRequestParameterNameThenRedirectUrlContainsParam() throws IOException {
DefaultSavedRequest request = (DefaultSavedRequest) this.mapper
.readValue(REQUEST_WITH_MATCHING_REQUEST_PARAM_NAME_JSON, Object.class);
.readValue(REQUEST_WITH_MATCHING_REQUEST_PARAM_NAME_JSON, Object.class);
assertThat(request.getRedirectUrl()).isEqualTo("http://localhost?success");
}

View File

@@ -66,7 +66,7 @@ public class SavedCookieMixinTests extends AbstractMixinTests {
public void serializeWithOverrideConfigurationTest() throws JsonProcessingException, JSONException {
SavedCookie savedCookie = new SavedCookie(new Cookie("SESSION", "123456789"));
this.mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.PUBLIC_ONLY)
.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.ANY);
.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.ANY);
String actualJson = this.mapper.writeValueAsString(savedCookie);
JSONAssert.assertEquals(COOKIE_JSON, actualJson, true);
}

View File

@@ -209,8 +209,9 @@ public final class ResolvableMethod {
}
private String formatMethod() {
return this.method().getName() + Arrays.stream(this.method.getParameters()).map(this::formatParameter)
.collect(Collectors.joining(",\n\t", "(\n\t", "\n)"));
return this.method().getName() + Arrays.stream(this.method.getParameters())
.map(this::formatParameter)
.collect(Collectors.joining(",\n\t", "(\n\t", "\n)"));
}
private String formatParameter(Parameter param) {
@@ -335,7 +336,7 @@ public final class ResolvableMethod {
public final Builder<T> annotPresent(Class<? extends Annotation>... annotationTypes) {
String message = "annotationPresent=" + Arrays.toString(annotationTypes);
addFilter(message, (candidate) -> Arrays.stream(annotationTypes)
.allMatch((annotType) -> AnnotatedElementUtils.findMergedAnnotation(candidate, annotType) != null));
.allMatch((annotType) -> AnnotatedElementUtils.findMergedAnnotation(candidate, annotType) != null));
return this;
}
@@ -347,8 +348,9 @@ public final class ResolvableMethod {
String message = "annotationNotPresent=" + Arrays.toString(annotationTypes);
addFilter(message, (candidate) -> {
if (annotationTypes.length != 0) {
return Arrays.stream(annotationTypes).noneMatch(
(annotType) -> AnnotatedElementUtils.findMergedAnnotation(candidate, annotType) != null);
return Arrays.stream(annotationTypes)
.noneMatch((
annotType) -> AnnotatedElementUtils.findMergedAnnotation(candidate, annotType) != null);
}
else {
return candidate.getAnnotations().length == 0;
@@ -408,8 +410,9 @@ public final class ResolvableMethod {
}
private String formatMethods(Set<Method> methods) {
return "\nMatched:\n" + methods.stream().map(Method::toGenericString)
.collect(Collectors.joining(",\n\t", "[\n\t", "\n]"));
return "\nMatched:\n" + methods.stream()
.map(Method::toGenericString)
.collect(Collectors.joining(",\n\t", "[\n\t", "\n]"));
}
public ResolvableMethod mockCall(Consumer<T> invoker) {
@@ -483,8 +486,9 @@ public final class ResolvableMethod {
}
private String formatFilters() {
return this.filters.stream().map(Object::toString)
.collect(Collectors.joining(",\n\t\t", "[\n\t\t", "\n\t]"));
return this.filters.stream()
.map(Object::toString)
.collect(Collectors.joining(",\n\t\t", "[\n\t\t", "\n\t]"));
}
}

View File

@@ -98,35 +98,35 @@ public class AuthenticationPrincipalArgumentResolverTests {
public void resolveArgumentString() throws Exception {
setAuthenticationPrincipal("john");
assertThat(this.resolver.resolveArgument(showUserAnnotationString(), null, null, null))
.isEqualTo(this.expectedPrincipal);
.isEqualTo(this.expectedPrincipal);
}
@Test
public void resolveArgumentPrincipalStringOnObject() throws Exception {
setAuthenticationPrincipal("john");
assertThat(this.resolver.resolveArgument(showUserAnnotationObject(), null, null, null))
.isEqualTo(this.expectedPrincipal);
.isEqualTo(this.expectedPrincipal);
}
@Test
public void resolveArgumentUserDetails() throws Exception {
setAuthenticationPrincipal(new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER")));
assertThat(this.resolver.resolveArgument(showUserAnnotationUserDetails(), null, null, null))
.isEqualTo(this.expectedPrincipal);
.isEqualTo(this.expectedPrincipal);
}
@Test
public void resolveArgumentCustomUserPrincipal() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
assertThat(this.resolver.resolveArgument(showUserAnnotationCustomUserPrincipal(), null, null, null))
.isEqualTo(this.expectedPrincipal);
.isEqualTo(this.expectedPrincipal);
}
@Test
public void resolveArgumentCustomAnnotation() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
assertThat(this.resolver.resolveArgument(showUserCustomAnnotation(), null, null, null))
.isEqualTo(this.expectedPrincipal);
.isEqualTo(this.expectedPrincipal);
}
@Test
@@ -144,7 +144,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
given(this.beanResolver.resolve(any(), eq("test"))).willReturn(principal.property);
this.expectedPrincipal = principal.property;
assertThat(this.resolver.resolveArgument(showUserSpelBean(), null, null, null))
.isEqualTo(this.expectedPrincipal);
.isEqualTo(this.expectedPrincipal);
verify(this.beanResolver).resolve(any(), eq("test"));
}
@@ -163,7 +163,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
setAuthenticationPrincipal(principal);
this.expectedPrincipal = principal.id;
assertThat(this.resolver.resolveArgument(showUserSpelPrimitive(), null, null, null))
.isEqualTo(this.expectedPrincipal);
.isEqualTo(this.expectedPrincipal);
}
@Test
@@ -175,22 +175,22 @@ public class AuthenticationPrincipalArgumentResolverTests {
@Test
public void resolveArgumentErrorOnInvalidType() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
assertThatExceptionOfType(ClassCastException.class).isThrownBy(
() -> this.resolver.resolveArgument(showUserAnnotationErrorOnInvalidType(), null, null, null));
assertThatExceptionOfType(ClassCastException.class)
.isThrownBy(() -> this.resolver.resolveArgument(showUserAnnotationErrorOnInvalidType(), null, null, null));
}
@Test
public void resolveArgumentCustomserErrorOnInvalidType() throws Exception {
setAuthenticationPrincipal(new CustomUserPrincipal());
assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> this.resolver
.resolveArgument(showUserAnnotationCurrentUserErrorOnInvalidType(), null, null, null));
.resolveArgument(showUserAnnotationCurrentUserErrorOnInvalidType(), null, null, null));
}
@Test
public void resolveArgumentObject() throws Exception {
setAuthenticationPrincipal(new Object());
assertThat(this.resolver.resolveArgument(showUserAnnotationObject(), null, null, null))
.isEqualTo(this.expectedPrincipal);
.isEqualTo(this.expectedPrincipal);
}
private MethodParameter showUserNoAnnotation() {
@@ -249,7 +249,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
private void setAuthenticationPrincipal(Object principal) {
this.expectedPrincipal = principal;
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken(this.expectedPrincipal, "password", "ROLE_USER"));
.setAuthentication(new TestingAuthenticationToken(this.expectedPrincipal, "password", "ROLE_USER"));
}
@Target({ ElementType.PARAMETER })

View File

@@ -78,14 +78,14 @@ public class CsrfTokenArgumentResolverTests {
@Test
public void resolveArgumentNotFound() throws Exception {
assertThat(this.resolver.resolveArgument(token(), this.mavContainer, this.webRequest, this.binderFactory))
.isNull();
.isNull();
}
@Test
public void resolveArgumentFound() throws Exception {
this.request.setAttribute(CsrfToken.class.getName(), this.token);
assertThat(this.resolver.resolveArgument(token(), this.mavContainer, this.webRequest, this.binderFactory))
.isSameAs(this.token);
.isSameAs(this.token);
}
private MethodParameter noToken() {

View File

@@ -84,7 +84,7 @@ public class CurrentSecurityContextArgumentResolverTests {
String principal = "custom_security_context";
setAuthenticationPrincipalWithCustomSecurityContext(principal);
CustomSecurityContext customSecurityContext = (CustomSecurityContext) this.resolver
.resolveArgument(showAnnotationWithCustomSecurityContext(), null, null, null);
.resolveArgument(showAnnotationWithCustomSecurityContext(), null, null, null);
assertThat(customSecurityContext.getAuthentication().getPrincipal()).isEqualTo(principal);
}
@@ -93,7 +93,7 @@ public class CurrentSecurityContextArgumentResolverTests {
String principal = "custom_security_context_type_match";
setAuthenticationPrincipalWithCustomSecurityContext(principal);
CustomSecurityContext customSecurityContext = (CustomSecurityContext) this.resolver
.resolveArgument(showAnnotationWithCustomSecurityContext(), null, null, null);
.resolveArgument(showAnnotationWithCustomSecurityContext(), null, null, null);
assertThat(customSecurityContext.getAuthentication().getPrincipal()).isEqualTo(principal);
}
@@ -103,7 +103,7 @@ public class CurrentSecurityContextArgumentResolverTests {
Authentication authentication = context.getAuthentication();
context.setAuthentication(null);
assertThat(this.resolver.resolveArgument(showSecurityContextAuthenticationAnnotation(), null, null, null))
.isNull();
.isNull();
context.setAuthentication(authentication);
}
@@ -112,7 +112,7 @@ public class CurrentSecurityContextArgumentResolverTests {
String principal = "john";
setAuthenticationPrincipal(principal);
Authentication auth1 = (Authentication) this.resolver
.resolveArgument(showSecurityContextAuthenticationAnnotation(), null, null, null);
.resolveArgument(showSecurityContextAuthenticationAnnotation(), null, null, null);
assertThat(auth1.getPrincipal()).isEqualTo(principal);
}
@@ -121,7 +121,7 @@ public class CurrentSecurityContextArgumentResolverTests {
String principal = "john";
given(this.beanResolver.resolve(any(), eq("test"))).willReturn(principal);
assertThat(this.resolver.resolveArgument(showSecurityContextAuthenticationWithBean(), null, null, null))
.isEqualTo(principal);
.isEqualTo(principal);
verify(this.beanResolver).resolve(any(), eq("test"));
}
@@ -131,7 +131,7 @@ public class CurrentSecurityContextArgumentResolverTests {
Authentication authentication = context.getAuthentication();
context.setAuthentication(null);
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> this.resolver
.resolveArgument(showSecurityContextAuthenticationWithPrincipal(), null, null, null));
.resolveArgument(showSecurityContextAuthenticationWithPrincipal(), null, null, null));
context.setAuthentication(authentication);
}
@@ -151,7 +151,7 @@ public class CurrentSecurityContextArgumentResolverTests {
String principal = "smith";
setAuthenticationPrincipal(principal);
String principalResult = (String) this.resolver
.resolveArgument(showSecurityContextAuthenticationWithPrincipal(), null, null, null);
.resolveArgument(showSecurityContextAuthenticationWithPrincipal(), null, null, null);
assertThat(principalResult).isEqualTo(principal);
}
@@ -167,7 +167,7 @@ public class CurrentSecurityContextArgumentResolverTests {
String principal = "invalid_type_implicit";
setAuthenticationPrincipal(principal);
assertThat(this.resolver.resolveArgument(showSecurityContextErrorOnInvalidTypeImplicit(), null, null, null))
.isNull();
.isNull();
}
@Test
@@ -175,7 +175,7 @@ public class CurrentSecurityContextArgumentResolverTests {
String principal = "invalid_type_false";
setAuthenticationPrincipal(principal);
assertThat(this.resolver.resolveArgument(showSecurityContextErrorOnInvalidTypeFalse(), null, null, null))
.isNull();
.isNull();
}
@Test
@@ -203,13 +203,13 @@ public class CurrentSecurityContextArgumentResolverTests {
@Test
public void metaAnnotationWhenCurrentSecurityWithErrorOnInvalidTypeThenInjectSecurityContext() {
assertThat(this.resolver.resolveArgument(showCurrentSecurityWithErrorOnInvalidType(), null, null, null))
.isNotNull();
.isNotNull();
}
@Test
public void metaAnnotationWhenCurrentSecurityWithErrorOnInvalidTypeThenMisMatch() {
assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> this.resolver
.resolveArgument(showCurrentSecurityWithErrorOnInvalidTypeMisMatch(), null, null, null));
.resolveArgument(showCurrentSecurityWithErrorOnInvalidTypeMisMatch(), null, null, null));
}
private MethodParameter showSecurityContextNoAnnotation() {
@@ -283,7 +283,7 @@ public class CurrentSecurityContextArgumentResolverTests {
private void setAuthenticationPrincipal(Object principal) {
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken(principal, "password", "ROLE_USER"));
.setAuthentication(new TestingAuthenticationToken(principal, "password", "ROLE_USER"));
}
private void setAuthenticationPrincipalWithCustomSecurityContext(Object principal) {

View File

@@ -97,7 +97,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
MethodParameter parameter = this.authenticationPrincipal.arg(String.class);
given(this.authentication.getPrincipal()).willReturn("user");
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
assertThat(argument.block()).isEqualTo(this.authentication.getPrincipal());
}
@@ -114,17 +114,19 @@ public class AuthenticationPrincipalArgumentResolverTests {
MethodParameter parameter = this.authenticationPrincipal.arg(Mono.class, String.class);
given(this.authentication.getPrincipal()).willReturn("user");
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
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);
MethodParameter parameter = ResolvableMethod.on(getClass())
.named("authenticationPrincipalNoGeneric")
.build()
.arg(Mono.class);
given(this.authentication.getPrincipal()).willReturn("user");
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
assertThat(argument.cast(Mono.class).block().block()).isEqualTo(this.authentication.getPrincipal());
}
@@ -134,7 +136,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
MethodParameter parameter = this.spel.arg(Long.class);
given(this.authentication.getPrincipal()).willReturn(user);
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
assertThat(argument.block()).isEqualTo(user.getId());
}
@@ -144,7 +146,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
MethodParameter parameter = this.spelPrimitive.arg(int.class);
given(this.authentication.getPrincipal()).willReturn(user);
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
assertThat(argument.block()).isEqualTo(user.getId());
}
@@ -155,7 +157,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
given(this.authentication.getPrincipal()).willReturn(user);
given(this.beanResolver.resolve(any(), eq("beanName"))).willReturn(new Bean());
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
assertThat(argument.block()).isEqualTo(user.getId());
}
@@ -164,37 +166,43 @@ public class AuthenticationPrincipalArgumentResolverTests {
MethodParameter parameter = this.meta.arg(String.class);
given(this.authentication.getPrincipal()).willReturn("user");
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
assertThat(argument.block()).isEqualTo("user");
}
@Test
public void resolveArgumentWhenErrorOnInvalidTypeImplicit() {
MethodParameter parameter = ResolvableMethod.on(getClass()).named("errorOnInvalidTypeWhenImplicit").build()
.arg(Integer.class);
MethodParameter parameter = ResolvableMethod.on(getClass())
.named("errorOnInvalidTypeWhenImplicit")
.build()
.arg(Integer.class);
given(this.authentication.getPrincipal()).willReturn("user");
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
assertThat(argument.block()).isNull();
}
@Test
public void resolveArgumentWhenErrorOnInvalidTypeExplicitFalse() {
MethodParameter parameter = ResolvableMethod.on(getClass()).named("errorOnInvalidTypeWhenExplicitFalse").build()
.arg(Integer.class);
MethodParameter parameter = ResolvableMethod.on(getClass())
.named("errorOnInvalidTypeWhenExplicitFalse")
.build()
.arg(Integer.class);
given(this.authentication.getPrincipal()).willReturn("user");
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
assertThat(argument.block()).isNull();
}
@Test
public void resolveArgumentWhenErrorOnInvalidTypeExplicitTrue() {
MethodParameter parameter = ResolvableMethod.on(getClass()).named("errorOnInvalidTypeWhenExplicitTrue").build()
.arg(Integer.class);
MethodParameter parameter = ResolvableMethod.on(getClass())
.named("errorOnInvalidTypeWhenExplicitTrue")
.build()
.arg(Integer.class);
given(this.authentication.getPrincipal()).willReturn("user");
Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> argument.block());
}

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