Remove restricted static imports

Replace static imports with class referenced methods. With the exception
of a few well known static imports, checkstyle restricts the static
imports that a class can use. For example, `asList(...)` would be
replaced with `Arrays.asList(...)`.

Issue gh-8945
This commit is contained in:
Phillip Webb
2020-07-27 21:34:26 -07:00
committed by Rob Winch
parent 9a3fa6e812
commit e9130489a6
252 changed files with 2216 additions and 2222 deletions

View File

@@ -40,9 +40,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.DEFAULT_PARAMETER;
import static org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY;
import static org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.TWO_WEEKS_S;
/**
* Tests
@@ -110,7 +107,7 @@ public class TokenBasedRememberMeServicesTests {
Authentication result = this.services.autoLogin(new MockHttpServletRequest(), response);
assertThat(result).isNull();
// No cookie set
assertThat(response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull();
assertThat(response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull();
}
@Test
@@ -123,27 +120,28 @@ public class TokenBasedRememberMeServicesTests {
Authentication result = this.services.autoLogin(request, response);
assertThat(result).isNull();
assertThat(response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull();
assertThat(response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull();
}
@Test
public void autoLoginReturnsNullForExpiredCookieAndClearsCookie() {
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForToken(
System.currentTimeMillis() - 1000000, "someone", "password", "key"));
Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
generateCorrectCookieContentForToken(System.currentTimeMillis() - 1000000, "someone", "password",
"key"));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(this.services.autoLogin(request, response)).isNull();
Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
assertThat(returnedCookie.getMaxAge()).isZero();
}
@Test
public void autoLoginReturnsNullAndClearsCookieIfMissingThreeTokensInCookieValue() {
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
new String(Base64.encodeBase64("x".getBytes())));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
@@ -151,21 +149,22 @@ public class TokenBasedRememberMeServicesTests {
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(this.services.autoLogin(request, response)).isNull();
Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
assertThat(returnedCookie.getMaxAge()).isZero();
}
@Test
public void autoLoginClearsNonBase64EncodedCookie() {
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, "NOT_BASE_64_ENCODED");
Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
"NOT_BASE_64_ENCODED");
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(this.services.autoLogin(request, response)).isNull();
Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
assertThat(returnedCookie.getMaxAge()).isZero();
}
@@ -173,8 +172,9 @@ public class TokenBasedRememberMeServicesTests {
@Test
public void autoLoginClearsCookieIfSignatureBlocksDoesNotMatchExpectedValue() {
udsWillReturnUser();
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForToken(
System.currentTimeMillis() + 1000000, "someone", "password", "WRONG_KEY"));
Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
generateCorrectCookieContentForToken(System.currentTimeMillis() + 1000000, "someone", "password",
"WRONG_KEY"));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
@@ -182,14 +182,14 @@ public class TokenBasedRememberMeServicesTests {
assertThat(this.services.autoLogin(request, response)).isNull();
Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
assertThat(returnedCookie.getMaxAge()).isZero();
}
@Test
public void autoLoginClearsCookieIfTokenDoesNotContainANumberInCookieValue() {
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
new String(Base64.encodeBase64("username:NOT_A_NUMBER:signature".getBytes())));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
@@ -197,7 +197,7 @@ public class TokenBasedRememberMeServicesTests {
MockHttpServletResponse response = new MockHttpServletResponse();
assertThat(this.services.autoLogin(request, response)).isNull();
Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
assertThat(returnedCookie.getMaxAge()).isZero();
}
@@ -205,8 +205,9 @@ public class TokenBasedRememberMeServicesTests {
@Test
public void autoLoginClearsCookieIfUserNotFound() {
udsWillThrowNotFound();
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForToken(
System.currentTimeMillis() + 1000000, "someone", "password", "key"));
Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
generateCorrectCookieContentForToken(System.currentTimeMillis() + 1000000, "someone", "password",
"key"));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
@@ -214,7 +215,7 @@ public class TokenBasedRememberMeServicesTests {
assertThat(this.services.autoLogin(request, response)).isNull();
Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(returnedCookie).isNotNull();
assertThat(returnedCookie.getMaxAge()).isZero();
}
@@ -222,8 +223,9 @@ public class TokenBasedRememberMeServicesTests {
@Test(expected = IllegalArgumentException.class)
public void autoLoginClearsCookieIfUserServiceMisconfigured() {
udsWillReturnNull();
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForToken(
System.currentTimeMillis() + 1000000, "someone", "password", "key"));
Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
generateCorrectCookieContentForToken(System.currentTimeMillis() + 1000000, "someone", "password",
"key"));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
@@ -235,8 +237,9 @@ public class TokenBasedRememberMeServicesTests {
@Test
public void autoLoginWithValidTokenAndUserSucceeds() {
udsWillReturnUser();
Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForToken(
System.currentTimeMillis() + 1000000, "someone", "password", "key"));
Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
generateCorrectCookieContentForToken(System.currentTimeMillis() + 1000000, "someone", "password",
"key"));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(cookie);
@@ -254,7 +257,7 @@ public class TokenBasedRememberMeServicesTests {
assertThat(this.services.getKey()).isEqualTo("key");
assertThat(this.services.getParameter()).isEqualTo(DEFAULT_PARAMETER);
assertThat(this.services.getParameter()).isEqualTo(AbstractRememberMeServices.DEFAULT_PARAMETER);
this.services.setParameter("some_param");
assertThat(this.services.getParameter()).isEqualTo("some_param");
@@ -268,7 +271,7 @@ public class TokenBasedRememberMeServicesTests {
MockHttpServletResponse response = new MockHttpServletResponse();
this.services.loginFail(request, response);
Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(cookie).isNotNull();
assertThat(cookie.getMaxAge()).isZero();
}
@@ -278,12 +281,12 @@ public class TokenBasedRememberMeServicesTests {
TokenBasedRememberMeServices services = new TokenBasedRememberMeServices("key",
new AbstractRememberMeServicesTests.MockUserDetailsService(null, false));
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter(DEFAULT_PARAMETER, "false");
request.addParameter(AbstractRememberMeServices.DEFAULT_PARAMETER, "false");
MockHttpServletResponse response = new MockHttpServletResponse();
services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password", "ROLE_ABC"));
Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(cookie).isNull();
}
@@ -298,7 +301,7 @@ public class TokenBasedRememberMeServicesTests {
this.services.loginSuccess(request, response,
new TestingAuthenticationToken("someone", "password", "ROLE_ABC"));
Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
String expiryTime = this.services.decodeCookie(cookie.getValue())[1];
long expectedExpiryTime = 1000L * 500000000;
expectedExpiryTime += System.currentTimeMillis();
@@ -318,7 +321,7 @@ public class TokenBasedRememberMeServicesTests {
this.services.loginSuccess(request, response,
new TestingAuthenticationToken("someone", "password", "ROLE_ABC"));
Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(cookie).isNotNull();
assertThat(cookie.getMaxAge()).isEqualTo(this.services.getTokenValiditySeconds());
assertThat(Base64.isArrayByteBase64(cookie.getValue().getBytes())).isTrue();
@@ -336,18 +339,18 @@ public class TokenBasedRememberMeServicesTests {
@Test
public void negativeValidityPeriodIsSetOnCookieButExpiryTimeRemainsAtTwoWeeks() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter(DEFAULT_PARAMETER, "true");
request.addParameter(AbstractRememberMeServices.DEFAULT_PARAMETER, "true");
MockHttpServletResponse response = new MockHttpServletResponse();
this.services.setTokenValiditySeconds(-1);
this.services.loginSuccess(request, response,
new TestingAuthenticationToken("someone", "password", "ROLE_ABC"));
Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertThat(cookie).isNotNull();
// Check the expiry time is within 50ms of two weeks from current time
assertThat(determineExpiryTimeFromBased64EncodedToken(cookie.getValue())
- System.currentTimeMillis() > TWO_WEEKS_S - 50).isTrue();
- System.currentTimeMillis() > AbstractRememberMeServices.TWO_WEEKS_S - 50).isTrue();
assertThat(cookie.getMaxAge()).isEqualTo(-1);
assertThat(Base64.isArrayByteBase64(cookie.getValue().getBytes())).isTrue();
}

View File

@@ -23,7 +23,7 @@ import org.junit.Test;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.hamcrest.core.StringContains.containsString;
import static org.hamcrest.CoreMatchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;

View File

@@ -40,11 +40,11 @@ import static org.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willDoNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.when;
/**
* @author Rob Winch
@@ -61,7 +61,7 @@ public class AbstractSecurityWebApplicationInitializerTests {
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
}.onStartup(context);
@@ -80,7 +80,7 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer(MyRootConfiguration.class) {
}.onStartup(context);
@@ -99,7 +99,7 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
@@ -122,7 +122,7 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
@@ -146,7 +146,7 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
@@ -184,9 +184,9 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
when(context.addFilter(anyString(), eq(filter1))).thenReturn(registration);
when(context.addFilter(anyString(), eq(filter2))).thenReturn(registration);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter1))).willReturn(registration);
given(context.addFilter(anyString(), eq(filter2))).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
@@ -212,7 +212,7 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
@@ -235,7 +235,7 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
@@ -256,8 +256,8 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
when(context.addFilter(anyString(), eq(filter))).thenReturn(registration);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter))).willReturn(registration);
assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
@@ -279,9 +279,9 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
when(context.addFilter(anyString(), eq(filter1))).thenReturn(registration);
when(context.addFilter(anyString(), eq(filter2))).thenReturn(registration);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter1))).willReturn(registration);
given(context.addFilter(anyString(), eq(filter2))).willReturn(registration);
new AbstractSecurityWebApplicationInitializer() {
@Override
@@ -305,7 +305,7 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
@@ -328,7 +328,7 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
@@ -349,8 +349,8 @@ public class AbstractSecurityWebApplicationInitializerTests {
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
when(context.addFilter(anyString(), eq(filter))).thenReturn(registration);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
given(context.addFilter(anyString(), eq(filter))).willReturn(registration);
assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() {
@Override
@@ -369,12 +369,12 @@ public class AbstractSecurityWebApplicationInitializerTests {
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
ArgumentCaptor<Set<SessionTrackingMode>> modesCaptor = ArgumentCaptor
.forClass(new HashSet<SessionTrackingMode>() {
}.getClass());
doNothing().when(context).setSessionTrackingModes(modesCaptor.capture());
willDoNothing().given(context).setSessionTrackingModes(modesCaptor.capture());
new AbstractSecurityWebApplicationInitializer() {
}.onStartup(context);
@@ -392,12 +392,12 @@ public class AbstractSecurityWebApplicationInitializerTests {
FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class);
ArgumentCaptor<DelegatingFilterProxy> proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class);
when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration);
given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration);
ArgumentCaptor<Set<SessionTrackingMode>> modesCaptor = ArgumentCaptor
.forClass(new HashSet<SessionTrackingMode>() {
}.getClass());
doNothing().when(context).setSessionTrackingModes(modesCaptor.capture());
willDoNothing().given(context).setSessionTrackingModes(modesCaptor.capture());
new AbstractSecurityWebApplicationInitializer() {
@Override

View File

@@ -45,12 +45,11 @@ import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.springframework.security.web.context.HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY;
/**
* @author Luke Taylor
@@ -153,7 +152,7 @@ public class HttpSessionSecurityContextRepositoryTests {
SecurityContext ctx = SecurityContextHolder.getContext();
ctx.setAuthentication(this.testToken);
HttpSession session = mock(HttpSession.class);
when(session.getAttribute(SPRING_SECURITY_CONTEXT_KEY)).thenReturn(ctx);
given(session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)).willReturn(ctx);
request.setSession(session);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse());
assertThat(repo.loadContext(holder)).isSameAs(ctx);
@@ -164,7 +163,7 @@ public class HttpSessionSecurityContextRepositoryTests {
repo.saveContext(ctx, holder.getRequest(), holder.getResponse());
// Must be called even though the value in the local VM is already the same
verify(session).setAttribute(SPRING_SECURITY_CONTEXT_KEY, ctx);
verify(session).setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, ctx);
}
@Test
@@ -172,7 +171,8 @@ public class HttpSessionSecurityContextRepositoryTests {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
MockHttpServletRequest request = new MockHttpServletRequest();
SecurityContextHolder.getContext().setAuthentication(this.testToken);
request.getSession().setAttribute(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);
@@ -192,7 +192,8 @@ public class HttpSessionSecurityContextRepositoryTests {
context.setAuthentication(this.testToken);
repo.saveContext(context, holder.getRequest(), holder.getResponse());
assertThat(request.getSession(false)).isNotNull();
assertThat(request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isEqualTo(context);
assertThat(request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY))
.isEqualTo(context);
}
@Test
@@ -328,7 +329,7 @@ public class HttpSessionSecurityContextRepositoryTests {
MockHttpServletRequest request = new MockHttpServletRequest();
HttpServletResponse response = mock(HttpServletResponse.class);
ServletOutputStream outputstream = mock(ServletOutputStream.class);
when(response.getOutputStream()).thenReturn(outputstream);
given(response.getOutputStream()).willReturn(outputstream);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(this.testToken);
@@ -344,7 +345,7 @@ public class HttpSessionSecurityContextRepositoryTests {
MockHttpServletRequest request = new MockHttpServletRequest();
HttpServletResponse response = mock(HttpServletResponse.class);
ServletOutputStream outputstream = mock(ServletOutputStream.class);
when(response.getOutputStream()).thenReturn(outputstream);
given(response.getOutputStream()).willReturn(outputstream);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
SecurityContextHolder.setContext(repo.loadContext(holder));
SecurityContextHolder.getContext().setAuthentication(this.testToken);
@@ -387,13 +388,15 @@ public class HttpSessionSecurityContextRepositoryTests {
MockHttpServletRequest request = new MockHttpServletRequest();
SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext();
ctxInSession.setAuthentication(this.testToken);
request.getSession().setAttribute(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()));
repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse());
assertThat(request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isNull();
assertThat(request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY))
.isNull();
}
@Test
@@ -420,11 +423,13 @@ public class HttpSessionSecurityContextRepositoryTests {
repo.loadContext(holder);
SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext();
ctxInSession.setAuthentication(this.testToken);
request.getSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY, ctxInSession);
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(SPRING_SECURITY_CONTEXT_KEY));
assertThat(ctxInSession).isSameAs(
request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY));
}
// SEC-3070
@@ -434,7 +439,8 @@ public class HttpSessionSecurityContextRepositoryTests {
MockHttpServletRequest request = new MockHttpServletRequest();
SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext();
ctxInSession.setAuthentication(this.testToken);
request.getSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY, ctxInSession);
request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
ctxInSession);
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse());
repo.loadContext(holder);
@@ -442,7 +448,8 @@ public class HttpSessionSecurityContextRepositoryTests {
ctxInSession.setAuthentication(null);
repo.saveContext(ctxInSession, holder.getRequest(), holder.getResponse());
assertThat(request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isNull();
assertThat(request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY))
.isNull();
}
@Test
@@ -527,7 +534,8 @@ public class HttpSessionSecurityContextRepositoryTests {
new HttpServletResponseWrapper(holder.getResponse()));
assertThat(request.getSession(false)).isNotNull();
assertThat(request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isEqualTo(context);
assertThat(request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY))
.isEqualTo(context);
}
@Test(expected = IllegalStateException.class)

View File

@@ -23,12 +23,9 @@ import org.junit.rules.ExpectedException;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.CACHE;
import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.COOKIES;
import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.EXECUTION_CONTEXTS;
import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.STORAGE;
/**
* @author Rafiullah Hamedy
@@ -64,7 +61,7 @@ public class ClearSiteDataHeaderWriterTests {
@Test
public void writeHeaderWhenRequestNotSecureThenHeaderIsNotPresent() {
this.request.setSecure(false);
ClearSiteDataHeaderWriter headerWriter = new ClearSiteDataHeaderWriter(CACHE);
ClearSiteDataHeaderWriter headerWriter = new ClearSiteDataHeaderWriter(Directive.CACHE);
headerWriter.writeHeaders(this.request, this.response);
assertThat(this.response.getHeader(HEADER_NAME)).isNull();
@@ -72,7 +69,7 @@ public class ClearSiteDataHeaderWriterTests {
@Test
public void writeHeaderWhenRequestIsSecureThenHeaderValueMatchesPassedSource() {
ClearSiteDataHeaderWriter headerWriter = new ClearSiteDataHeaderWriter(STORAGE);
ClearSiteDataHeaderWriter headerWriter = new ClearSiteDataHeaderWriter(Directive.STORAGE);
headerWriter.writeHeaders(this.request, this.response);
assertThat(this.response.getHeader(HEADER_NAME)).isEqualTo("\"storage\"");
@@ -80,8 +77,8 @@ public class ClearSiteDataHeaderWriterTests {
@Test
public void writeHeaderWhenRequestIsSecureThenHeaderValueMatchesPassedSources() {
ClearSiteDataHeaderWriter headerWriter = new ClearSiteDataHeaderWriter(CACHE, COOKIES, STORAGE,
EXECUTION_CONTEXTS);
ClearSiteDataHeaderWriter headerWriter = new ClearSiteDataHeaderWriter(Directive.CACHE, Directive.COOKIES,
Directive.STORAGE, Directive.EXECUTION_CONTEXTS);
headerWriter.writeHeaders(this.request, this.response);
assertThat(this.response.getHeader(HEADER_NAME))

View File

@@ -27,6 +27,7 @@ import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.aopalliance.intercept.MethodInterceptor;
import org.apache.commons.logging.Log;
@@ -54,8 +55,6 @@ import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.ValueConstants;
import static java.util.stream.Collectors.joining;
/**
* Convenience class to resolve method parameters from hints.
*
@@ -211,13 +210,14 @@ public final class ResolvableMethod {
private String formatMethod() {
return this.method().getName() + Arrays.stream(this.method.getParameters()).map(this::formatParameter)
.collect(joining(",\n\t", "(\n\t", "\n)"));
.collect(Collectors.joining(",\n\t", "(\n\t", "\n)"));
}
private String formatParameter(Parameter param) {
Annotation[] annot = param.getAnnotations();
return annot.length > 0
? Arrays.stream(annot).map(this::formatAnnotation).collect(joining(",", "[", "]")) + " " + param
? Arrays.stream(annot).map(this::formatAnnotation).collect(Collectors.joining(",", "[", "]")) + " "
+ param
: param.toString();
}
@@ -413,8 +413,8 @@ public final class ResolvableMethod {
}
private String formatMethods(Set<Method> methods) {
return "\nMatched:\n"
+ methods.stream().map(Method::toGenericString).collect(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) {
@@ -490,7 +490,8 @@ public final class ResolvableMethod {
}
private String formatFilters() {
return this.filters.stream().map(Object::toString).collect(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

@@ -31,7 +31,6 @@ import org.springframework.security.web.server.csrf.DefaultCsrfToken;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.security.web.reactive.result.view.CsrfRequestDataValueProcessor.DEFAULT_CSRF_ATTR_NAME;
/**
* @author Rob Winch
@@ -50,7 +49,7 @@ public class CsrfRequestDataValueProcessorTests {
@Before
public void setup() {
this.expected.put(this.token.getParameterName(), this.token.getToken());
this.exchange.getAttributes().put(DEFAULT_CSRF_ATTR_NAME, this.token);
this.exchange.getAttributes().put(CsrfRequestDataValueProcessor.DEFAULT_CSRF_ATTR_NAME, this.token);
}
@Test
@@ -120,7 +119,7 @@ public class CsrfRequestDataValueProcessorTests {
@Test
public void createGetExtraHiddenFieldsHasCsrfToken() {
CsrfToken token = new DefaultCsrfToken("1", "a", "b");
this.exchange.getAttributes().put(DEFAULT_CSRF_ATTR_NAME, token);
this.exchange.getAttributes().put(CsrfRequestDataValueProcessor.DEFAULT_CSRF_ATTR_NAME, token);
Map<String, String> expected = new HashMap<>();
expected.put(token.getParameterName(), token.getToken());

View File

@@ -39,6 +39,7 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
@@ -61,8 +62,6 @@ import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.springframework.security.core.context.ReactiveSecurityContextHolder.withSecurityContext;
import static org.springframework.security.web.server.authentication.SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR;
/**
* @author Artur Otrzonsek
@@ -136,7 +135,8 @@ public class SwitchUserWebFilterTests {
// when
this.switchUserWebFilter.filter(exchange, chain)
.subscriberContext(withSecurityContext(Mono.just(securityContext))).block();
.subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext)))
.block();
// then
verifyNoInteractions(chain);
@@ -156,7 +156,7 @@ public class SwitchUserWebFilterTests {
assertThat(switchUserAuthentication.getName()).isEqualTo(targetUsername);
assertThat(switchUserAuthentication.getAuthorities()).anyMatch(SwitchUserGrantedAuthority.class::isInstance);
assertThat(switchUserAuthentication.getAuthorities())
.anyMatch((a) -> a.getAuthority().contains(ROLE_PREVIOUS_ADMINISTRATOR));
.anyMatch((a) -> a.getAuthority().contains(SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR));
assertThat(
switchUserAuthentication.getAuthorities().stream().filter(a -> a instanceof SwitchUserGrantedAuthority)
.map(a -> ((SwitchUserGrantedAuthority) a).getSource()).map(Principal::getName))
@@ -169,8 +169,8 @@ public class SwitchUserWebFilterTests {
final Authentication originalAuthentication = new UsernamePasswordAuthenticationToken("origPrincipal",
"origCredentials");
final GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority(ROLE_PREVIOUS_ADMINISTRATOR,
originalAuthentication);
final GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority(
SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR, originalAuthentication);
final Authentication switchUserAuthentication = new UsernamePasswordAuthenticationToken("switchPrincipal",
"switchCredentials", Collections.singleton(switchAuthority));
@@ -191,7 +191,8 @@ public class SwitchUserWebFilterTests {
// when
this.switchUserWebFilter.filter(exchange, chain)
.subscriberContext(withSecurityContext(Mono.just(securityContext))).block();
.subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext)))
.block();
// then
final ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
@@ -221,7 +222,8 @@ public class SwitchUserWebFilterTests {
// when
this.switchUserWebFilter.filter(exchange, chain)
.subscriberContext(withSecurityContext(Mono.just(securityContext))).block();
.subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext)))
.block();
verifyNoInteractions(chain);
}
@@ -241,7 +243,8 @@ public class SwitchUserWebFilterTests {
// when
this.switchUserWebFilter.filter(exchange, chain)
.subscriberContext(withSecurityContext(Mono.just(securityContext))).block();
.subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext)))
.block();
verify(this.failureHandler).onAuthenticationFailure(any(WebFilterExchange.class), any(DisabledException.class));
verifyNoInteractions(chain);
@@ -266,7 +269,8 @@ public class SwitchUserWebFilterTests {
// when then
this.switchUserWebFilter.filter(exchange, chain)
.subscriberContext(withSecurityContext(Mono.just(securityContext))).block();
.subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext)))
.block();
verifyNoInteractions(chain);
}
@@ -279,8 +283,8 @@ public class SwitchUserWebFilterTests {
final Authentication originalAuthentication = new UsernamePasswordAuthenticationToken("origPrincipal",
"origCredentials");
final GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority(ROLE_PREVIOUS_ADMINISTRATOR,
originalAuthentication);
final GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority(
SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR, originalAuthentication);
final Authentication switchUserAuthentication = new UsernamePasswordAuthenticationToken("switchPrincipal",
"switchCredentials", Collections.singleton(switchAuthority));
@@ -294,7 +298,8 @@ public class SwitchUserWebFilterTests {
// when
this.switchUserWebFilter.filter(exchange, chain)
.subscriberContext(withSecurityContext(Mono.just(securityContext))).block();
.subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext)))
.block();
// then
final ArgumentCaptor<SecurityContext> securityContextCaptor = ArgumentCaptor.forClass(SecurityContext.class);
@@ -329,7 +334,8 @@ public class SwitchUserWebFilterTests {
// when then
this.switchUserWebFilter.filter(exchange, chain)
.subscriberContext(withSecurityContext(Mono.just(securityContext))).block();
.subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext)))
.block();
verifyNoInteractions(chain);
}

View File

@@ -25,14 +25,13 @@ import reactor.core.publisher.Mono;
import org.springframework.security.web.server.authorization.ServerWebExchangeDelegatingServerAccessDeniedHandler.DelegateEntry;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult;
import org.springframework.web.server.ServerWebExchange;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult.match;
import static org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult.notMatch;
public class ServerWebExchangeDelegatingServerAccessDeniedHandlerTests {
@@ -55,7 +54,7 @@ public class ServerWebExchangeDelegatingServerAccessDeniedHandlerTests {
public void handleWhenNothingMatchesThenOnlyDefaultHandlerInvoked() {
ServerAccessDeniedHandler handler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
given(matcher.matches(this.exchange)).willReturn(notMatch());
given(matcher.matches(this.exchange)).willReturn(MatchResult.notMatch());
given(handler.handle(this.exchange, null)).willReturn(Mono.empty());
given(this.accessDeniedHandler.handle(this.exchange, null)).willReturn(Mono.empty());
@@ -75,7 +74,7 @@ public class ServerWebExchangeDelegatingServerAccessDeniedHandlerTests {
ServerWebExchangeMatcher firstMatcher = mock(ServerWebExchangeMatcher.class);
ServerAccessDeniedHandler secondHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher secondMatcher = mock(ServerWebExchangeMatcher.class);
given(firstMatcher.matches(this.exchange)).willReturn(match());
given(firstMatcher.matches(this.exchange)).willReturn(MatchResult.match());
given(firstHandler.handle(this.exchange, null)).willReturn(Mono.empty());
given(secondHandler.handle(this.exchange, null)).willReturn(Mono.empty());
@@ -98,8 +97,8 @@ public class ServerWebExchangeDelegatingServerAccessDeniedHandlerTests {
ServerWebExchangeMatcher firstMatcher = mock(ServerWebExchangeMatcher.class);
ServerAccessDeniedHandler secondHandler = mock(ServerAccessDeniedHandler.class);
ServerWebExchangeMatcher secondMatcher = mock(ServerWebExchangeMatcher.class);
given(firstMatcher.matches(this.exchange)).willReturn(notMatch());
given(secondMatcher.matches(this.exchange)).willReturn(match());
given(firstMatcher.matches(this.exchange)).willReturn(MatchResult.notMatch());
given(secondMatcher.matches(this.exchange)).willReturn(MatchResult.match());
given(firstHandler.handle(this.exchange, null)).willReturn(Mono.empty());
given(secondHandler.handle(this.exchange, null)).willReturn(Mono.empty());

View File

@@ -33,18 +33,16 @@ import org.springframework.security.web.server.util.matcher.ServerWebExchangeMat
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilterChain;
import org.springframework.web.server.WebSession;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.springframework.mock.web.server.MockServerWebExchange.from;
import static org.springframework.web.reactive.function.BodyInserters.fromMultipartData;
/**
* @author Rob Winch
@@ -64,9 +62,9 @@ public class CsrfWebFilterTests {
private CsrfWebFilter csrfFilter = new CsrfWebFilter();
private MockServerWebExchange get = from(MockServerHttpRequest.get("/"));
private MockServerWebExchange get = MockServerWebExchange.from(MockServerHttpRequest.get("/"));
private ServerWebExchange post = from(MockServerHttpRequest.post("/"));
private ServerWebExchange post = MockServerWebExchange.from(MockServerHttpRequest.post("/"));
@Test
public void filterWhenGetThenSessionNotCreatedAndChainContinues() {
@@ -108,7 +106,7 @@ public class CsrfWebFilterTests {
public void filterWhenPostAndEstablishedCsrfTokenAndRequestParamInvalidTokenThenCsrfException() {
this.csrfFilter.setCsrfTokenRepository(this.repository);
given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
this.post = from(MockServerHttpRequest.post("/")
this.post = MockServerWebExchange.from(MockServerHttpRequest.post("/")
.body(this.token.getParameterName() + "=" + this.token.getToken() + "INVALID"));
Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);
@@ -126,8 +124,9 @@ public class CsrfWebFilterTests {
this.csrfFilter.setCsrfTokenRepository(this.repository);
given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
given(this.repository.generateToken(any())).willReturn(Mono.just(this.token));
this.post = from(MockServerHttpRequest.post("/").contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(this.token.getParameterName() + "=" + this.token.getToken()));
this.post = MockServerWebExchange
.from(MockServerHttpRequest.post("/").contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(this.token.getParameterName() + "=" + this.token.getToken()));
Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);
@@ -140,7 +139,7 @@ public class CsrfWebFilterTests {
public void filterWhenPostAndEstablishedCsrfTokenAndHeaderInvalidTokenThenCsrfException() {
this.csrfFilter.setCsrfTokenRepository(this.repository);
given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
this.post = from(
this.post = MockServerWebExchange.from(
MockServerHttpRequest.post("/").header(this.token.getHeaderName(), this.token.getToken() + "INVALID"));
Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);
@@ -158,7 +157,8 @@ public class CsrfWebFilterTests {
this.csrfFilter.setCsrfTokenRepository(this.repository);
given(this.repository.loadToken(any())).willReturn(Mono.just(this.token));
given(this.repository.generateToken(any())).willReturn(Mono.just(this.token));
this.post = from(MockServerHttpRequest.post("/").header(this.token.getHeaderName(), this.token.getToken()));
this.post = MockServerWebExchange
.from(MockServerHttpRequest.post("/").header(this.token.getHeaderName(), this.token.getToken()));
Mono<Void> result = this.csrfFilter.filter(this.post, this.chain);
@@ -170,8 +170,8 @@ public class CsrfWebFilterTests {
@Test
// gh-8452
public void matchesRequireCsrfProtectionWhenNonStandardHTTPMethodIsUsed() {
MockServerWebExchange nonStandardHttpExchange = from(
MockServerHttpRequest.method("non-standard-http-method", "/"));
MockServerWebExchange nonStandardHttpExchange = MockServerWebExchange
.from(MockServerHttpRequest.method("non-standard-http-method", "/"));
ServerWebExchangeMatcher serverWebExchangeMatcher = CsrfWebFilter.DEFAULT_CSRF_MATCHER;
assertThat(serverWebExchangeMatcher.matches(nonStandardHttpExchange).map(MatchResult::isMatch).block())
@@ -186,7 +186,7 @@ public class CsrfWebFilterTests {
ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class);
this.csrfFilter.setRequireCsrfProtectionMatcher(matcher);
MockServerWebExchange exchange = from(MockServerHttpRequest.post("/post").build());
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/post").build());
CsrfWebFilter.skipExchange(exchange);
this.csrfFilter.filter(exchange, this.chain).block();
@@ -201,8 +201,8 @@ public class CsrfWebFilterTests {
WebTestClient client = WebTestClient.bindToController(new OkController()).webFilter(this.csrfFilter).build();
client.post().uri("/").contentType(MediaType.MULTIPART_FORM_DATA)
.body(fromMultipartData(this.token.getParameterName(), this.token.getToken())).exchange().expectStatus()
.isForbidden();
.body(BodyInserters.fromMultipartData(this.token.getParameterName(), this.token.getToken())).exchange()
.expectStatus().isForbidden();
}
@Test
@@ -215,8 +215,8 @@ public class CsrfWebFilterTests {
WebTestClient client = WebTestClient.bindToController(new OkController()).webFilter(this.csrfFilter).build();
client.post().uri("/").contentType(MediaType.MULTIPART_FORM_DATA)
.body(fromMultipartData(this.token.getParameterName(), this.token.getToken())).exchange().expectStatus()
.is2xxSuccessful();
.body(BodyInserters.fromMultipartData(this.token.getParameterName(), this.token.getToken())).exchange()
.expectStatus().is2xxSuccessful();
}
@Test

View File

@@ -26,8 +26,6 @@ import org.springframework.web.server.ServerWebExchange;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers.anyExchange;
import static org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers.pathMatchers;
/**
* @author Rob Winch
@@ -39,7 +37,7 @@ public class ServerWebExchangeMatchersTests {
@Test
public void pathMatchersWhenSingleAndSamePatternThenMatches() {
assertThat(pathMatchers("/").matches(this.exchange).block().isMatch()).isTrue();
assertThat(ServerWebExchangeMatchers.pathMatchers("/").matches(this.exchange).block().isMatch()).isTrue();
}
@Test
@@ -57,19 +55,21 @@ public class ServerWebExchangeMatchersTests {
@Test
public void pathMatchersWhenSingleAndDifferentPatternThenDoesNotMatch() {
assertThat(pathMatchers("/foobar").matches(this.exchange).block().isMatch()).isFalse();
assertThat(ServerWebExchangeMatchers.pathMatchers("/foobar").matches(this.exchange).block().isMatch())
.isFalse();
}
@Test
public void pathMatchersWhenMultiThenMatches() {
assertThat(pathMatchers("/foobar", "/").matches(this.exchange).block().isMatch()).isTrue();
assertThat(ServerWebExchangeMatchers.pathMatchers("/foobar", "/").matches(this.exchange).block().isMatch())
.isTrue();
}
@Test
public void anyExchangeWhenMockThenMatches() {
ServerWebExchange mockExchange = mock(ServerWebExchange.class);
assertThat(anyExchange().matches(mockExchange).block().isMatch()).isTrue();
assertThat(ServerWebExchangeMatchers.anyExchange().matches(mockExchange).block().isMatch()).isTrue();
verifyZeroInteractions(mockExchange);
}
@@ -83,7 +83,7 @@ public class ServerWebExchangeMatchersTests {
*/
@Test
public void anyExchangeWhenTwoCreatedThenDifferentToPreventIssuesInMap() {
assertThat(anyExchange()).isNotEqualTo(anyExchange());
assertThat(ServerWebExchangeMatchers.anyExchange()).isNotEqualTo(ServerWebExchangeMatchers.anyExchange());
}
}

