Migrate to assertThatExceptionOfType

Consistently use `assertThatExceptionOfType(...).isThrownBy(...)`
rather than `assertThatCode` or `assertThatThrownBy`. This aligns with
Spring Boot and Spring Cloud. It also allows the convenience
`assertThatIllegalArgument` and `assertThatIllegalState` methods to
be used.

Issue gh-8945
This commit is contained in:
Phillip Webb
2020-08-04 14:20:45 -07:00
committed by Rob Winch
parent ef8f113619
commit 319d3364aa
196 changed files with 2241 additions and 2116 deletions

View File

@@ -63,7 +63,7 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.startsWith;
@@ -165,9 +165,8 @@ public class AuthenticationConfigurationTests {
new BootGlobalAuthenticationConfigurerAdapter()));
AuthenticationManager authenticationManager = config.getAuthenticationManager();
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
assertThatThrownBy(
() -> authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("boot", "password")))
.isInstanceOf(AuthenticationException.class);
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
() -> authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("boot", "password")));
}
@Test
@@ -207,8 +206,8 @@ public class AuthenticationConfigurationTests {
.getAuthenticationManager();
given(uds.loadUserByUsername("user")).willReturn(PasswordEncodedUser.user(), PasswordEncodedUser.user());
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
assertThatThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "invalid")))
.isInstanceOf(AuthenticationException.class);
assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "invalid")));
}
@Test
@@ -222,8 +221,8 @@ public class AuthenticationConfigurationTests {
given(uds.loadUserByUsername("user")).willReturn(User.withUserDetails(user).build(),
User.withUserDetails(user).build());
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
assertThatThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "invalid")))
.isInstanceOf(AuthenticationException.class);
assertThatExceptionOfType(AuthenticationException.class)
.isThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "invalid")));
}
@Test
@@ -291,7 +290,7 @@ public class AuthenticationConfigurationTests {
this.spring.register(AuthenticationConfigurationSubclass.class).autowire();
AuthenticationManagerBuilder ap = this.spring.getContext().getBean(AuthenticationManagerBuilder.class);
this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager();
assertThatThrownBy(ap::build).isInstanceOf(AlreadyBuiltException.class);
assertThatExceptionOfType(AlreadyBuiltException.class).isThrownBy(ap::build);
}
@EnableGlobalMethodSecurity(securedEnabled = true)

View File

@@ -35,7 +35,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
@@ -73,9 +73,11 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void notPublisherPreAuthorizeFindByIdThenThrowsIllegalStateException() {
assertThatThrownBy(() -> this.messageService.notPublisherPreAuthorizeFindById(1L))
.isInstanceOf(IllegalStateException.class).extracting(Throwable::getMessage).isEqualTo(
"The returnType class java.lang.String on public abstract java.lang.String org.springframework.security.config.annotation.method.configuration.ReactiveMessageService.notPublisherPreAuthorizeFindById(long) must return an instance of org.reactivestreams.Publisher (i.e. Mono / Flux) in order to support Reactor Context");
assertThatIllegalStateException().isThrownBy(() -> this.messageService.notPublisherPreAuthorizeFindById(1L))
.withMessage("The returnType class java.lang.String on public abstract java.lang.String "
+ "org.springframework.security.config.annotation.method.configuration.ReactiveMessageService"
+ ".notPublisherPreAuthorizeFindById(long) must return an instance of org.reactivestreams"
+ ".Publisher (i.e. Mono / Flux) in order to support Reactor Context");
}
@Test

View File

@@ -61,7 +61,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
@@ -125,7 +125,8 @@ public class GlobalMethodSecurityConfigurationTests {
this.spring.register(CustomTrustResolverConfig.class).autowire();
AuthenticationTrustResolver trustResolver = this.spring.getContext().getBean(AuthenticationTrustResolver.class);
given(trustResolver.isAnonymous(any())).willReturn(true, false);
assertThatThrownBy(() -> this.service.preAuthorizeNotAnonymous()).isInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> this.service.preAuthorizeNotAnonymous());
this.service.preAuthorizeNotAnonymous();
verify(trustResolver, atLeastOnce()).isAnonymous(any());
}
@@ -136,7 +137,7 @@ public class GlobalMethodSecurityConfigurationTests {
public void defaultWebSecurityExpressionHandlerHasBeanResolverSet() {
this.spring.register(ExpressionHandlerHasBeanResolverSetConfig.class).autowire();
Authz authz = this.spring.getContext().getBean(Authz.class);
assertThatThrownBy(() -> this.service.preAuthorizeBean(false)).isInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorizeBean(false));
this.service.preAuthorizeBean(true);
}
@@ -144,7 +145,7 @@ public class GlobalMethodSecurityConfigurationTests {
@WithMockUser
public void methodSecuritySupportsAnnotaitonsOnInterfaceParamerNames() {
this.spring.register(MethodSecurityServiceConfig.class).autowire();
assertThatThrownBy(() -> this.service.postAnnotation("deny")).isInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.postAnnotation("deny"));
this.service.postAnnotation("grant");
// no exception
}
@@ -157,7 +158,8 @@ public class GlobalMethodSecurityConfigurationTests {
given(permission.hasPermission(any(), eq("something"), eq("read"))).willReturn(true, false);
this.service.hasPermission("something");
// no exception
assertThatThrownBy(() -> this.service.hasPermission("something")).isInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> this.service.hasPermission("something"));
}
@Test
@@ -171,7 +173,7 @@ public class GlobalMethodSecurityConfigurationTests {
@WithMockUser
public void enableGlobalMethodSecurityWorksOnSuperclass() {
this.spring.register(ChildConfig.class).autowire();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize());
}
// SEC-2479
@@ -186,7 +188,7 @@ public class GlobalMethodSecurityConfigurationTests {
child.register(Sec2479ChildConfig.class);
child.refresh();
this.spring.context(child).autowire();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize());
}
}
}
@@ -228,7 +230,7 @@ public class GlobalMethodSecurityConfigurationTests {
@WithMockUser
public void preAuthorizeBeanSpel() {
this.spring.register(PreAuthorizeBeanSpelConfig.class).autowire();
assertThatThrownBy(() -> this.service.preAuthorizeBean(false)).isInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorizeBean(false));
this.service.preAuthorizeBean(true);
}
@@ -237,7 +239,7 @@ public class GlobalMethodSecurityConfigurationTests {
@WithMockUser
public void roleHierarchy() {
this.spring.register(RoleHierarchyConfig.class).autowire();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize());
this.service.preAuthorizeAdmin();
}
@@ -247,7 +249,7 @@ public class GlobalMethodSecurityConfigurationTests {
this.spring.register(CustomGrantedAuthorityConfig.class).autowire();
CustomGrantedAuthorityConfig.CustomAuthorityService customService = this.spring.getContext()
.getBean(CustomGrantedAuthorityConfig.CustomAuthorityService.class);
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize());
customService.customPrefixRoleUser();
// no exception
}
@@ -258,7 +260,7 @@ public class GlobalMethodSecurityConfigurationTests {
this.spring.register(EmptyRolePrefixGrantedAuthorityConfig.class).autowire();
EmptyRolePrefixGrantedAuthorityConfig.CustomAuthorityService customService = this.spring.getContext()
.getBean(EmptyRolePrefixGrantedAuthorityConfig.CustomAuthorityService.class);
assertThatThrownBy(() -> this.service.securedUser()).isInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.securedUser());
customService.emptyPrefixRoleUser();
// no exception
}

View File

