Merge branch '5.8.x' into 6.0.x
Closes gh-13882
This commit is contained in:
+4
-4
@@ -40,9 +40,9 @@ class WithSecurityContextTestRuntimeHints implements TestRuntimeHintsRegistrar {
|
||||
@Override
|
||||
public void registerHints(RuntimeHints hints, Class<?> testClass, ClassLoader classLoader) {
|
||||
Stream.concat(getClassAnnotations(testClass), getMethodAnnotations(testClass))
|
||||
.filter(MergedAnnotation::isPresent)
|
||||
.map((withSecurityContext) -> withSecurityContext.getClass("factory"))
|
||||
.forEach((factory) -> registerDeclaredConstructors(hints, factory));
|
||||
.filter(MergedAnnotation::isPresent)
|
||||
.map((withSecurityContext) -> withSecurityContext.getClass("factory"))
|
||||
.forEach((factory) -> registerDeclaredConstructors(hints, factory));
|
||||
}
|
||||
|
||||
private Stream<MergedAnnotation<WithSecurityContext>> getClassAnnotations(Class<?> testClass) {
|
||||
@@ -51,7 +51,7 @@ class WithSecurityContextTestRuntimeHints implements TestRuntimeHintsRegistrar {
|
||||
|
||||
private Stream<MergedAnnotation<WithSecurityContext>> getMethodAnnotations(Class<?> testClass) {
|
||||
return Arrays.stream(testClass.getDeclaredMethods())
|
||||
.map((method) -> MergedAnnotations.from(method, SUPERCLASS).get(WithSecurityContext.class));
|
||||
.map((method) -> MergedAnnotations.from(method, SUPERCLASS).get(WithSecurityContext.class));
|
||||
}
|
||||
|
||||
private void registerDeclaredConstructors(RuntimeHints hints, Class<?> factory) {
|
||||
|
||||
+1
-1
@@ -84,7 +84,7 @@ public class ReactorContextTestExecutionListener extends DelegatingTestExecution
|
||||
private static class SecuritySubContext<T> implements CoreSubscriber<T> {
|
||||
|
||||
private static String CONTEXT_DEFAULTED_ATTR_NAME = SecuritySubContext.class.getName()
|
||||
.concat(".CONTEXT_DEFAULTED_ATTR_NAME");
|
||||
.concat(".CONTEXT_DEFAULTED_ATTR_NAME");
|
||||
|
||||
private final CoreSubscriber<T> delegate;
|
||||
|
||||
|
||||
+1
-1
@@ -38,7 +38,7 @@ import org.springframework.security.core.context.SecurityContextHolderStrategy;
|
||||
final class WithAnonymousUserSecurityContextFactory implements WithSecurityContextFactory<WithAnonymousUser> {
|
||||
|
||||
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
|
||||
.getContextHolderStrategy();
|
||||
.getContextHolderStrategy();
|
||||
|
||||
@Override
|
||||
public SecurityContext createSecurityContext(WithAnonymousUser withUser) {
|
||||
|
||||
@@ -47,7 +47,6 @@ import org.springframework.test.web.servlet.MockMvc;
|
||||
* </ul>
|
||||
*
|
||||
* @see WithUserDetails
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 4.0
|
||||
*/
|
||||
|
||||
+1
-1
@@ -42,7 +42,7 @@ import org.springframework.util.StringUtils;
|
||||
final class WithMockUserSecurityContextFactory implements WithSecurityContextFactory<WithMockUser> {
|
||||
|
||||
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
|
||||
.getContextHolderStrategy();
|
||||
.getContextHolderStrategy();
|
||||
|
||||
@Override
|
||||
public SecurityContext createSecurityContext(WithMockUser withUser) {
|
||||
|
||||
+4
-4
@@ -55,7 +55,7 @@ import org.springframework.test.web.servlet.MockMvc;
|
||||
public class WithSecurityContextTestExecutionListener extends AbstractTestExecutionListener {
|
||||
|
||||
static final String SECURITY_CONTEXT_ATTR_NAME = WithSecurityContextTestExecutionListener.class.getName()
|
||||
.concat(".SECURITY_CONTEXT");
|
||||
.concat(".SECURITY_CONTEXT");
|
||||
|
||||
static final SecurityContextHolderStrategy DEFAULT_SECURITY_CONTEXT_HOLDER_STRATEGY = new TestSecurityContextHolderStrategyAdapter();
|
||||
|
||||
@@ -101,7 +101,7 @@ public class WithSecurityContextTestExecutionListener extends AbstractTestExecut
|
||||
@Override
|
||||
public void beforeTestExecution(TestContext testContext) {
|
||||
Supplier<SecurityContext> supplier = (Supplier<SecurityContext>) testContext
|
||||
.removeAttribute(SECURITY_CONTEXT_ATTR_NAME);
|
||||
.removeAttribute(SECURITY_CONTEXT_ATTR_NAME);
|
||||
if (supplier != null) {
|
||||
this.securityContextHolderStrategyConverter.convert(testContext).setContext(supplier.get());
|
||||
}
|
||||
@@ -115,7 +115,7 @@ public class WithSecurityContextTestExecutionListener extends AbstractTestExecut
|
||||
|
||||
private TestSecurityContext createTestSecurityContext(Class<?> annotated, TestContext context) {
|
||||
TestContextAnnotationUtils.AnnotationDescriptor<WithSecurityContext> withSecurityContextDescriptor = TestContextAnnotationUtils
|
||||
.findAnnotationDescriptor(annotated, WithSecurityContext.class);
|
||||
.findAnnotationDescriptor(annotated, WithSecurityContext.class);
|
||||
if (withSecurityContextDescriptor == null) {
|
||||
return null;
|
||||
}
|
||||
@@ -133,7 +133,7 @@ public class WithSecurityContextTestExecutionListener extends AbstractTestExecut
|
||||
withSecurityContext = AnnotationUtils.synthesizeAnnotation(withSecurityContext, annotated);
|
||||
WithSecurityContextFactory factory = createFactory(withSecurityContext, context);
|
||||
Class<? extends Annotation> type = (Class<? extends Annotation>) GenericTypeResolver
|
||||
.resolveTypeArgument(factory.getClass(), WithSecurityContextFactory.class);
|
||||
.resolveTypeArgument(factory.getClass(), WithSecurityContextFactory.class);
|
||||
Annotation annotation = findAnnotation(annotated, type);
|
||||
Supplier<SecurityContext> supplier = () -> {
|
||||
try {
|
||||
|
||||
-1
@@ -46,7 +46,6 @@ import org.springframework.test.web.servlet.MockMvc;
|
||||
* </ul>
|
||||
*
|
||||
* @see WithMockUser
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 4.0
|
||||
*/
|
||||
|
||||
+1
-1
@@ -46,7 +46,7 @@ final class WithUserDetailsSecurityContextFactory implements WithSecurityContext
|
||||
private static final boolean reactorPresent;
|
||||
|
||||
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
|
||||
.getContextHolderStrategy();
|
||||
.getContextHolderStrategy();
|
||||
|
||||
private BeanFactory beans;
|
||||
|
||||
|
||||
+49
-30
@@ -433,7 +433,7 @@ public final class SecurityMockServerConfigurers {
|
||||
if (context != null) {
|
||||
exchange.getAttributes().remove(ATTRIBUTE_NAME);
|
||||
return webFilterChain.filter(exchange)
|
||||
.contextWrite(ReactiveSecurityContextHolder.withSecurityContext(context.get()));
|
||||
.contextWrite(ReactiveSecurityContextHolder.withSecurityContext(context.get()));
|
||||
}
|
||||
return webFilterChain.filter(exchange);
|
||||
}
|
||||
@@ -473,8 +473,10 @@ public final class SecurityMockServerConfigurers {
|
||||
* @return the {@link JwtMutator} for further configuration
|
||||
*/
|
||||
public JwtMutator jwt(Consumer<Jwt.Builder> jwtBuilderConsumer) {
|
||||
Jwt.Builder jwtBuilder = Jwt.withTokenValue("token").header("alg", "none").claim(JwtClaimNames.SUB, "user")
|
||||
.claim("scope", "read");
|
||||
Jwt.Builder jwtBuilder = Jwt.withTokenValue("token")
|
||||
.header("alg", "none")
|
||||
.claim(JwtClaimNames.SUB, "user")
|
||||
.claim("scope", "read");
|
||||
jwtBuilderConsumer.accept(jwtBuilder);
|
||||
this.jwt = jwtBuilder.build();
|
||||
return this;
|
||||
@@ -675,8 +677,9 @@ public final class SecurityMockServerConfigurers {
|
||||
}
|
||||
|
||||
private Collection<GrantedAuthority> getAuthorities(Collection<?> scopes) {
|
||||
return scopes.stream().map((scope) -> new SimpleGrantedAuthority("SCOPE_" + scope))
|
||||
.collect(Collectors.toList());
|
||||
return scopes.stream()
|
||||
.map((scope) -> new SimpleGrantedAuthority("SCOPE_" + scope))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private OAuth2AccessToken getOAuth2AccessToken(OAuth2AuthenticatedPrincipal principal) {
|
||||
@@ -788,16 +791,20 @@ public final class SecurityMockServerConfigurers {
|
||||
@Override
|
||||
public void beforeServerCreated(WebHttpHandlerBuilder builder) {
|
||||
OAuth2AuthenticationToken token = getToken();
|
||||
mockOAuth2Client().accessToken(this.accessToken).clientRegistration(this.clientRegistration)
|
||||
.principalName(token.getPrincipal().getName()).beforeServerCreated(builder);
|
||||
mockOAuth2Client().accessToken(this.accessToken)
|
||||
.clientRegistration(this.clientRegistration)
|
||||
.principalName(token.getPrincipal().getName())
|
||||
.beforeServerCreated(builder);
|
||||
mockAuthentication(token).beforeServerCreated(builder);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterConfigureAdded(WebTestClient.MockServerSpec<?> serverSpec) {
|
||||
OAuth2AuthenticationToken token = getToken();
|
||||
mockOAuth2Client().accessToken(this.accessToken).clientRegistration(this.clientRegistration)
|
||||
.principalName(token.getPrincipal().getName()).afterConfigureAdded(serverSpec);
|
||||
mockOAuth2Client().accessToken(this.accessToken)
|
||||
.clientRegistration(this.clientRegistration)
|
||||
.principalName(token.getPrincipal().getName())
|
||||
.afterConfigureAdded(serverSpec);
|
||||
mockAuthentication(token).afterConfigureAdded(serverSpec);
|
||||
}
|
||||
|
||||
@@ -805,9 +812,10 @@ public final class SecurityMockServerConfigurers {
|
||||
public void afterConfigurerAdded(WebTestClient.Builder builder,
|
||||
@Nullable WebHttpHandlerBuilder httpHandlerBuilder, @Nullable ClientHttpConnector connector) {
|
||||
OAuth2AuthenticationToken token = getToken();
|
||||
mockOAuth2Client().accessToken(this.accessToken).clientRegistration(this.clientRegistration)
|
||||
.principalName(token.getPrincipal().getName())
|
||||
.afterConfigurerAdded(builder, httpHandlerBuilder, connector);
|
||||
mockOAuth2Client().accessToken(this.accessToken)
|
||||
.clientRegistration(this.clientRegistration)
|
||||
.principalName(token.getPrincipal().getName())
|
||||
.afterConfigurerAdded(builder, httpHandlerBuilder, connector);
|
||||
mockAuthentication(token).afterConfigurerAdded(builder, httpHandlerBuilder, connector);
|
||||
}
|
||||
|
||||
@@ -818,8 +826,10 @@ public final class SecurityMockServerConfigurers {
|
||||
}
|
||||
|
||||
private ClientRegistration.Builder clientRegistrationBuilder() {
|
||||
return ClientRegistration.withRegistrationId("test").authorizationGrantType(AuthorizationGrantType.PASSWORD)
|
||||
.clientId("test-client").tokenUri("https://token-uri.example.org");
|
||||
return ClientRegistration.withRegistrationId("test")
|
||||
.authorizationGrantType(AuthorizationGrantType.PASSWORD)
|
||||
.clientId("test-client")
|
||||
.tokenUri("https://token-uri.example.org");
|
||||
}
|
||||
|
||||
private Collection<GrantedAuthority> defaultAuthorities() {
|
||||
@@ -948,16 +958,20 @@ public final class SecurityMockServerConfigurers {
|
||||
@Override
|
||||
public void beforeServerCreated(WebHttpHandlerBuilder builder) {
|
||||
OAuth2AuthenticationToken token = getToken();
|
||||
mockOAuth2Client().accessToken(this.accessToken).principalName(token.getPrincipal().getName())
|
||||
.clientRegistration(this.clientRegistration).beforeServerCreated(builder);
|
||||
mockOAuth2Client().accessToken(this.accessToken)
|
||||
.principalName(token.getPrincipal().getName())
|
||||
.clientRegistration(this.clientRegistration)
|
||||
.beforeServerCreated(builder);
|
||||
mockAuthentication(token).beforeServerCreated(builder);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterConfigureAdded(WebTestClient.MockServerSpec<?> serverSpec) {
|
||||
OAuth2AuthenticationToken token = getToken();
|
||||
mockOAuth2Client().accessToken(this.accessToken).principalName(token.getPrincipal().getName())
|
||||
.clientRegistration(this.clientRegistration).afterConfigureAdded(serverSpec);
|
||||
mockOAuth2Client().accessToken(this.accessToken)
|
||||
.principalName(token.getPrincipal().getName())
|
||||
.clientRegistration(this.clientRegistration)
|
||||
.afterConfigureAdded(serverSpec);
|
||||
mockAuthentication(token).afterConfigureAdded(serverSpec);
|
||||
}
|
||||
|
||||
@@ -965,15 +979,18 @@ public final class SecurityMockServerConfigurers {
|
||||
public void afterConfigurerAdded(WebTestClient.Builder builder,
|
||||
@Nullable WebHttpHandlerBuilder httpHandlerBuilder, @Nullable ClientHttpConnector connector) {
|
||||
OAuth2AuthenticationToken token = getToken();
|
||||
mockOAuth2Client().accessToken(this.accessToken).principalName(token.getPrincipal().getName())
|
||||
.clientRegistration(this.clientRegistration)
|
||||
.afterConfigurerAdded(builder, httpHandlerBuilder, connector);
|
||||
mockOAuth2Client().accessToken(this.accessToken)
|
||||
.principalName(token.getPrincipal().getName())
|
||||
.clientRegistration(this.clientRegistration)
|
||||
.afterConfigurerAdded(builder, httpHandlerBuilder, connector);
|
||||
mockAuthentication(token).afterConfigurerAdded(builder, httpHandlerBuilder, connector);
|
||||
}
|
||||
|
||||
private ClientRegistration.Builder clientRegistrationBuilder() {
|
||||
return ClientRegistration.withRegistrationId("test").authorizationGrantType(AuthorizationGrantType.PASSWORD)
|
||||
.clientId("test-client").tokenUri("https://token-uri.example.org");
|
||||
return ClientRegistration.withRegistrationId("test")
|
||||
.authorizationGrantType(AuthorizationGrantType.PASSWORD)
|
||||
.clientId("test-client")
|
||||
.tokenUri("https://token-uri.example.org");
|
||||
}
|
||||
|
||||
private OAuth2AuthenticationToken getToken() {
|
||||
@@ -1104,14 +1121,14 @@ public final class SecurityMockServerConfigurers {
|
||||
OAuth2AuthorizedClient client = getClient();
|
||||
return (filters) -> filters.add(0, (exchange, chain) -> {
|
||||
ServerOAuth2AuthorizedClientRepository authorizedClientRepository = OAuth2ClientServerTestUtils
|
||||
.getAuthorizedClientRepository(exchange);
|
||||
.getAuthorizedClientRepository(exchange);
|
||||
if (!(authorizedClientRepository instanceof TestOAuth2AuthorizedClientRepository)) {
|
||||
authorizedClientRepository = new TestOAuth2AuthorizedClientRepository(authorizedClientRepository);
|
||||
OAuth2ClientServerTestUtils.setAuthorizedClientRepository(exchange, authorizedClientRepository);
|
||||
}
|
||||
TestOAuth2AuthorizedClientRepository.enable(exchange);
|
||||
return authorizedClientRepository.saveAuthorizedClient(client, null, exchange)
|
||||
.then(chain.filter(exchange));
|
||||
.then(chain.filter(exchange));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1123,8 +1140,10 @@ public final class SecurityMockServerConfigurers {
|
||||
|
||||
private ClientRegistration.Builder clientRegistrationBuilder() {
|
||||
return ClientRegistration.withRegistrationId(this.registrationId)
|
||||
.authorizationGrantType(AuthorizationGrantType.PASSWORD).clientId("test-client")
|
||||
.clientSecret("test-secret").tokenUri("https://idp.example.org/oauth/token");
|
||||
.authorizationGrantType(AuthorizationGrantType.PASSWORD)
|
||||
.clientId("test-client")
|
||||
.clientSecret("test-secret")
|
||||
.tokenUri("https://idp.example.org/oauth/token");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1134,7 +1153,7 @@ public final class SecurityMockServerConfigurers {
|
||||
private static final class TestOAuth2AuthorizedClientManager implements ReactiveOAuth2AuthorizedClientManager {
|
||||
|
||||
static final String ENABLED_ATTR_NAME = TestOAuth2AuthorizedClientManager.class.getName()
|
||||
.concat(".ENABLED");
|
||||
.concat(".ENABLED");
|
||||
|
||||
private final ReactiveOAuth2AuthorizedClientManager delegate;
|
||||
|
||||
@@ -1173,7 +1192,7 @@ public final class SecurityMockServerConfigurers {
|
||||
static final String TOKEN_ATTR_NAME = TestOAuth2AuthorizedClientRepository.class.getName().concat(".TOKEN");
|
||||
|
||||
static final String ENABLED_ATTR_NAME = TestOAuth2AuthorizedClientRepository.class.getName()
|
||||
.concat(".ENABLED");
|
||||
.concat(".ENABLED");
|
||||
|
||||
private final ServerOAuth2AuthorizedClientRepository delegate;
|
||||
|
||||
@@ -1321,7 +1340,7 @@ public final class SecurityMockServerConfigurers {
|
||||
return null;
|
||||
}
|
||||
List<HandlerMethodArgumentResolver> resolvers = (List<HandlerMethodArgumentResolver>) ReflectionTestUtils
|
||||
.invokeGetterMethod(configurer, "customResolvers");
|
||||
.invokeGetterMethod(configurer, "customResolvers");
|
||||
if (resolvers == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
+6
-3
@@ -178,7 +178,8 @@ public final class SecurityMockMvcRequestBuilders {
|
||||
@Override
|
||||
public MockHttpServletRequest buildRequest(ServletContext servletContext) {
|
||||
MockHttpServletRequestBuilder loginRequest = post(this.loginProcessingUrl).accept(this.acceptMediaType)
|
||||
.param(this.usernameParam, this.username).param(this.passwordParam, this.password);
|
||||
.param(this.usernameParam, this.username)
|
||||
.param(this.passwordParam, this.password);
|
||||
if (this.parent != null) {
|
||||
loginRequest = (MockHttpServletRequestBuilder) loginRequest.merge(this.parent);
|
||||
}
|
||||
@@ -204,8 +205,10 @@ public final class SecurityMockMvcRequestBuilders {
|
||||
* @return the {@link FormLoginRequestBuilder} for additional customizations
|
||||
*/
|
||||
public FormLoginRequestBuilder loginProcessingUrl(String loginProcessingUrl, Object... uriVars) {
|
||||
this.loginProcessingUrl = UriComponentsBuilder.fromPath(loginProcessingUrl).buildAndExpand(uriVars).encode()
|
||||
.toString();
|
||||
this.loginProcessingUrl = UriComponentsBuilder.fromPath(loginProcessingUrl)
|
||||
.buildAndExpand(uriVars)
|
||||
.encode()
|
||||
.toString();
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
+28
-16
@@ -464,7 +464,7 @@ public final class SecurityMockMvcRequestPostProcessors {
|
||||
|
||||
private static SecurityContextHolderStrategy getSecurityContextHolderStrategy(HttpServletRequest request) {
|
||||
WebApplicationContext context = WebApplicationContextUtils
|
||||
.findWebApplicationContext(request.getServletContext());
|
||||
.findWebApplicationContext(request.getServletContext());
|
||||
if (context == null) {
|
||||
return DEFAULT_SECURITY_CONTEXT_HOLDER_STRATEGY;
|
||||
}
|
||||
@@ -1075,8 +1075,10 @@ public final class SecurityMockMvcRequestPostProcessors {
|
||||
* @return the {@link JwtRequestPostProcessor} for additional customization
|
||||
*/
|
||||
public JwtRequestPostProcessor jwt(Consumer<Jwt.Builder> jwtBuilderConsumer) {
|
||||
Jwt.Builder jwtBuilder = Jwt.withTokenValue("token").header("alg", "none").claim(JwtClaimNames.SUB, "user")
|
||||
.claim("scope", "read");
|
||||
Jwt.Builder jwtBuilder = Jwt.withTokenValue("token")
|
||||
.header("alg", "none")
|
||||
.claim(JwtClaimNames.SUB, "user")
|
||||
.claim("scope", "read");
|
||||
jwtBuilderConsumer.accept(jwtBuilder);
|
||||
this.jwt = jwtBuilder.build();
|
||||
return this;
|
||||
@@ -1242,8 +1244,9 @@ public final class SecurityMockMvcRequestPostProcessors {
|
||||
}
|
||||
|
||||
private Collection<GrantedAuthority> getAuthorities(Collection<?> scopes) {
|
||||
return scopes.stream().map((scope) -> new SimpleGrantedAuthority("SCOPE_" + scope))
|
||||
.collect(Collectors.toList());
|
||||
return scopes.stream()
|
||||
.map((scope) -> new SimpleGrantedAuthority("SCOPE_" + scope))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private OAuth2AccessToken getOAuth2AccessToken(OAuth2AuthenticatedPrincipal principal) {
|
||||
@@ -1359,12 +1362,16 @@ public final class SecurityMockMvcRequestPostProcessors {
|
||||
this.clientRegistration.getRegistrationId());
|
||||
request = new AuthenticationRequestPostProcessor(token).postProcessRequest(request);
|
||||
return new OAuth2ClientRequestPostProcessor().clientRegistration(this.clientRegistration)
|
||||
.principalName(oauth2User.getName()).accessToken(this.accessToken).postProcessRequest(request);
|
||||
.principalName(oauth2User.getName())
|
||||
.accessToken(this.accessToken)
|
||||
.postProcessRequest(request);
|
||||
}
|
||||
|
||||
private ClientRegistration.Builder clientRegistrationBuilder() {
|
||||
return ClientRegistration.withRegistrationId("test").authorizationGrantType(AuthorizationGrantType.PASSWORD)
|
||||
.clientId("test-client").tokenUri("https://token-uri.example.org");
|
||||
return ClientRegistration.withRegistrationId("test")
|
||||
.authorizationGrantType(AuthorizationGrantType.PASSWORD)
|
||||
.clientId("test-client")
|
||||
.tokenUri("https://token-uri.example.org");
|
||||
}
|
||||
|
||||
private Collection<GrantedAuthority> defaultAuthorities() {
|
||||
@@ -1491,12 +1498,15 @@ public final class SecurityMockMvcRequestPostProcessors {
|
||||
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
|
||||
OidcUser oidcUser = this.oidcUser.get();
|
||||
return new OAuth2LoginRequestPostProcessor(this.accessToken).oauth2User(oidcUser)
|
||||
.clientRegistration(this.clientRegistration).postProcessRequest(request);
|
||||
.clientRegistration(this.clientRegistration)
|
||||
.postProcessRequest(request);
|
||||
}
|
||||
|
||||
private ClientRegistration.Builder clientRegistrationBuilder() {
|
||||
return ClientRegistration.withRegistrationId("test").authorizationGrantType(AuthorizationGrantType.PASSWORD)
|
||||
.clientId("test-client").tokenUri("https://token-uri.example.org");
|
||||
return ClientRegistration.withRegistrationId("test")
|
||||
.authorizationGrantType(AuthorizationGrantType.PASSWORD)
|
||||
.clientId("test-client")
|
||||
.tokenUri("https://token-uri.example.org");
|
||||
}
|
||||
|
||||
private Collection<GrantedAuthority> getAuthorities() {
|
||||
@@ -1605,7 +1615,7 @@ public final class SecurityMockMvcRequestPostProcessors {
|
||||
OAuth2AuthorizedClient client = new OAuth2AuthorizedClient(this.clientRegistration, this.principalName,
|
||||
this.accessToken);
|
||||
OAuth2AuthorizedClientRepository authorizedClientRepository = OAuth2ClientServletTestUtils
|
||||
.getAuthorizedClientRepository(request);
|
||||
.getAuthorizedClientRepository(request);
|
||||
if (!(authorizedClientRepository instanceof TestOAuth2AuthorizedClientRepository)) {
|
||||
authorizedClientRepository = new TestOAuth2AuthorizedClientRepository(authorizedClientRepository);
|
||||
OAuth2ClientServletTestUtils.setAuthorizedClientRepository(request, authorizedClientRepository);
|
||||
@@ -1617,8 +1627,10 @@ public final class SecurityMockMvcRequestPostProcessors {
|
||||
|
||||
private ClientRegistration.Builder clientRegistrationBuilder() {
|
||||
return ClientRegistration.withRegistrationId(this.registrationId)
|
||||
.authorizationGrantType(AuthorizationGrantType.PASSWORD).clientId("test-client")
|
||||
.clientSecret("test-secret").tokenUri("https://idp.example.org/oauth/token");
|
||||
.authorizationGrantType(AuthorizationGrantType.PASSWORD)
|
||||
.clientId("test-client")
|
||||
.clientSecret("test-secret")
|
||||
.tokenUri("https://idp.example.org/oauth/token");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1628,7 +1640,7 @@ public final class SecurityMockMvcRequestPostProcessors {
|
||||
private static final class TestOAuth2AuthorizedClientManager implements OAuth2AuthorizedClientManager {
|
||||
|
||||
static final String ENABLED_ATTR_NAME = TestOAuth2AuthorizedClientManager.class.getName()
|
||||
.concat(".ENABLED");
|
||||
.concat(".ENABLED");
|
||||
|
||||
private final OAuth2AuthorizedClientManager delegate;
|
||||
|
||||
@@ -1667,7 +1679,7 @@ public final class SecurityMockMvcRequestPostProcessors {
|
||||
static final String TOKEN_ATTR_NAME = TestOAuth2AuthorizedClientRepository.class.getName().concat(".TOKEN");
|
||||
|
||||
static final String ENABLED_ATTR_NAME = TestOAuth2AuthorizedClientRepository.class.getName()
|
||||
.concat(".ENABLED");
|
||||
.concat(".ENABLED");
|
||||
|
||||
private final OAuth2AuthorizedClientRepository delegate;
|
||||
|
||||
|
||||
@@ -166,7 +166,7 @@ public abstract class WebTestUtils {
|
||||
return result;
|
||||
}
|
||||
WebApplicationContext webApplicationContext = WebApplicationContextUtils
|
||||
.getWebApplicationContext(servletContext);
|
||||
.getWebApplicationContext(servletContext);
|
||||
if (webApplicationContext == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
+16
-11
@@ -43,33 +43,38 @@ class WebTestUtilsTestRuntimeHintsTests {
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
SpringFactoriesLoader.forResourceLocation("META-INF/spring/aot.factories").load(TestRuntimeHintsRegistrar.class)
|
||||
.forEach((registrar) -> registrar.registerHints(this.hints, WebTestUtilsTestRuntimeHintsTests.class,
|
||||
ClassUtils.getDefaultClassLoader()));
|
||||
SpringFactoriesLoader.forResourceLocation("META-INF/spring/aot.factories")
|
||||
.load(TestRuntimeHintsRegistrar.class)
|
||||
.forEach((registrar) -> registrar.registerHints(this.hints, WebTestUtilsTestRuntimeHintsTests.class,
|
||||
ClassUtils.getDefaultClassLoader()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void filterChainProxyHasHints() {
|
||||
assertThat(RuntimeHintsPredicates.reflection().onType(FilterChainProxy.class)
|
||||
.withMemberCategories(MemberCategory.INVOKE_DECLARED_METHODS)).accepts(this.hints);
|
||||
assertThat(RuntimeHintsPredicates.reflection()
|
||||
.onType(FilterChainProxy.class)
|
||||
.withMemberCategories(MemberCategory.INVOKE_DECLARED_METHODS)).accepts(this.hints);
|
||||
}
|
||||
|
||||
@Test
|
||||
void csrfFilterHasHints() {
|
||||
assertThat(RuntimeHintsPredicates.reflection().onType(CsrfFilter.class)
|
||||
.withMemberCategories(MemberCategory.DECLARED_FIELDS)).accepts(this.hints);
|
||||
assertThat(RuntimeHintsPredicates.reflection()
|
||||
.onType(CsrfFilter.class)
|
||||
.withMemberCategories(MemberCategory.DECLARED_FIELDS)).accepts(this.hints);
|
||||
}
|
||||
|
||||
@Test
|
||||
void securityContextPersistenceFilterHasHints() {
|
||||
assertThat(RuntimeHintsPredicates.reflection().onType(SecurityContextPersistenceFilter.class)
|
||||
.withMemberCategories(MemberCategory.DECLARED_FIELDS)).accepts(this.hints);
|
||||
assertThat(RuntimeHintsPredicates.reflection()
|
||||
.onType(SecurityContextPersistenceFilter.class)
|
||||
.withMemberCategories(MemberCategory.DECLARED_FIELDS)).accepts(this.hints);
|
||||
}
|
||||
|
||||
@Test
|
||||
void securityContextHolderFilterHasHints() {
|
||||
assertThat(RuntimeHintsPredicates.reflection().onType(SecurityContextHolderFilter.class)
|
||||
.withMemberCategories(MemberCategory.DECLARED_FIELDS)).accepts(this.hints);
|
||||
assertThat(RuntimeHintsPredicates.reflection()
|
||||
.onType(SecurityContextHolderFilter.class)
|
||||
.withMemberCategories(MemberCategory.DECLARED_FIELDS)).accepts(this.hints);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+15
-13
@@ -58,40 +58,42 @@ class WithSecurityContextTestRuntimeHintsTests {
|
||||
@WithMockUser
|
||||
void withMockUserHasHints() {
|
||||
assertThat(RuntimeHintsPredicates.reflection()
|
||||
.onType(TypeReference
|
||||
.of("org.springframework.security.test.context.support.WithMockUserSecurityContextFactory"))
|
||||
.withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(this.hints);
|
||||
.onType(TypeReference
|
||||
.of("org.springframework.security.test.context.support.WithMockUserSecurityContextFactory"))
|
||||
.withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(this.hints);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithAnonymousUser
|
||||
void withAnonymousUserHasHints() {
|
||||
assertThat(RuntimeHintsPredicates.reflection()
|
||||
.onType(TypeReference.of(
|
||||
"org.springframework.security.test.context.support.WithAnonymousUserSecurityContextFactory"))
|
||||
.withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(this.hints);
|
||||
.onType(TypeReference
|
||||
.of("org.springframework.security.test.context.support.WithAnonymousUserSecurityContextFactory"))
|
||||
.withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(this.hints);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUserDetails
|
||||
void withUserDetailsHasHints() {
|
||||
assertThat(RuntimeHintsPredicates.reflection()
|
||||
.onType(TypeReference
|
||||
.of("org.springframework.security.test.context.support.WithUserDetailsSecurityContextFactory"))
|
||||
.withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(this.hints);
|
||||
.onType(TypeReference
|
||||
.of("org.springframework.security.test.context.support.WithUserDetailsSecurityContextFactory"))
|
||||
.withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(this.hints);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockTestUser
|
||||
void withMockTestUserHasHints() {
|
||||
assertThat(RuntimeHintsPredicates.reflection().onType(WithMockTestUserSecurityContextFactory.class)
|
||||
.withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(this.hints);
|
||||
assertThat(RuntimeHintsPredicates.reflection()
|
||||
.onType(WithMockTestUserSecurityContextFactory.class)
|
||||
.withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(this.hints);
|
||||
}
|
||||
|
||||
@Test
|
||||
void withMockCustomUserOnClassHasHints() {
|
||||
assertThat(RuntimeHintsPredicates.reflection().onType(WithMockCustomUserSecurityContextFactory.class)
|
||||
.withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(this.hints);
|
||||
assertThat(RuntimeHintsPredicates.reflection()
|
||||
.onType(WithMockCustomUserSecurityContextFactory.class)
|
||||
.withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(this.hints);
|
||||
}
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
|
||||
+3
-2
@@ -44,8 +44,9 @@ public class SecurityTestExecutionListenerTests {
|
||||
@WithMockUser
|
||||
@Test
|
||||
public void reactorContextTestSecurityContextHolderExecutionListenerTestIsRegistered() {
|
||||
Mono<String> name = ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication)
|
||||
.map(Principal::getName);
|
||||
Mono<String> name = ReactiveSecurityContextHolder.getContext()
|
||||
.map(SecurityContext::getAuthentication)
|
||||
.map(Principal::getName);
|
||||
StepVerifier.create(name).expectNext("user").verifyComplete();
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -54,7 +54,7 @@ public class WithMockUserTests {
|
||||
@Test
|
||||
public void getMessageUnauthenticated() {
|
||||
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
|
||||
.isThrownBy(() -> this.messageService.getMessage());
|
||||
.isThrownBy(() -> this.messageService.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-1
@@ -52,7 +52,7 @@ public class WithUserDetailsTests {
|
||||
@Test
|
||||
public void getMessageUnauthenticated() {
|
||||
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
|
||||
.isThrownBy(() -> this.messageService.getMessage());
|
||||
.isThrownBy(() -> this.messageService.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+5
-5
@@ -100,8 +100,8 @@ public class ReactorContextTestExecutionListenerTests {
|
||||
TestSecurityContextHolder.setAuthentication(contextHolder);
|
||||
this.listener.beforeTestMethod(this.testContext);
|
||||
Mono<Authentication> authentication = Mono.just("any")
|
||||
.flatMap((s) -> ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication))
|
||||
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(expectedAuthentication));
|
||||
.flatMap((s) -> ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication))
|
||||
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(expectedAuthentication));
|
||||
StepVerifier.create(authentication).expectNext(expectedAuthentication).verifyComplete();
|
||||
}
|
||||
|
||||
@@ -114,8 +114,8 @@ public class ReactorContextTestExecutionListenerTests {
|
||||
TestSecurityContextHolder.setAuthentication(contextHolder);
|
||||
this.listener.beforeTestMethod(this.testContext);
|
||||
Mono<Authentication> authentication = Mono.just("any")
|
||||
.flatMap((s) -> ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication))
|
||||
.contextWrite(ReactiveSecurityContextHolder.clearContext());
|
||||
.flatMap((s) -> ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication))
|
||||
.contextWrite(ReactiveSecurityContextHolder.clearContext());
|
||||
StepVerifier.create(authentication).verifyComplete();
|
||||
}
|
||||
|
||||
@@ -161,7 +161,7 @@ public class ReactorContextTestExecutionListenerTests {
|
||||
|
||||
public void assertAuthentication(Authentication expected) {
|
||||
Mono<Authentication> authentication = ReactiveSecurityContextHolder.getContext()
|
||||
.map(SecurityContext::getAuthentication);
|
||||
.map(SecurityContext::getAuthentication);
|
||||
StepVerifier.create(authentication).expectNext(expected).verifyComplete();
|
||||
}
|
||||
|
||||
|
||||
+6
-4
@@ -52,7 +52,7 @@ public class WithMockUserSecurityContextFactoryTests {
|
||||
given(this.withUser.roles()).willReturn(new String[] { "USER" });
|
||||
given(this.withUser.authorities()).willReturn(new String[] {});
|
||||
assertThat(this.factory.createSecurityContext(this.withUser).getAuthentication().getName())
|
||||
.isEqualTo(this.withUser.value());
|
||||
.isEqualTo(this.withUser.value());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -62,7 +62,7 @@ public class WithMockUserSecurityContextFactoryTests {
|
||||
given(this.withUser.roles()).willReturn(new String[] { "USER" });
|
||||
given(this.withUser.authorities()).willReturn(new String[] {});
|
||||
assertThat(this.factory.createSecurityContext(this.withUser).getAuthentication().getName())
|
||||
.isEqualTo(this.withUser.username());
|
||||
.isEqualTo(this.withUser.username());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -72,7 +72,8 @@ public class WithMockUserSecurityContextFactoryTests {
|
||||
given(this.withUser.roles()).willReturn(new String[] { "USER", "CUSTOM" });
|
||||
given(this.withUser.authorities()).willReturn(new String[] {});
|
||||
assertThat(this.factory.createSecurityContext(this.withUser).getAuthentication().getAuthorities())
|
||||
.extracting("authority").containsOnly("ROLE_USER", "ROLE_CUSTOM");
|
||||
.extracting("authority")
|
||||
.containsOnly("ROLE_USER", "ROLE_CUSTOM");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -82,7 +83,8 @@ public class WithMockUserSecurityContextFactoryTests {
|
||||
given(this.withUser.roles()).willReturn(new String[] { "USER" });
|
||||
given(this.withUser.authorities()).willReturn(new String[] { "USER", "CUSTOM" });
|
||||
assertThat(this.factory.createSecurityContext(this.withUser).getAuthentication().getAuthorities())
|
||||
.extracting("authority").containsOnly("USER", "CUSTOM");
|
||||
.extracting("authority")
|
||||
.containsOnly("USER", "CUSTOM");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-1
@@ -160,7 +160,7 @@ public class WithSecurityContextTestExcecutionListenerTests {
|
||||
given(testContext.getApplicationContext()).willThrow(new IllegalStateException(""));
|
||||
this.listener.beforeTestMethod(testContext);
|
||||
assertThat(SecurityContextHolder.getContext().getAuthentication().getPrincipal())
|
||||
.isInstanceOf(WithSuperClassWithSecurityContext.class);
|
||||
.isInstanceOf(WithSuperClassWithSecurityContext.class);
|
||||
}
|
||||
|
||||
@WithSuperClassWithSecurityContext
|
||||
|
||||
+2
-2
@@ -135,10 +135,10 @@ public class WithSecurityContextTestExecutionListenerTests {
|
||||
securityContext.setAuthentication(new TestingAuthenticationToken("user", "passsword", "ROLE_USER"));
|
||||
Supplier<SecurityContext> supplier = () -> securityContext;
|
||||
given(this.testContext.removeAttribute(WithSecurityContextTestExecutionListener.SECURITY_CONTEXT_ATTR_NAME))
|
||||
.willReturn(supplier);
|
||||
.willReturn(supplier);
|
||||
this.listener.beforeTestExecution(this.testContext);
|
||||
assertThat(TestSecurityContextHolder.getContext().getAuthentication())
|
||||
.isEqualTo(securityContext.getAuthentication());
|
||||
.isEqualTo(securityContext.getAuthentication());
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
+1
-1
@@ -122,7 +122,7 @@ public class WithUserDetailsSecurityContextFactoryTests {
|
||||
given(this.withUserDetails.value()).willReturn(username);
|
||||
given(this.withUserDetails.userDetailsServiceBeanName()).willReturn(beanName);
|
||||
given(this.beans.getBean(beanName, ReactiveUserDetailsService.class))
|
||||
.willReturn(this.reactiveUserDetailsService);
|
||||
.willReturn(this.reactiveUserDetailsService);
|
||||
given(this.reactiveUserDetailsService.findByUsername(username)).willReturn(Mono.just(this.userDetails));
|
||||
SecurityContext context = this.factory.createSecurityContext(this.withUserDetails);
|
||||
assertThat(context.getAuthentication()).isInstanceOf(UsernamePasswordAuthenticationToken.class);
|
||||
|
||||
+41
-23
@@ -50,11 +50,13 @@ public class SecurityMockServerConfigurerOpaqueTokenTests extends AbstractMockSe
|
||||
private GrantedAuthority authority2 = new SimpleGrantedAuthority("two");
|
||||
|
||||
private WebTestClient client = WebTestClient.bindToController(this.securityContextController)
|
||||
.webFilter(new SecurityContextServerWebExchangeWebFilter())
|
||||
.argumentResolvers((resolvers) -> resolvers
|
||||
.addCustomResolver(new CurrentSecurityContextArgumentResolver(new ReactiveAdapterRegistry())))
|
||||
.apply(SecurityMockServerConfigurers.springSecurity()).configureClient()
|
||||
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build();
|
||||
.webFilter(new SecurityContextServerWebExchangeWebFilter())
|
||||
.argumentResolvers((resolvers) -> resolvers
|
||||
.addCustomResolver(new CurrentSecurityContextArgumentResolver(new ReactiveAdapterRegistry())))
|
||||
.apply(SecurityMockServerConfigurers.springSecurity())
|
||||
.configureClient()
|
||||
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
|
||||
.build();
|
||||
|
||||
@Test
|
||||
public void mockOpaqueTokenWhenUsingDefaultsThenBearerTokenAuthentication() {
|
||||
@@ -70,9 +72,11 @@ public class SecurityMockServerConfigurerOpaqueTokenTests extends AbstractMockSe
|
||||
@Test
|
||||
public void mockOpaqueTokenWhenAuthoritiesThenBearerTokenAuthentication() {
|
||||
this.client
|
||||
.mutateWith(
|
||||
SecurityMockServerConfigurers.mockOpaqueToken().authorities(this.authority1, this.authority2))
|
||||
.get().exchange().expectStatus().isOk();
|
||||
.mutateWith(SecurityMockServerConfigurers.mockOpaqueToken().authorities(this.authority1, this.authority2))
|
||||
.get()
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
SecurityContext context = this.securityContextController.removeSecurityContext();
|
||||
assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities()).containsOnly(this.authority1,
|
||||
this.authority2);
|
||||
@@ -82,9 +86,12 @@ public class SecurityMockServerConfigurerOpaqueTokenTests extends AbstractMockSe
|
||||
public void mockOpaqueTokenWhenAttributesThenBearerTokenAuthentication() {
|
||||
String sub = new String("my-subject");
|
||||
this.client
|
||||
.mutateWith(SecurityMockServerConfigurers.mockOpaqueToken()
|
||||
.attributes((attributes) -> attributes.put(OAuth2TokenIntrospectionClaimNames.SUB, sub)))
|
||||
.get().exchange().expectStatus().isOk();
|
||||
.mutateWith(SecurityMockServerConfigurers.mockOpaqueToken()
|
||||
.attributes((attributes) -> attributes.put(OAuth2TokenIntrospectionClaimNames.SUB, sub)))
|
||||
.get()
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
SecurityContext context = this.securityContextController.removeSecurityContext();
|
||||
assertThat(context.getAuthentication()).isInstanceOf(BearerTokenAuthentication.class);
|
||||
BearerTokenAuthentication token = (BearerTokenAuthentication) context.getAuthentication();
|
||||
@@ -94,8 +101,11 @@ public class SecurityMockServerConfigurerOpaqueTokenTests extends AbstractMockSe
|
||||
@Test
|
||||
public void mockOpaqueTokenWhenPrincipalThenBearerTokenAuthentication() {
|
||||
OAuth2AuthenticatedPrincipal principal = TestOAuth2AuthenticatedPrincipals.active();
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOpaqueToken().principal(principal)).get().exchange()
|
||||
.expectStatus().isOk();
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOpaqueToken().principal(principal))
|
||||
.get()
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
SecurityContext context = this.securityContextController.removeSecurityContext();
|
||||
assertThat(context.getAuthentication()).isInstanceOf(BearerTokenAuthentication.class);
|
||||
BearerTokenAuthentication token = (BearerTokenAuthentication) context.getAuthentication();
|
||||
@@ -105,26 +115,34 @@ public class SecurityMockServerConfigurerOpaqueTokenTests extends AbstractMockSe
|
||||
@Test
|
||||
public void mockOpaqueTokenWhenPrincipalSpecifiedThenLastCalledTakesPrecedence() {
|
||||
OAuth2AuthenticatedPrincipal principal = TestOAuth2AuthenticatedPrincipals
|
||||
.active((a) -> a.put("scope", "user"));
|
||||
.active((a) -> a.put("scope", "user"));
|
||||
this.client
|
||||
.mutateWith(SecurityMockServerConfigurers.mockOpaqueToken()
|
||||
.attributes((a) -> a.put(OAuth2TokenIntrospectionClaimNames.SUB, "foo")).principal(principal))
|
||||
.get().exchange().expectStatus().isOk();
|
||||
.mutateWith(SecurityMockServerConfigurers.mockOpaqueToken()
|
||||
.attributes((a) -> a.put(OAuth2TokenIntrospectionClaimNames.SUB, "foo"))
|
||||
.principal(principal))
|
||||
.get()
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
SecurityContext context = this.securityContextController.removeSecurityContext();
|
||||
assertThat(context.getAuthentication()).isInstanceOf(BearerTokenAuthentication.class);
|
||||
BearerTokenAuthentication token = (BearerTokenAuthentication) context.getAuthentication();
|
||||
assertThat((String) ((OAuth2AuthenticatedPrincipal) token.getPrincipal())
|
||||
.getAttribute(OAuth2TokenIntrospectionClaimNames.SUB))
|
||||
.isEqualTo(principal.getAttribute(OAuth2TokenIntrospectionClaimNames.SUB));
|
||||
.getAttribute(OAuth2TokenIntrospectionClaimNames.SUB))
|
||||
.isEqualTo(principal.getAttribute(OAuth2TokenIntrospectionClaimNames.SUB));
|
||||
this.client
|
||||
.mutateWith(SecurityMockServerConfigurers.mockOpaqueToken().principal(principal)
|
||||
.attributes((a) -> a.put(OAuth2TokenIntrospectionClaimNames.SUB, "bar")))
|
||||
.get().exchange().expectStatus().isOk();
|
||||
.mutateWith(SecurityMockServerConfigurers.mockOpaqueToken()
|
||||
.principal(principal)
|
||||
.attributes((a) -> a.put(OAuth2TokenIntrospectionClaimNames.SUB, "bar")))
|
||||
.get()
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
context = this.securityContextController.removeSecurityContext();
|
||||
assertThat(context.getAuthentication()).isInstanceOf(BearerTokenAuthentication.class);
|
||||
token = (BearerTokenAuthentication) context.getAuthentication();
|
||||
assertThat((String) ((OAuth2AuthenticatedPrincipal) token.getPrincipal())
|
||||
.getAttribute(OAuth2TokenIntrospectionClaimNames.SUB)).isEqualTo("bar");
|
||||
.getAttribute(OAuth2TokenIntrospectionClaimNames.SUB)).isEqualTo("bar");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+27
-14
@@ -41,9 +41,11 @@ import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
public class SecurityMockServerConfigurersAnnotatedTests extends AbstractMockServerConfigurersTests {
|
||||
|
||||
WebTestClient client = WebTestClient.bindToController(this.controller)
|
||||
.webFilter(new SecurityContextServerWebExchangeWebFilter())
|
||||
.apply(SecurityMockServerConfigurers.springSecurity()).configureClient()
|
||||
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build();
|
||||
.webFilter(new SecurityContextServerWebExchangeWebFilter())
|
||||
.apply(SecurityMockServerConfigurers.springSecurity())
|
||||
.configureClient()
|
||||
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
|
||||
.build();
|
||||
|
||||
@Test
|
||||
@WithMockUser
|
||||
@@ -59,10 +61,12 @@ public class SecurityMockServerConfigurersAnnotatedTests extends AbstractMockSer
|
||||
TestingAuthenticationToken authentication = new TestingAuthenticationToken("authentication", "secret",
|
||||
"ROLE_USER");
|
||||
this.client = WebTestClient.bindToController(this.controller)
|
||||
.webFilter(new SecurityContextServerWebExchangeWebFilter())
|
||||
.apply(SecurityMockServerConfigurers.springSecurity())
|
||||
.apply(SecurityMockServerConfigurers.mockAuthentication(authentication)).configureClient()
|
||||
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build();
|
||||
.webFilter(new SecurityContextServerWebExchangeWebFilter())
|
||||
.apply(SecurityMockServerConfigurers.springSecurity())
|
||||
.apply(SecurityMockServerConfigurers.mockAuthentication(authentication))
|
||||
.configureClient()
|
||||
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
|
||||
.build();
|
||||
this.client.get().exchange().expectStatus().isOk();
|
||||
this.controller.assertPrincipalIsEqualTo(authentication);
|
||||
}
|
||||
@@ -72,8 +76,11 @@ public class SecurityMockServerConfigurersAnnotatedTests extends AbstractMockSer
|
||||
public void withMockUserWhenMutateWithMockPrincipalThenOverridesAnnotation() {
|
||||
TestingAuthenticationToken authentication = new TestingAuthenticationToken("authentication", "secret",
|
||||
"ROLE_USER");
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockAuthentication(authentication)).get().exchange()
|
||||
.expectStatus().isOk();
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockAuthentication(authentication))
|
||||
.get()
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
this.controller.assertPrincipalIsEqualTo(authentication);
|
||||
}
|
||||
|
||||
@@ -82,8 +89,11 @@ public class SecurityMockServerConfigurersAnnotatedTests extends AbstractMockSer
|
||||
public void withMockUserWhenMutateWithMockPrincipalAndNoMutateThenOverridesAnnotationAndUsesAnnotation() {
|
||||
TestingAuthenticationToken authentication = new TestingAuthenticationToken("authentication", "secret",
|
||||
"ROLE_USER");
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockAuthentication(authentication)).get().exchange()
|
||||
.expectStatus().isOk();
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockAuthentication(authentication))
|
||||
.get()
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
this.controller.assertPrincipalIsEqualTo(authentication);
|
||||
this.client.get().exchange().expectStatus().isOk();
|
||||
assertPrincipalCreatedFromUserDetails(this.controller.removePrincipal(), this.userBuilder.build());
|
||||
@@ -103,9 +113,12 @@ public class SecurityMockServerConfigurersAnnotatedTests extends AbstractMockSer
|
||||
TestingAuthenticationToken authentication = new TestingAuthenticationToken("authentication", "secret",
|
||||
"ROLE_USER");
|
||||
ForkJoinPool.commonPool()
|
||||
.submit(() -> this.client.mutateWith(SecurityMockServerConfigurers.mockAuthentication(authentication))
|
||||
.get().exchange().expectStatus().isOk())
|
||||
.join();
|
||||
.submit(() -> this.client.mutateWith(SecurityMockServerConfigurers.mockAuthentication(authentication))
|
||||
.get()
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk())
|
||||
.join();
|
||||
this.controller.assertPrincipalIsEqualTo(authentication);
|
||||
ForkJoinPool.commonPool().submit(() -> this.client.get().exchange().expectStatus().isOk()).join();
|
||||
assertPrincipalCreatedFromUserDetails(this.controller.removePrincipal(), this.userBuilder.build());
|
||||
|
||||
+25
-11
@@ -43,14 +43,20 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
public class SecurityMockServerConfigurersClassAnnotatedTests extends AbstractMockServerConfigurersTests {
|
||||
|
||||
WebTestClient client = WebTestClient.bindToController(this.controller)
|
||||
.webFilter(new SecurityContextServerWebExchangeWebFilter())
|
||||
.apply(SecurityMockServerConfigurers.springSecurity()).configureClient()
|
||||
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build();
|
||||
.webFilter(new SecurityContextServerWebExchangeWebFilter())
|
||||
.apply(SecurityMockServerConfigurers.springSecurity())
|
||||
.configureClient()
|
||||
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
|
||||
.build();
|
||||
|
||||
@Test
|
||||
public void wheMockUserWhenClassAnnotatedThenSuccess() {
|
||||
this.client.get().exchange().expectStatus().isOk().expectBody(String.class)
|
||||
.consumeWith((response) -> assertThat(response.getResponseBody()).contains("\"username\":\"user\""));
|
||||
this.client.get()
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.consumeWith((response) -> assertThat(response.getResponseBody()).contains("\"username\":\"user\""));
|
||||
Authentication authentication = TestSecurityContextHolder.getContext().getAuthentication();
|
||||
this.controller.assertPrincipalIsEqualTo(authentication);
|
||||
}
|
||||
@@ -58,18 +64,26 @@ public class SecurityMockServerConfigurersClassAnnotatedTests extends AbstractMo
|
||||
@Test
|
||||
@WithMockUser("method-user")
|
||||
public void withMockUserWhenClassAndMethodAnnotationThenMethodOverrides() {
|
||||
this.client.get().exchange().expectStatus().isOk().expectBody(String.class).consumeWith(
|
||||
(response) -> assertThat(response.getResponseBody()).contains("\"username\":\"method-user\""));
|
||||
this.client.get()
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.consumeWith((response) -> assertThat(response.getResponseBody()).contains("\"username\":\"method-user\""));
|
||||
Authentication authentication = TestSecurityContextHolder.getContext().getAuthentication();
|
||||
this.controller.assertPrincipalIsEqualTo(authentication);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void withMockUserWhenMutateWithThenMustateWithOverrides() {
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockUser("mutateWith-mockUser")).get().exchange()
|
||||
.expectStatus().isOk().expectBody(String.class)
|
||||
.consumeWith((response) -> assertThat(response.getResponseBody())
|
||||
.contains("\"username\":\"mutateWith-mockUser\""));
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockUser("mutateWith-mockUser"))
|
||||
.get()
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.consumeWith((response) -> assertThat(response.getResponseBody())
|
||||
.contains("\"username\":\"mutateWith-mockUser\""));
|
||||
Principal principal = this.controller.removePrincipal();
|
||||
assertPrincipalCreatedFromUserDetails(principal, this.userBuilder.username("mutateWith-mockUser").build());
|
||||
}
|
||||
|
||||
+39
-21
@@ -48,11 +48,13 @@ public class SecurityMockServerConfigurersJwtTests extends AbstractMockServerCon
|
||||
GrantedAuthority authority2 = new SimpleGrantedAuthority("AUTHORITY2");
|
||||
|
||||
WebTestClient client = WebTestClient.bindToController(this.securityContextController)
|
||||
.webFilter(new SecurityContextServerWebExchangeWebFilter())
|
||||
.argumentResolvers((resolvers) -> resolvers
|
||||
.addCustomResolver(new CurrentSecurityContextArgumentResolver(new ReactiveAdapterRegistry())))
|
||||
.apply(SecurityMockServerConfigurers.springSecurity()).configureClient()
|
||||
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build();
|
||||
.webFilter(new SecurityContextServerWebExchangeWebFilter())
|
||||
.argumentResolvers((resolvers) -> resolvers
|
||||
.addCustomResolver(new CurrentSecurityContextArgumentResolver(new ReactiveAdapterRegistry())))
|
||||
.apply(SecurityMockServerConfigurers.springSecurity())
|
||||
.configureClient()
|
||||
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
|
||||
.build();
|
||||
|
||||
@Test
|
||||
public void mockJwtWhenUsingDefaultsTheCreatesJwtAuthentication() {
|
||||
@@ -69,8 +71,11 @@ public class SecurityMockServerConfigurersJwtTests extends AbstractMockServerCon
|
||||
@Test
|
||||
public void mockJwtWhenProvidingBuilderConsumerThenProducesJwtAuthentication() {
|
||||
String name = new String("user");
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockJwt().jwt((jwt) -> jwt.subject(name))).get().exchange()
|
||||
.expectStatus().isOk();
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockJwt().jwt((jwt) -> jwt.subject(name)))
|
||||
.get()
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
SecurityContext context = this.securityContextController.removeSecurityContext();
|
||||
assertThat(context.getAuthentication()).isInstanceOf(JwtAuthenticationToken.class);
|
||||
JwtAuthenticationToken token = (JwtAuthenticationToken) context.getAuthentication();
|
||||
@@ -79,9 +84,14 @@ public class SecurityMockServerConfigurersJwtTests extends AbstractMockServerCon
|
||||
|
||||
@Test
|
||||
public void mockJwtWhenProvidingCustomAuthoritiesThenProducesJwtAuthentication() {
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockJwt()
|
||||
.jwt((jwt) -> jwt.claim("scope", "ignored authorities")).authorities(this.authority1, this.authority2))
|
||||
.get().exchange().expectStatus().isOk();
|
||||
this.client
|
||||
.mutateWith(SecurityMockServerConfigurers.mockJwt()
|
||||
.jwt((jwt) -> jwt.claim("scope", "ignored authorities"))
|
||||
.authorities(this.authority1, this.authority2))
|
||||
.get()
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
SecurityContext context = this.securityContextController.removeSecurityContext();
|
||||
assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities()).containsOnly(this.authority1,
|
||||
this.authority2);
|
||||
@@ -90,21 +100,26 @@ public class SecurityMockServerConfigurersJwtTests extends AbstractMockServerCon
|
||||
@Test
|
||||
public void mockJwtWhenProvidingScopedAuthoritiesThenProducesJwtAuthentication() {
|
||||
this.client
|
||||
.mutateWith(
|
||||
SecurityMockServerConfigurers.mockJwt().jwt((jwt) -> jwt.claim("scope", "scoped authorities")))
|
||||
.get().exchange().expectStatus().isOk();
|
||||
.mutateWith(SecurityMockServerConfigurers.mockJwt().jwt((jwt) -> jwt.claim("scope", "scoped authorities")))
|
||||
.get()
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
SecurityContext context = this.securityContextController.removeSecurityContext();
|
||||
assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities()).containsOnly(
|
||||
new SimpleGrantedAuthority("SCOPE_scoped"), new SimpleGrantedAuthority("SCOPE_authorities"));
|
||||
assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities())
|
||||
.containsOnly(new SimpleGrantedAuthority("SCOPE_scoped"), new SimpleGrantedAuthority("SCOPE_authorities"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mockJwtWhenProvidingGrantedAuthoritiesThenProducesJwtAuthentication() {
|
||||
this.client
|
||||
.mutateWith(
|
||||
SecurityMockServerConfigurers.mockJwt().jwt((jwt) -> jwt.claim("scope", "ignored authorities"))
|
||||
.authorities((jwt) -> Arrays.asList(this.authority1)))
|
||||
.get().exchange().expectStatus().isOk();
|
||||
.mutateWith(SecurityMockServerConfigurers.mockJwt()
|
||||
.jwt((jwt) -> jwt.claim("scope", "ignored authorities"))
|
||||
.authorities((jwt) -> Arrays.asList(this.authority1)))
|
||||
.get()
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
SecurityContext context = this.securityContextController.removeSecurityContext();
|
||||
assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities()).containsOnly(this.authority1);
|
||||
}
|
||||
@@ -112,8 +127,11 @@ public class SecurityMockServerConfigurersJwtTests extends AbstractMockServerCon
|
||||
@Test
|
||||
public void mockJwtWhenProvidingPreparedJwtThenProducesJwtAuthentication() {
|
||||
Jwt originalToken = TestJwts.jwt().header("header1", "value1").subject("some_user").build();
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockJwt().jwt(originalToken)).get().exchange()
|
||||
.expectStatus().isOk();
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockJwt().jwt(originalToken))
|
||||
.get()
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
SecurityContext context = this.securityContextController.removeSecurityContext();
|
||||
assertThat(context.getAuthentication()).isInstanceOf(JwtAuthenticationToken.class);
|
||||
JwtAuthenticationToken retrievedToken = (JwtAuthenticationToken) context.getAuthentication();
|
||||
|
||||
+66
-33
@@ -74,11 +74,13 @@ public class SecurityMockServerConfigurersOAuth2ClientTests extends AbstractMock
|
||||
this.authorizedClientManager = new DefaultReactiveOAuth2AuthorizedClientManager(
|
||||
this.clientRegistrationRepository, this.authorizedClientRepository);
|
||||
this.client = WebTestClient.bindToController(this.controller)
|
||||
.argumentResolvers((c) -> c
|
||||
.addCustomResolver(new OAuth2AuthorizedClientArgumentResolver(this.authorizedClientManager)))
|
||||
.webFilter(new SecurityContextServerWebExchangeWebFilter())
|
||||
.apply(SecurityMockServerConfigurers.springSecurity()).configureClient()
|
||||
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build();
|
||||
.argumentResolvers((c) -> c
|
||||
.addCustomResolver(new OAuth2AuthorizedClientArgumentResolver(this.authorizedClientManager)))
|
||||
.webFilter(new SecurityContextServerWebExchangeWebFilter())
|
||||
.apply(SecurityMockServerConfigurers.springSecurity())
|
||||
.configureClient()
|
||||
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
|
||||
.build();
|
||||
|
||||
}
|
||||
|
||||
@@ -86,14 +88,18 @@ public class SecurityMockServerConfigurersOAuth2ClientTests extends AbstractMock
|
||||
public void oauth2ClientWhenUsingDefaultsThenException() throws Exception {
|
||||
WebHttpHandlerBuilder builder = WebHttpHandlerBuilder.webHandler(new DispatcherHandler());
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> SecurityMockServerConfigurers.mockOAuth2Client().beforeServerCreated(builder))
|
||||
.withMessageContaining("ClientRegistration");
|
||||
.isThrownBy(() -> SecurityMockServerConfigurers.mockOAuth2Client().beforeServerCreated(builder))
|
||||
.withMessageContaining("ClientRegistration");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oauth2ClientWhenUsingRegistrationIdThenProducesAuthorizedClient() throws Exception {
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Client("registration-id")).get().uri("/client")
|
||||
.exchange().expectStatus().isOk();
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Client("registration-id"))
|
||||
.get()
|
||||
.uri("/client")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
OAuth2AuthorizedClient client = this.controller.authorizedClient;
|
||||
assertThat(client).isNotNull();
|
||||
assertThat(client.getClientRegistration().getRegistrationId()).isEqualTo("registration-id");
|
||||
@@ -104,9 +110,15 @@ public class SecurityMockServerConfigurersOAuth2ClientTests extends AbstractMock
|
||||
@Test
|
||||
public void oauth2ClientWhenClientRegistrationThenUses() throws Exception {
|
||||
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
|
||||
.registrationId("registration-id").clientId("client-id").build();
|
||||
.registrationId("registration-id")
|
||||
.clientId("client-id")
|
||||
.build();
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Client().clientRegistration(clientRegistration))
|
||||
.get().uri("/client").exchange().expectStatus().isOk();
|
||||
.get()
|
||||
.uri("/client")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
OAuth2AuthorizedClient client = this.controller.authorizedClient;
|
||||
assertThat(client).isNotNull();
|
||||
assertThat(client.getClientRegistration().getRegistrationId()).isEqualTo("registration-id");
|
||||
@@ -117,9 +129,13 @@ public class SecurityMockServerConfigurersOAuth2ClientTests extends AbstractMock
|
||||
@Test
|
||||
public void oauth2ClientWhenClientRegistrationConsumerThenUses() throws Exception {
|
||||
this.client
|
||||
.mutateWith(SecurityMockServerConfigurers.mockOAuth2Client("registration-id")
|
||||
.clientRegistration((c) -> c.clientId("client-id")))
|
||||
.get().uri("/client").exchange().expectStatus().isOk();
|
||||
.mutateWith(SecurityMockServerConfigurers.mockOAuth2Client("registration-id")
|
||||
.clientRegistration((c) -> c.clientId("client-id")))
|
||||
.get()
|
||||
.uri("/client")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
OAuth2AuthorizedClient client = this.controller.authorizedClient;
|
||||
assertThat(client).isNotNull();
|
||||
assertThat(client.getClientRegistration().getRegistrationId()).isEqualTo("registration-id");
|
||||
@@ -131,18 +147,26 @@ public class SecurityMockServerConfigurersOAuth2ClientTests extends AbstractMock
|
||||
@Test
|
||||
public void oauth2ClientWhenPrincipalNameThenUses() throws Exception {
|
||||
this.client
|
||||
.mutateWith(
|
||||
SecurityMockServerConfigurers.mockOAuth2Client("registration-id").principalName("test-subject"))
|
||||
.get().uri("/client").exchange().expectStatus().isOk().expectBody(String.class)
|
||||
.isEqualTo("test-subject");
|
||||
.mutateWith(SecurityMockServerConfigurers.mockOAuth2Client("registration-id").principalName("test-subject"))
|
||||
.get()
|
||||
.uri("/client")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk()
|
||||
.expectBody(String.class)
|
||||
.isEqualTo("test-subject");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oauth2ClientWhenAccessTokenThenUses() throws Exception {
|
||||
OAuth2AccessToken accessToken = TestOAuth2AccessTokens.noScopes();
|
||||
this.client
|
||||
.mutateWith(SecurityMockServerConfigurers.mockOAuth2Client("registration-id").accessToken(accessToken))
|
||||
.get().uri("/client").exchange().expectStatus().isOk();
|
||||
.mutateWith(SecurityMockServerConfigurers.mockOAuth2Client("registration-id").accessToken(accessToken))
|
||||
.get()
|
||||
.uri("/client")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
OAuth2AuthorizedClient client = this.controller.authorizedClient;
|
||||
assertThat(client).isNotNull();
|
||||
assertThat(client.getClientRegistration().getRegistrationId()).isEqualTo("registration-id");
|
||||
@@ -152,15 +176,20 @@ public class SecurityMockServerConfigurersOAuth2ClientTests extends AbstractMock
|
||||
|
||||
@Test
|
||||
public void oauth2ClientWhenUsedOnceThenDoesNotAffectRemainingTests() throws Exception {
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Client("registration-id")).get().uri("/client")
|
||||
.exchange().expectStatus().isOk();
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Client("registration-id"))
|
||||
.get()
|
||||
.uri("/client")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
OAuth2AuthorizedClient client = this.controller.authorizedClient;
|
||||
assertThat(client).isNotNull();
|
||||
assertThat(client.getClientRegistration().getClientId()).isEqualTo("test-client");
|
||||
client = new OAuth2AuthorizedClient(TestClientRegistrations.clientRegistration().build(), "sub",
|
||||
TestOAuth2AccessTokens.noScopes());
|
||||
given(this.authorizedClientRepository.loadAuthorizedClient(eq("registration-id"), any(Authentication.class),
|
||||
any(ServerWebExchange.class))).willReturn(Mono.just(client));
|
||||
any(ServerWebExchange.class)))
|
||||
.willReturn(Mono.just(client));
|
||||
this.client.get().uri("/client").exchange().expectStatus().isOk();
|
||||
client = this.controller.authorizedClient;
|
||||
assertThat(client).isNotNull();
|
||||
@@ -173,16 +202,20 @@ public class SecurityMockServerConfigurersOAuth2ClientTests extends AbstractMock
|
||||
@Test
|
||||
public void oauth2ClientWhenUsedThenSetsClientToRepository() {
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Client("registration-id"))
|
||||
.mutateWith((clientBuilder, httpBuilder, connector) -> httpBuilder
|
||||
.filters((filters) -> filters.add((exchange, chain) -> {
|
||||
ServerOAuth2AuthorizedClientRepository repository = (ServerOAuth2AuthorizedClientRepository) ReflectionTestUtils
|
||||
.getField(this.authorizedClientManager, "authorizedClientRepository");
|
||||
assertThat(repository).isInstanceOf(TestOAuth2AuthorizedClientRepository.class);
|
||||
return repository.loadAuthorizedClient("registration-id", null, exchange)
|
||||
.switchIfEmpty(Mono.error(new AssertionError("no authorized client found")))
|
||||
.then(chain.filter(exchange));
|
||||
})))
|
||||
.get().uri("/client").exchange().expectStatus().isOk();
|
||||
.mutateWith((clientBuilder, httpBuilder, connector) -> httpBuilder
|
||||
.filters((filters) -> filters.add((exchange, chain) -> {
|
||||
ServerOAuth2AuthorizedClientRepository repository = (ServerOAuth2AuthorizedClientRepository) ReflectionTestUtils
|
||||
.getField(this.authorizedClientManager, "authorizedClientRepository");
|
||||
assertThat(repository).isInstanceOf(TestOAuth2AuthorizedClientRepository.class);
|
||||
return repository.loadAuthorizedClient("registration-id", null, exchange)
|
||||
.switchIfEmpty(Mono.error(new AssertionError("no authorized client found")))
|
||||
.then(chain.filter(exchange));
|
||||
})))
|
||||
.get()
|
||||
.uri("/client")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
}
|
||||
|
||||
@RestController
|
||||
|
||||
+65
-26
@@ -61,30 +61,40 @@ public class SecurityMockServerConfigurersOAuth2LoginTests extends AbstractMockS
|
||||
@BeforeEach
|
||||
public void setup() {
|
||||
this.client = WebTestClient.bindToController(this.controller)
|
||||
.argumentResolvers((c) -> c.addCustomResolver(new OAuth2AuthorizedClientArgumentResolver(
|
||||
this.clientRegistrationRepository, this.authorizedClientRepository)))
|
||||
.webFilter(new SecurityContextServerWebExchangeWebFilter())
|
||||
.apply(SecurityMockServerConfigurers.springSecurity()).configureClient()
|
||||
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build();
|
||||
.argumentResolvers((c) -> c.addCustomResolver(new OAuth2AuthorizedClientArgumentResolver(
|
||||
this.clientRegistrationRepository, this.authorizedClientRepository)))
|
||||
.webFilter(new SecurityContextServerWebExchangeWebFilter())
|
||||
.apply(SecurityMockServerConfigurers.springSecurity())
|
||||
.configureClient()
|
||||
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oauth2LoginWhenUsingDefaultsThenProducesDefaultAuthentication() {
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login()).get().uri("/token").exchange()
|
||||
.expectStatus().isOk();
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login())
|
||||
.get()
|
||||
.uri("/token")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
OAuth2AuthenticationToken token = this.controller.token;
|
||||
assertThat(token).isNotNull();
|
||||
assertThat(token.getAuthorizedClientRegistrationId()).isEqualTo("test");
|
||||
assertThat(token.getPrincipal()).isInstanceOf(OAuth2User.class);
|
||||
assertThat(token.getPrincipal().getAttributes()).containsEntry("sub", "user");
|
||||
assertThat((Collection<GrantedAuthority>) token.getPrincipal().getAuthorities())
|
||||
.contains(new SimpleGrantedAuthority("SCOPE_read"));
|
||||
.contains(new SimpleGrantedAuthority("SCOPE_read"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oauth2LoginWhenUsingDefaultsThenProducesDefaultAuthorizedClient() {
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login()).get().uri("/client").exchange()
|
||||
.expectStatus().isOk();
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login())
|
||||
.get()
|
||||
.uri("/client")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
OAuth2AuthorizedClient client = this.controller.authorizedClient;
|
||||
assertThat(client).isNotNull();
|
||||
assertThat(client.getClientRegistration().getRegistrationId()).isEqualTo("test");
|
||||
@@ -95,20 +105,28 @@ public class SecurityMockServerConfigurersOAuth2LoginTests extends AbstractMockS
|
||||
@Test
|
||||
public void oauth2LoginWhenAuthoritiesSpecifiedThenGrantsAccess() {
|
||||
this.client
|
||||
.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login()
|
||||
.authorities(new SimpleGrantedAuthority("SCOPE_admin")))
|
||||
.get().uri("/token").exchange().expectStatus().isOk();
|
||||
.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login()
|
||||
.authorities(new SimpleGrantedAuthority("SCOPE_admin")))
|
||||
.get()
|
||||
.uri("/token")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
OAuth2AuthenticationToken token = this.controller.token;
|
||||
assertThat((Collection<GrantedAuthority>) token.getPrincipal().getAuthorities())
|
||||
.contains(new SimpleGrantedAuthority("SCOPE_admin"));
|
||||
.contains(new SimpleGrantedAuthority("SCOPE_admin"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oauth2LoginWhenAttributeSpecifiedThenUserHasAttribute() {
|
||||
this.client
|
||||
.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login()
|
||||
.attributes((a) -> a.put("iss", "https://idp.example.org")))
|
||||
.get().uri("/token").exchange().expectStatus().isOk();
|
||||
.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login()
|
||||
.attributes((a) -> a.put("iss", "https://idp.example.org")))
|
||||
.get()
|
||||
.uri("/token")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
OAuth2AuthenticationToken token = this.controller.token;
|
||||
assertThat(token.getPrincipal().getAttributes()).containsEntry("iss", "https://idp.example.org");
|
||||
}
|
||||
@@ -117,12 +135,20 @@ public class SecurityMockServerConfigurersOAuth2LoginTests extends AbstractMockS
|
||||
public void oauth2LoginWhenNameSpecifiedThenUserHasName() throws Exception {
|
||||
OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.commaSeparatedStringToAuthorityList("SCOPE_read"),
|
||||
Collections.singletonMap("custom-attribute", "test-subject"), "custom-attribute");
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oauth2User)).get()
|
||||
.uri("/token").exchange().expectStatus().isOk();
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oauth2User))
|
||||
.get()
|
||||
.uri("/token")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
OAuth2AuthenticationToken token = this.controller.token;
|
||||
assertThat(token.getPrincipal().getName()).isEqualTo("test-subject");
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oauth2User)).get()
|
||||
.uri("/client").exchange().expectStatus().isOk();
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oauth2User))
|
||||
.get()
|
||||
.uri("/client")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
OAuth2AuthorizedClient client = this.controller.authorizedClient;
|
||||
assertThat(client.getPrincipalName()).isEqualTo("test-subject");
|
||||
}
|
||||
@@ -131,13 +157,26 @@ public class SecurityMockServerConfigurersOAuth2LoginTests extends AbstractMockS
|
||||
public void oauth2LoginWhenOAuth2UserSpecifiedThenLastCalledTakesPrecedence() throws Exception {
|
||||
OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("SCOPE_read"),
|
||||
Collections.singletonMap("sub", "subject"), "sub");
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login()
|
||||
.attributes((a) -> a.put("subject", "foo")).oauth2User(oauth2User)).get().uri("/token").exchange()
|
||||
.expectStatus().isOk();
|
||||
this.client
|
||||
.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login()
|
||||
.attributes((a) -> a.put("subject", "foo"))
|
||||
.oauth2User(oauth2User))
|
||||
.get()
|
||||
.uri("/token")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
OAuth2AuthenticationToken token = this.controller.token;
|
||||
assertThat(token.getPrincipal().getAttributes()).containsEntry("sub", "subject");
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oauth2User)
|
||||
.attributes((a) -> a.put("sub", "bar"))).get().uri("/token").exchange().expectStatus().isOk();
|
||||
this.client
|
||||
.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login()
|
||||
.oauth2User(oauth2User)
|
||||
.attributes((a) -> a.put("sub", "bar")))
|
||||
.get()
|
||||
.uri("/token")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
token = this.controller.token;
|
||||
assertThat(token.getPrincipal().getAttributes()).containsEntry("sub", "bar");
|
||||
}
|
||||
|
||||
+69
-29
@@ -62,31 +62,41 @@ public class SecurityMockServerConfigurersOidcLoginTests extends AbstractMockSer
|
||||
@BeforeEach
|
||||
public void setup() {
|
||||
this.client = WebTestClient.bindToController(this.controller)
|
||||
.argumentResolvers((c) -> c.addCustomResolver(new OAuth2AuthorizedClientArgumentResolver(
|
||||
this.clientRegistrationRepository, this.authorizedClientRepository)))
|
||||
.webFilter(new SecurityContextServerWebExchangeWebFilter())
|
||||
.apply(SecurityMockServerConfigurers.springSecurity()).configureClient()
|
||||
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build();
|
||||
.argumentResolvers((c) -> c.addCustomResolver(new OAuth2AuthorizedClientArgumentResolver(
|
||||
this.clientRegistrationRepository, this.authorizedClientRepository)))
|
||||
.webFilter(new SecurityContextServerWebExchangeWebFilter())
|
||||
.apply(SecurityMockServerConfigurers.springSecurity())
|
||||
.configureClient()
|
||||
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oidcLoginWhenUsingDefaultsThenProducesDefaultAuthentication() {
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOidcLogin()).get().uri("/token").exchange()
|
||||
.expectStatus().isOk();
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOidcLogin())
|
||||
.get()
|
||||
.uri("/token")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
OAuth2AuthenticationToken token = this.controller.token;
|
||||
assertThat(token).isNotNull();
|
||||
assertThat(token.getAuthorizedClientRegistrationId()).isEqualTo("test");
|
||||
assertThat(token.getPrincipal()).isInstanceOf(OidcUser.class);
|
||||
assertThat(token.getPrincipal().getAttributes()).containsEntry("sub", "user");
|
||||
assertThat((Collection<GrantedAuthority>) token.getPrincipal().getAuthorities())
|
||||
.contains(new SimpleGrantedAuthority("SCOPE_read"));
|
||||
.contains(new SimpleGrantedAuthority("SCOPE_read"));
|
||||
assertThat(((OidcUser) token.getPrincipal()).getIdToken().getTokenValue()).isEqualTo("id-token");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oidcLoginWhenUsingDefaultsThenProducesDefaultAuthorizedClient() {
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOidcLogin()).get().uri("/client").exchange()
|
||||
.expectStatus().isOk();
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOidcLogin())
|
||||
.get()
|
||||
.uri("/client")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
OAuth2AuthorizedClient client = this.controller.authorizedClient;
|
||||
assertThat(client).isNotNull();
|
||||
assertThat(client.getClientRegistration().getRegistrationId()).isEqualTo("test");
|
||||
@@ -97,20 +107,28 @@ public class SecurityMockServerConfigurersOidcLoginTests extends AbstractMockSer
|
||||
@Test
|
||||
public void oidcLoginWhenAuthoritiesSpecifiedThenGrantsAccess() {
|
||||
this.client
|
||||
.mutateWith(SecurityMockServerConfigurers.mockOidcLogin()
|
||||
.authorities(new SimpleGrantedAuthority("SCOPE_admin")))
|
||||
.get().uri("/token").exchange().expectStatus().isOk();
|
||||
.mutateWith(SecurityMockServerConfigurers.mockOidcLogin()
|
||||
.authorities(new SimpleGrantedAuthority("SCOPE_admin")))
|
||||
.get()
|
||||
.uri("/token")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
OAuth2AuthenticationToken token = this.controller.token;
|
||||
assertThat((Collection<GrantedAuthority>) token.getPrincipal().getAuthorities())
|
||||
.contains(new SimpleGrantedAuthority("SCOPE_admin"));
|
||||
.contains(new SimpleGrantedAuthority("SCOPE_admin"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oidcLoginWhenIdTokenSpecifiedThenUserHasClaims() {
|
||||
this.client
|
||||
.mutateWith(SecurityMockServerConfigurers.mockOidcLogin()
|
||||
.idToken((i) -> i.issuer("https://idp.example.org")))
|
||||
.get().uri("/token").exchange().expectStatus().isOk();
|
||||
.mutateWith(
|
||||
SecurityMockServerConfigurers.mockOidcLogin().idToken((i) -> i.issuer("https://idp.example.org")))
|
||||
.get()
|
||||
.uri("/token")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
OAuth2AuthenticationToken token = this.controller.token;
|
||||
assertThat(token.getPrincipal().getAttributes()).containsEntry("iss", "https://idp.example.org");
|
||||
}
|
||||
@@ -118,8 +136,12 @@ public class SecurityMockServerConfigurersOidcLoginTests extends AbstractMockSer
|
||||
@Test
|
||||
public void oidcLoginWhenUserInfoSpecifiedThenUserHasClaims() throws Exception {
|
||||
this.client
|
||||
.mutateWith(SecurityMockServerConfigurers.mockOidcLogin().userInfoToken((u) -> u.email("email@email")))
|
||||
.get().uri("/token").exchange().expectStatus().isOk();
|
||||
.mutateWith(SecurityMockServerConfigurers.mockOidcLogin().userInfoToken((u) -> u.email("email@email")))
|
||||
.get()
|
||||
.uri("/token")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
OAuth2AuthenticationToken token = this.controller.token;
|
||||
assertThat(token.getPrincipal().getAttributes()).containsEntry("email", "email@email");
|
||||
}
|
||||
@@ -129,12 +151,20 @@ public class SecurityMockServerConfigurersOidcLoginTests extends AbstractMockSer
|
||||
OidcUser oidcUser = new DefaultOidcUser(AuthorityUtils.commaSeparatedStringToAuthorityList("SCOPE_read"),
|
||||
OidcIdToken.withTokenValue("id-token").claim("custom-attribute", "test-subject").build(),
|
||||
"custom-attribute");
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oidcUser)).get().uri("/token")
|
||||
.exchange().expectStatus().isOk();
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oidcUser))
|
||||
.get()
|
||||
.uri("/token")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
OAuth2AuthenticationToken token = this.controller.token;
|
||||
assertThat(token.getPrincipal().getName()).isEqualTo("test-subject");
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oidcUser)).get()
|
||||
.uri("/client").exchange().expectStatus().isOk();
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oidcUser))
|
||||
.get()
|
||||
.uri("/client")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
OAuth2AuthorizedClient client = this.controller.authorizedClient;
|
||||
assertThat(client.getPrincipalName()).isEqualTo("test-subject");
|
||||
}
|
||||
@@ -144,14 +174,24 @@ public class SecurityMockServerConfigurersOidcLoginTests extends AbstractMockSer
|
||||
public void oidcLoginWhenOidcUserSpecifiedThenLastCalledTakesPrecedence() throws Exception {
|
||||
OidcUser oidcUser = new DefaultOidcUser(AuthorityUtils.createAuthorityList("SCOPE_read"),
|
||||
TestOidcIdTokens.idToken().build());
|
||||
this.client.mutateWith(
|
||||
SecurityMockServerConfigurers.mockOidcLogin().idToken((i) -> i.subject("foo")).oidcUser(oidcUser)).get()
|
||||
.uri("/token").exchange().expectStatus().isOk();
|
||||
this.client
|
||||
.mutateWith(
|
||||
SecurityMockServerConfigurers.mockOidcLogin().idToken((i) -> i.subject("foo")).oidcUser(oidcUser))
|
||||
.get()
|
||||
.uri("/token")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
OAuth2AuthenticationToken token = this.controller.token;
|
||||
assertThat(token.getPrincipal().getAttributes()).containsEntry("sub", "subject");
|
||||
this.client.mutateWith(
|
||||
SecurityMockServerConfigurers.mockOidcLogin().oidcUser(oidcUser).idToken((i) -> i.subject("bar"))).get()
|
||||
.uri("/token").exchange().expectStatus().isOk();
|
||||
this.client
|
||||
.mutateWith(
|
||||
SecurityMockServerConfigurers.mockOidcLogin().oidcUser(oidcUser).idToken((i) -> i.subject("bar")))
|
||||
.get()
|
||||
.uri("/token")
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
token = this.controller.token;
|
||||
assertThat(token.getPrincipal().getAttributes()).containsEntry("sub", "bar");
|
||||
}
|
||||
|
||||
+49
-23
@@ -39,16 +39,21 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
public class SecurityMockServerConfigurersTests extends AbstractMockServerConfigurersTests {
|
||||
|
||||
WebTestClient client = WebTestClient.bindToController(this.controller)
|
||||
.webFilter(new CsrfWebFilter(), new SecurityContextServerWebExchangeWebFilter())
|
||||
.apply(SecurityMockServerConfigurers.springSecurity()).configureClient()
|
||||
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build();
|
||||
.webFilter(new CsrfWebFilter(), new SecurityContextServerWebExchangeWebFilter())
|
||||
.apply(SecurityMockServerConfigurers.springSecurity())
|
||||
.configureClient()
|
||||
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
|
||||
.build();
|
||||
|
||||
@Test
|
||||
public void mockAuthenticationWhenLocalThenSuccess() {
|
||||
TestingAuthenticationToken authentication = new TestingAuthenticationToken("authentication", "secret",
|
||||
"ROLE_USER");
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockAuthentication(authentication)).get().exchange()
|
||||
.expectStatus().isOk();
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockAuthentication(authentication))
|
||||
.get()
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
this.controller.assertPrincipalIsEqualTo(authentication);
|
||||
}
|
||||
|
||||
@@ -57,10 +62,12 @@ public class SecurityMockServerConfigurersTests extends AbstractMockServerConfig
|
||||
TestingAuthenticationToken authentication = new TestingAuthenticationToken("authentication", "secret",
|
||||
"ROLE_USER");
|
||||
this.client = WebTestClient.bindToController(this.controller)
|
||||
.webFilter(new SecurityContextServerWebExchangeWebFilter())
|
||||
.apply(SecurityMockServerConfigurers.springSecurity())
|
||||
.apply(SecurityMockServerConfigurers.mockAuthentication(authentication)).configureClient()
|
||||
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build();
|
||||
.webFilter(new SecurityContextServerWebExchangeWebFilter())
|
||||
.apply(SecurityMockServerConfigurers.springSecurity())
|
||||
.apply(SecurityMockServerConfigurers.mockAuthentication(authentication))
|
||||
.configureClient()
|
||||
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
|
||||
.build();
|
||||
this.client.get().exchange().expectStatus().isOk();
|
||||
this.controller.assertPrincipalIsEqualTo(authentication);
|
||||
}
|
||||
@@ -75,9 +82,12 @@ public class SecurityMockServerConfigurersTests extends AbstractMockServerConfig
|
||||
@Test
|
||||
public void mockUserWhenGlobalThenSuccess() {
|
||||
this.client = WebTestClient.bindToController(this.controller)
|
||||
.webFilter(new SecurityContextServerWebExchangeWebFilter())
|
||||
.apply(SecurityMockServerConfigurers.springSecurity()).apply(SecurityMockServerConfigurers.mockUser())
|
||||
.configureClient().defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build();
|
||||
.webFilter(new SecurityContextServerWebExchangeWebFilter())
|
||||
.apply(SecurityMockServerConfigurers.springSecurity())
|
||||
.apply(SecurityMockServerConfigurers.mockUser())
|
||||
.configureClient()
|
||||
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
|
||||
.build();
|
||||
this.client.get().exchange().expectStatus().isOk();
|
||||
Principal actual = this.controller.removePrincipal();
|
||||
assertPrincipalCreatedFromUserDetails(actual, this.userBuilder.build());
|
||||
@@ -85,8 +95,11 @@ public class SecurityMockServerConfigurersTests extends AbstractMockServerConfig
|
||||
|
||||
@Test
|
||||
public void mockUserStringWhenLocalThenSuccess() {
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockUser(this.userBuilder.build().getUsername())).get()
|
||||
.exchange().expectStatus().isOk();
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockUser(this.userBuilder.build().getUsername()))
|
||||
.get()
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
Principal actual = this.controller.removePrincipal();
|
||||
assertPrincipalCreatedFromUserDetails(actual, this.userBuilder.build());
|
||||
}
|
||||
@@ -95,8 +108,11 @@ public class SecurityMockServerConfigurersTests extends AbstractMockServerConfig
|
||||
public void mockUserStringWhenCustomThenSuccess() {
|
||||
this.userBuilder = User.withUsername("admin").password("secret").roles("USER", "ADMIN");
|
||||
this.client
|
||||
.mutateWith(SecurityMockServerConfigurers.mockUser("admin").password("secret").roles("USER", "ADMIN"))
|
||||
.get().exchange().expectStatus().isOk();
|
||||
.mutateWith(SecurityMockServerConfigurers.mockUser("admin").password("secret").roles("USER", "ADMIN"))
|
||||
.get()
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
Principal actual = this.controller.removePrincipal();
|
||||
assertPrincipalCreatedFromUserDetails(actual, this.userBuilder.build());
|
||||
}
|
||||
@@ -104,24 +120,34 @@ public class SecurityMockServerConfigurersTests extends AbstractMockServerConfig
|
||||
@Test
|
||||
public void mockUserUserDetailsLocalThenSuccess() {
|
||||
UserDetails userDetails = this.userBuilder.build();
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockUser(userDetails)).get().exchange().expectStatus()
|
||||
.isOk();
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.mockUser(userDetails))
|
||||
.get()
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isOk();
|
||||
Principal actual = this.controller.removePrincipal();
|
||||
assertPrincipalCreatedFromUserDetails(actual, this.userBuilder.build());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void csrfWhenMutateWithThenDisablesCsrf() {
|
||||
this.client.post().exchange().expectStatus().isEqualTo(HttpStatus.FORBIDDEN).expectBody()
|
||||
.consumeWith((b) -> assertThat(new String(b.getResponseBody())).contains("CSRF"));
|
||||
this.client.post()
|
||||
.exchange()
|
||||
.expectStatus()
|
||||
.isEqualTo(HttpStatus.FORBIDDEN)
|
||||
.expectBody()
|
||||
.consumeWith((b) -> assertThat(new String(b.getResponseBody())).contains("CSRF"));
|
||||
this.client.mutateWith(SecurityMockServerConfigurers.csrf()).post().exchange().expectStatus().isOk();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void csrfWhenGlobalThenDisablesCsrf() {
|
||||
this.client = WebTestClient.bindToController(this.controller).webFilter(new CsrfWebFilter())
|
||||
.apply(SecurityMockServerConfigurers.springSecurity()).apply(SecurityMockServerConfigurers.csrf())
|
||||
.configureClient().build();
|
||||
this.client = WebTestClient.bindToController(this.controller)
|
||||
.webFilter(new CsrfWebFilter())
|
||||
.apply(SecurityMockServerConfigurers.springSecurity())
|
||||
.apply(SecurityMockServerConfigurers.csrf())
|
||||
.configureClient()
|
||||
.build();
|
||||
this.client.get().exchange().expectStatus().isOk();
|
||||
}
|
||||
|
||||
|
||||
+35
-22
@@ -65,49 +65,62 @@ public class Sec2935Tests {
|
||||
// SEC-2935
|
||||
@Test
|
||||
public void postProcessorUserNoUser() throws Exception {
|
||||
this.mvc.perform(get("/admin/abc").with(user("user").roles("ADMIN", "USER"))).andExpect(status().isNotFound())
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
this.mvc.perform(get("/admin/abc").with(user("user").roles("ADMIN", "USER")))
|
||||
.andExpect(status().isNotFound())
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
this.mvc.perform(get("/admin/abc")).andExpect(status().isUnauthorized()).andExpect(unauthenticated());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void postProcessorUserOtherUser() throws Exception {
|
||||
this.mvc.perform(get("/admin/abc").with(user("user1").roles("ADMIN", "USER"))).andExpect(status().isNotFound())
|
||||
.andExpect(authenticated().withUsername("user1"));
|
||||
this.mvc.perform(get("/admin/abc").with(user("user2").roles("USER"))).andExpect(status().isForbidden())
|
||||
.andExpect(authenticated().withUsername("user2"));
|
||||
this.mvc.perform(get("/admin/abc").with(user("user1").roles("ADMIN", "USER")))
|
||||
.andExpect(status().isNotFound())
|
||||
.andExpect(authenticated().withUsername("user1"));
|
||||
this.mvc.perform(get("/admin/abc").with(user("user2").roles("USER")))
|
||||
.andExpect(status().isForbidden())
|
||||
.andExpect(authenticated().withUsername("user2"));
|
||||
}
|
||||
|
||||
@WithMockUser
|
||||
@Test
|
||||
public void postProcessorUserWithMockUser() throws Exception {
|
||||
this.mvc.perform(get("/admin/abc").with(user("user1").roles("ADMIN", "USER"))).andExpect(status().isNotFound())
|
||||
.andExpect(authenticated().withUsername("user1"));
|
||||
this.mvc.perform(get("/admin/abc")).andExpect(status().isForbidden())
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
this.mvc.perform(get("/admin/abc").with(user("user1").roles("ADMIN", "USER")))
|
||||
.andExpect(status().isNotFound())
|
||||
.andExpect(authenticated().withUsername("user1"));
|
||||
this.mvc.perform(get("/admin/abc"))
|
||||
.andExpect(status().isForbidden())
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
}
|
||||
|
||||
// SEC-2941
|
||||
@Test
|
||||
public void defaultRequest() throws Exception {
|
||||
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity())
|
||||
.defaultRequest(get("/").with(user("default"))).build();
|
||||
this.mvc.perform(get("/admin/abc").with(user("user1").roles("ADMIN", "USER"))).andExpect(status().isNotFound())
|
||||
.andExpect(authenticated().withUsername("user1"));
|
||||
this.mvc.perform(get("/admin/abc")).andExpect(status().isForbidden())
|
||||
.andExpect(authenticated().withUsername("default"));
|
||||
this.mvc = MockMvcBuilders.webAppContextSetup(this.context)
|
||||
.apply(springSecurity())
|
||||
.defaultRequest(get("/").with(user("default")))
|
||||
.build();
|
||||
this.mvc.perform(get("/admin/abc").with(user("user1").roles("ADMIN", "USER")))
|
||||
.andExpect(status().isNotFound())
|
||||
.andExpect(authenticated().withUsername("user1"));
|
||||
this.mvc.perform(get("/admin/abc"))
|
||||
.andExpect(status().isForbidden())
|
||||
.andExpect(authenticated().withUsername("default"));
|
||||
}
|
||||
|
||||
@Disabled
|
||||
@WithMockUser
|
||||
@Test
|
||||
public void defaultRequestOverridesWithMockUser() throws Exception {
|
||||
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity())
|
||||
.defaultRequest(get("/").with(user("default"))).build();
|
||||
this.mvc.perform(get("/admin/abc").with(user("user1").roles("ADMIN", "USER"))).andExpect(status().isNotFound())
|
||||
.andExpect(authenticated().withUsername("user1"));
|
||||
this.mvc.perform(get("/admin/abc")).andExpect(status().isForbidden())
|
||||
.andExpect(authenticated().withUsername("default"));
|
||||
this.mvc = MockMvcBuilders.webAppContextSetup(this.context)
|
||||
.apply(springSecurity())
|
||||
.defaultRequest(get("/").with(user("default")))
|
||||
.build();
|
||||
this.mvc.perform(get("/admin/abc").with(user("user1").roles("ADMIN", "USER")))
|
||||
.andExpect(status().isNotFound())
|
||||
.andExpect(authenticated().withUsername("user1"));
|
||||
this.mvc.perform(get("/admin/abc"))
|
||||
.andExpect(status().isForbidden())
|
||||
.andExpect(authenticated().withUsername("default"));
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
|
||||
+12
-7
@@ -62,8 +62,9 @@ public class SecurityMockMvcRequestBuildersFormLoginTests {
|
||||
|
||||
@Test
|
||||
public void custom() {
|
||||
MockHttpServletRequest request = formLogin("/login").user("username", "admin").password("password", "secret")
|
||||
.buildRequest(this.servletContext);
|
||||
MockHttpServletRequest request = formLogin("/login").user("username", "admin")
|
||||
.password("password", "secret")
|
||||
.buildRequest(this.servletContext);
|
||||
CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
|
||||
assertThat(request.getParameter("username")).isEqualTo("admin");
|
||||
assertThat(request.getParameter("password")).isEqualTo("secret");
|
||||
@@ -75,7 +76,9 @@ public class SecurityMockMvcRequestBuildersFormLoginTests {
|
||||
@Test
|
||||
public void customWithUriVars() {
|
||||
MockHttpServletRequest request = formLogin().loginProcessingUrl("/uri-login/{var1}/{var2}", "val1", "val2")
|
||||
.user("username", "admin").password("password", "secret").buildRequest(this.servletContext);
|
||||
.user("username", "admin")
|
||||
.password("password", "secret")
|
||||
.buildRequest(this.servletContext);
|
||||
CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
|
||||
assertThat(request.getParameter("username")).isEqualTo("admin");
|
||||
assertThat(request.getParameter("password")).isEqualTo("secret");
|
||||
@@ -94,11 +97,12 @@ public class SecurityMockMvcRequestBuildersFormLoginTests {
|
||||
RequestPostProcessor postProcessor = mock(RequestPostProcessor.class);
|
||||
given(postProcessor.postProcessRequest(any())).willAnswer((i) -> i.getArgument(0));
|
||||
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new Object())
|
||||
.defaultRequest(MockMvcRequestBuilders.get("/").with(postProcessor)).build();
|
||||
.defaultRequest(MockMvcRequestBuilders.get("/").with(postProcessor))
|
||||
.build();
|
||||
MvcResult mvcResult = mockMvc.perform(formLogin()).andReturn();
|
||||
assertThat(mvcResult.getRequest().getMethod()).isEqualTo(HttpMethod.POST.name());
|
||||
assertThat(mvcResult.getRequest().getHeader("Accept"))
|
||||
.isEqualTo(MediaType.toString(Arrays.asList(MediaType.APPLICATION_FORM_URLENCODED)));
|
||||
.isEqualTo(MediaType.toString(Arrays.asList(MediaType.APPLICATION_FORM_URLENCODED)));
|
||||
assertThat(mvcResult.getRequest().getParameter("username")).isEqualTo("user");
|
||||
assertThat(mvcResult.getRequest().getParameter("password")).isEqualTo("password");
|
||||
assertThat(mvcResult.getRequest().getRequestURI()).isEqualTo("/login");
|
||||
@@ -109,8 +113,9 @@ public class SecurityMockMvcRequestBuildersFormLoginTests {
|
||||
// gh-3920
|
||||
@Test
|
||||
public void usesAcceptMediaForContentNegotiation() {
|
||||
MockHttpServletRequest request = formLogin("/login").user("username", "admin").password("password", "secret")
|
||||
.buildRequest(this.servletContext);
|
||||
MockHttpServletRequest request = formLogin("/login").user("username", "admin")
|
||||
.password("password", "secret")
|
||||
.buildRequest(this.servletContext);
|
||||
assertThat(request.getHeader("Accept")).isEqualTo(MediaType.APPLICATION_FORM_URLENCODED_VALUE);
|
||||
}
|
||||
|
||||
|
||||
+4
-3
@@ -69,7 +69,7 @@ public class SecurityMockMvcRequestBuildersFormLogoutTests {
|
||||
@Test
|
||||
public void customWithUriVars() {
|
||||
MockHttpServletRequest request = logout().logoutUrl("/uri-logout/{var1}/{var2}", "val1", "val2")
|
||||
.buildRequest(this.servletContext);
|
||||
.buildRequest(this.servletContext);
|
||||
CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
|
||||
assertThat(request.getMethod()).isEqualTo("POST");
|
||||
assertThat(request.getParameter(token.getParameterName())).isEqualTo(token.getToken());
|
||||
@@ -86,11 +86,12 @@ public class SecurityMockMvcRequestBuildersFormLogoutTests {
|
||||
RequestPostProcessor postProcessor = mock(RequestPostProcessor.class);
|
||||
given(postProcessor.postProcessRequest(any())).willAnswer((i) -> i.getArgument(0));
|
||||
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new Object())
|
||||
.defaultRequest(MockMvcRequestBuilders.get("/").with(postProcessor)).build();
|
||||
.defaultRequest(MockMvcRequestBuilders.get("/").with(postProcessor))
|
||||
.build();
|
||||
MvcResult mvcResult = mockMvc.perform(logout()).andReturn();
|
||||
assertThat(mvcResult.getRequest().getMethod()).isEqualTo(HttpMethod.POST.name());
|
||||
assertThat(mvcResult.getRequest().getHeader("Accept"))
|
||||
.isEqualTo(MediaType.toString(Arrays.asList(MediaType.TEXT_HTML, MediaType.ALL)));
|
||||
.isEqualTo(MediaType.toString(Arrays.asList(MediaType.TEXT_HTML, MediaType.ALL)));
|
||||
assertThat(mvcResult.getRequest().getRequestURI()).isEqualTo("/logout");
|
||||
assertThat(mvcResult.getRequest().getParameter("_csrf")).isNotEmpty();
|
||||
verify(postProcessor).postProcessRequest(any());
|
||||
|
||||
+1
-1
@@ -61,7 +61,7 @@ public class SecurityMockMvcRequestPostProcessorsAuthenticationTests {
|
||||
public void setup() {
|
||||
this.request = new MockHttpServletRequest();
|
||||
this.webTestUtils.when(() -> WebTestUtils.getSecurityContextRepository(this.request))
|
||||
.thenReturn(this.repository);
|
||||
.thenReturn(this.repository);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
|
||||
+3
-3
@@ -46,7 +46,7 @@ public class SecurityMockMvcRequestPostProcessorsCertificateTests {
|
||||
public void x509SingleCertificate() {
|
||||
MockHttpServletRequest postProcessedRequest = x509(this.certificate).postProcessRequest(this.request);
|
||||
X509Certificate[] certificates = (X509Certificate[]) postProcessedRequest
|
||||
.getAttribute("jakarta.servlet.request.X509Certificate");
|
||||
.getAttribute("jakarta.servlet.request.X509Certificate");
|
||||
assertThat(certificates).containsOnly(this.certificate);
|
||||
}
|
||||
|
||||
@@ -54,10 +54,10 @@ public class SecurityMockMvcRequestPostProcessorsCertificateTests {
|
||||
public void x509ResourceName() throws Exception {
|
||||
MockHttpServletRequest postProcessedRequest = x509("rod.cer").postProcessRequest(this.request);
|
||||
X509Certificate[] certificates = (X509Certificate[]) postProcessedRequest
|
||||
.getAttribute("jakarta.servlet.request.X509Certificate");
|
||||
.getAttribute("jakarta.servlet.request.X509Certificate");
|
||||
assertThat(certificates).hasSize(1);
|
||||
assertThat(certificates[0].getSubjectDN().getName())
|
||||
.isEqualTo("CN=rod, OU=Spring Security, O=Spring Framework");
|
||||
.isEqualTo("CN=rod, OU=Spring Security, O=Spring Framework");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+3
-3
@@ -87,7 +87,7 @@ public class SecurityMockMvcRequestPostProcessorsDigestTests {
|
||||
String username = "custom";
|
||||
this.password = "secret";
|
||||
MockHttpServletRequest postProcessedRequest = digest(username).password(this.password)
|
||||
.postProcessRequest(this.request);
|
||||
.postProcessRequest(this.request);
|
||||
assertThat(extractUser()).isEqualTo(username);
|
||||
}
|
||||
|
||||
@@ -96,7 +96,7 @@ public class SecurityMockMvcRequestPostProcessorsDigestTests {
|
||||
String username = "admin";
|
||||
this.entryPoint.setRealmName("Custom");
|
||||
MockHttpServletRequest postProcessedRequest = digest(username).realm(this.entryPoint.getRealmName())
|
||||
.postProcessRequest(this.request);
|
||||
.postProcessRequest(this.request);
|
||||
assertThat(extractUser()).isEqualTo(username);
|
||||
}
|
||||
|
||||
@@ -104,7 +104,7 @@ public class SecurityMockMvcRequestPostProcessorsDigestTests {
|
||||
public void digestWithFilterFails() throws Exception {
|
||||
String username = "admin";
|
||||
MockHttpServletRequest postProcessedRequest = digest(username).realm("Invalid")
|
||||
.postProcessRequest(this.request);
|
||||
.postProcessRequest(this.request);
|
||||
assertThat(extractUser()).isNull();
|
||||
}
|
||||
|
||||
|
||||
+7
-5
@@ -119,8 +119,9 @@ public class SecurityMockMvcRequestPostProcessorsJwtTests {
|
||||
|
||||
@Test
|
||||
public void jwtWhenProvidingCustomAuthoritiesThenProducesJwtAuthentication() {
|
||||
jwt().jwt((jwt) -> jwt.claim("scope", "ignored authorities")).authorities(this.authority1, this.authority2)
|
||||
.postProcessRequest(this.request);
|
||||
jwt().jwt((jwt) -> jwt.claim("scope", "ignored authorities"))
|
||||
.authorities(this.authority1, this.authority2)
|
||||
.postProcessRequest(this.request);
|
||||
verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request),
|
||||
any(HttpServletResponse.class));
|
||||
SecurityContext context = this.contextCaptor.getValue();
|
||||
@@ -134,14 +135,15 @@ public class SecurityMockMvcRequestPostProcessorsJwtTests {
|
||||
verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request),
|
||||
any(HttpServletResponse.class));
|
||||
SecurityContext context = this.contextCaptor.getValue();
|
||||
assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities()).containsOnly(
|
||||
new SimpleGrantedAuthority("SCOPE_scoped"), new SimpleGrantedAuthority("SCOPE_authorities"));
|
||||
assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities())
|
||||
.containsOnly(new SimpleGrantedAuthority("SCOPE_scoped"), new SimpleGrantedAuthority("SCOPE_authorities"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void jwtWhenProvidingGrantedAuthoritiesThenProducesJwtAuthentication() {
|
||||
jwt().jwt((jwt) -> jwt.claim("scope", "ignored authorities"))
|
||||
.authorities((jwt) -> Arrays.asList(this.authority1)).postProcessRequest(this.request);
|
||||
.authorities((jwt) -> Arrays.asList(this.authority1))
|
||||
.postProcessRequest(this.request);
|
||||
verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request),
|
||||
any(HttpServletResponse.class));
|
||||
SecurityContext context = this.contextCaptor.getValue();
|
||||
|
||||
+20
-14
@@ -99,55 +99,59 @@ public class SecurityMockMvcRequestPostProcessorsOAuth2ClientTests {
|
||||
@Test
|
||||
public void oauth2ClientWhenUsingDefaultsThenException() throws Exception {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> oauth2Client().postProcessRequest(new MockHttpServletRequest()))
|
||||
.withMessageContaining("ClientRegistration");
|
||||
.isThrownBy(() -> oauth2Client().postProcessRequest(new MockHttpServletRequest()))
|
||||
.withMessageContaining("ClientRegistration");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oauth2ClientWhenUsingDefaultsThenProducesDefaultAuthorizedClient() throws Exception {
|
||||
this.mvc.perform(get("/access-token").with(oauth2Client("registration-id")))
|
||||
.andExpect(content().string("access-token"));
|
||||
.andExpect(content().string("access-token"));
|
||||
this.mvc.perform(get("/client-id").with(oauth2Client("registration-id")))
|
||||
.andExpect(content().string("test-client"));
|
||||
.andExpect(content().string("test-client"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oauth2ClientWhenClientRegistrationThenUses() throws Exception {
|
||||
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
|
||||
.registrationId("registration-id").clientId("client-id").build();
|
||||
.registrationId("registration-id")
|
||||
.clientId("client-id")
|
||||
.build();
|
||||
this.mvc.perform(get("/client-id").with(oauth2Client().clientRegistration(clientRegistration)))
|
||||
.andExpect(content().string("client-id"));
|
||||
.andExpect(content().string("client-id"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oauth2ClientWhenClientRegistrationConsumerThenUses() throws Exception {
|
||||
this.mvc.perform(get("/client-id")
|
||||
this.mvc
|
||||
.perform(get("/client-id")
|
||||
.with(oauth2Client("registration-id").clientRegistration((c) -> c.clientId("client-id"))))
|
||||
.andExpect(content().string("client-id"));
|
||||
.andExpect(content().string("client-id"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oauth2ClientWhenPrincipalNameThenUses() throws Exception {
|
||||
this.mvc.perform(get("/principal-name").with(oauth2Client("registration-id").principalName("test-subject")))
|
||||
.andExpect(content().string("test-subject"));
|
||||
.andExpect(content().string("test-subject"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oauth2ClientWhenAccessTokenThenUses() throws Exception {
|
||||
OAuth2AccessToken accessToken = TestOAuth2AccessTokens.noScopes();
|
||||
this.mvc.perform(get("/access-token").with(oauth2Client("registration-id").accessToken(accessToken)))
|
||||
.andExpect(content().string("no-scopes"));
|
||||
.andExpect(content().string("no-scopes"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oauth2ClientWhenUsedOnceThenDoesNotAffectRemainingTests() throws Exception {
|
||||
this.mvc.perform(get("/client-id").with(oauth2Client("registration-id")))
|
||||
.andExpect(content().string("test-client"));
|
||||
.andExpect(content().string("test-client"));
|
||||
OAuth2AuthorizedClient client = new OAuth2AuthorizedClient(TestClientRegistrations.clientRegistration().build(),
|
||||
"sub", TestOAuth2AccessTokens.noScopes());
|
||||
OAuth2AuthorizedClientRepository repository = this.context.getBean(OAuth2AuthorizedClientRepository.class);
|
||||
given(repository.loadAuthorizedClient(eq("registration-id"), any(Authentication.class),
|
||||
any(HttpServletRequest.class))).willReturn(client);
|
||||
any(HttpServletRequest.class)))
|
||||
.willReturn(client);
|
||||
this.mvc.perform(get("/client-id")).andExpect(content().string("client-id"));
|
||||
verify(repository).loadAuthorizedClient(eq("registration-id"), any(Authentication.class),
|
||||
any(HttpServletRequest.class));
|
||||
@@ -157,10 +161,12 @@ public class SecurityMockMvcRequestPostProcessorsOAuth2ClientTests {
|
||||
@Test
|
||||
public void oauth2ClientWhenUsedThenSetsClientToRepository() throws Exception {
|
||||
HttpServletRequest request = this.mvc.perform(get("/client-id").with(oauth2Client("registration-id")))
|
||||
.andExpect(content().string("test-client")).andReturn().getRequest();
|
||||
.andExpect(content().string("test-client"))
|
||||
.andReturn()
|
||||
.getRequest();
|
||||
OAuth2AuthorizedClientManager manager = this.context.getBean(OAuth2AuthorizedClientManager.class);
|
||||
OAuth2AuthorizedClientRepository repository = (OAuth2AuthorizedClientRepository) ReflectionTestUtils
|
||||
.getField(manager, "authorizedClientRepository");
|
||||
.getField(manager, "authorizedClientRepository");
|
||||
assertThat(repository).isInstanceOf(TestOAuth2AuthorizedClientRepository.class);
|
||||
assertThat((OAuth2AuthorizedClient) repository.loadAuthorizedClient("id", null, request)).isNotNull();
|
||||
}
|
||||
|
||||
+20
-15
@@ -100,16 +100,17 @@ public class SecurityMockMvcRequestPostProcessorsOAuth2LoginTests {
|
||||
|
||||
@Test
|
||||
public void oauth2LoginWhenAuthoritiesSpecifiedThenGrantsAccess() throws Exception {
|
||||
this.mvc.perform(
|
||||
get("/admin/scopes").with(oauth2Login().authorities(new SimpleGrantedAuthority("SCOPE_admin"))))
|
||||
.andExpect(content().string("[\"SCOPE_admin\"]"));
|
||||
this.mvc
|
||||
.perform(get("/admin/scopes").with(oauth2Login().authorities(new SimpleGrantedAuthority("SCOPE_admin"))))
|
||||
.andExpect(content().string("[\"SCOPE_admin\"]"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oauth2LoginWhenAttributeSpecifiedThenUserHasAttribute() throws Exception {
|
||||
this.mvc.perform(
|
||||
get("/attributes/iss").with(oauth2Login().attributes((a) -> a.put("iss", "https://idp.example.org"))))
|
||||
.andExpect(content().string("https://idp.example.org"));
|
||||
this.mvc
|
||||
.perform(get("/attributes/iss")
|
||||
.with(oauth2Login().attributes((a) -> a.put("iss", "https://idp.example.org"))))
|
||||
.andExpect(content().string("https://idp.example.org"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -117,30 +118,34 @@ public class SecurityMockMvcRequestPostProcessorsOAuth2LoginTests {
|
||||
OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.commaSeparatedStringToAuthorityList("SCOPE_read"),
|
||||
Collections.singletonMap("custom-attribute", "test-subject"), "custom-attribute");
|
||||
this.mvc.perform(get("/attributes/custom-attribute").with(oauth2Login().oauth2User(oauth2User)))
|
||||
.andExpect(content().string("test-subject"));
|
||||
.andExpect(content().string("test-subject"));
|
||||
this.mvc.perform(get("/name").with(oauth2Login().oauth2User(oauth2User)))
|
||||
.andExpect(content().string("test-subject"));
|
||||
.andExpect(content().string("test-subject"));
|
||||
this.mvc.perform(get("/client-name").with(oauth2Login().oauth2User(oauth2User)))
|
||||
.andExpect(content().string("test-subject"));
|
||||
.andExpect(content().string("test-subject"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oauth2LoginWhenClientRegistrationSpecifiedThenUses() throws Exception {
|
||||
this.mvc.perform(get("/client-id")
|
||||
this.mvc
|
||||
.perform(get("/client-id")
|
||||
.with(oauth2Login().clientRegistration(TestClientRegistrations.clientRegistration().build())))
|
||||
.andExpect(content().string("client-id"));
|
||||
.andExpect(content().string("client-id"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oauth2LoginWhenOAuth2UserSpecifiedThenLastCalledTakesPrecedence() throws Exception {
|
||||
OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("SCOPE_read"),
|
||||
Collections.singletonMap("username", "user"), "username");
|
||||
this.mvc.perform(get("/attributes/sub")
|
||||
this.mvc
|
||||
.perform(get("/attributes/sub")
|
||||
.with(oauth2Login().attributes((a) -> a.put("sub", "bar")).oauth2User(oauth2User)))
|
||||
.andExpect(status().isOk()).andExpect(content().string("no-attribute"));
|
||||
this.mvc.perform(get("/attributes/sub")
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("no-attribute"));
|
||||
this.mvc
|
||||
.perform(get("/attributes/sub")
|
||||
.with(oauth2Login().oauth2User(oauth2User).attributes((a) -> a.put("sub", "bar"))))
|
||||
.andExpect(content().string("bar"));
|
||||
.andExpect(content().string("bar"));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
+8
-7
@@ -107,19 +107,19 @@ public class SecurityMockMvcRequestPostProcessorsOidcLoginTests {
|
||||
@Test
|
||||
public void oidcLoginWhenAuthoritiesSpecifiedThenGrantsAccess() throws Exception {
|
||||
this.mvc.perform(get("/admin/scopes").with(oidcLogin().authorities(new SimpleGrantedAuthority("SCOPE_admin"))))
|
||||
.andExpect(content().string("[\"SCOPE_admin\"]"));
|
||||
.andExpect(content().string("[\"SCOPE_admin\"]"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oidcLoginWhenIdTokenSpecifiedThenUserHasClaims() throws Exception {
|
||||
this.mvc.perform(get("/id-token/iss").with(oidcLogin().idToken((i) -> i.issuer("https://idp.example.org"))))
|
||||
.andExpect(content().string("https://idp.example.org"));
|
||||
.andExpect(content().string("https://idp.example.org"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oidcLoginWhenUserInfoSpecifiedThenUserHasClaims() throws Exception {
|
||||
this.mvc.perform(get("/user-info/email").with(oidcLogin().userInfoToken((u) -> u.email("email@email"))))
|
||||
.andExpect(content().string("email@email"));
|
||||
.andExpect(content().string("email@email"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -128,10 +128,10 @@ public class SecurityMockMvcRequestPostProcessorsOidcLoginTests {
|
||||
OidcIdToken.withTokenValue("id-token").claim("custom-attribute", "test-subject").build(),
|
||||
"custom-attribute");
|
||||
this.mvc.perform(get("/id-token/custom-attribute").with(oidcLogin().oidcUser(oidcUser)))
|
||||
.andExpect(content().string("test-subject"));
|
||||
.andExpect(content().string("test-subject"));
|
||||
this.mvc.perform(get("/name").with(oidcLogin().oidcUser(oidcUser))).andExpect(content().string("test-subject"));
|
||||
this.mvc.perform(get("/client-name").with(oidcLogin().oidcUser(oidcUser)))
|
||||
.andExpect(content().string("test-subject"));
|
||||
.andExpect(content().string("test-subject"));
|
||||
}
|
||||
|
||||
// gh-7794
|
||||
@@ -140,9 +140,10 @@ public class SecurityMockMvcRequestPostProcessorsOidcLoginTests {
|
||||
OidcUser oidcUser = new DefaultOidcUser(AuthorityUtils.createAuthorityList("SCOPE_read"),
|
||||
TestOidcIdTokens.idToken().build());
|
||||
this.mvc.perform(get("/id-token/sub").with(oidcLogin().idToken((i) -> i.subject("foo")).oidcUser(oidcUser)))
|
||||
.andExpect(status().isOk()).andExpect(content().string("subject"));
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("subject"));
|
||||
this.mvc.perform(get("/id-token/sub").with(oidcLogin().oidcUser(oidcUser).idToken((i) -> i.subject("bar"))))
|
||||
.andExpect(content().string("bar"));
|
||||
.andExpect(content().string("bar"));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
+12
-8
@@ -90,9 +90,10 @@ public class SecurityMockMvcRequestPostProcessorsOpaqueTokenTests {
|
||||
|
||||
@Test
|
||||
public void opaqueTokenWhenAttributeSpecifiedThenUserHasAttribute() throws Exception {
|
||||
this.mvc.perform(
|
||||
get("/opaque-token/iss").with(opaqueToken().attributes((a) -> a.put("iss", "https://idp.example.org"))))
|
||||
.andExpect(content().string("https://idp.example.org"));
|
||||
this.mvc
|
||||
.perform(get("/opaque-token/iss")
|
||||
.with(opaqueToken().attributes((a) -> a.put("iss", "https://idp.example.org"))))
|
||||
.andExpect(content().string("https://idp.example.org"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -108,13 +109,16 @@ public class SecurityMockMvcRequestPostProcessorsOpaqueTokenTests {
|
||||
@Test
|
||||
public void opaqueTokenWhenPrincipalSpecifiedThenLastCalledTakesPrecedence() throws Exception {
|
||||
OAuth2AuthenticatedPrincipal principal = TestOAuth2AuthenticatedPrincipals
|
||||
.active((a) -> a.put("scope", "user"));
|
||||
this.mvc.perform(get("/opaque-token/sub")
|
||||
.active((a) -> a.put("scope", "user"));
|
||||
this.mvc
|
||||
.perform(get("/opaque-token/sub")
|
||||
.with(opaqueToken().attributes((a) -> a.put("sub", "foo")).principal(principal)))
|
||||
.andExpect(status().isOk()).andExpect(content().string((String) principal.getAttribute("sub")));
|
||||
this.mvc.perform(get("/opaque-token/sub")
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string((String) principal.getAttribute("sub")));
|
||||
this.mvc
|
||||
.perform(get("/opaque-token/sub")
|
||||
.with(opaqueToken().principal(principal).attributes((a) -> a.put("sub", "bar"))))
|
||||
.andExpect(content().string("bar"));
|
||||
.andExpect(content().string("bar"));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
+1
-1
@@ -60,7 +60,7 @@ public class SecurityMockMvcRequestPostProcessorsSecurityContextTests {
|
||||
public void setup() {
|
||||
this.request = new MockHttpServletRequest();
|
||||
this.webTestUtils.when(() -> WebTestUtils.getSecurityContextRepository(this.request))
|
||||
.thenReturn(this.repository);
|
||||
.thenReturn(this.repository);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
|
||||
+4
-2
@@ -59,8 +59,10 @@ public class SecurityMockMvcRequestPostProcessorsTestSecurityContextStatelessTes
|
||||
|
||||
@BeforeEach
|
||||
public void setup() {
|
||||
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).addFilters(this.springSecurityFilterChain)
|
||||
.defaultRequest(get("/").with(testSecurityContext())).build();
|
||||
this.mvc = MockMvcBuilders.webAppContextSetup(this.context)
|
||||
.addFilters(this.springSecurityFilterChain)
|
||||
.defaultRequest(get("/").with(testSecurityContext()))
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-1
@@ -55,7 +55,7 @@ public class SecurityMockMvcRequestPostProcessorsTestSecurityContextTests {
|
||||
public void setup() {
|
||||
this.request = new MockHttpServletRequest();
|
||||
this.webTestUtils.when(() -> WebTestUtils.getSecurityContextRepository(this.request))
|
||||
.thenReturn(this.repository);
|
||||
.thenReturn(this.repository);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
|
||||
+1
-1
@@ -62,7 +62,7 @@ public class SecurityMockMvcRequestPostProcessorsUserDetailsTests {
|
||||
public void setup() {
|
||||
this.request = new MockHttpServletRequest();
|
||||
this.webTestUtils.when(() -> WebTestUtils.getSecurityContextRepository(this.request))
|
||||
.thenReturn(this.repository);
|
||||
.thenReturn(this.repository);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
|
||||
+4
-4
@@ -69,7 +69,7 @@ public class SecurityMockMvcRequestPostProcessorsUserTests {
|
||||
public void setup() {
|
||||
this.request = new MockHttpServletRequest();
|
||||
this.webTestUtils.when(() -> WebTestUtils.getSecurityContextRepository(this.request))
|
||||
.thenReturn(this.repository);
|
||||
.thenReturn(this.repository);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
@@ -100,8 +100,8 @@ public class SecurityMockMvcRequestPostProcessorsUserTests {
|
||||
assertThat(context.getAuthentication()).isInstanceOf(UsernamePasswordAuthenticationToken.class);
|
||||
assertThat(context.getAuthentication().getName()).isEqualTo(username);
|
||||
assertThat(context.getAuthentication().getCredentials()).isEqualTo("newpass");
|
||||
assertThat(context.getAuthentication().getAuthorities()).extracting("authority").containsOnly("ROLE_CUSTOM",
|
||||
"ROLE_ADMIN");
|
||||
assertThat(context.getAuthentication().getAuthorities()).extracting("authority")
|
||||
.containsOnly("ROLE_CUSTOM", "ROLE_ADMIN");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -118,7 +118,7 @@ public class SecurityMockMvcRequestPostProcessorsUserTests {
|
||||
@Test
|
||||
public void userRolesWithRolePrefixErrors() {
|
||||
assertThatIllegalArgumentException()
|
||||
.isThrownBy(() -> user("user").roles("ROLE_INVALID").postProcessRequest(this.request));
|
||||
.isThrownBy(() -> user("user").roles("ROLE_INVALID").postProcessRequest(this.request));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+5
-4
@@ -67,14 +67,15 @@ public class SecurityMockMvcResultMatchersTests {
|
||||
|
||||
@Test
|
||||
public void withAuthenticationWhenMatchesThenSuccess() throws Exception {
|
||||
this.mockMvc.perform(formLogin()).andExpect(authenticated().withAuthentication(
|
||||
(auth) -> assertThat(auth).isInstanceOf(UsernamePasswordAuthenticationToken.class)));
|
||||
this.mockMvc.perform(formLogin())
|
||||
.andExpect(authenticated().withAuthentication(
|
||||
(auth) -> assertThat(auth).isInstanceOf(UsernamePasswordAuthenticationToken.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void withAuthenticationWhenNotMatchesThenFails() throws Exception {
|
||||
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> this.mockMvc.perform(formLogin()).andExpect(
|
||||
authenticated().withAuthentication((auth) -> assertThat(auth.getName()).isEqualTo("notmatch"))));
|
||||
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> this.mockMvc.perform(formLogin())
|
||||
.andExpect(authenticated().withAuthentication((auth) -> assertThat(auth.getName()).isEqualTo("notmatch"))));
|
||||
}
|
||||
|
||||
// SEC-2719
|
||||
|
||||
+1
-1
@@ -91,7 +91,7 @@ public class SecurityMockMvcConfigurerTests {
|
||||
|
||||
private void assertFilterAdded(Filter filter) {
|
||||
ArgumentCaptor<SecurityMockMvcConfigurer.DelegateFilter> filterArg = ArgumentCaptor
|
||||
.forClass(SecurityMockMvcConfigurer.DelegateFilter.class);
|
||||
.forClass(SecurityMockMvcConfigurer.DelegateFilter.class);
|
||||
verify(this.builder).addFilters(filterArg.capture());
|
||||
assertThat(filterArg.getValue().getDelegate()).isEqualTo(filter);
|
||||
}
|
||||
|
||||
+8
-4
@@ -56,8 +56,10 @@ public class SecurityMockMvcConfigurersTests {
|
||||
*/
|
||||
@Test
|
||||
public void applySpringSecurityWhenAddFilterFirstThenFilterFirst() throws Exception {
|
||||
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).addFilters(this.noOpFilter)
|
||||
.apply(springSecurity()).build();
|
||||
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
|
||||
.addFilters(this.noOpFilter)
|
||||
.apply(springSecurity())
|
||||
.build();
|
||||
mockMvc.perform(get("/")).andExpect(status().isOk());
|
||||
}
|
||||
|
||||
@@ -69,8 +71,10 @@ public class SecurityMockMvcConfigurersTests {
|
||||
*/
|
||||
@Test
|
||||
public void applySpringSecurityWhenAddFilterSecondThenSecurityFirst() throws Exception {
|
||||
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).apply(springSecurity())
|
||||
.addFilters(this.noOpFilter).build();
|
||||
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
|
||||
.apply(springSecurity())
|
||||
.addFilters(this.noOpFilter)
|
||||
.build();
|
||||
mockMvc.perform(get("/")).andExpect(status().is4xxClientError());
|
||||
}
|
||||
|
||||
|
||||
+4
-2
@@ -59,8 +59,10 @@ public class CustomCsrfShowcaseTests {
|
||||
|
||||
@BeforeEach
|
||||
public void setup() {
|
||||
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).defaultRequest(get("/").with(csrf()))
|
||||
.apply(springSecurity()).build();
|
||||
this.mvc = MockMvcBuilders.webAppContextSetup(this.context)
|
||||
.defaultRequest(get("/").with(csrf()))
|
||||
.apply(springSecurity())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+4
-2
@@ -54,8 +54,10 @@ public class DefaultCsrfShowcaseTests {
|
||||
|
||||
@BeforeEach
|
||||
public void setup() {
|
||||
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).defaultRequest(get("/").with(csrf()))
|
||||
.apply(springSecurity()).build();
|
||||
this.mvc = MockMvcBuilders.webAppContextSetup(this.context)
|
||||
.defaultRequest(get("/").with(csrf()))
|
||||
.apply(springSecurity())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+14
-7
@@ -61,8 +61,10 @@ public class AuthenticationTests {
|
||||
|
||||
@BeforeEach
|
||||
public void setup() {
|
||||
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity())
|
||||
.defaultRequest(get("/").accept(MediaType.TEXT_HTML)).build();
|
||||
this.mvc = MockMvcBuilders.webAppContextSetup(this.context)
|
||||
.apply(springSecurity())
|
||||
.defaultRequest(get("/").accept(MediaType.TEXT_HTML))
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -73,19 +75,24 @@ public class AuthenticationTests {
|
||||
@Test
|
||||
public void httpBasicAuthenticationSuccess() throws Exception {
|
||||
this.mvc.perform(get("/secured/butnotfound").with(httpBasic("user", "password")))
|
||||
.andExpect(status().isNotFound()).andExpect(authenticated().withUsername("user"));
|
||||
.andExpect(status().isNotFound())
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticationSuccess() throws Exception {
|
||||
this.mvc.perform(formLogin()).andExpect(status().isFound()).andExpect(redirectedUrl("/"))
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
this.mvc.perform(formLogin())
|
||||
.andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("/"))
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticationFailed() throws Exception {
|
||||
this.mvc.perform(formLogin().user("user").password("invalid")).andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("/login?error")).andExpect(unauthenticated());
|
||||
this.mvc.perform(formLogin().user("user").password("invalid"))
|
||||
.andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("/login?error"))
|
||||
.andExpect(unauthenticated());
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
+9
-6
@@ -70,21 +70,24 @@ public class CustomConfigAuthenticationTests {
|
||||
@Test
|
||||
public void authenticationSuccess() throws Exception {
|
||||
this.mvc.perform(formLogin("/authenticate").user("user", "user").password("pass", "password"))
|
||||
.andExpect(status().isFound()).andExpect(redirectedUrl("/"))
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
.andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("/"))
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void withUserSuccess() throws Exception {
|
||||
this.mvc.perform(get("/").with(user("user"))).andExpect(status().isNotFound())
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
this.mvc.perform(get("/").with(user("user")))
|
||||
.andExpect(status().isNotFound())
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticationFailed() throws Exception {
|
||||
this.mvc.perform(formLogin("/authenticate").user("user", "notfound").password("pass", "invalid"))
|
||||
.andExpect(status().isFound()).andExpect(redirectedUrl("/authenticate?error"))
|
||||
.andExpect(unauthenticated());
|
||||
.andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("/authenticate?error"))
|
||||
.andExpect(unauthenticated());
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
+8
-4
@@ -63,14 +63,18 @@ public class CustomLoginRequestBuilderAuthenticationTests {
|
||||
|
||||
@Test
|
||||
public void authenticationSuccess() throws Exception {
|
||||
this.mvc.perform(login()).andExpect(status().isFound()).andExpect(redirectedUrl("/"))
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
this.mvc.perform(login())
|
||||
.andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("/"))
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticationFailed() throws Exception {
|
||||
this.mvc.perform(login().user("notfound").password("invalid")).andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("/authenticate?error")).andExpect(unauthenticated());
|
||||
this.mvc.perform(login().user("notfound").password("invalid"))
|
||||
.andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("/authenticate?error"))
|
||||
.andExpect(unauthenticated());
|
||||
}
|
||||
|
||||
static FormLoginRequestBuilder login() {
|
||||
|
||||
+15
-13
@@ -56,34 +56,36 @@ public class DefaultfSecurityRequestsTests {
|
||||
@BeforeEach
|
||||
public void setup() {
|
||||
this.mvc = MockMvcBuilders.webAppContextSetup(this.context)
|
||||
.defaultRequest(get("/").with(user("user").roles("ADMIN"))).apply(springSecurity()).build();
|
||||
.defaultRequest(get("/").with(user("user").roles("ADMIN")))
|
||||
.apply(springSecurity())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestProtectedUrlWithUser() throws Exception {
|
||||
this.mvc.perform(get("/"))
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestProtectedUrlWithAdmin() throws Exception {
|
||||
this.mvc.perform(get("/admin"))
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestProtectedUrlWithAnonymous() throws Exception {
|
||||
this.mvc.perform(get("/admin").with(anonymous()))
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isUnauthorized())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(unauthenticated());
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isUnauthorized())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(unauthenticated());
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
+16
-16
@@ -68,39 +68,39 @@ public class SecurityRequestsTests {
|
||||
@Test
|
||||
public void requestProtectedUrlWithUser() throws Exception {
|
||||
this.mvc.perform(get("/").with(user("user")))
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestProtectedUrlWithAdmin() throws Exception {
|
||||
this.mvc.perform(get("/admin").with(user("admin").roles("ADMIN")))
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with admin
|
||||
.andExpect(authenticated().withUsername("admin"));
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with admin
|
||||
.andExpect(authenticated().withUsername("admin"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestProtectedUrlWithUserDetails() throws Exception {
|
||||
UserDetails user = this.userDetailsService.loadUserByUsername("user");
|
||||
this.mvc.perform(get("/").with(user(user)))
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withAuthenticationPrincipal(user));
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withAuthenticationPrincipal(user));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestProtectedUrlWithAuthentication() throws Exception {
|
||||
Authentication authentication = new TestingAuthenticationToken("test", "notused", "ROLE_USER");
|
||||
this.mvc.perform(get("/").with(authentication(authentication)))
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withAuthentication(authentication));
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withAuthentication(authentication));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
+15
-14
@@ -53,38 +53,39 @@ public class WithUserAuthenticationTests {
|
||||
|
||||
@BeforeEach
|
||||
public void setup() {
|
||||
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).apply(SecurityMockMvcConfigurers.springSecurity())
|
||||
.build();
|
||||
this.mvc = MockMvcBuilders.webAppContextSetup(this.context)
|
||||
.apply(SecurityMockMvcConfigurers.springSecurity())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser
|
||||
public void requestProtectedUrlWithUser() throws Exception {
|
||||
this.mvc.perform(get("/"))
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithAdminRob
|
||||
public void requestProtectedUrlWithAdminRob() throws Exception {
|
||||
this.mvc.perform(get("/"))
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withUsername("rob").withRoles("ADMIN"));
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withUsername("rob").withRoles("ADMIN"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(roles = "ADMIN")
|
||||
public void requestProtectedUrlWithAdmin() throws Exception {
|
||||
this.mvc.perform(get("/admin"))
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withUsername("user").withRoles("ADMIN"));
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withUsername("user").withRoles("ADMIN"));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
+12
-12
@@ -62,29 +62,29 @@ public class WithUserClassLevelAuthenticationTests {
|
||||
@Test
|
||||
public void requestProtectedUrlWithUser() throws Exception {
|
||||
this.mvc.perform(get("/"))
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestProtectedUrlWithAdmin() throws Exception {
|
||||
this.mvc.perform(get("/admin"))
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withUsername("user").withRoles("ADMIN"));
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withUsername("user").withRoles("ADMIN"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithAnonymousUser
|
||||
public void requestProtectedUrlWithAnonymous() throws Exception {
|
||||
this.mvc.perform(get("/"))
|
||||
// Ensure did not get past security
|
||||
.andExpect(status().isUnauthorized())
|
||||
// Ensure not authenticated
|
||||
.andExpect(unauthenticated());
|
||||
// Ensure did not get past security
|
||||
.andExpect(status().isUnauthorized())
|
||||
// Ensure not authenticated
|
||||
.andExpect(unauthenticated());
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
+8
-8
@@ -62,20 +62,20 @@ public class WithUserDetailsAuthenticationTests {
|
||||
@WithUserDetails
|
||||
public void requestProtectedUrlWithUser() throws Exception {
|
||||
this.mvc.perform(get("/"))
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withUsername("user"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUserDetails("admin")
|
||||
public void requestProtectedUrlWithAdmin() throws Exception {
|
||||
this.mvc.perform(get("/admin"))
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withUsername("admin").withRoles("ADMIN", "USER"));
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withUsername("admin").withRoles("ADMIN", "USER"));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
+8
-8
@@ -62,19 +62,19 @@ public class WithUserDetailsClassLevelAuthenticationTests {
|
||||
@Test
|
||||
public void requestRootUrlWithAdmin() throws Exception {
|
||||
this.mvc.perform(get("/"))
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withUsername("admin").withRoles("ADMIN", "USER"));
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withUsername("admin").withRoles("ADMIN", "USER"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestProtectedUrlWithAdmin() throws Exception {
|
||||
this.mvc.perform(get("/admin"))
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withUsername("admin").withRoles("ADMIN", "USER"));
|
||||
// Ensure we got past Security
|
||||
.andExpect(status().isNotFound())
|
||||
// Ensure it appears we are authenticated with user
|
||||
.andExpect(authenticated().withUsername("admin").withRoles("ADMIN", "USER"));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
+8
-8
@@ -77,21 +77,21 @@ public class WebTestUtilsTests {
|
||||
@Test
|
||||
public void getCsrfTokenRepositorytNoWac() {
|
||||
assertThat(WebTestUtils.getCsrfTokenRepository(this.request))
|
||||
.isInstanceOf(HttpSessionCsrfTokenRepository.class);
|
||||
.isInstanceOf(HttpSessionCsrfTokenRepository.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getCsrfTokenRepositorytNoSecurity() {
|
||||
loadConfig(Config.class);
|
||||
assertThat(WebTestUtils.getCsrfTokenRepository(this.request))
|
||||
.isInstanceOf(HttpSessionCsrfTokenRepository.class);
|
||||
.isInstanceOf(HttpSessionCsrfTokenRepository.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getCsrfTokenRepositorytSecurityNoCsrf() {
|
||||
loadConfig(SecurityNoCsrfConfig.class);
|
||||
assertThat(WebTestUtils.getCsrfTokenRepository(this.request))
|
||||
.isInstanceOf(HttpSessionCsrfTokenRepository.class);
|
||||
.isInstanceOf(HttpSessionCsrfTokenRepository.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -106,21 +106,21 @@ public class WebTestUtilsTests {
|
||||
@Test
|
||||
public void getSecurityContextRepositoryNoWac() {
|
||||
assertThat(WebTestUtils.getSecurityContextRepository(this.request))
|
||||
.isInstanceOf(HttpSessionSecurityContextRepository.class);
|
||||
.isInstanceOf(HttpSessionSecurityContextRepository.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getSecurityContextRepositoryNoSecurity() {
|
||||
loadConfig(Config.class);
|
||||
assertThat(WebTestUtils.getSecurityContextRepository(this.request))
|
||||
.isInstanceOf(HttpSessionSecurityContextRepository.class);
|
||||
.isInstanceOf(HttpSessionSecurityContextRepository.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getSecurityContextRepositorySecurityNoCsrf() {
|
||||
loadConfig(SecurityNoCsrfConfig.class);
|
||||
assertThat(WebTestUtils.getSecurityContextRepository(this.request))
|
||||
.isInstanceOf(DelegatingSecurityContextRepository.class);
|
||||
.isInstanceOf(DelegatingSecurityContextRepository.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -176,8 +176,8 @@ public class WebTestUtilsTests {
|
||||
context.register(config);
|
||||
context.refresh();
|
||||
this.context = context;
|
||||
this.request.getServletContext().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
|
||||
context);
|
||||
this.request.getServletContext()
|
||||
.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
Reference in New Issue
Block a user