View File

@@ -55,12 +55,12 @@ import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.doThrow;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.verifyZeroInteractions;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.mockito.Mockito.verifyZeroInteractions;
/**
* Tests {@link SecurityContextHolderAwareRequestFilter}.
@@ -159,7 +159,7 @@ public class SecurityContextHolderAwareRequestFilterTests {
@Test
public void authenticateNullEntryPointTrue() throws Exception {
when(this.request.authenticate(this.response)).thenReturn(true);
given(this.request.authenticate(this.response)).willReturn(true);
this.filter.setAuthenticationEntryPoint(null);
this.filter.afterPropertiesSet();
@@ -171,8 +171,8 @@ public class SecurityContextHolderAwareRequestFilterTests {
@Test
public void login() throws Exception {
TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password", "ROLE_USER");
when(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class)))
.thenReturn(expectedAuth);
given(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class)))
.willReturn(expectedAuth);
wrappedRequest().login(expectedAuth.getName(), String.valueOf(expectedAuth.getCredentials()));
@@ -185,8 +185,8 @@ public class SecurityContextHolderAwareRequestFilterTests {
@Test
public void loginWithExistingUser() throws Exception {
TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password", "ROLE_USER");
when(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class)))
.thenReturn(new TestingAuthenticationToken("newuser", "not be found", "ROLE_USER"));
given(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class)))
.willReturn(new TestingAuthenticationToken("newuser", "not be found", "ROLE_USER"));
SecurityContextHolder.getContext().setAuthentication(expectedAuth);
try {
@@ -203,8 +203,8 @@ public class SecurityContextHolderAwareRequestFilterTests {
@Test
public void loginFail() throws Exception {
AuthenticationException authException = new BadCredentialsException("Invalid");
when(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class)))
.thenThrow(authException);
given(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class)))
.willThrow(authException);
try {
wrappedRequest().login("invalid", "credentials");
@@ -241,7 +241,7 @@ public class SecurityContextHolderAwareRequestFilterTests {
String username = "username";
String password = "password";
ServletException authException = new ServletException("Failed Login");
doThrow(authException).when(this.request).login(username, password);
willThrow(authException).given(this.request).login(username, password);
try {
wrappedRequest().login(username, password);
@@ -292,7 +292,7 @@ public class SecurityContextHolderAwareRequestFilterTests {
context.setAuthentication(expectedAuth);
SecurityContextHolder.setContext(context);
AsyncContext asyncContext = mock(AsyncContext.class);
when(this.request.getAsyncContext()).thenReturn(asyncContext);
given(this.request.getAsyncContext()).willReturn(asyncContext);
Runnable runnable = () -> {
};
@@ -314,7 +314,7 @@ public class SecurityContextHolderAwareRequestFilterTests {
context.setAuthentication(expectedAuth);
SecurityContextHolder.setContext(context);
AsyncContext asyncContext = mock(AsyncContext.class);
when(this.request.startAsync()).thenReturn(asyncContext);
given(this.request.startAsync()).willReturn(asyncContext);
Runnable runnable = () -> {
};
@@ -336,7 +336,7 @@ public class SecurityContextHolderAwareRequestFilterTests {
context.setAuthentication(expectedAuth);
SecurityContextHolder.setContext(context);
AsyncContext asyncContext = mock(AsyncContext.class);
when(this.request.startAsync(this.request, this.response)).thenReturn(asyncContext);
given(this.request.startAsync(this.request, this.response)).willReturn(asyncContext);
Runnable runnable = () -> {
};