@@ -33,8 +33,8 @@ import org.springframework.security.test.context.annotation.SecurityTestExecutio
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Rob Winch
@@ -54,16 +54,17 @@ public class NamespaceGlobalMethodSecurityExpressionHandlerTests {
@WithMockUser
public void methodSecurityWhenUsingCustomPermissionEvaluatorThenPreAuthorizesAccordingly() {
this.spring.register(CustomAccessDecisionManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatCode(() -> this.service.hasPermission("granted")).doesNotThrowAnyException();
assertThatThrownBy(() -> this.service.hasPermission("denied")).isInstanceOf(AccessDeniedException.class);
assertThat(this.service.hasPermission("granted")).isNull();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.hasPermission("denied"));
}
@Test
@WithMockUser
public void methodSecurityWhenUsingCustomPermissionEvaluatorThenPostAuthorizesAccordingly() {
this.spring.register(CustomAccessDecisionManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatCode(() -> this.service.postHasPermission("granted")).doesNotThrowAnyException();
assertThatThrownBy(() -> this.service.postHasPermission("denied")).isInstanceOf(AccessDeniedException.class);
assertThat(this.service.postHasPermission("granted")).isNull();
assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> this.service.postHasPermission("denied"));
}
@EnableGlobalMethodSecurity(prePostEnabled = true)

View File

@@ -57,8 +57,7 @@ import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Rob Winch
@@ -78,32 +77,32 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser
public void methodSecurityWhenCustomAccessDecisionManagerThenAuthorizes() {
this.spring.register(CustomAccessDecisionManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
assertThatThrownBy(() -> this.service.secured()).isInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize());
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.secured());
}
@Test
@WithMockUser
public void methodSecurityWhenCustomAfterInvocationManagerThenAuthorizes() {
this.spring.register(CustomAfterInvocationManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatThrownBy(() -> this.service.preAuthorizePermitAll()).isInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorizePermitAll());
}
@Test
@WithMockUser
public void methodSecurityWhenCustomAuthenticationManagerThenAuthorizes() {
this.spring.register(CustomAuthenticationConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(UnsupportedOperationException.class);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> this.service.preAuthorize());
}
@Test
@WithMockUser
public void methodSecurityWhenJsr250EnabledThenAuthorizes() {
this.spring.register(Jsr250Config.class, MethodSecurityServiceConfig.class).autowire();
assertThatCode(() -> this.service.preAuthorize()).doesNotThrowAnyException();
assertThatCode(() -> this.service.secured()).doesNotThrowAnyException();
assertThatThrownBy(() -> this.service.jsr250()).isInstanceOf(AccessDeniedException.class);
assertThatCode(() -> this.service.jsr250PermitAll()).doesNotThrowAnyException();
this.service.preAuthorize();
this.service.secured();
this.service.jsr250PermitAll();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.jsr250());
}
@Test
@@ -111,9 +110,9 @@ public class NamespaceGlobalMethodSecurityTests {
public void methodSecurityWhenCustomMethodSecurityMetadataSourceThenAuthorizes() {
this.spring.register(CustomMethodSecurityMetadataSourceConfig.class, MethodSecurityServiceConfig.class)
.autowire();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
assertThatThrownBy(() -> this.service.secured()).isInstanceOf(AccessDeniedException.class);
assertThatThrownBy(() -> this.service.jsr250()).isInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize());
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.secured());
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.jsr250());
}
@Test
@@ -144,7 +143,7 @@ public class NamespaceGlobalMethodSecurityTests {
this.spring.register(CustomOrderConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThat(this.spring.getContext().getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class)
.getOrder()).isEqualTo(-135);
assertThatThrownBy(() -> this.service.jsr250()).isInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.jsr250());
}
@Test
@@ -153,7 +152,7 @@ public class NamespaceGlobalMethodSecurityTests {
this.spring.register(DefaultOrderConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThat(this.spring.getContext().getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class)
.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE);
assertThatThrownBy(() -> this.service.jsr250()).isInstanceOf(UnsupportedOperationException.class);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> this.service.jsr250());
}
@Test
@@ -163,25 +162,25 @@ public class NamespaceGlobalMethodSecurityTests {
.autowire();
assertThat(this.spring.getContext().getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class)
.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE);
assertThatThrownBy(() -> this.service.jsr250()).isInstanceOf(UnsupportedOperationException.class);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> this.service.jsr250());
}
@Test
@WithMockUser
public void methodSecurityWhenPrePostEnabledThenPreAuthorizes() {
this.spring.register(PreAuthorizeConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatCode(() -> this.service.secured()).doesNotThrowAnyException();
assertThatCode(() -> this.service.jsr250()).doesNotThrowAnyException();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
this.service.secured();
this.service.jsr250();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize());
}
@Test
@WithMockUser
public void methodSecurityWhenPrePostEnabledAndCustomGlobalMethodSecurityConfigurationThenPreAuthorizes() {
this.spring.register(PreAuthorizeExtendsGMSCConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatCode(() -> this.service.secured()).doesNotThrowAnyException();
assertThatCode(() -> this.service.jsr250()).doesNotThrowAnyException();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
this.service.secured();
this.service.jsr250();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize());
}
@Test
@@ -190,7 +189,7 @@ public class NamespaceGlobalMethodSecurityTests {
this.spring.register(ProxyTargetClassConfig.class, MethodSecurityServiceConfig.class).autowire();
// make sure service was actually proxied
assertThat(this.service.getClass().getInterfaces()).doesNotContain(MethodSecurityService.class);
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize());
}
@Test
@@ -198,7 +197,7 @@ public class NamespaceGlobalMethodSecurityTests {
public void methodSecurityWhenDefaultProxyThenWiresToInterface() {
this.spring.register(DefaultProxyConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThat(this.service.getClass().getInterfaces()).contains(MethodSecurityService.class);
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize());
}
@Test
@@ -213,26 +212,27 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser
public void methodSecurityWhenSecuredEnabledThenSecures() {
this.spring.register(SecuredConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatThrownBy(() -> this.service.secured()).isInstanceOf(AccessDeniedException.class);
assertThatCode(() -> this.service.securedUser()).doesNotThrowAnyException();
assertThatCode(() -> this.service.preAuthorize()).doesNotThrowAnyException();
assertThatCode(() -> this.service.jsr250()).doesNotThrowAnyException();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.secured());
this.service.securedUser();
this.service.preAuthorize();
this.service.jsr250();
}
@Test
@WithMockUser
public void methodSecurityWhenMissingEnableAnnotationThenShowsHelpfulError() {
assertThatThrownBy(() -> this.spring.register(ExtendsNoEnableAnntotationConfig.class).autowire())
.hasStackTraceContaining(EnableGlobalMethodSecurity.class.getName() + " is required");
assertThatExceptionOfType(Exception.class)
.isThrownBy(() -> this.spring.register(ExtendsNoEnableAnntotationConfig.class).autowire())
.withStackTraceContaining(EnableGlobalMethodSecurity.class.getName() + " is required");
}
@Test
@WithMockUser
public void methodSecurityWhenImportingGlobalMethodSecurityConfigurationSubclassThenAuthorizes() {
this.spring.register(ImportSubclassGMSCConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatCode(() -> this.service.secured()).doesNotThrowAnyException();
assertThatCode(() -> this.service.jsr250()).doesNotThrowAnyException();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
this.service.secured();
this.service.jsr250();
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize());
}
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)

View File

@@ -35,7 +35,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Demonstrate the samples
@@ -62,15 +62,16 @@ public class SampleEnableGlobalMethodSecurityTests {
this.spring.register(SampleWebSecurityConfig.class).autowire();
assertThat(this.methodSecurityService.secured()).isNull();
assertThat(this.methodSecurityService.jsr250()).isNull();
assertThatThrownBy(() -> this.methodSecurityService.preAuthorize()).isInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> this.methodSecurityService.preAuthorize());
}
@Test
public void customPermissionHandler() {
this.spring.register(CustomPermissionEvaluatorWebSecurityConfig.class).autowire();
assertThat(this.methodSecurityService.hasPermission("allowed")).isNull();
assertThatThrownBy(() -> this.methodSecurityService.hasPermission("denied"))
.isInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(AccessDeniedException.class)
.isThrownBy(() -> this.methodSecurityService.hasPermission("denied"));
}
@EnableGlobalMethodSecurity(prePostEnabled = true)

View File

@@ -44,7 +44,6 @@ import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@@ -76,8 +75,8 @@ public class Sec2758Tests {
@Test
public void methodSecurityWhenNullifyingRolePrefixThenPassivityRestored() {
this.spring.register(SecurityConfig.class).autowire();
assertThatCode(() -> this.service.doJsr250()).doesNotThrowAnyException();
assertThatCode(() -> this.service.doPreAuthorize()).doesNotThrowAnyException();
this.service.doJsr250();
this.service.doPreAuthorize();
}
@EnableWebSecurity

View File

@@ -56,7 +56,6 @@ import org.springframework.web.accept.HeaderContentNegotiationStrategy;
import org.springframework.web.filter.OncePerRequestFilter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
@@ -142,7 +141,7 @@ public class WebSecurityConfigurerAdapterTests {
public void loadConfigWhenUserDetailsServiceHasCircularReferenceThenStillLoads() {
this.spring.register(RequiresUserDetailsServiceConfig.class, UserDetailsServiceConfig.class).autowire();
MyFilter myFilter = this.spring.getContext().getBean(MyFilter.class);
assertThatCode(() -> myFilter.userDetailsService.loadUserByUsername("user")).doesNotThrowAnyException();
myFilter.userDetailsService.loadUserByUsername("user");
assertThatExceptionOfType(UsernameNotFoundException.class)
.isThrownBy(() -> myFilter.userDetailsService.loadUserByUsername("admin"));
}

View File

@@ -21,6 +21,7 @@ import javax.servlet.http.HttpServletRequest;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
@@ -46,7 +47,7 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
@@ -131,32 +132,37 @@ public class OAuth2ClientConfigurationTests {
// gh-5321
@Test
public void loadContextWhenOAuth2AuthorizedClientRepositoryRegisteredTwiceThenThrowNoUniqueBeanDefinitionException() {
assertThatThrownBy(
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
() -> this.spring.register(OAuth2AuthorizedClientRepositoryRegisteredTwiceConfig.class).autowire())
.hasRootCauseInstanceOf(NoUniqueBeanDefinitionException.class)
.hasMessageContaining("Expected single matching bean of type '"
+ OAuth2AuthorizedClientRepository.class.getName()
.withRootCauseInstanceOf(NoUniqueBeanDefinitionException.class).withMessageContaining(
"Expected single matching bean of type '" + OAuth2AuthorizedClientRepository.class.getName()
+ "' but found 2: authorizedClientRepository1,authorizedClientRepository2");
}
@Test
public void loadContextWhenClientRegistrationRepositoryNotRegisteredThenThrowNoSuchBeanDefinitionException() {
assertThatThrownBy(() -> this.spring.register(ClientRegistrationRepositoryNotRegisteredConfig.class).autowire())
.hasRootCauseInstanceOf(NoSuchBeanDefinitionException.class).hasMessageContaining(
assertThatExceptionOfType(Exception.class)
.isThrownBy(
() -> this.spring.register(ClientRegistrationRepositoryNotRegisteredConfig.class).autowire())
.withRootCauseInstanceOf(NoSuchBeanDefinitionException.class).withMessageContaining(
"No qualifying bean of type '" + ClientRegistrationRepository.class.getName() + "' available");
}
@Test
public void loadContextWhenClientRegistrationRepositoryRegisteredTwiceThenThrowNoUniqueBeanDefinitionException() {
assertThatThrownBy(() -> this.spring.register(ClientRegistrationRepositoryRegisteredTwiceConfig.class)
.autowire()).hasRootCauseInstanceOf(NoUniqueBeanDefinitionException.class).hasMessageContaining(
"expected single matching bean but found 2: clientRegistrationRepository1,clientRegistrationRepository2");
assertThatExceptionOfType(Exception.class)
.isThrownBy(
() -> this.spring.register(ClientRegistrationRepositoryRegisteredTwiceConfig.class).autowire())
.withMessageContaining(
"expected single matching bean but found 2: clientRegistrationRepository1,clientRegistrationRepository2")
.withRootCauseInstanceOf(NoUniqueBeanDefinitionException.class);
}
@Test
public void loadContextWhenAccessTokenResponseClientRegisteredTwiceThenThrowNoUniqueBeanDefinitionException() {
assertThatThrownBy(() -> this.spring.register(AccessTokenResponseClientRegisteredTwiceConfig.class).autowire())
.hasRootCauseInstanceOf(NoUniqueBeanDefinitionException.class).hasMessageContaining(
assertThatExceptionOfType(Exception.class)
.isThrownBy(() -> this.spring.register(AccessTokenResponseClientRegisteredTwiceConfig.class).autowire())
.withRootCauseInstanceOf(NoUniqueBeanDefinitionException.class).withMessageContaining(
"expected single matching bean but found 2: accessTokenResponseClient1,accessTokenResponseClient2");
}

View File

@@ -61,7 +61,7 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@@ -128,11 +128,11 @@ public class WebSecurityConfigurationTests {
@Test
public void loadConfigWhenWebSecurityConfigurersHaveSameOrderThenThrowBeanCreationException() {
Throwable thrown = catchThrowable(() -> this.spring.register(DuplicateOrderConfig.class).autowire());
assertThat(thrown).isInstanceOf(BeanCreationException.class)
.hasMessageContaining("@Order on WebSecurityConfigurers must be unique")
.hasMessageContaining(DuplicateOrderConfig.WebConfigurer1.class.getName())
.hasMessageContaining(DuplicateOrderConfig.WebConfigurer2.class.getName());
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(DuplicateOrderConfig.class).autowire())
.withMessageContaining("@Order on WebSecurityConfigurers must be unique")
.withMessageContaining(DuplicateOrderConfig.WebConfigurer1.class.getName())
.withMessageContaining(DuplicateOrderConfig.WebConfigurer2.class.getName());
}
@Test
@@ -155,10 +155,9 @@ public class WebSecurityConfigurationTests {
@Test
public void loadConfigWhenSecurityExpressionHandlerIsNullThenException() {
Throwable thrown = catchThrowable(
() -> this.spring.register(NullWebSecurityExpressionHandlerConfig.class).autowire());
assertThat(thrown).isInstanceOf(BeanCreationException.class);
assertThat(thrown).hasRootCauseExactlyInstanceOf(IllegalArgumentException.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(NullWebSecurityExpressionHandlerConfig.class).autowire())
.havingRootCause().isExactlyInstanceOf(IllegalArgumentException.class);
}
@Test
@@ -250,10 +249,10 @@ public class WebSecurityConfigurationTests {
@Test
public void loadConfigWhenBothAdapterAndFilterChainConfiguredThenException() {
Throwable thrown = catchThrowable(() -> this.spring.register(AdapterAndFilterChainConfig.class).autowire());
assertThat(thrown).isInstanceOf(BeanCreationException.class)
.hasRootCauseExactlyInstanceOf(IllegalStateException.class)
.hasMessageContaining("Found WebSecurityConfigurerAdapter as well as SecurityFilterChain.");
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(AdapterAndFilterChainConfig.class).autowire())
.withRootCauseExactlyInstanceOf(IllegalStateException.class)
.withMessageContaining("Found WebSecurityConfigurerAdapter as well as SecurityFilterChain.");
}

View File

@@ -42,7 +42,7 @@ import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.security.config.Customizer.withDefaults;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options;
@@ -65,8 +65,8 @@ public class CorsConfigurerTests {
@Test
public void configureWhenNoMvcThenException() {
assertThatThrownBy(() -> this.spring.register(DefaultCorsConfig.class).autowire())
.isInstanceOf(BeanCreationException.class).hasMessageContaining(
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(DefaultCorsConfig.class).autowire()).withMessageContaining(
"Please ensure Spring Security & Spring MVC are configured in a shared ApplicationContext");
}

View File

@@ -52,7 +52,7 @@ import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.RequestDataValueProcessor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.BDDMockito.given;
@@ -343,8 +343,9 @@ public class CsrfConfigurerTests {
// SEC-2749
@Test
public void configureWhenRequireCsrfProtectionMatcherNullThenException() {
assertThatThrownBy(() -> this.spring.register(NullRequireCsrfProtectionMatcherConfig.class).autowire())
.isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(NullRequireCsrfProtectionMatcherConfig.class).autowire())
.withRootCauseInstanceOf(IllegalArgumentException.class);
}
@Test
@@ -356,8 +357,9 @@ public class CsrfConfigurerTests {
@Test
public void getWhenNullAuthenticationStrategyThenException() {
assertThatThrownBy(() -> this.spring.register(NullAuthenticationStrategy.class).autowire())
.isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(NullAuthenticationStrategy.class).autowire())
.withRootCauseInstanceOf(IllegalArgumentException.class);
}
@Test

View File

@@ -56,7 +56,7 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
@@ -84,9 +84,9 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void configureWhenHasRoleStartingWithStringRoleThenException() {
assertThatThrownBy(() -> this.spring.register(HasRoleStartingWithRoleConfig.class).autowire())
.isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class)
.hasMessageContaining(
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(HasRoleStartingWithRoleConfig.class).autowire())
.withRootCauseInstanceOf(IllegalArgumentException.class).withMessageContaining(
"role should not start with 'ROLE_' since it is automatically inserted. Got 'ROLE_USER'");
}
@@ -98,15 +98,16 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void configureWhenAuthorizedRequestsAndNoRequestsThenException() {
assertThatThrownBy(() -> this.spring.register(NoRequestsConfig.class).autowire())
.isInstanceOf(BeanCreationException.class).hasMessageContaining(
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(NoRequestsConfig.class).autowire()).withMessageContaining(
"At least one mapping is required (i.e. authorizeRequests().anyRequest().authenticated())");
}
@Test
public void configureWhenAnyRequestIncompleteMappingThenException() {
assertThatThrownBy(() -> this.spring.register(IncompleteMappingConfig.class).autowire())
.isInstanceOf(BeanCreationException.class).hasMessageContaining("An incomplete mapping was found for ");
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(IncompleteMappingConfig.class).autowire())
.withMessageContaining("An incomplete mapping was found for ");
}
@Test

View File

@@ -36,7 +36,7 @@ import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.security.config.Customizer.withDefaults;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
@@ -320,14 +320,16 @@ public class HeadersConfigurerTests {
@Test
public void configureWhenContentSecurityPolicyEmptyThenException() {
assertThatThrownBy(() -> this.spring.register(ContentSecurityPolicyInvalidConfig.class).autowire())
.isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(ContentSecurityPolicyInvalidConfig.class).autowire())
.withRootCauseInstanceOf(IllegalArgumentException.class);
}
@Test
public void configureWhenContentSecurityPolicyEmptyInLambdaThenException() {
assertThatThrownBy(() -> this.spring.register(ContentSecurityPolicyInvalidInLambdaConfig.class).autowire())
.isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(ContentSecurityPolicyInvalidInLambdaConfig.class).autowire())
.withRootCauseInstanceOf(IllegalArgumentException.class);
}
@Test
@@ -381,8 +383,9 @@ public class HeadersConfigurerTests {
@Test
public void configureWhenFeaturePolicyEmptyThenException() {
assertThatThrownBy(() -> this.spring.register(FeaturePolicyInvalidConfig.class).autowire())
.isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(FeaturePolicyInvalidConfig.class).autowire())
.withRootCauseInstanceOf(IllegalArgumentException.class);
}
@Test

View File

@@ -36,7 +36,7 @@ import org.springframework.security.web.authentication.logout.LogoutSuccessHandl
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.test.web.servlet.MockMvc;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
@@ -66,26 +66,30 @@ public class LogoutConfigurerTests {
@Test
public void configureWhenDefaultLogoutSuccessHandlerForHasNullLogoutHandlerThenException() {
assertThatThrownBy(() -> this.spring.register(NullLogoutSuccessHandlerConfig.class).autowire())
.isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(NullLogoutSuccessHandlerConfig.class).autowire())
.withRootCauseInstanceOf(IllegalArgumentException.class);
}
@Test
public void configureWhenDefaultLogoutSuccessHandlerForHasNullLogoutHandlerInLambdaThenException() {
assertThatThrownBy(() -> this.spring.register(NullLogoutSuccessHandlerInLambdaConfig.class).autowire())
.isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(NullLogoutSuccessHandlerInLambdaConfig.class).autowire())
.withRootCauseInstanceOf(IllegalArgumentException.class);
}
@Test
public void configureWhenDefaultLogoutSuccessHandlerForHasNullMatcherThenException() {
assertThatThrownBy(() -> this.spring.register(NullMatcherConfig.class).autowire())
.isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(NullMatcherConfig.class).autowire())
.withRootCauseInstanceOf(IllegalArgumentException.class);
}
@Test
public void configureWhenDefaultLogoutSuccessHandlerForHasNullMatcherInLambdaThenException() {
assertThatThrownBy(() -> this.spring.register(NullMatcherInLambdaConfig.class).autowire())
.isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(NullMatcherInLambdaConfig.class).autowire())
.withRootCauseInstanceOf(IllegalArgumentException.class);
}
@Test
@@ -161,14 +165,16 @@ public class LogoutConfigurerTests {
// SEC-3170
@Test
public void configureWhenLogoutHandlerNullThenException() {
assertThatThrownBy(() -> this.spring.register(NullLogoutHandlerConfig.class).autowire())
.isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(NullLogoutHandlerConfig.class).autowire())
.withRootCauseInstanceOf(IllegalArgumentException.class);
}
@Test
public void configureWhenLogoutHandlerNullInLambdaThenException() {
assertThatThrownBy(() -> this.spring.register(NullLogoutHandlerInLambdaConfig.class).autowire())
.isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(NullLogoutHandlerInLambdaConfig.class).autowire())
.withRootCauseInstanceOf(IllegalArgumentException.class);
}
// SEC-3170

View File

@@ -33,7 +33,7 @@ import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.RequestRejectedException;
import org.springframework.test.web.servlet.MockMvc;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
/**
@@ -54,21 +54,22 @@ public class NamespaceHttpFirewallTests {
@Test
public void requestWhenPathContainsDoubleDotsThenBehaviorMatchesNamespace() {
this.rule.register(HttpFirewallConfig.class).autowire();
assertThatCode(() -> this.mvc.perform(get("/public/../private/"))).isInstanceOf(RequestRejectedException.class);
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.mvc.perform(get("/public/../private/")));
}
@Test
public void requestWithCustomFirewallThenBehaviorMatchesNamespace() {
this.rule.register(CustomHttpFirewallConfig.class).autowire();
assertThatCode(() -> this.mvc.perform(get("/").param("deny", "true")))
.isInstanceOf(RequestRejectedException.class);
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.mvc.perform(get("/").param("deny", "true")));
}
@Test
public void requestWithCustomFirewallBeanThenBehaviorMatchesNamespace() {
this.rule.register(CustomHttpFirewallBeanConfig.class).autowire();
assertThatCode(() -> this.mvc.perform(get("/").param("deny", "true")))
.isInstanceOf(RequestRejectedException.class);
assertThatExceptionOfType(RequestRejectedException.class)
.isThrownBy(() -> this.mvc.perform(get("/").param("deny", "true")));
}
@EnableWebSecurity

View File

@@ -27,7 +27,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
import org.springframework.security.config.test.SpringTestRule;
import org.springframework.test.web.servlet.MockMvc;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
@@ -57,9 +57,9 @@ public class PermitAllSupportTests {
@Test
public void configureWhenNotAuthorizeRequestsThenException() {
assertThatCode(() -> this.spring.register(NoAuthorizedUrlsConfig.class).autowire())
.isInstanceOf(BeanCreationException.class)
.hasMessageContaining("permitAll only works with HttpSecurity.authorizeRequests");
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(NoAuthorizedUrlsConfig.class).autowire())
.withMessageContaining("permitAll only works with HttpSecurity.authorizeRequests");
}
@EnableWebSecurity

View File

@@ -47,7 +47,8 @@ import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
@@ -81,8 +82,10 @@ public class RememberMeConfigurerTests {
@Test
public void postWhenNoUserDetailsServiceThenException() {
this.spring.register(NullUserDetailsConfig.class).autowire();
assertThatThrownBy(() -> this.mvc.perform(post("/login").param("username", "user").param("password", "password")
.param("remember-me", "true").with(csrf()))).hasMessageContaining("UserDetailsService is required");
assertThatIllegalStateException()
.isThrownBy(() -> this.mvc.perform(post("/login").param("username", "user")
.param("password", "password").param("remember-me", "true").with(csrf())))
.withMessageContaining("UserDetailsService is required");
}
@Test
@@ -168,9 +171,11 @@ public class RememberMeConfigurerTests {
@Test
public void configureWhenRememberMeCookieNameAndRememberMeServicesThenException() {
assertThatThrownBy(() -> this.spring.register(RememberMeCookieNameAndRememberMeServicesConfig.class).autowire())
.isInstanceOf(BeanCreationException.class).hasRootCauseInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Can not set rememberMeCookieName and custom rememberMeServices.");
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(
() -> this.spring.register(RememberMeCookieNameAndRememberMeServicesConfig.class).autowire())
.withRootCauseInstanceOf(IllegalArgumentException.class)
.withMessageContaining("Can not set rememberMeCookieName and custom rememberMeServices.");
}
@Test

View File

@@ -29,6 +29,7 @@ import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
@@ -91,7 +92,7 @@ import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -479,9 +480,10 @@ public class OAuth2LoginConfigurerTests {
@Test
public void oidcLoginCustomWithNoUniqueJwtDecoderFactory() {
assertThatThrownBy(() -> loadConfig(OAuth2LoginConfig.class, NoUniqueJwtDecoderFactoryConfig.class))
.hasRootCauseInstanceOf(NoUniqueBeanDefinitionException.class)
.hasMessageContaining("No qualifying bean of type "
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> loadConfig(OAuth2LoginConfig.class, NoUniqueJwtDecoderFactoryConfig.class))
.withRootCauseInstanceOf(NoUniqueBeanDefinitionException.class)
.withMessageContaining("No qualifying bean of type "
+ "'org.springframework.security.oauth2.jwt.JwtDecoderFactory<org.springframework.security.oauth2.client.registration.ClientRegistration>' "
+ "available: expected single matching bean but found 2: jwtDecoderFactory1,jwtDecoderFactory2");
}

View File

@@ -133,7 +133,8 @@ import org.springframework.web.client.RestOperations;
import org.springframework.web.context.support.GenericWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.mockito.ArgumentMatchers.any;
@@ -565,9 +566,10 @@ public class OAuth2ResourceServerConfigurerTests {
@Test
public void getBearerTokenResolverWhenDuplicateResolverBeansThenWiringException() {
assertThatCode(() -> this.spring.register(MultipleBearerTokenResolverBeansConfig.class, JwtDecoderConfig.class)
.autowire()).isInstanceOf(BeanCreationException.class)
.hasRootCauseInstanceOf(NoUniqueBeanDefinitionException.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring
.register(MultipleBearerTokenResolverBeansConfig.class, JwtDecoderConfig.class).autowire())
.withRootCauseInstanceOf(NoUniqueBeanDefinitionException.class);
}
@Test
@@ -675,7 +677,8 @@ public class OAuth2ResourceServerConfigurerTests {
context.registerBean("decoderTwo", JwtDecoder.class, () -> decoder);
this.spring.context(context).autowire();
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
assertThatCode(() -> jwtConfigurer.getJwtDecoder()).isInstanceOf(NoUniqueBeanDefinitionException.class);
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class)
.isThrownBy(() -> jwtConfigurer.getJwtDecoder());
}
@Test
@@ -701,14 +704,14 @@ public class OAuth2ResourceServerConfigurerTests {
public void authenticationEntryPointWhenGivenNullThenThrowsException() {
ApplicationContext context = mock(ApplicationContext.class);
OAuth2ResourceServerConfigurer configurer = new OAuth2ResourceServerConfigurer(context);
assertThatCode(() -> configurer.authenticationEntryPoint(null)).isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> configurer.authenticationEntryPoint(null));
}
@Test
public void accessDeniedHandlerWhenGivenNullThenThrowsException() {
ApplicationContext context = mock(ApplicationContext.class);
OAuth2ResourceServerConfigurer configurer = new OAuth2ResourceServerConfigurer(context);
assertThatCode(() -> configurer.accessDeniedHandler(null)).isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> configurer.accessDeniedHandler(null));
}
@Test
@@ -862,8 +865,8 @@ public class OAuth2ResourceServerConfigurerTests {
@Test
public void configureWhenOnlyIntrospectionUrlThenException() {
assertThatCode(() -> this.spring.register(OpaqueTokenHalfConfiguredConfig.class).autowire())
.isInstanceOf(BeanCreationException.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(OpaqueTokenHalfConfiguredConfig.class).autowire());
}
@Test
@@ -991,27 +994,30 @@ public class OAuth2ResourceServerConfigurerTests {
@Test
public void configuredWhenMissingJwtAuthenticationProviderThenWiringException() {
assertThatCode(() -> this.spring.register(JwtlessConfig.class).autowire())
.isInstanceOf(BeanCreationException.class).hasMessageContaining("neither was found");
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(JwtlessConfig.class).autowire())
.withMessageContaining("neither was found");
}
@Test
public void configureWhenMissingJwkSetUriThenWiringException() {
assertThatCode(() -> this.spring.register(JwtHalfConfiguredConfig.class).autowire())
.isInstanceOf(BeanCreationException.class).hasMessageContaining("No qualifying bean of type");
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(JwtHalfConfiguredConfig.class).autowire())
.withMessageContaining("No qualifying bean of type");
}
@Test
public void configureWhenUsingBothJwtAndOpaqueThenWiringException() {
assertThatCode(() -> this.spring.register(OpaqueAndJwtConfig.class).autowire())
.isInstanceOf(BeanCreationException.class)
.hasMessageContaining("Spring Security only supports JWTs or Opaque Tokens");
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(OpaqueAndJwtConfig.class).autowire())
.withMessageContaining("Spring Security only supports JWTs or Opaque Tokens");
}
@Test
public void configureWhenUsingBothAuthenticationManagerResolverAndOpaqueThenWiringException() {
assertThatCode(() -> this.spring.register(AuthenticationManagerResolverPlusOtherConfig.class).autowire())
.isInstanceOf(BeanCreationException.class).hasMessageContaining("authenticationManagerResolver");
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(AuthenticationManagerResolverPlusOtherConfig.class).autowire())
.withMessageContaining("authenticationManagerResolver");
}
@Test
@@ -1064,8 +1070,8 @@ public class OAuth2ResourceServerConfigurerTests {
context.registerBean("converterTwo", JwtAuthenticationConverter.class, () -> converterBean);
this.spring.context(context).autowire();
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
assertThatCode(jwtConfigurer::getJwtAuthenticationConverter)
.isInstanceOf(NoUniqueBeanDefinitionException.class);
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class)
.isThrownBy(jwtConfigurer::getJwtAuthenticationConverter);
}
private static <T> void registerMockBean(GenericApplicationContext context, String name, Class<T> clazz) {

View File

@@ -29,7 +29,8 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.util.InMemoryResource;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* @author Rob Winch
@@ -45,15 +46,15 @@ public class UserDetailsResourceFactoryBeanTests {
@Test
public void setResourceLoaderWhenNullThenThrowsException() {
assertThatThrownBy(() -> this.factory.setResourceLoader(null)).isInstanceOf(IllegalArgumentException.class)
.hasStackTraceContaining("resourceLoader cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> this.factory.setResourceLoader(null))
.withStackTraceContaining("resourceLoader cannot be null");
}
@Test
public void getObjectWhenPropertiesResourceLocationNullThenThrowsIllegalStateException() {
this.factory.setResourceLoader(this.resourceLoader);
assertThatThrownBy(() -> this.factory.getObject()).isInstanceOf(IllegalArgumentException.class)
.hasStackTraceContaining("resource cannot be null if resourceLocation is null");
assertThatIllegalArgumentException().isThrownBy(() -> this.factory.getObject())
.withStackTraceContaining("resource cannot be null if resourceLocation is null");
}
@Test
@@ -72,8 +73,8 @@ public class UserDetailsResourceFactoryBeanTests {
@Test
public void getObjectWhenInvalidUserThenThrowsMeaningfulException() {
this.factory.setResource(new InMemoryResource("user=invalidFormatHere"));
assertThatThrownBy(() -> this.factory.getObject()).isInstanceOf(IllegalStateException.class)
.hasStackTraceContaining("user").hasStackTraceContaining("invalidFormatHere");
assertThatIllegalStateException().isThrownBy(() -> this.factory.getObject()).withStackTraceContaining("user")
.withStackTraceContaining("invalidFormatHere");
}
@Test

View File

@@ -38,7 +38,7 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe
import org.springframework.security.config.test.SpringTestRule;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link RsaKeyConversionServicePostProcessor}
@@ -131,9 +131,9 @@ public class RsaKeyConversionServicePostProcessorTests {
@Test
public void valueWhenOverridingConversionServiceThenUsed() {
assertThatCode(
assertThatExceptionOfType(Exception.class).isThrownBy(
() -> this.spring.register(OverrideConversionServiceConfig.class, DefaultConfig.class).autowire())
.hasRootCauseInstanceOf(IllegalArgumentException.class);
.withRootCauseInstanceOf(IllegalArgumentException.class);
}
@EnableWebSecurity

View File

@@ -36,7 +36,7 @@ import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@@ -59,8 +59,8 @@ public class AccessDeniedConfigTests {
@Test
public void configureWhenAccessDeniedHandlerIsMissingLeadingSlashThenException() {
SpringTestContext context = this.spring.configLocations(this.xml("NoLeadingSlash"));
assertThatThrownBy(() -> context.autowire()).isInstanceOf(BeanCreationException.class)
.hasMessageContaining("errorPage must begin with '/'");
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> context.autowire())
.withMessageContaining("errorPage must begin with '/'");
}
@Test
@@ -73,8 +73,8 @@ public class AccessDeniedConfigTests {
@Test
public void configureWhenAccessDeniedHandlerUsesPathAndRefThenException() {
SpringTestContext context = this.spring.configLocations(this.xml("UsesPathAndRef"));
assertThatThrownBy(() -> context.autowire()).isInstanceOf(BeanDefinitionParsingException.class)
.hasMessageContaining("attribute error-page cannot be used together with the 'ref' attribute");
assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(() -> context.autowire())
.withMessageContaining("attribute error-page cannot be used together with the 'ref' attribute");
}
private String xml(String configName) {

View File

@@ -42,7 +42,7 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
@@ -89,14 +89,14 @@ public class FormLoginConfigTests {
@Test
public void autowireWhenLoginPageIsMisconfiguredThenDetects() {
assertThatThrownBy(() -> this.spring.configLocations(this.xml("NoLeadingSlashLoginPage")).autowire())
.isInstanceOf(BeanCreationException.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.configLocations(this.xml("NoLeadingSlashLoginPage")).autowire());
}
@Test
public void autowireWhenDefaultTargetUrlIsMisconfiguredThenDetects() {
assertThatThrownBy(() -> this.spring.configLocations(this.xml("NoLeadingSlashDefaultTargetUrl")).autowire())
.isInstanceOf(BeanCreationException.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.configLocations(this.xml("NoLeadingSlashDefaultTargetUrl")).autowire());
}
@Test

View File

@@ -36,7 +36,7 @@ import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
@@ -59,8 +59,9 @@ public class HttpCorsConfigTests {
@Test
public void autowireWhenMissingMvcThenGivesInformativeError() {
assertThatThrownBy(() -> this.spring.configLocations(this.xml("RequiresMvc")).autowire())
.isInstanceOf(BeanCreationException.class).hasMessageContaining(
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.configLocations(this.xml("RequiresMvc")).autowire())
.withMessageContaining(
"Please ensure Spring Security & Spring MVC are configured in a shared ApplicationContext");
}

View File

@@ -37,7 +37,7 @@ import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@@ -92,9 +92,9 @@ public class HttpHeadersConfigTests {
@Test
public void configureWhenHeadersDisabledHavingChildElementThenAutowireFails() {
assertThatThrownBy(() -> this.spring.configLocations(this.xml("HeadersDisabledHavingChildElement")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class)
.hasMessageContaining("Cannot specify <headers disabled=\"true\"> with child elements");
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> this.spring.configLocations(this.xml("HeadersDisabledHavingChildElement")).autowire())
.withMessageContaining("Cannot specify <headers disabled=\"true\"> with child elements");
}
@Test
@@ -185,24 +185,20 @@ public class HttpHeadersConfigTests {
@Test
public void configureWhenUsingFrameOptionsAllowFromNoOriginThenAutowireFails() {
assertThatThrownBy(() -> this.spring
.configLocations(this.xml("DefaultsDisabledWithFrameOptionsAllowFromNoOrigin")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class)
.hasMessageContaining("Strategy requires a 'value' to be set."); // FIXME
// better
// error
// message?
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> this.spring
.configLocations(this.xml("DefaultsDisabledWithFrameOptionsAllowFromNoOrigin")).autowire())
.withMessageContaining("Strategy requires a 'value' to be set.");
// FIXME better error message?
}
@Test
public void configureWhenUsingFrameOptionsAllowFromBlankOriginThenAutowireFails() {
assertThatThrownBy(() -> this.spring
.configLocations(this.xml("DefaultsDisabledWithFrameOptionsAllowFromBlankOrigin")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class)
.hasMessageContaining("Strategy requires a 'value' to be set."); // FIXME
// better
// error
// message?
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> this.spring
.configLocations(this.xml("DefaultsDisabledWithFrameOptionsAllowFromBlankOrigin")).autowire())
.withMessageContaining("Strategy requires a 'value' to be set.");
// FIXME better error message?
}
@Test
@@ -243,15 +239,14 @@ public class HttpHeadersConfigTests {
@Test
public void configureWhenUsingCustomHeaderNameOnlyThenAutowireFails() {
assertThatThrownBy(() -> this.spring.configLocations(this.xml("DefaultsDisabledWithOnlyHeaderName")).autowire())
.isInstanceOf(BeanCreationException.class);
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
() -> this.spring.configLocations(this.xml("DefaultsDisabledWithOnlyHeaderName")).autowire());
}
@Test
public void configureWhenUsingCustomHeaderValueOnlyThenAutowireFails() {
assertThatThrownBy(
() -> this.spring.configLocations(this.xml("DefaultsDisabledWithOnlyHeaderValue")).autowire())
.isInstanceOf(BeanCreationException.class);
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
() -> this.spring.configLocations(this.xml("DefaultsDisabledWithOnlyHeaderValue")).autowire());
}
@Test
@@ -283,10 +278,10 @@ public class HttpHeadersConfigTests {
@Test
public void configureWhenXssProtectionDisabledAndBlockSetThenAutowireFails() {
assertThatThrownBy(() -> this.spring
.configLocations(this.xml("DefaultsDisabledWithXssProtectionDisabledAndBlockSet")).autowire())
.isInstanceOf(BeanCreationException.class)
.hasMessageContaining("Cannot set block to true with enabled false");
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring
.configLocations(this.xml("DefaultsDisabledWithXssProtectionDisabledAndBlockSet")).autowire())
.withMessageContaining("Cannot set block to true with enabled false");
}
@Test
@@ -326,16 +321,16 @@ public class HttpHeadersConfigTests {
@Test
public void configureWhenUsingHpkpWithoutPinsThenAutowireFails() {
assertThatThrownBy(() -> this.spring.configLocations(this.xml("DefaultsDisabledWithEmptyHpkp")).autowire())
.isInstanceOf(XmlBeanDefinitionStoreException.class)
.hasMessageContaining("The content of element 'hpkp' is not complete");
assertThatExceptionOfType(XmlBeanDefinitionStoreException.class)
.isThrownBy(() -> this.spring.configLocations(this.xml("DefaultsDisabledWithEmptyHpkp")).autowire())
.withMessageContaining("The content of element 'hpkp' is not complete");
}
@Test
public void configureWhenUsingHpkpWithEmptyPinsThenAutowireFails() {
assertThatThrownBy(() -> this.spring.configLocations(this.xml("DefaultsDisabledWithEmptyPins")).autowire())
.isInstanceOf(XmlBeanDefinitionStoreException.class)
.hasMessageContaining("The content of element 'pins' is not complete");
assertThatExceptionOfType(XmlBeanDefinitionStoreException.class)
.isThrownBy(() -> this.spring.configLocations(this.xml("DefaultsDisabledWithEmptyPins")).autowire())
.withMessageContaining("The content of element 'pins' is not complete");
}
@Test
@@ -452,42 +447,47 @@ public class HttpHeadersConfigTests {
@Test
public void configureWhenHstsDisabledAndIncludeSubdomainsSpecifiedThenAutowireFails() {
assertThatThrownBy(
assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(
() -> this.spring.configLocations(this.xml("HstsDisabledSpecifyingIncludeSubdomains")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class).hasMessageContaining("include-subdomains");
.withMessageContaining("include-subdomains");
}
@Test
public void configureWhenHstsDisabledAndMaxAgeSpecifiedThenAutowireFails() {
assertThatThrownBy(() -> this.spring.configLocations(this.xml("HstsDisabledSpecifyingMaxAge")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class).hasMessageContaining("max-age");
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> this.spring.configLocations(this.xml("HstsDisabledSpecifyingMaxAge")).autowire())
.withMessageContaining("max-age");
}
@Test
public void configureWhenHstsDisabledAndRequestMatcherSpecifiedThenAutowireFails() {
assertThatThrownBy(
() -> this.spring.configLocations(this.xml("HstsDisabledSpecifyingRequestMatcher")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class).hasMessageContaining("request-matcher-ref");
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(
() -> this.spring.configLocations(this.xml("HstsDisabledSpecifyingRequestMatcher")).autowire())
.withMessageContaining("request-matcher-ref");
}
@Test
public void configureWhenXssProtectionDisabledAndEnabledThenAutowireFails() {
assertThatThrownBy(() -> this.spring.configLocations(this.xml("XssProtectionDisabledAndEnabled")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class).hasMessageContaining("enabled");
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> this.spring.configLocations(this.xml("XssProtectionDisabledAndEnabled")).autowire())
.withMessageContaining("enabled");
}
@Test
public void configureWhenXssProtectionDisabledAndBlockSpecifiedThenAutowireFails() {
assertThatThrownBy(
() -> this.spring.configLocations(this.xml("XssProtectionDisabledSpecifyingBlock")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class).hasMessageContaining("block");
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(
() -> this.spring.configLocations(this.xml("XssProtectionDisabledSpecifyingBlock")).autowire())
.withMessageContaining("block");
}
@Test
public void configureWhenFrameOptionsDisabledAndPolicySpecifiedThenAutowireFails() {
assertThatThrownBy(
() -> this.spring.configLocations(this.xml("FrameOptionsDisabledSpecifyingPolicy")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class).hasMessageContaining("policy");
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(
() -> this.spring.configLocations(this.xml("FrameOptionsDisabledSpecifyingPolicy")).autowire())
.withMessageContaining("policy");
}
@Test
@@ -514,9 +514,8 @@ public class HttpHeadersConfigTests {
@Test
public void configureWhenContentSecurityPolicyConfiguredWithEmptyDirectivesThenAutowireFails() {
assertThatThrownBy(
() -> this.spring.configLocations(this.xml("ContentSecurityPolicyWithEmptyDirectives")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class);
assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(
() -> this.spring.configLocations(this.xml("ContentSecurityPolicyWithEmptyDirectives")).autowire());
}
@Test

View File

@@ -35,7 +35,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
@@ -151,26 +151,26 @@ public class InterceptUrlConfigTests {
@Test
public void configureWhenUsingAntMatcherAndServletPathThenThrowsException() {
assertThatCode(() -> this.spring.configLocations(this.xml("AntMatcherServletPath")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class);
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> this.spring.configLocations(this.xml("AntMatcherServletPath")).autowire());
}
@Test
public void configureWhenUsingRegexMatcherAndServletPathThenThrowsException() {
assertThatCode(() -> this.spring.configLocations(this.xml("RegexMatcherServletPath")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class);
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> this.spring.configLocations(this.xml("RegexMatcherServletPath")).autowire());
}
@Test
public void configureWhenUsingCiRegexMatcherAndServletPathThenThrowsException() {
assertThatCode(() -> this.spring.configLocations(this.xml("CiRegexMatcherServletPath")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class);
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> this.spring.configLocations(this.xml("CiRegexMatcherServletPath")).autowire());
}
@Test
public void configureWhenUsingDefaultMatcherAndServletPathThenThrowsException() {
assertThatCode(() -> this.spring.configLocations(this.xml("DefaultMatcherServletPath")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class);
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> this.spring.configLocations(this.xml("DefaultMatcherServletPath")).autowire());
}
private MockServletContext mockServletContext(String servletPath) {

View File

@@ -111,7 +111,7 @@ import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.support.XmlWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willAnswer;
@@ -296,8 +296,8 @@ public class MiscHttpConfigTests {
@Test
public void configureWhenTwoFiltersWithSameOrderThenException() {
assertThatCode(() -> this.spring.configLocations(xml("CollidingFilters")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class);
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> this.spring.configLocations(xml("CollidingFilters")).autowire());
}
@Test
@@ -319,8 +319,8 @@ public class MiscHttpConfigTests {
@Test
public void configureWhenUsingInvalidLogoutSuccessUrlThenThrowsException() {
assertThatCode(() -> this.spring.configLocations(xml("InvalidLogoutSuccessUrl")).autowire())
.isInstanceOf(BeanCreationException.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.configLocations(xml("InvalidLogoutSuccessUrl")).autowire());
}
@Test
@@ -432,9 +432,8 @@ public class MiscHttpConfigTests {
@Test
public void configureWhenUserDetailsServiceInParentContextThenLocatesSuccessfully() {
assertThatCode(
() -> this.spring.configLocations(MiscHttpConfigTests.xml("MissingUserDetailsService")).autowire())
.isInstanceOf(BeansException.class);
assertThatExceptionOfType(BeansException.class).isThrownBy(
() -> this.spring.configLocations(MiscHttpConfigTests.xml("MissingUserDetailsService")).autowire());
try (XmlWebApplicationContext parent = new XmlWebApplicationContext()) {
parent.setConfigLocations(MiscHttpConfigTests.xml("AutoConfig"));
parent.refresh();

View File

@@ -27,7 +27,7 @@ import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.web.bind.annotation.GetMapping;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@@ -61,14 +61,16 @@ public class MultiHttpBlockConfigTests {
@Test
public void configureWhenUsingDuplicateHttpElementsThenThrowsWiringException() {
assertThatCode(() -> this.spring.configLocations(this.xml("IdenticalHttpElements")).autowire())
.isInstanceOf(BeanCreationException.class).hasCauseInstanceOf(IllegalArgumentException.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.configLocations(this.xml("IdenticalHttpElements")).autowire())
.withCauseInstanceOf(IllegalArgumentException.class);
}
@Test
public void configureWhenUsingIndenticallyPatternedHttpElementsThenThrowsWiringException() {
assertThatCode(() -> this.spring.configLocations(this.xml("IdenticallyPatternedHttpElements")).autowire())
.isInstanceOf(BeanCreationException.class).hasCauseInstanceOf(IllegalArgumentException.class);
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.configLocations(this.xml("IdenticallyPatternedHttpElements")).autowire())
.withCauseInstanceOf(IllegalArgumentException.class);
}
/**

View File

@@ -96,8 +96,7 @@ import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestOperations;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.mockito.ArgumentMatchers.any;
@@ -436,8 +435,8 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
@Test
public void configureWhenDecoderAndJwkSetUriThenException() {
assertThatThrownBy(() -> this.spring.configLocations(xml("JwtDecoderAndJwkSetUri")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class);
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> this.spring.configLocations(xml("JwtDecoderAndJwkSetUri")).autowire());
}
@Test
@@ -554,14 +553,14 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
@Test
public void configureWhenOnlyIntrospectionUrlThenException() {
assertThatCode(() -> this.spring.configLocations(xml("OpaqueTokenHalfConfigured")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class);
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> this.spring.configLocations(xml("OpaqueTokenHalfConfigured")).autowire());
}
@Test
public void configureWhenIntrospectorAndIntrospectionUriThenError() {
assertThatCode(() -> this.spring.configLocations(xml("OpaqueTokenAndIntrospectionUri")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class);
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> this.spring.configLocations(xml("OpaqueTokenAndIntrospectionUri")).autowire());
}
@Test
@@ -642,22 +641,23 @@ public class OAuth2ResourceServerBeanDefinitionParserTests {
@Test
public void configuredWhenMissingJwtAuthenticationProviderThenWiringException() {
assertThatCode(() -> this.spring.configLocations(xml("Jwtless")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class).hasMessageContaining("Please select one");
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> this.spring.configLocations(xml("Jwtless")).autowire())
.withMessageContaining("Please select one");
}
@Test
public void configureWhenMissingJwkSetUriThenWiringException() {
assertThatCode(() -> this.spring.configLocations(xml("JwtHalfConfigured")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class).hasMessageContaining("Please specify either");
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> this.spring.configLocations(xml("JwtHalfConfigured")).autowire())
.withMessageContaining("Please specify either");
}
@Test
public void configureWhenUsingBothAuthenticationManagerResolverAndJwtThenException() {
assertThatCode(
assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(
() -> this.spring.configLocations(xml("AuthenticationManagerResolverPlusOtherConfig")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class)
.hasMessageContaining("authentication-manager-resolver-ref");
.withMessageContaining("authentication-manager-resolver-ref");
}
@Test

View File

@@ -44,7 +44,7 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.CoreMatchers.containsString;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
@@ -92,8 +92,8 @@ public class OpenIDConfigTests {
@Test
public void configureWhenOpenIDAndFormLoginBothConfigureLoginPagesThenWiringException() {
assertThatCode(() -> this.spring.configLocations(this.xml("WithFormLoginAndOpenIDLoginPages")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class);
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> this.spring.configLocations(this.xml("WithFormLoginAndOpenIDLoginPages")).autowire());
}
@Test

View File

@@ -41,7 +41,7 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.verify;
@@ -155,8 +155,8 @@ public class RememberMeConfigTests {
@Test
public void configureWhenUsingDataSourceAndANegativeTokenValidityThenThrowsWiringException() {
assertThatCode(() -> this.spring.configLocations(this.xml("NegativeTokenValidityWithDataSource")).autowire())
.isInstanceOf(FatalBeanException.class);
assertThatExceptionOfType(FatalBeanException.class).isThrownBy(
() -> this.spring.configLocations(this.xml("NegativeTokenValidityWithDataSource")).autowire());
}
@Test
@@ -186,9 +186,8 @@ public class RememberMeConfigTests {
@Test
public void configureWhenUsingPersistentTokenRepositoryAndANegativeTokenValidityThenThrowsWiringException() {
assertThatCode(
() -> this.spring.configLocations(this.xml("NegativeTokenValidityWithPersistentRepository")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class);
assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(() -> this.spring
.configLocations(this.xml("NegativeTokenValidityWithPersistentRepository")).autowire());
}
@Test
@@ -231,8 +230,8 @@ public class RememberMeConfigTests {
@Test
public void configureWhenUsingRememberMeParameterAndServicesRefThenThrowsWiringException() {
assertThatCode(() -> this.spring.configLocations(this.xml("WithRememberMeParameterAndServicesRef")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class);
assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(
() -> this.spring.configLocations(this.xml("WithRememberMeParameterAndServicesRef")).autowire());
}
/**
@@ -249,11 +248,13 @@ public class RememberMeConfigTests {
*/
@Test
public void configureWhenUsingRememberMeCookieAndServicesRefThenThrowsWiringException() {
assertThatCode(() -> this.spring.configLocations(this.xml("WithRememberMeCookieAndServicesRef")).autowire())
.isInstanceOf(BeanDefinitionParsingException.class).hasMessageContaining(
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(
() -> this.spring.configLocations(this.xml("WithRememberMeCookieAndServicesRef")).autowire())
.withMessageContaining(
"Configuration problem: services-ref can't be used in combination with attributes "
+ "token-repository-ref,data-source-ref, user-service-ref, token-validity-seconds, use-secure-cookie, "
+ "remember-me-parameter or remember-me-cookie");
+ "token-repository-ref,data-source-ref, user-service-ref, token-validity-seconds, "
+ "use-secure-cookie, remember-me-parameter or remember-me-cookie");
}
private ResultActions rememberAuthentication(String username, String password) throws Exception {

View File

@@ -47,8 +47,7 @@ import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.server.ServerWebExchange;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.atLeastOnce;
@@ -294,7 +293,7 @@ public class FormLoginTests {
}
public DefaultLoginPage assertLoginFormNotPresent() {
assertThatThrownBy(() -> loginForm().username("")).isInstanceOf(NoSuchElementException.class);
assertThatExceptionOfType(NoSuchElementException.class).isThrownBy(() -> loginForm().username(""));
return this;
}
@@ -353,7 +352,7 @@ public class FormLoginTests {
}
public OAuth2Login assertClientRegistrationByName(String clientName) {
assertThatCode(() -> findClientRegistrationByName(clientName)).doesNotThrowAnyException();
findClientRegistrationByName(clientName);
return this;
}

View File

@@ -80,7 +80,7 @@ import org.springframework.web.reactive.config.EnableWebFlux;
import org.springframework.web.server.ServerWebExchange;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
@@ -334,7 +334,7 @@ public class OAuth2ResourceServerSpecTests {
context.registerBean("firstJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
context.registerBean("secondJwtDecoder", ReactiveJwtDecoder.class, () -> beanWiredJwtDecoder);
ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt();
assertThatCode(() -> jwt.getJwtDecoder()).isInstanceOf(NoUniqueBeanDefinitionException.class);
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class).isThrownBy(() -> jwt.getJwtDecoder());
}
@Test
@@ -343,7 +343,7 @@ public class OAuth2ResourceServerSpecTests {
ServerHttpSecurity http = new ServerHttpSecurity();
http.setApplicationContext(context);
ServerHttpSecurity.OAuth2ResourceServerSpec.JwtSpec jwt = http.oauth2ResourceServer().jwt();
assertThatCode(() -> jwt.getJwtDecoder()).isInstanceOf(NoSuchBeanDefinitionException.class);
assertThatExceptionOfType(NoSuchBeanDefinitionException.class).isThrownBy(() -> jwt.getJwtDecoder());
}
@Test
@@ -366,8 +366,9 @@ public class OAuth2ResourceServerSpecTests {
@Test
public void configureWhenUsingBothAuthenticationManagerResolverAndOpaqueThenWiringException() {
assertThatCode(() -> this.spring.register(AuthenticationManagerResolverPlusOtherConfig.class).autowire())
.isInstanceOf(BeanCreationException.class).hasMessageContaining("authenticationManagerResolver");
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() -> this.spring.register(AuthenticationManagerResolverPlusOtherConfig.class).autowire())
.withMessageContaining("authenticationManagerResolver");
}
private static Dispatcher requiresAuth(String username, String password, String response) {

View File

@@ -20,7 +20,6 @@ import java.util.HashMap;
import java.util.Map;
import org.assertj.core.api.ThrowableAssert;
import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -68,8 +67,7 @@ import org.springframework.web.socket.server.HandshakeFailureException;
import org.springframework.web.socket.server.HandshakeHandler;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
/**
@@ -103,8 +101,8 @@ public class WebSocketMessageBrokerConfigTests {
public void sendWhenNoIdSpecifiedThenIntegratesWithClientInboundChannel() {
this.spring.configLocations(xml("NoIdConfig")).autowire();
this.clientInboundChannel.send(message("/permitAll"));
assertThatThrownBy(() -> this.clientInboundChannel.send(message("/denyAll")))
.hasCauseInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(Exception.class).isThrownBy(() -> this.clientInboundChannel.send(message("/denyAll")))
.withCauseInstanceOf(AccessDeniedException.class);
}
@Test
@@ -112,141 +110,146 @@ public class WebSocketMessageBrokerConfigTests {
this.spring.configLocations(xml("NoIdConfig")).autowire();
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT);
headers.setNativeHeader(this.token.getHeaderName(), this.token.getToken());
assertThatCode(() -> this.clientInboundChannel.send(message("/permitAll", headers))).doesNotThrowAnyException();
this.clientInboundChannel.send(message("/permitAll", headers));
}
@Test
public void sendWhenAnonymousMessageWithConnectAckMessageTypeThenPermitted() {
this.spring.configLocations(xml("NoIdConfig")).autowire();
Message<?> message = message("/permitAll", SimpMessageType.CONNECT_ACK);
assertThatCode(send(message)).doesNotThrowAnyException();
send(message);
}
@Test
public void sendWhenAnonymousMessageWithDisconnectMessageTypeThenPermitted() {
this.spring.configLocations(xml("NoIdConfig")).autowire();
Message<?> message = message("/permitAll", SimpMessageType.DISCONNECT);
assertThatCode(send(message)).doesNotThrowAnyException();
send(message);
}
@Test
public void sendWhenAnonymousMessageWithDisconnectAckMessageTypeThenPermitted() {
this.spring.configLocations(xml("NoIdConfig")).autowire();
Message<?> message = message("/permitAll", SimpMessageType.DISCONNECT_ACK);
assertThatCode(send(message)).doesNotThrowAnyException();
send(message);
}
@Test
public void sendWhenAnonymousMessageWithHeartbeatMessageTypeThenPermitted() {
this.spring.configLocations(xml("NoIdConfig")).autowire();
Message<?> message = message("/permitAll", SimpMessageType.HEARTBEAT);
assertThatCode(send(message)).doesNotThrowAnyException();
send(message);
}
@Test
public void sendWhenAnonymousMessageWithMessageMessageTypeThenPermitted() {
this.spring.configLocations(xml("NoIdConfig")).autowire();
Message<?> message = message("/permitAll", SimpMessageType.MESSAGE);
assertThatCode(send(message)).doesNotThrowAnyException();
send(message);
}
@Test
public void sendWhenAnonymousMessageWithOtherMessageTypeThenPermitted() {
this.spring.configLocations(xml("NoIdConfig")).autowire();
Message<?> message = message("/permitAll", SimpMessageType.OTHER);
assertThatCode(send(message)).doesNotThrowAnyException();
send(message);
}
@Test
public void sendWhenAnonymousMessageWithSubscribeMessageTypeThenPermitted() {
this.spring.configLocations(xml("NoIdConfig")).autowire();
Message<?> message = message("/permitAll", SimpMessageType.SUBSCRIBE);
assertThatCode(send(message)).doesNotThrowAnyException();
send(message);
}
@Test
public void sendWhenAnonymousMessageWithUnsubscribeMessageTypeThenPermitted() {
this.spring.configLocations(xml("NoIdConfig")).autowire();
Message<?> message = message("/permitAll", SimpMessageType.UNSUBSCRIBE);
assertThatCode(send(message)).doesNotThrowAnyException();
send(message);
}
@Test
public void sendWhenConnectWithoutCsrfTokenThenDenied() {
this.spring.configLocations(xml("SyncConfig")).autowire();
Message<?> message = message("/message", SimpMessageType.CONNECT);
assertThatThrownBy(send(message)).hasCauseInstanceOf(InvalidCsrfTokenException.class);
assertThatExceptionOfType(Exception.class).isThrownBy(send(message))
.withCauseInstanceOf(InvalidCsrfTokenException.class);
}
@Test
public void sendWhenConnectWithSameOriginDisabledThenCsrfTokenNotRequired() {
this.spring.configLocations(xml("SyncSameOriginDisabledConfig")).autowire();
Message<?> message = message("/message", SimpMessageType.CONNECT);
assertThatCode(send(message)).doesNotThrowAnyException();
send(message);
}
@Test
public void sendWhenInterceptWiredForMessageTypeThenDeniesOnTypeMismatch() {
this.spring.configLocations(xml("MessageInterceptTypeConfig")).autowire();
Message<?> message = message("/permitAll", SimpMessageType.MESSAGE);
assertThatCode(send(message)).doesNotThrowAnyException();
send(message);
message = message("/permitAll", SimpMessageType.UNSUBSCRIBE);
assertThatThrownBy(send(message)).hasCauseInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(Exception.class).isThrownBy(send(message))
.withCauseInstanceOf(AccessDeniedException.class);
message = message("/anyOther", SimpMessageType.MESSAGE);
assertThatThrownBy(send(message)).hasCauseInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(Exception.class).isThrownBy(send(message))
.withCauseInstanceOf(AccessDeniedException.class);
}
@Test
public void sendWhenInterceptWiredForSubscribeTypeThenDeniesOnTypeMismatch() {
this.spring.configLocations(xml("SubscribeInterceptTypeConfig")).autowire();
Message<?> message = message("/permitAll", SimpMessageType.SUBSCRIBE);
assertThatCode(send(message)).doesNotThrowAnyException();
send(message);
message = message("/permitAll", SimpMessageType.UNSUBSCRIBE);
assertThatThrownBy(send(message)).hasCauseInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(Exception.class).isThrownBy(send(message))
.withCauseInstanceOf(AccessDeniedException.class);
message = message("/anyOther", SimpMessageType.SUBSCRIBE);
assertThatThrownBy(send(message)).hasCauseInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(Exception.class).isThrownBy(send(message))
.withCauseInstanceOf(AccessDeniedException.class);
}
@Test
public void configureWhenUsingConnectMessageTypeThenAutowireFails() {
ThrowingCallable bad = () -> this.spring.configLocations(xml("ConnectInterceptTypeConfig")).autowire();
assertThatThrownBy(bad).isInstanceOf(BeanDefinitionParsingException.class);
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> this.spring.configLocations(xml("ConnectInterceptTypeConfig")).autowire());
}
@Test
public void configureWhenUsingConnectAckMessageTypeThenAutowireFails() {
ThrowingCallable bad = () -> this.spring.configLocations(xml("ConnectAckInterceptTypeConfig")).autowire();
assertThatThrownBy(bad).isInstanceOf(BeanDefinitionParsingException.class);
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> this.spring.configLocations(xml("ConnectAckInterceptTypeConfig")).autowire());
}
@Test
public void configureWhenUsingDisconnectMessageTypeThenAutowireFails() {
ThrowingCallable bad = () -> this.spring.configLocations(xml("DisconnectInterceptTypeConfig")).autowire();
assertThatThrownBy(bad).isInstanceOf(BeanDefinitionParsingException.class);
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> this.spring.configLocations(xml("DisconnectInterceptTypeConfig")).autowire());
}
@Test
public void configureWhenUsingDisconnectAckMessageTypeThenAutowireFails() {
ThrowingCallable bad = () -> this.spring.configLocations(xml("DisconnectAckInterceptTypeConfig")).autowire();
assertThatThrownBy(bad).isInstanceOf(BeanDefinitionParsingException.class);
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> this.spring.configLocations(xml("DisconnectAckInterceptTypeConfig")).autowire());
}
@Test
public void configureWhenUsingHeartbeatMessageTypeThenAutowireFails() {
ThrowingCallable bad = () -> this.spring.configLocations(xml("HeartbeatInterceptTypeConfig")).autowire();
assertThatThrownBy(bad).isInstanceOf(BeanDefinitionParsingException.class);
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> this.spring.configLocations(xml("HeartbeatInterceptTypeConfig")).autowire());
}
@Test
public void configureWhenUsingOtherMessageTypeThenAutowireFails() {
ThrowingCallable bad = () -> this.spring.configLocations(xml("OtherInterceptTypeConfig")).autowire();
assertThatThrownBy(bad).isInstanceOf(BeanDefinitionParsingException.class);
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> this.spring.configLocations(xml("OtherInterceptTypeConfig")).autowire());
}
@Test
public void configureWhenUsingUnsubscribeMessageTypeThenAutowireFails() {
ThrowingCallable bad = () -> this.spring.configLocations(xml("UnsubscribeInterceptTypeConfig")).autowire();
assertThatThrownBy(bad).isInstanceOf(BeanDefinitionParsingException.class);
assertThatExceptionOfType(BeanDefinitionParsingException.class)
.isThrownBy(() -> this.spring.configLocations(xml("UnsubscribeInterceptTypeConfig")).autowire());
}
@Test
@@ -301,16 +304,17 @@ public class WebSocketMessageBrokerConfigTests {
public void sendWhenUsingCustomPathMatcherThenSecurityAppliesIt() {
this.spring.configLocations(xml("CustomPathMatcherConfig")).autowire();
Message<?> message = message("/denyAll.a");
assertThatThrownBy(send(message)).hasCauseInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(Exception.class).isThrownBy(send(message))
.withCauseInstanceOf(AccessDeniedException.class);
message = message("/denyAll.a.b");
assertThatCode(send(message)).doesNotThrowAnyException();
send(message);
}
@Test
public void sendWhenIdSpecifiedThenSecurityDoesNotIntegrateWithClientInboundChannel() {
this.spring.configLocations(xml("IdConfig")).autowire();
Message<?> message = message("/denyAll");
assertThatCode(send(message)).doesNotThrowAnyException();
send(message);
}
@Test
@@ -318,14 +322,16 @@ public class WebSocketMessageBrokerConfigTests {
public void sendWhenIdSpecifiedAndExplicitlyIntegratedWhenBrokerUsesClientInboundChannel() {
this.spring.configLocations(xml("IdIntegratedConfig")).autowire();
Message<?> message = message("/denyAll");
assertThatThrownBy(send(message)).hasCauseInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(Exception.class).isThrownBy(send(message))
.withCauseInstanceOf(AccessDeniedException.class);
}
@Test
public void sendWhenNoIdSpecifiedThenSecurityDoesntOverrideCustomInterceptors() {
this.spring.configLocations(xml("CustomInterceptorConfig")).autowire();
Message<?> message = message("/throwAll");
assertThatThrownBy(send(message)).hasCauseInstanceOf(UnsupportedOperationException.class);
assertThatExceptionOfType(Exception.class).isThrownBy(send(message))
.withCauseInstanceOf(UnsupportedOperationException.class);
}
@Test
@@ -333,7 +339,8 @@ public class WebSocketMessageBrokerConfigTests {
public void sendWhenCustomExpressionHandlerThenAuthorizesAccordingly() {
this.spring.configLocations(xml("CustomExpressionHandlerConfig")).autowire();
Message<?> message = message("/denyNile");
assertThatThrownBy(send(message)).hasCauseInstanceOf(AccessDeniedException.class);
assertThatExceptionOfType(Exception.class).isThrownBy(send(message))
.withCauseInstanceOf(AccessDeniedException.class);
}
private String xml(String configName) {