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

@ -20,6 +20,7 @@ import java.util.ArrayList;
import java.util.List;
import io.rsocket.RSocketFactory;
import io.rsocket.exceptions.RejectedSetupException;
import io.rsocket.frame.decoder.PayloadDecoder;
import io.rsocket.transport.netty.server.CloseableChannel;
import io.rsocket.transport.netty.server.TcpServerTransport;
@ -46,7 +47,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.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Rob Winch
@ -87,10 +88,11 @@ public class HelloRSocketITests {
this.requester = RSocketRequester.builder().rsocketStrategies(this.handler.getRSocketStrategies())
.connectTcp("localhost", this.server.address().getPort()).block();
String data = "rob";
assertThatCode(() -> this.requester.route("secure.retrieve-mono").data(data).retrieveMono(String.class).block())
.isNotNull();
assertThatExceptionOfType(Exception.class).isThrownBy(
() -> this.requester.route("secure.retrieve-mono").data(data).retrieveMono(String.class).block())
.matches((ex) -> ex instanceof RejectedSetupException
|| ex.getClass().toString().contains("ReactiveException"));
// FIXME: https://github.com/rsocket/rsocket-java/issues/686
// .isInstanceOf(RejectedSetupException.class);
assertThat(this.controller.payloads).isEmpty();
}

View File

@ -21,6 +21,7 @@ import java.util.List;
import io.rsocket.RSocketFactory;
import io.rsocket.exceptions.ApplicationErrorException;
import io.rsocket.exceptions.RejectedSetupException;
import io.rsocket.frame.decoder.PayloadDecoder;
import io.rsocket.transport.netty.server.CloseableChannel;
import io.rsocket.transport.netty.server.TcpServerTransport;
@ -49,7 +50,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.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Rob Winch
@ -103,8 +104,8 @@ public class RSocketMessageHandlerConnectionITests {
UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("user", "password");
this.requester = requester().setupMetadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE)
.connectTcp(this.server.address().getHostName(), this.server.address().getPort()).block();
assertThatCode(() -> this.requester.route("secure.admin.retrieve-mono").data("data").retrieveMono(String.class)
.block()).isInstanceOf(ApplicationErrorException.class);
assertThatExceptionOfType(ApplicationErrorException.class).isThrownBy(() -> this.requester
.route("secure.admin.retrieve-mono").data("data").retrieveMono(String.class).block());
}
@Test
@ -137,10 +138,11 @@ public class RSocketMessageHandlerConnectionITests {
public void connectWhenNotAuthenticated() {
this.requester = requester().connectTcp(this.server.address().getHostName(), this.server.address().getPort())
.block();
assertThatCode(() -> this.requester.route("retrieve-mono").data("data").retrieveMono(String.class).block())
.isNotNull();
assertThatExceptionOfType(Exception.class)
.isThrownBy(() -> this.requester.route("retrieve-mono").data("data").retrieveMono(String.class).block())
.matches((ex) -> ex instanceof RejectedSetupException
|| ex.getClass().toString().contains("ReactiveException"));
// FIXME: https://github.com/rsocket/rsocket-java/issues/686
// .isInstanceOf(RejectedSetupException.class);
}
@Test
@ -148,10 +150,11 @@ public class RSocketMessageHandlerConnectionITests {
UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("evil", "password");
this.requester = requester().setupMetadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE)
.connectTcp(this.server.address().getHostName(), this.server.address().getPort()).block();
assertThatCode(() -> this.requester.route("retrieve-mono").data("data").retrieveMono(String.class).block())
.isNotNull();
assertThatExceptionOfType(Exception.class)
.isThrownBy(() -> this.requester.route("retrieve-mono").data("data").retrieveMono(String.class).block())
.matches((ex) -> ex instanceof RejectedSetupException
|| ex.getClass().toString().contains("ReactiveException"));
// FIXME: https://github.com/rsocket/rsocket-java/issues/686
// .isInstanceOf(RejectedSetupException.class);
}
@Test
@ -159,8 +162,8 @@ public class RSocketMessageHandlerConnectionITests {
UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("user", "password");
this.requester = requester().setupMetadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE)
.connectTcp(this.server.address().getHostName(), this.server.address().getPort()).block();
assertThatCode(() -> this.requester.route("prohibit").data("data").retrieveMono(String.class).block())
.isInstanceOf(ApplicationErrorException.class);
assertThatExceptionOfType(ApplicationErrorException.class)
.isThrownBy(() -> this.requester.route("prohibit").data("data").retrieveMono(String.class).block());
}
@Test

View File

@ -52,7 +52,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.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Rob Winch
@ -96,8 +96,9 @@ public class RSocketMessageHandlerITests {
@Test
public void retrieveMonoWhenSecureThenDenied() throws Exception {
String data = "rob";
assertThatCode(() -> this.requester.route("secure.retrieve-mono").data(data).retrieveMono(String.class).block())
.isInstanceOf(ApplicationErrorException.class).hasMessageContaining("Access Denied");
assertThatExceptionOfType(ApplicationErrorException.class).isThrownBy(
() -> this.requester.route("secure.retrieve-mono").data(data).retrieveMono(String.class).block())
.withMessageContaining("Access Denied");
assertThat(this.controller.payloads).isEmpty();
}
@ -105,10 +106,11 @@ public class RSocketMessageHandlerITests {
public void retrieveMonoWhenAuthenticationFailedThenException() throws Exception {
String data = "rob";
UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("invalid", "password");
assertThatCode(() -> this.requester.route("secure.retrieve-mono")
.metadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE).data(data)
.retrieveMono(String.class).block()).isInstanceOf(ApplicationErrorException.class)
.hasMessageContaining("Invalid Credentials");
assertThatExceptionOfType(ApplicationErrorException.class)
.isThrownBy(() -> this.requester.route("secure.retrieve-mono")
.metadata(credentials, UsernamePasswordMetadata.BASIC_AUTHENTICATION_MIME_TYPE).data(data)
.retrieveMono(String.class).block())
.withMessageContaining("Invalid Credentials");
assertThat(this.controller.payloads).isEmpty();
}
@ -134,9 +136,10 @@ public class RSocketMessageHandlerITests {
@Test
public void retrieveFluxWhenDataFluxAndSecureThenDenied() throws Exception {
Flux<String> data = Flux.just("a", "b", "c");
assertThatCode(() -> this.requester.route("secure.retrieve-flux").data(data, String.class)
.retrieveFlux(String.class).collectList().block()).isInstanceOf(ApplicationErrorException.class)
.hasMessageContaining("Access Denied");
assertThatExceptionOfType(ApplicationErrorException.class)
.isThrownBy(() -> this.requester.route("secure.retrieve-flux").data(data, String.class)
.retrieveFlux(String.class).collectList().block())
.withMessageContaining("Access Denied");
assertThat(this.controller.payloads).isEmpty();
}
@ -152,9 +155,9 @@ public class RSocketMessageHandlerITests {
@Test
public void retrieveFluxWhenDataStringAndSecureThenDenied() throws Exception {
String data = "a";
assertThatCode(
assertThatExceptionOfType(ApplicationErrorException.class).isThrownBy(
() -> this.requester.route("secure.hello").data(data).retrieveFlux(String.class).collectList().block())
.isInstanceOf(ApplicationErrorException.class).hasMessageContaining("Access Denied");
.withMessageContaining("Access Denied");
assertThat(this.controller.payloads).isEmpty();
}

View File

@ -52,7 +52,7 @@ import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Rob Winch
@ -93,8 +93,8 @@ public class SimpleAuthenticationITests {
this.requester = RSocketRequester.builder().rsocketStrategies(this.handler.getRSocketStrategies())
.connectTcp("localhost", this.server.address().getPort()).block();
String data = "rob";
assertThatCode(() -> this.requester.route("secure.retrieve-mono").data(data).retrieveMono(String.class).block())
.isInstanceOf(ApplicationErrorException.class);
assertThatExceptionOfType(ApplicationErrorException.class).isThrownBy(
() -> this.requester.route("secure.retrieve-mono").data(data).retrieveMono(String.class).block());
assertThat(this.controller.payloads).isEmpty();
}

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) {

View File

@ -33,9 +33,7 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsChecker;
import org.springframework.security.crypto.password.PasswordEncoder;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
@ -85,7 +83,7 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
@Test
public void setSchedulerWhenNullThenIllegalArgumentException() {
assertThatCode(() -> this.manager.setScheduler(null)).isInstanceOf(IllegalArgumentException.class);
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> this.manager.setScheduler(null));
}
@Test
@ -125,7 +123,8 @@ public class UserDetailsRepositoryReactiveAuthenticationManagerTests {
this.manager.setUserDetailsPasswordService(this.userDetailsPasswordService);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(this.user,
this.user.getPassword());
assertThatThrownBy(() -> this.manager.authenticate(token).block()).isInstanceOf(BadCredentialsException.class);
assertThatExceptionOfType(BadCredentialsException.class)
.isThrownBy(() -> this.manager.authenticate(token).block());
verifyZeroInteractions(this.userDetailsPasswordService);
}

View File

@ -49,7 +49,7 @@ import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
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.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
@ -362,7 +362,7 @@ public class DaoAuthenticationProviderTests {
UserDetails user = PasswordEncodedUser.user();
given(encoder.matches(any(), any())).willReturn(false);
given(userDetailsService.loadUserByUsername(any())).willReturn(user);
assertThatThrownBy(() -> provider.authenticate(token)).isInstanceOf(BadCredentialsException.class);
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> provider.authenticate(token));
verifyZeroInteractions(passwordManager);
}

View File

@ -18,7 +18,7 @@ package org.springframework.security.authentication.jaas;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author Clement Ng
@ -26,20 +26,16 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
*/
public class JaasGrantedAuthorityTests {
/**
*/
@Test
public void authorityWithNullRoleFailsAssertion() {
assertThatThrownBy(() -> new JaasGrantedAuthority(null, null)).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("role cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> new JaasGrantedAuthority(null, null))
.withMessageContaining("role cannot be null");
}
/**
*/
@Test
public void authorityWithNullPrincipleFailsAssertion() {
assertThatThrownBy(() -> new JaasGrantedAuthority("role", null)).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("principal cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> new JaasGrantedAuthority("role", null))
.withMessageContaining("principal cannot be null");
}
}

View File

@ -28,7 +28,7 @@ import org.junit.Test;
import org.springframework.core.convert.converter.Converter;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link RsaKeyConverters}
@ -99,8 +99,7 @@ public class RsaKeyConvertersTests {
@Test
public void pkcs8WhenConvertingPkcs1PrivateKeyThenIllegalArgumentException() {
assertThatCode(() -> this.pkcs8.convert(toInputStream(PKCS1_PRIVATE_KEY)))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.pkcs8.convert(toInputStream(PKCS1_PRIVATE_KEY)));
}
@Test
@ -111,8 +110,7 @@ public class RsaKeyConvertersTests {
@Test
public void x509WhenConvertingDerEncodedX509PublicKeyThenIllegalArgumentException() {
assertThatCode(() -> this.x509.convert(toInputStream(MALFORMED_X509_KEY)))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.x509.convert(toInputStream(MALFORMED_X509_KEY)));
}
private static InputStream toInputStream(String string) {

View File

@ -32,7 +32,7 @@ import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Rob Winch
@ -51,7 +51,8 @@ public class SecurityJackson2ModulesTests {
@Test
public void readValueWhenNotAllowedOrMappedThenThrowsException() {
String content = "{\"@class\":\"org.springframework.security.jackson2.SecurityJackson2ModulesTests$NotAllowlisted\",\"property\":\"bar\"}";
assertThatThrownBy(() -> this.mapper.readValue(content, Object.class)).hasStackTraceContaining("allowlist");
assertThatExceptionOfType(Exception.class).isThrownBy(() -> this.mapper.readValue(content, Object.class))
.withStackTraceContaining("allowlist");
}
@Test

View File

@ -27,7 +27,7 @@ import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
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.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
@ -120,41 +120,43 @@ public class DelegatingPasswordEncoderTests {
@Test
public void matchesWhenUnMappedThenIllegalArgumentException() {
assertThatThrownBy(() -> this.passwordEncoder.matches(this.rawPassword, "{unmapped}" + this.rawPassword))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("There is no PasswordEncoder mapped for the id \"unmapped\"");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.passwordEncoder.matches(this.rawPassword, "{unmapped}" + this.rawPassword))
.withMessage("There is no PasswordEncoder mapped for the id \"unmapped\"");
verifyZeroInteractions(this.bcrypt, this.noop);
}
@Test
public void matchesWhenNoClosingPrefixStringThenIllegalArgumentExcetion() {
assertThatThrownBy(() -> this.passwordEncoder.matches(this.rawPassword, "{bcrypt" + this.rawPassword))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("There is no PasswordEncoder mapped for the id \"null\"");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.passwordEncoder.matches(this.rawPassword, "{bcrypt" + this.rawPassword))
.withMessage("There is no PasswordEncoder mapped for the id \"null\"");
verifyZeroInteractions(this.bcrypt, this.noop);
}
@Test
public void matchesWhenNoStartingPrefixStringThenFalse() {
assertThatThrownBy(() -> this.passwordEncoder.matches(this.rawPassword, "bcrypt}" + this.rawPassword))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("There is no PasswordEncoder mapped for the id \"null\"");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.passwordEncoder.matches(this.rawPassword, "bcrypt}" + this.rawPassword))
.withMessage("There is no PasswordEncoder mapped for the id \"null\"");
verifyZeroInteractions(this.bcrypt, this.noop);
}
@Test
public void matchesWhenNoIdStringThenFalse() {
assertThatThrownBy(() -> this.passwordEncoder.matches(this.rawPassword, "{}" + this.rawPassword))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("There is no PasswordEncoder mapped for the id \"\"");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.passwordEncoder.matches(this.rawPassword, "{}" + this.rawPassword))
.withMessage("There is no PasswordEncoder mapped for the id \"\"");
verifyZeroInteractions(this.bcrypt, this.noop);
}
@Test
public void matchesWhenPrefixInMiddleThenFalse() {
assertThatThrownBy(() -> this.passwordEncoder.matches(this.rawPassword, "invalid" + this.bcryptEncodedPassword))
assertThatIllegalArgumentException()
.isThrownBy(
() -> this.passwordEncoder.matches(this.rawPassword, "invalid" + this.bcryptEncodedPassword))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("There is no PasswordEncoder mapped for the id \"null\"");
.withMessage("There is no PasswordEncoder mapped for the id \"null\"");
verifyZeroInteractions(this.bcrypt, this.noop);
}
@ -162,9 +164,9 @@ public class DelegatingPasswordEncoderTests {
public void matchesWhenIdIsNullThenFalse() {
this.delegates = new Hashtable<>(this.delegates);
DelegatingPasswordEncoder passwordEncoder = new DelegatingPasswordEncoder(this.bcryptId, this.delegates);
assertThatThrownBy(() -> passwordEncoder.matches(this.rawPassword, this.rawPassword))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("There is no PasswordEncoder mapped for the id \"null\"");
assertThatIllegalArgumentException()
.isThrownBy(() -> passwordEncoder.matches(this.rawPassword, this.rawPassword))
.withMessage("There is no PasswordEncoder mapped for the id \"null\"");
verifyZeroInteractions(this.bcrypt, this.noop);
}

View File

@ -14,4 +14,12 @@
<module name="io.spring.javaformat.checkstyle.SpringChecks">
<property name="excludes" value="io.spring.javaformat.checkstyle.check.SpringHeaderCheck" />
</module>
<module name="com.puppycrawl.tools.checkstyle.TreeWalker">
<module name="com.puppycrawl.tools.checkstyle.checks.regexp.RegexpSinglelineJavaCheck">
<property name="maximum" value="0"/>
<property name="format" value="org\.assertj\.core\.api\.Assertions\.(catchThrowable|catchThrowableOfType|assertThatThrownBy|assertThatCode)" />
<property name="message" value="Please use assertThatExceptionOfType." />
<property name="ignoreComments" value="true" />
</module>
</module>
</module>

View File

@ -32,6 +32,7 @@ import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.fail;
/**
@ -138,15 +139,8 @@ public class ApacheDSContainerTests {
server.setLdapOverSslEnabled(true);
server.setKeyStoreFile(temporaryKeyStoreFile);
server.setCertificatePassord("incorrect-password");
try {
server.afterPropertiesSet();
fail("Expected a RuntimeException to be thrown.");
}
catch (RuntimeException ex) {
assertThat(ex).hasMessage("Server startup failed");
assertThat(ex).hasRootCauseInstanceOf(UnrecoverableKeyException.class);
}
assertThatExceptionOfType(RuntimeException.class).isThrownBy(server::afterPropertiesSet)
.withMessage("Server startup failed").withRootCauseInstanceOf(UnrecoverableKeyException.class);
}
/**

View File

@ -36,7 +36,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.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link LdapUserDetailsManager#changePassword}, specifically relating to the
@ -63,8 +63,8 @@ public class LdapUserDetailsManagerModifyPasswordTests {
@Test
@WithMockUser(username = "bob", password = "bobspassword", authorities = "ROLE_USER")
public void changePasswordWhenOldPasswordIsIncorrectThenThrowsException() {
assertThatCode(() -> this.userDetailsManager.changePassword("wrongoldpassword", "bobsnewpassword"))
.isInstanceOf(BadCredentialsException.class);
assertThatExceptionOfType(BadCredentialsException.class)
.isThrownBy(() -> this.userDetailsManager.changePassword("wrongoldpassword", "bobsnewpassword"));
}
@Test

View File

@ -26,7 +26,8 @@ import org.springframework.security.oauth2.client.registration.TestClientRegistr
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
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.assertThatIllegalArgumentException;
/**
* Tests for {@link AuthorizationCodeOAuth2AuthorizedClientProvider}.
@ -54,8 +55,7 @@ public class AuthorizationCodeOAuth2AuthorizedClientProviderTests {
@Test
public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.authorize(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.authorize(null));
}
@Test
@ -77,8 +77,8 @@ public class AuthorizationCodeOAuth2AuthorizedClientProviderTests {
public void authorizeWhenAuthorizationCodeAndNotAuthorizedThenAuthorize() {
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistration).principal(this.principal).build();
assertThatThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext))
.isInstanceOf(ClientAuthorizationRequiredException.class);
assertThatExceptionOfType(ClientAuthorizationRequiredException.class)
.isThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext));
}
}

View File

@ -26,7 +26,8 @@ import org.springframework.security.oauth2.client.registration.TestClientRegistr
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
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.assertThatIllegalArgumentException;
/**
* Tests for {@link AuthorizationCodeReactiveOAuth2AuthorizedClientProvider}.
@ -54,8 +55,7 @@ public class AuthorizationCodeReactiveOAuth2AuthorizedClientProviderTests {
@Test
public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.authorize(null).block())
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.authorize(null).block());
}
@Test
@ -77,8 +77,8 @@ public class AuthorizationCodeReactiveOAuth2AuthorizedClientProviderTests {
public void authorizeWhenAuthorizationCodeAndNotAuthorizedThenAuthorize() {
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistration).principal(this.principal).build();
assertThatThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext).block())
.isInstanceOf(ClientAuthorizationRequiredException.class);
assertThatExceptionOfType(ClientAuthorizationRequiredException.class)
.isThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext).block());
}
}

View File

@ -35,8 +35,8 @@ import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
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.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
@ -108,57 +108,58 @@ public class AuthorizedClientServiceOAuth2AuthorizedClientManagerTests {
@Test
public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(
assertThatIllegalArgumentException().isThrownBy(
() -> new AuthorizedClientServiceOAuth2AuthorizedClientManager(null, this.authorizedClientService))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("clientRegistrationRepository cannot be null");
.withMessage("clientRegistrationRepository cannot be null");
}
@Test
public void constructorWhenOAuth2AuthorizedClientServiceIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(
assertThatIllegalArgumentException().isThrownBy(
() -> new AuthorizedClientServiceOAuth2AuthorizedClientManager(this.clientRegistrationRepository, null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("authorizedClientService cannot be null");
.withMessage("authorizedClientService cannot be null");
}
@Test
public void setAuthorizedClientProviderWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientManager.setAuthorizedClientProvider(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("authorizedClientProvider cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.setAuthorizedClientProvider(null))
.withMessage("authorizedClientProvider cannot be null");
}
@Test
public void setContextAttributesMapperWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientManager.setContextAttributesMapper(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("contextAttributesMapper cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.setContextAttributesMapper(null))
.withMessage("contextAttributesMapper cannot be null");
}
@Test
public void setAuthorizationSuccessHandlerWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientManager.setAuthorizationSuccessHandler(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("authorizationSuccessHandler cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.setAuthorizationSuccessHandler(null))
.withMessage("authorizationSuccessHandler cannot be null");
}
@Test
public void setAuthorizationFailureHandlerWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientManager.setAuthorizationFailureHandler(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("authorizationFailureHandler cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.setAuthorizationFailureHandler(null))
.withMessage("authorizationFailureHandler cannot be null");
}
@Test
public void authorizeWhenRequestIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientManager.authorize(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("authorizeRequest cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientManager.authorize(null))
.withMessage("authorizeRequest cannot be null");
}
@Test
public void authorizeWhenClientRegistrationNotFoundThenThrowIllegalArgumentException() {
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId("invalid-registration-id").principal(this.principal).build();
assertThatThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Could not find ClientRegistration with id 'invalid-registration-id'");
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest))
.withMessage("Could not find ClientRegistration with id 'invalid-registration-id'");
}
@SuppressWarnings("unchecked")
@ -308,7 +309,8 @@ public class AuthorizedClientServiceOAuth2AuthorizedClientManagerTests {
.willThrow(authorizationException);
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
.principal(this.principal).build();
assertThatCode(() -> this.authorizedClientManager.authorize(reauthorizeRequest))
assertThatExceptionOfType(ClientAuthorizationException.class)
.isThrownBy(() -> this.authorizedClientManager.authorize(reauthorizeRequest))
.isEqualTo(authorizationException);
verify(this.authorizationFailureHandler).onAuthorizationFailure(eq(authorizationException), eq(this.principal),
any());
@ -324,7 +326,8 @@ public class AuthorizedClientServiceOAuth2AuthorizedClientManagerTests {
.willThrow(authorizationException);
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
.principal(this.principal).build();
assertThatCode(() -> this.authorizedClientManager.authorize(reauthorizeRequest))
assertThatExceptionOfType(ClientAuthorizationException.class)
.isThrownBy(() -> this.authorizedClientManager.authorize(reauthorizeRequest))
.isEqualTo(authorizationException);
verify(this.authorizationFailureHandler).onAuthorizationFailure(eq(authorizationException), eq(this.principal),
any());

View File

@ -39,8 +39,8 @@ import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
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.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
@ -105,46 +105,52 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
@Test
public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(null,
this.authorizedClientService)).isInstanceOf(IllegalArgumentException.class)
.hasMessage("clientRegistrationRepository cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(null,
this.authorizedClientService))
.withMessage("clientRegistrationRepository cannot be null");
}
@Test
public void constructorWhenOAuth2AuthorizedClientServiceIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(
this.clientRegistrationRepository, null)).isInstanceOf(IllegalArgumentException.class)
.hasMessage("authorizedClientService cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(
this.clientRegistrationRepository, null))
.withMessage("authorizedClientService cannot be null");
}
@Test
public void setAuthorizedClientProviderWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientManager.setAuthorizedClientProvider(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("authorizedClientProvider cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.setAuthorizedClientProvider(null))
.withMessage("authorizedClientProvider cannot be null");
}
@Test
public void setContextAttributesMapperWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientManager.setContextAttributesMapper(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("contextAttributesMapper cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.setContextAttributesMapper(null))
.withMessage("contextAttributesMapper cannot be null");
}
@Test
public void setAuthorizationSuccessHandlerWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientManager.setAuthorizationSuccessHandler(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("authorizationSuccessHandler cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.setAuthorizationSuccessHandler(null))
.withMessage("authorizationSuccessHandler cannot be null");
}
@Test
public void setAuthorizationFailureHandlerWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientManager.setAuthorizationFailureHandler(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("authorizationFailureHandler cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.setAuthorizationFailureHandler(null))
.withMessage("authorizationFailureHandler cannot be null");
}
@Test
public void authorizeWhenRequestIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientManager.authorize(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("authorizeRequest cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientManager.authorize(null))
.withMessage("authorizeRequest cannot be null");
}
@Test
@ -243,7 +249,9 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
this.clientRegistration.getRegistrationId());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.error(exception));
assertThatCode(() -> this.authorizedClientManager.authorize(authorizeRequest).block()).isEqualTo(exception);
assertThatExceptionOfType(ClientAuthorizationException.class)
.isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block())
.isEqualTo(exception);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
@ -269,7 +277,9 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
this.clientRegistration.getRegistrationId());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.error(exception));
assertThatCode(() -> this.authorizedClientManager.authorize(authorizeRequest).block()).isEqualTo(exception);
assertThatExceptionOfType(ClientAuthorizationException.class)
.isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block())
.isEqualTo(exception);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
@ -295,7 +305,9 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
this.clientRegistration.getRegistrationId());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.error(exception));
assertThatCode(() -> this.authorizedClientManager.authorize(authorizeRequest).block()).isEqualTo(exception);
assertThatExceptionOfType(ClientAuthorizationException.class)
.isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block())
.isEqualTo(exception);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
@ -318,7 +330,9 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null));
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.error(exception));
assertThatCode(() -> this.authorizedClientManager.authorize(authorizeRequest).block()).isEqualTo(exception);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block())
.isEqualTo(exception);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
@ -344,7 +358,9 @@ public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
PublisherProbe<Void> authorizationFailureHandlerProbe = PublisherProbe.empty();
this.authorizedClientManager.setAuthorizationFailureHandler(
(client, principal, attributes) -> authorizationFailureHandlerProbe.mono());
assertThatCode(() -> this.authorizedClientManager.authorize(authorizeRequest).block()).isEqualTo(exception);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block())
.isEqualTo(exception);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();

View File

@ -34,7 +34,7 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenRespon
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
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.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -65,32 +65,34 @@ public class ClientCredentialsOAuth2AuthorizedClientProviderTests {
@Test
public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("accessTokenResponseClient cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
.isInstanceOf(IllegalArgumentException.class).withMessage("accessTokenResponseClient cannot be null");
}
@Test
public void setClockSkewWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.setClockSkew(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clockSkew cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.setClockSkew(null))
.withMessage("clockSkew cannot be null");
}
@Test
public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1)))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clockSkew must be >= 0");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1)))
.withMessage("clockSkew must be >= 0");
}
@Test
public void setClockWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.setClock(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clock cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.setClock(null))
.withMessage("clock cannot be null");
}
@Test
public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.authorize(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("context cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.authorize(null))
.withMessage("context cannot be null");
}
@Test

View File

@ -35,7 +35,7 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenRespon
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
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.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -66,32 +66,34 @@ public class ClientCredentialsReactiveOAuth2AuthorizedClientProviderTests {
@Test
public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("accessTokenResponseClient cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
.withMessage("accessTokenResponseClient cannot be null");
}
@Test
public void setClockSkewWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.setClockSkew(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clockSkew cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.setClockSkew(null))
.withMessage("clockSkew cannot be null");
}
@Test
public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1)))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clockSkew must be >= 0");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1)))
.withMessage("clockSkew must be >= 0");
}
@Test
public void setClockWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.setClock(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clock cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.setClock(null))
.withMessage("clock cannot be null");
}
@Test
public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.authorize(null).block())
.isInstanceOf(IllegalArgumentException.class).hasMessage("context cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.authorize(null).block())
.withMessage("context cannot be null");
}
@Test

View File

@ -27,7 +27,7 @@ import org.springframework.security.oauth2.client.registration.TestClientRegistr
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
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.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -41,18 +41,18 @@ public class DelegatingOAuth2AuthorizedClientProviderTests {
@Test
public void constructorWhenProvidersIsEmptyThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new DelegatingOAuth2AuthorizedClientProvider(new OAuth2AuthorizedClientProvider[0]))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> new DelegatingOAuth2AuthorizedClientProvider(Collections.emptyList()))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingOAuth2AuthorizedClientProvider(new OAuth2AuthorizedClientProvider[0]));
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingOAuth2AuthorizedClientProvider(Collections.emptyList()));
}
@Test
public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
DelegatingOAuth2AuthorizedClientProvider delegate = new DelegatingOAuth2AuthorizedClientProvider(
mock(OAuth2AuthorizedClientProvider.class));
assertThatThrownBy(() -> delegate.authorize(null)).isInstanceOf(IllegalArgumentException.class)
.hasMessage("context cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> delegate.authorize(null))
.withMessage("context cannot be null");
}
@Test

View File

@ -28,7 +28,7 @@ import org.springframework.security.oauth2.client.registration.TestClientRegistr
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
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.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -42,18 +42,18 @@ public class DelegatingReactiveOAuth2AuthorizedClientProviderTests {
@Test
public void constructorWhenProvidersIsEmptyThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new DelegatingReactiveOAuth2AuthorizedClientProvider(
new ReactiveOAuth2AuthorizedClientProvider[0])).isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> new DelegatingReactiveOAuth2AuthorizedClientProvider(Collections.emptyList()))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingReactiveOAuth2AuthorizedClientProvider(
new ReactiveOAuth2AuthorizedClientProvider[0]));
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingReactiveOAuth2AuthorizedClientProvider(Collections.emptyList()));
}
@Test
public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
DelegatingReactiveOAuth2AuthorizedClientProvider delegate = new DelegatingReactiveOAuth2AuthorizedClientProvider(
mock(ReactiveOAuth2AuthorizedClientProvider.class));
assertThatThrownBy(() -> delegate.authorize(null).block()).isInstanceOf(IllegalArgumentException.class)
.hasMessage("context cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> delegate.authorize(null).block())
.withMessage("context cannot be null");
}
@Test

View File

@ -29,8 +29,8 @@ import org.springframework.security.oauth2.client.registration.TestClientRegistr
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatObject;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -67,8 +67,9 @@ public class InMemoryOAuth2AuthorizedClientServiceTests {
@Test
public void constructorWhenAuthorizedClientsIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new InMemoryOAuth2AuthorizedClientService(this.clientRegistrationRepository, null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("authorizedClients cannot be empty");
assertThatIllegalArgumentException()
.isThrownBy(() -> new InMemoryOAuth2AuthorizedClientService(this.clientRegistrationRepository, null))
.withMessage("authorizedClients cannot be empty");
}
@Test

View File

@ -35,7 +35,7 @@ import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
/**
@ -76,40 +76,36 @@ public class InMemoryReactiveOAuth2AuthorizedClientServiceTests {
@Test
public void constructorNullClientRegistrationRepositoryThenThrowsIllegalArgumentException() {
this.clientRegistrationRepository = null;
assertThatThrownBy(() -> new InMemoryReactiveOAuth2AuthorizedClientService(this.clientRegistrationRepository))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> new InMemoryReactiveOAuth2AuthorizedClientService(this.clientRegistrationRepository));
}
@Test
public void loadAuthorizedClientWhenClientRegistrationIdNullThenIllegalArgumentException() {
this.clientRegistrationId = null;
assertThatThrownBy(
() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(
() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName));
}
@Test
public void loadAuthorizedClientWhenClientRegistrationIdEmptyThenIllegalArgumentException() {
this.clientRegistrationId = "";
assertThatThrownBy(
() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(
() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName));
}
@Test
public void loadAuthorizedClientWhenPrincipalNameNullThenIllegalArgumentException() {
this.principalName = null;
assertThatThrownBy(
() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(
() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName));
}
@Test
public void loadAuthorizedClientWhenPrincipalNameEmptyThenIllegalArgumentException() {
this.principalName = "";
assertThatThrownBy(
() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(
() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName));
}
@Test
@ -145,8 +141,8 @@ public class InMemoryReactiveOAuth2AuthorizedClientServiceTests {
@Test
public void saveAuthorizedClientWhenAuthorizedClientNullThenIllegalArgumentException() {
OAuth2AuthorizedClient authorizedClient = null;
assertThatThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(authorizedClient, this.principal))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(authorizedClient, this.principal));
}
@Test
@ -154,38 +150,36 @@ public class InMemoryReactiveOAuth2AuthorizedClientServiceTests {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principalName, this.accessToken);
this.principal = null;
assertThatThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(authorizedClient, this.principal))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(authorizedClient, this.principal));
}
@Test
public void removeAuthorizedClientWhenClientRegistrationIdNullThenIllegalArgumentException() {
this.clientRegistrationId = null;
assertThatThrownBy(
() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(
() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName));
}
@Test
public void removeAuthorizedClientWhenClientRegistrationIdEmptyThenIllegalArgumentException() {
this.clientRegistrationId = "";
assertThatThrownBy(
() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(
() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName));
}
@Test
public void removeAuthorizedClientWhenPrincipalNameNullThenIllegalArgumentException() {
this.principalName = null;
assertThatThrownBy(() -> this.authorizedClientService.removeAuthorizedClient(this.clientRegistrationId,
this.principalName)).isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientService
.removeAuthorizedClient(this.clientRegistrationId, this.principalName));
}
@Test
public void removeAuthorizedClientWhenPrincipalNameEmptyThenIllegalArgumentException() {
this.principalName = "";
assertThatThrownBy(() -> this.authorizedClientService.removeAuthorizedClient(this.clientRegistrationId,
this.principalName)).isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientService
.removeAuthorizedClient(this.clientRegistrationId, this.principalName));
}
@Test

View File

@ -54,7 +54,8 @@ import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
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.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.within;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
@ -103,40 +104,45 @@ public class JdbcOAuth2AuthorizedClientServiceTests {
@Test
public void constructorWhenJdbcOperationsIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new JdbcOAuth2AuthorizedClientService(null, this.clientRegistrationRepository))
.isInstanceOf(IllegalArgumentException.class).hasMessage("jdbcOperations cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> new JdbcOAuth2AuthorizedClientService(null, this.clientRegistrationRepository))
.withMessage("jdbcOperations cannot be null");
}
@Test
public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new JdbcOAuth2AuthorizedClientService(this.jdbcOperations, null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clientRegistrationRepository cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> new JdbcOAuth2AuthorizedClientService(this.jdbcOperations, null))
.withMessage("clientRegistrationRepository cannot be null");
}
@Test
public void setAuthorizedClientRowMapperWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientService.setAuthorizedClientRowMapper(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("authorizedClientRowMapper cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.setAuthorizedClientRowMapper(null))
.withMessage("authorizedClientRowMapper cannot be null");
}
@Test
public void setAuthorizedClientParametersMapperWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientService.setAuthorizedClientParametersMapper(null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("authorizedClientParametersMapper cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.setAuthorizedClientParametersMapper(null))
.withMessage("authorizedClientParametersMapper cannot be null");
}
@Test
public void loadAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientService.loadAuthorizedClient(null, "principalName"))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clientRegistrationId cannot be empty");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.loadAuthorizedClient(null, "principalName"))
.withMessage("clientRegistrationId cannot be empty");
}
@Test
public void loadAuthorizedClientWhenPrincipalNameIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientService
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("principalName cannot be empty");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), null))
.withMessage("principalName cannot be empty");
}
@Test
@ -177,26 +183,28 @@ public class JdbcOAuth2AuthorizedClientServiceTests {
Authentication principal = createPrincipal();
OAuth2AuthorizedClient expected = createAuthorizedClient(principal, this.clientRegistration);
this.authorizedClientService.saveAuthorizedClient(expected, principal);
assertThatThrownBy(() -> this.authorizedClientService
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName()))
.isInstanceOf(DataRetrievalFailureException.class)
.hasMessage("The ClientRegistration with id '" + this.clientRegistration.getRegistrationId()
+ "' exists in the data source, however, it was not found in the ClientRegistrationRepository.");
assertThatExceptionOfType(DataRetrievalFailureException.class)
.isThrownBy(() -> this.authorizedClientService
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName()))
.withMessage("The ClientRegistration with id '" + this.clientRegistration.getRegistrationId()
+ "' exists in the data source, however, it was not found in the ClientRegistrationRepository.");
}
@Test
public void saveAuthorizedClientWhenAuthorizedClientIsNullThenThrowIllegalArgumentException() {
Authentication principal = createPrincipal();
assertThatThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(null, principal))
.isInstanceOf(IllegalArgumentException.class).hasMessage("authorizedClient cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(null, principal))
.withMessage("authorizedClient cannot be null");
}
@Test
public void saveAuthorizedClientWhenPrincipalIsNullThenThrowIllegalArgumentException() {
Authentication principal = createPrincipal();
OAuth2AuthorizedClient authorizedClient = createAuthorizedClient(principal, this.clientRegistration);
assertThatThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(authorizedClient, null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("principal cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(authorizedClient, null))
.withMessage("principal cannot be null");
}
@Test
@ -293,15 +301,17 @@ public class JdbcOAuth2AuthorizedClientServiceTests {
@Test
public void removeAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientService.removeAuthorizedClient(null, "principalName"))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clientRegistrationId cannot be empty");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.removeAuthorizedClient(null, "principalName"))
.withMessage("clientRegistrationId cannot be empty");
}
@Test
public void removeAuthorizedClientWhenPrincipalNameIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientService
.removeAuthorizedClient(this.clientRegistration.getRegistrationId(), null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("principalName cannot be empty");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService
.removeAuthorizedClient(this.clientRegistration.getRegistrationId(), null))
.withMessage("principalName cannot be empty");
}
@Test

View File

@ -26,7 +26,7 @@ import org.springframework.security.oauth2.client.registration.TestClientRegistr
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
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.entry;
/**
@ -52,20 +52,23 @@ public class OAuth2AuthorizationContextTests {
@Test
public void withClientRegistrationWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> OAuth2AuthorizationContext.withClientRegistration(null).build())
.isInstanceOf(IllegalArgumentException.class).hasMessage("clientRegistration cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> OAuth2AuthorizationContext.withClientRegistration(null).build())
.withMessage("clientRegistration cannot be null");
}
@Test
public void withAuthorizedClientWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> OAuth2AuthorizationContext.withAuthorizedClient(null).build())
.isInstanceOf(IllegalArgumentException.class).hasMessage("authorizedClient cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> OAuth2AuthorizationContext.withAuthorizedClient(null).build())
.withMessage("authorizedClient cannot be null");
}
@Test
public void withClientRegistrationWhenPrincipalIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> OAuth2AuthorizationContext.withClientRegistration(this.clientRegistration).build())
.isInstanceOf(IllegalArgumentException.class).hasMessage("principal cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> OAuth2AuthorizationContext.withClientRegistration(this.clientRegistration).build())
.withMessage("principal cannot be null");
}
@Test

View File

@ -26,7 +26,7 @@ import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
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.entry;
/**
@ -46,28 +46,29 @@ public class OAuth2AuthorizeRequestTests {
@Test
public void withClientRegistrationIdWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> OAuth2AuthorizeRequest.withClientRegistrationId(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clientRegistrationId cannot be empty");
assertThatIllegalArgumentException().isThrownBy(() -> OAuth2AuthorizeRequest.withClientRegistrationId(null))
.withMessage("clientRegistrationId cannot be empty");
}
@Test
public void withAuthorizedClientWhenAuthorizedClientIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> OAuth2AuthorizeRequest.withAuthorizedClient(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("authorizedClient cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> OAuth2AuthorizeRequest.withAuthorizedClient(null))
.withMessage("authorizedClient cannot be null");
}
@Test
public void withClientRegistrationIdWhenPrincipalIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).build())
.isInstanceOf(IllegalArgumentException.class).hasMessage("principal cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).build())
.withMessage("principal cannot be null");
}
@Test
public void withClientRegistrationIdWhenPrincipalNameIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> OAuth2AuthorizeRequest
assertThatIllegalArgumentException().isThrownBy(() -> OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal((String) null).build())
.isInstanceOf(IllegalArgumentException.class).hasMessage("principalName cannot be empty");
.withMessage("principalName cannot be empty");
}
@Test

View File

@ -19,7 +19,7 @@ package org.springframework.security.oauth2.client;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link OAuth2AuthorizedClientId}.
@ -30,14 +30,14 @@ public class OAuth2AuthorizedClientIdTests {
@Test
public void constructorWhenRegistrationIdNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OAuth2AuthorizedClientId(null, "test-principal"))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clientRegistrationId cannot be empty");
assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2AuthorizedClientId(null, "test-principal"))
.withMessage("clientRegistrationId cannot be empty");
}
@Test
public void constructorWhenPrincipalNameNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OAuth2AuthorizedClientId("test-client", null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("principalName cannot be empty");
assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2AuthorizedClientId("test-client", null))
.withMessage("principalName cannot be empty");
}
@Test

View File

@ -39,7 +39,8 @@ import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenRe
import org.springframework.web.client.RestOperations;
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.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
@ -82,8 +83,8 @@ public class OAuth2AuthorizedClientProviderBuilderTests {
@Test
public void providerWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> OAuth2AuthorizedClientProviderBuilder.builder().provider(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> OAuth2AuthorizedClientProviderBuilder.builder().provider(null));
}
@Test
@ -93,8 +94,8 @@ public class OAuth2AuthorizedClientProviderBuilderTests {
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(TestClientRegistrations.clientRegistration().build()).principal(this.principal)
.build();
assertThatThrownBy(() -> authorizedClientProvider.authorize(authorizationContext))
.isInstanceOf(ClientAuthorizationRequiredException.class);
assertThatExceptionOfType(ClientAuthorizationRequiredException.class)
.isThrownBy(() -> authorizedClientProvider.authorize(authorizationContext));
}
@Test
@ -155,8 +156,8 @@ public class OAuth2AuthorizedClientProviderBuilderTests {
// authorization_code
OAuth2AuthorizationContext authorizationCodeContext = OAuth2AuthorizationContext
.withClientRegistration(clientRegistration).principal(this.principal).build();
assertThatThrownBy(() -> authorizedClientProvider.authorize(authorizationCodeContext))
.isInstanceOf(ClientAuthorizationRequiredException.class);
assertThatExceptionOfType(ClientAuthorizationRequiredException.class)
.isThrownBy(() -> authorizedClientProvider.authorize(authorizationCodeContext));
// refresh_token
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration,
this.principal.getName(), expiredAccessToken(), TestOAuth2RefreshTokens.refreshToken());

View File

@ -34,7 +34,7 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenRespon
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
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.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -65,32 +65,34 @@ public class PasswordOAuth2AuthorizedClientProviderTests {
@Test
public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("accessTokenResponseClient cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
.withMessage("accessTokenResponseClient cannot be null");
}
@Test
public void setClockSkewWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.setClockSkew(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clockSkew cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.setClockSkew(null))
.withMessage("clockSkew cannot be null");
}
@Test
public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1)))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clockSkew must be >= 0");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1)))
.withMessage("clockSkew must be >= 0");
}
@Test
public void setClockWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.setClock(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clock cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.setClock(null))
.withMessage("clock cannot be null");
}
@Test
public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.authorize(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("context cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.authorize(null))
.withMessage("context cannot be null");
}
@Test

View File

@ -35,7 +35,7 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenRespon
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
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.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -66,32 +66,34 @@ public class PasswordReactiveOAuth2AuthorizedClientProviderTests {
@Test
public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("accessTokenResponseClient cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
.withMessage("accessTokenResponseClient cannot be null");
}
@Test
public void setClockSkewWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.setClockSkew(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clockSkew cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.setClockSkew(null))
.withMessage("clockSkew cannot be null");
}
@Test
public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1)))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clockSkew must be >= 0");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1)))
.withMessage("clockSkew must be >= 0");
}
@Test
public void setClockWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.setClock(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clock cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.setClock(null))
.withMessage("clock cannot be null");
}
@Test
public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.authorize(null).block())
.isInstanceOf(IllegalArgumentException.class).hasMessage("context cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.authorize(null).block())
.withMessage("context cannot be null");
}
@Test

View File

@ -38,7 +38,8 @@ import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
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.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -73,8 +74,8 @@ public class ReactiveOAuth2AuthorizedClientProviderBuilderTests {
@Test
public void providerWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> ReactiveOAuth2AuthorizedClientProviderBuilder.builder().provider(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> ReactiveOAuth2AuthorizedClientProviderBuilder.builder().provider(null));
}
@Test
@ -83,8 +84,8 @@ public class ReactiveOAuth2AuthorizedClientProviderBuilderTests {
.builder().authorizationCode().build();
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistrationBuilder.build()).principal(this.principal).build();
assertThatThrownBy(() -> authorizedClientProvider.authorize(authorizationContext).block())
.isInstanceOf(ClientAuthorizationRequiredException.class);
assertThatExceptionOfType(ClientAuthorizationRequiredException.class)
.isThrownBy(() -> authorizedClientProvider.authorize(authorizationContext).block());
}
@Test
@ -157,8 +158,8 @@ public class ReactiveOAuth2AuthorizedClientProviderBuilderTests {
// authorization_code
OAuth2AuthorizationContext authorizationCodeContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistrationBuilder.build()).principal(this.principal).build();
assertThatThrownBy(() -> authorizedClientProvider.authorize(authorizationCodeContext).block())
.isInstanceOf(ClientAuthorizationRequiredException.class);
assertThatExceptionOfType(ClientAuthorizationRequiredException.class)
.isThrownBy(() -> authorizedClientProvider.authorize(authorizationCodeContext).block());
// refresh_token
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistrationBuilder.build(),
this.principal.getName(), expiredAccessToken(), TestOAuth2RefreshTokens.refreshToken());

View File

@ -38,7 +38,7 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenRespon
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
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.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -78,32 +78,34 @@ public class RefreshTokenOAuth2AuthorizedClientProviderTests {
@Test
public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("accessTokenResponseClient cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
.withMessage("accessTokenResponseClient cannot be null");
}
@Test
public void setClockSkewWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.setClockSkew(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clockSkew cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.setClockSkew(null))
.withMessage("clockSkew cannot be null");
}
@Test
public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1)))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clockSkew must be >= 0");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1)))
.withMessage("clockSkew must be >= 0");
}
@Test
public void setClockWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.setClock(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clock cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.setClock(null))
.withMessage("clock cannot be null");
}
@Test
public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.authorize(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("context cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.authorize(null))
.withMessage("context cannot be null");
}
@Test
@ -193,9 +195,9 @@ public class RefreshTokenOAuth2AuthorizedClientProviderTests {
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(this.authorizedClient).principal(this.principal)
.attribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME, invalidRequestScope).build();
assertThatThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageStartingWith("The context attribute must be of type String[] '"
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext))
.withMessageStartingWith("The context attribute must be of type String[] '"
+ OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME + "'");
}

View File

@ -39,7 +39,7 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenRespon
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
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.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -79,32 +79,34 @@ public class RefreshTokenReactiveOAuth2AuthorizedClientProviderTests {
@Test
public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("accessTokenResponseClient cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
.withMessage("accessTokenResponseClient cannot be null");
}
@Test
public void setClockSkewWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.setClockSkew(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clockSkew cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.setClockSkew(null))
.withMessage("clockSkew cannot be null");
}
@Test
public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1)))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clockSkew must be >= 0");
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1)))
.withMessage("clockSkew must be >= 0");
}
@Test
public void setClockWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.setClock(null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clock cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.setClock(null))
.withMessage("clock cannot be null");
}
@Test
public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.authorizedClientProvider.authorize(null).block())
.isInstanceOf(IllegalArgumentException.class).hasMessage("context cannot be null");
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.authorize(null).block())
.withMessage("context cannot be null");
}
@Test
@ -196,9 +198,9 @@ public class RefreshTokenReactiveOAuth2AuthorizedClientProviderTests {
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(this.authorizedClient).principal(this.principal)
.attribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME, invalidRequestScope).build();
assertThatThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext).block())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageStartingWith("The context attribute must be of type String[] '"
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext).block())
.withMessageStartingWith("The context attribute must be of type String[] '"
+ OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME + "'");
}

View File

@ -38,7 +38,8 @@ import org.springframework.security.oauth2.core.endpoint.TestOAuth2Authorization
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses;
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.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -69,8 +70,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
@Test
public void constructorWhenAccessTokenResponseClientIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationProvider(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationProvider(null));
}
@Test
@ -84,10 +84,10 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
.errorCode(OAuth2ErrorCodes.INVALID_REQUEST).build();
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
authorizationResponse);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(
new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, authorizationExchange)))
.isInstanceOf(OAuth2AuthorizationException.class)
.hasMessageContaining(OAuth2ErrorCodes.INVALID_REQUEST);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(
new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, authorizationExchange)))
.withMessageContaining(OAuth2ErrorCodes.INVALID_REQUEST);
}
@Test
@ -96,10 +96,10 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests {
.build();
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
authorizationResponse);
assertThatThrownBy(() -> this.authenticationProvider.authenticate(
new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, authorizationExchange)))
.isInstanceOf(OAuth2AuthorizationException.class)
.hasMessageContaining("invalid_state_parameter");
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(
new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, authorizationExchange)))
.withMessageContaining("invalid_state_parameter");
}
@Test

View File

@ -30,7 +30,7 @@ import org.springframework.security.oauth2.core.endpoint.TestOAuth2Authorization
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link OAuth2AuthorizationCodeAuthenticationToken}.
@ -55,14 +55,14 @@ public class OAuth2AuthorizationCodeAuthenticationTokenTests {
@Test
public void constructorAuthorizationRequestResponseWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(null, this.authorizationExchange))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(null, this.authorizationExchange));
}
@Test
public void constructorAuthorizationRequestResponseWhenAuthorizationExchangeIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, null));
}
@Test
@ -81,21 +81,21 @@ public class OAuth2AuthorizationCodeAuthenticationTokenTests {
@Test
public void constructorTokenRequestResponseWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(null, this.authorizationExchange,
this.accessToken)).isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(null,
this.authorizationExchange, this.accessToken));
}
@Test
public void constructorTokenRequestResponseWhenAuthorizationExchangeIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(
() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, null, this.accessToken))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(
() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, null, this.accessToken));
}
@Test
public void constructorTokenRequestResponseWhenAccessTokenIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration,
this.authorizationExchange, null)).isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration,
this.authorizationExchange, null));
}
@Test

View File

@ -38,7 +38,7 @@ import org.springframework.security.oauth2.core.endpoint.TestOAuth2Authorization
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses;
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;
@ -70,13 +70,13 @@ public class OAuth2AuthorizationCodeReactiveAuthenticationManagerTests {
@Test
public void authenticateWhenErrorThenOAuth2AuthorizationException() {
this.authorizationResponse = TestOAuth2AuthorizationResponses.error();
assertThatCode(() -> authenticate()).isInstanceOf(OAuth2AuthorizationException.class);
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> authenticate());
}
@Test
public void authenticateWhenStateNotEqualThenOAuth2AuthorizationException() {
this.authorizationRequest.state("notequal");
assertThatCode(() -> authenticate()).isInstanceOf(OAuth2AuthorizationException.class);
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> authenticate());
}
@Test
@ -97,7 +97,7 @@ public class OAuth2AuthorizationCodeReactiveAuthenticationManagerTests {
public void authenticateWhenOAuth2AuthorizationExceptionThenOAuth2AuthorizationException() {
given(this.accessTokenResponseClient.getTokenResponse(any()))
.willReturn(Mono.error(() -> new OAuth2AuthorizationException(new OAuth2Error("error"))));
assertThatCode(() -> authenticate()).isInstanceOf(OAuth2AuthorizationException.class);
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> authenticate());
}
private OAuth2AuthorizationCodeAuthenticationToken authenticate() {

View File

@ -52,8 +52,8 @@ import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
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.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.BDDMockito.given;
@ -90,22 +90,20 @@ public class OAuth2LoginReactiveAuthenticationManagerTests {
@Test
public void constructorWhenNullAccessTokenResponseClientThenIllegalArgumentException() {
this.accessTokenResponseClient = null;
assertThatThrownBy(
() -> new OAuth2LoginReactiveAuthenticationManager(this.accessTokenResponseClient, this.userService))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(
() -> new OAuth2LoginReactiveAuthenticationManager(this.accessTokenResponseClient, this.userService));
}
@Test
public void constructorWhenNullUserServiceThenIllegalArgumentException() {
this.userService = null;
assertThatThrownBy(
() -> new OAuth2LoginReactiveAuthenticationManager(this.accessTokenResponseClient, this.userService))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(
() -> new OAuth2LoginReactiveAuthenticationManager(this.accessTokenResponseClient, this.userService));
}
@Test
public void setAuthoritiesMapperWhenAuthoritiesMapperIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.manager.setAuthoritiesMapper(null)).isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.manager.setAuthoritiesMapper(null));
}
@Test
@ -113,8 +111,8 @@ public class OAuth2LoginReactiveAuthenticationManagerTests {
// we didn't do anything because it should cause a ClassCastException (as verified
// below)
TestingAuthenticationToken token = new TestingAuthenticationToken("a", "b");
assertThatCode(() -> this.manager.authenticate(token)).doesNotThrowAnyException();
assertThatThrownBy(() -> this.manager.authenticate(token).block()).isInstanceOf(Throwable.class);
this.manager.authenticate(token);
assertThatExceptionOfType(Throwable.class).isThrownBy(() -> this.manager.authenticate(token).block());
}
@Test
@ -127,15 +125,15 @@ public class OAuth2LoginReactiveAuthenticationManagerTests {
@Test
public void authenticationWhenErrorThenOAuth2AuthenticationException() {
this.authorizationResponseBldr = OAuth2AuthorizationResponse.error("error").state("state");
assertThatThrownBy(() -> this.manager.authenticate(loginToken()).block())
.isInstanceOf(OAuth2AuthenticationException.class);
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.manager.authenticate(loginToken()).block());
}
@Test
public void authenticationWhenStateDoesNotMatchThenOAuth2AuthenticationException() {
this.authorizationResponseBldr.state("notmatch");
assertThatThrownBy(() -> this.manager.authenticate(loginToken()).block())
.isInstanceOf(OAuth2AuthenticationException.class);
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.manager.authenticate(loginToken()).block());
}
@Test

View File

@ -39,7 +39,8 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequ
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
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.assertThatIllegalArgumentException;
/**
* Tests for {@link DefaultAuthorizationCodeTokenResponseClient}.
@ -74,20 +75,17 @@ public class DefaultAuthorizationCodeTokenResponseClientTests {
@Test
public void setRequestEntityConverterWhenConverterIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null));
}
@Test
public void setRestOperationsWhenRestOperationsIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.tokenResponseClient.setRestOperations(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRestOperations(null));
}
@Test
public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null));
}
@Test
@ -151,22 +149,22 @@ public class DefaultAuthorizationCodeTokenResponseClientTests {
String accessTokenSuccessResponse = "{\n" + " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"not-bearer\",\n" + " \"expires_in\": \"3600\"\n" + "}\n";
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest()))
.isInstanceOf(OAuth2AuthorizationException.class)
.hasMessageContaining(
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest()))
.withMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
.hasMessageContaining("tokenType cannot be null");
.withMessageContaining("tokenType cannot be null");
}
@Test
public void getTokenResponseWhenSuccessResponseAndMissingTokenTypeParameterThenThrowOAuth2AuthorizationException() {
String accessTokenSuccessResponse = "{\n" + " \"access_token\": \"access-token-1234\"\n" + "}\n";
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest()))
.isInstanceOf(OAuth2AuthorizationException.class)
.hasMessageContaining(
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest()))
.withMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
.hasMessageContaining("tokenType cannot be null");
.withMessageContaining("tokenType cannot be null");
}
@Test
@ -195,8 +193,9 @@ public class DefaultAuthorizationCodeTokenResponseClientTests {
public void getTokenResponseWhenTokenUriInvalidThenThrowOAuth2AuthorizationException() {
String invalidTokenUri = "https://invalid-provider.com/oauth2/token";
ClientRegistration clientRegistration = this.from(this.clientRegistration).tokenUri(invalidTokenUri).build();
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest(
clientRegistration))).isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining(
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(
() -> this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest(clientRegistration)))
.withMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
}
@ -209,8 +208,9 @@ public class DefaultAuthorizationCodeTokenResponseClientTests {
+ " \"custom_parameter_2\": \"custom-value-2\"\n";
// "}\n"; // Make the JSON invalid/malformed
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest()))
.isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining(
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest()))
.withMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
}
@ -218,16 +218,18 @@ public class DefaultAuthorizationCodeTokenResponseClientTests {
public void getTokenResponseWhenErrorResponseThenThrowOAuth2AuthorizationException() {
String accessTokenErrorResponse = "{\n" + " \"error\": \"unauthorized_client\"\n" + "}\n";
this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest()))
.isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining("[unauthorized_client]");
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest()))
.withMessageContaining("[unauthorized_client]");
}
@Test
public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationException() {
this.server.enqueue(new MockResponse().setResponseCode(500));
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest()))
.isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(this.authorizationCodeGrantRequest()))
.withMessageContaining("[invalid_token_response] An error occurred while attempting to retrieve "
+ "the OAuth 2.0 Access Token Response");
}
private OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest() {

View File

@ -36,7 +36,8 @@ import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
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.assertThatIllegalArgumentException;
/**
* Tests for {@link DefaultClientCredentialsTokenResponseClient}.
@ -69,20 +70,17 @@ public class DefaultClientCredentialsTokenResponseClientTests {
@Test
public void setRequestEntityConverterWhenConverterIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null));
}
@Test
public void setRestOperationsWhenRestOperationsIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.tokenResponseClient.setRestOperations(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRestOperations(null));
}
@Test
public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null));
}
@Test
@ -152,11 +150,11 @@ public class DefaultClientCredentialsTokenResponseClientTests {
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
this.clientRegistration);
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
.isInstanceOf(OAuth2AuthorizationException.class)
.hasMessageContaining(
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
.withMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
.hasMessageContaining("tokenType cannot be null");
.withMessageContaining("tokenType cannot be null");
}
@Test
@ -165,11 +163,11 @@ public class DefaultClientCredentialsTokenResponseClientTests {
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
this.clientRegistration);
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
.isInstanceOf(OAuth2AuthorizationException.class)
.hasMessageContaining(
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
.withMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
.hasMessageContaining("tokenType cannot be null");
.withMessageContaining("tokenType cannot be null");
}
@Test
@ -203,8 +201,9 @@ public class DefaultClientCredentialsTokenResponseClientTests {
ClientRegistration clientRegistration = this.from(this.clientRegistration).tokenUri(invalidTokenUri).build();
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
clientRegistration);
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
.isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining(
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
.withMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
}
@ -218,8 +217,9 @@ public class DefaultClientCredentialsTokenResponseClientTests {
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
this.clientRegistration);
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
.isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining(
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
.withMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
}
@ -229,8 +229,9 @@ public class DefaultClientCredentialsTokenResponseClientTests {
this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
this.clientRegistration);
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
.isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining("[unauthorized_client]");
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
.withMessageContaining("[unauthorized_client]");
}
@Test
@ -238,8 +239,9 @@ public class DefaultClientCredentialsTokenResponseClientTests {
this.server.enqueue(new MockResponse().setResponseCode(500));
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest = new OAuth2ClientCredentialsGrantRequest(
this.clientRegistration);
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
.isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining(
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(clientCredentialsGrantRequest))
.withMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
}

View File

@ -37,7 +37,8 @@ import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
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.assertThatIllegalArgumentException;
/**
* Tests for {@link DefaultPasswordTokenResponseClient}.
@ -72,20 +73,17 @@ public class DefaultPasswordTokenResponseClientTests {
@Test
public void setRequestEntityConverterWhenConverterIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null));
}
@Test
public void setRestOperationsWhenRestOperationsIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.tokenResponseClient.setRestOperations(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRestOperations(null));
}
@Test
public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null));
}
@Test
@ -141,11 +139,11 @@ public class DefaultPasswordTokenResponseClientTests {
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
this.clientRegistrationBuilder.build(), this.username, this.password);
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest))
.isInstanceOf(OAuth2AuthorizationException.class)
.hasMessageContaining(
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest))
.withMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
.hasMessageContaining("tokenType cannot be null");
.withMessageContaining("tokenType cannot be null");
}
@Test
@ -169,8 +167,9 @@ public class DefaultPasswordTokenResponseClientTests {
this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
this.clientRegistrationBuilder.build(), this.username, this.password);
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest))
.isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining("[unauthorized_client]");
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest))
.withMessageContaining("[unauthorized_client]");
}
@Test
@ -178,9 +177,10 @@ public class DefaultPasswordTokenResponseClientTests {
this.server.enqueue(new MockResponse().setResponseCode(500));
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
this.clientRegistrationBuilder.build(), this.username, this.password);
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest))
.isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest))
.withMessageContaining("[invalid_token_response] An error occurred while attempting to "
+ "retrieve the OAuth 2.0 Access Token Response");
}
private MockResponse jsonResponse(String json) {

View File

@ -40,7 +40,8 @@ import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
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.assertThatIllegalArgumentException;
/**
* Tests for {@link DefaultRefreshTokenTokenResponseClient}.
@ -76,20 +77,17 @@ public class DefaultRefreshTokenTokenResponseClientTests {
@Test
public void setRequestEntityConverterWhenConverterIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRequestEntityConverter(null));
}
@Test
public void setRestOperationsWhenRestOperationsIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.tokenResponseClient.setRestOperations(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setRestOperations(null));
}
@Test
public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null));
}
@Test
@ -144,11 +142,11 @@ public class DefaultRefreshTokenTokenResponseClientTests {
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest))
.isInstanceOf(OAuth2AuthorizationException.class)
.hasMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
.hasMessageContaining("tokenType cannot be null");
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest))
.withMessageContaining("[invalid_token_response] An error occurred while attempting to "
+ "retrieve the OAuth 2.0 Access Token Response")
.withMessageContaining("tokenType cannot be null");
}
@Test
@ -174,8 +172,9 @@ public class DefaultRefreshTokenTokenResponseClientTests {
this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest))
.isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining("[unauthorized_client]");
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest))
.withMessageContaining("[unauthorized_client]");
}
@Test
@ -183,9 +182,10 @@ public class DefaultRefreshTokenTokenResponseClientTests {
this.server.enqueue(new MockResponse().setResponseCode(500));
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest))
.isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining(
"[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest))
.withMessageContaining("[invalid_token_response] An error occurred while attempting to "
+ "retrieve the OAuth 2.0 Access Token Response");
}
private MockResponse jsonResponse(String json) {

View File

@ -24,7 +24,7 @@ import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link OAuth2ClientCredentialsGrantRequest}.
@ -45,8 +45,7 @@ public class OAuth2ClientCredentialsGrantRequestTests {
@Test
public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OAuth2ClientCredentialsGrantRequest(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2ClientCredentialsGrantRequest(null));
}
@Test
@ -55,8 +54,8 @@ public class OAuth2ClientCredentialsGrantRequestTests {
.clientId("client-1").authorizationGrantType(AuthorizationGrantType.IMPLICIT)
.redirectUri("https://localhost:8080/redirect-uri").authorizationUri("https://provider.com/oauth2/auth")
.clientName("Client 1").build();
assertThatThrownBy(() -> new OAuth2ClientCredentialsGrantRequest(clientRegistration))
.isInstanceOf(IllegalArgumentException.class).hasMessage(
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2ClientCredentialsGrantRequest(clientRegistration)).withMessage(
"clientRegistration.authorizationGrantType must be AuthorizationGrantType.CLIENT_CREDENTIALS");
}

View File

@ -23,7 +23,7 @@ import org.springframework.security.oauth2.client.registration.TestClientRegistr
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link OAuth2PasswordGrantRequest}.
@ -41,32 +41,37 @@ public class OAuth2PasswordGrantRequestTests {
@Test
public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OAuth2PasswordGrantRequest(null, this.username, this.password))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clientRegistration cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2PasswordGrantRequest(null, this.username, this.password))
.withMessage("clientRegistration cannot be null");
}
@Test
public void constructorWhenUsernameIsEmptyThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OAuth2PasswordGrantRequest(this.clientRegistration, null, this.password))
.isInstanceOf(IllegalArgumentException.class).hasMessage("username cannot be empty");
assertThatThrownBy(() -> new OAuth2PasswordGrantRequest(this.clientRegistration, "", this.password))
.isInstanceOf(IllegalArgumentException.class).hasMessage("username cannot be empty");
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2PasswordGrantRequest(this.clientRegistration, null, this.password))
.withMessage("username cannot be empty");
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2PasswordGrantRequest(this.clientRegistration, "", this.password))
.withMessage("username cannot be empty");
}
@Test
public void constructorWhenPasswordIsEmptyThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OAuth2PasswordGrantRequest(this.clientRegistration, this.username, null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("password cannot be empty");
assertThatThrownBy(() -> new OAuth2PasswordGrantRequest(this.clientRegistration, this.username, ""))
.isInstanceOf(IllegalArgumentException.class).hasMessage("password cannot be empty");
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2PasswordGrantRequest(this.clientRegistration, this.username, null))
.withMessage("password cannot be empty");
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2PasswordGrantRequest(this.clientRegistration, this.username, ""))
.withMessage("password cannot be empty");
}
@Test
public void constructorWhenClientRegistrationInvalidGrantTypeThenThrowIllegalArgumentException() {
ClientRegistration registration = TestClientRegistrations.clientCredentials().build();
assertThatThrownBy(() -> new OAuth2PasswordGrantRequest(registration, this.username, this.password))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("clientRegistration.authorizationGrantType must be AuthorizationGrantType.PASSWORD");
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2PasswordGrantRequest(registration, this.username, this.password))
.withMessage("clientRegistration.authorizationGrantType must be AuthorizationGrantType.PASSWORD");
}
@Test

View File

@ -31,7 +31,7 @@ import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link OAuth2RefreshTokenGrantRequest}.
@ -55,20 +55,23 @@ public class OAuth2RefreshTokenGrantRequestTests {
@Test
public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OAuth2RefreshTokenGrantRequest(null, this.accessToken, this.refreshToken))
.isInstanceOf(IllegalArgumentException.class).hasMessage("clientRegistration cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2RefreshTokenGrantRequest(null, this.accessToken, this.refreshToken))
.withMessage("clientRegistration cannot be null");
}
@Test
public void constructorWhenAccessTokenIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OAuth2RefreshTokenGrantRequest(this.clientRegistration, null, this.refreshToken))
.isInstanceOf(IllegalArgumentException.class).hasMessage("accessToken cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2RefreshTokenGrantRequest(this.clientRegistration, null, this.refreshToken))
.withMessage("accessToken cannot be null");
}
@Test
public void constructorWhenRefreshTokenIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OAuth2RefreshTokenGrantRequest(this.clientRegistration, this.accessToken, null))
.isInstanceOf(IllegalArgumentException.class).hasMessage("refreshToken cannot be null");
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2RefreshTokenGrantRequest(this.clientRegistration, this.accessToken, null))
.withMessage("refreshToken cannot be null");
}
@Test

View File

@ -41,7 +41,7 @@ import org.springframework.security.oauth2.core.endpoint.PkceParameterNames;
import org.springframework.web.reactive.function.client.WebClient;
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.BDDMockito.given;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
@ -179,10 +179,10 @@ public class WebClientReactiveAuthorizationCodeTokenResponseClientTests {
String accessTokenErrorResponse = "{\n" + " \"error\": \"unauthorized_client\"\n" + "}\n";
this.server.enqueue(
jsonResponse(accessTokenErrorResponse).setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR.value()));
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest()).block())
.isInstanceOfSatisfying(OAuth2AuthorizationException.class,
(e) -> assertThat(e.getError().getErrorCode()).isEqualTo("unauthorized_client"))
.hasMessageContaining("unauthorized_client");
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest()).block())
.satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("unauthorized_client"))
.withMessageContaining("unauthorized_client");
}
// gh-5594
@ -191,8 +191,9 @@ public class WebClientReactiveAuthorizationCodeTokenResponseClientTests {
String accessTokenErrorResponse = "{}";
this.server.enqueue(
jsonResponse(accessTokenErrorResponse).setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR.value()));
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest()).block())
.isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining("server_error");
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest()).block())
.withMessageContaining("server_error");
}
@Test
@ -200,8 +201,9 @@ public class WebClientReactiveAuthorizationCodeTokenResponseClientTests {
String accessTokenSuccessResponse = "{\n" + " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"not-bearer\",\n" + " \"expires_in\": \"3600\"\n" + "}\n";
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest()).block())
.isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining("invalid_token_response");
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(authorizationCodeGrantRequest()).block())
.withMessageContaining("invalid_token_response");
}
@Test

View File

@ -34,7 +34,7 @@ import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
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.BDDMockito.given;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
@ -134,11 +134,11 @@ public class WebClientReactiveClientCredentialsTokenResponseClientTests {
ClientRegistration registration = this.clientRegistration.build();
enqueueUnexpectedResponse();
OAuth2ClientCredentialsGrantRequest request = new OAuth2ClientCredentialsGrantRequest(registration);
assertThatThrownBy(() -> this.client.getTokenResponse(request).block())
.isInstanceOfSatisfying(OAuth2AuthorizationException.class,
(e) -> assertThat(e.getError().getErrorCode()).isEqualTo("invalid_token_response"))
.hasMessageContaining("[invalid_token_response]")
.hasMessageContaining("Empty OAuth 2.0 Access Token Response");
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.client.getTokenResponse(request).block())
.satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("invalid_token_response"))
.withMessageContaining("[invalid_token_response]")
.withMessageContaining("Empty OAuth 2.0 Access Token Response");
}
private void enqueueUnexpectedResponse() {

View File

@ -36,7 +36,8 @@ import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
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.assertThatIllegalArgumentException;
/**
* Tests for {@link WebClientReactivePasswordTokenResponseClient}.
@ -70,14 +71,12 @@ public class WebClientReactivePasswordTokenResponseClientTests {
@Test
public void setWebClientWhenClientIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.tokenResponseClient.setWebClient(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setWebClient(null));
}
@Test
public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(null).block())
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null).block());
}
@Test
@ -134,12 +133,12 @@ public class WebClientReactivePasswordTokenResponseClientTests {
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
this.clientRegistrationBuilder.build(), this.username, this.password);
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest).block())
.isInstanceOfSatisfying(OAuth2AuthorizationException.class,
(e) -> assertThat(e.getError().getErrorCode()).isEqualTo("invalid_token_response"))
.hasMessageContaining("[invalid_token_response]")
.hasMessageContaining("An error occurred parsing the Access Token response")
.hasCauseInstanceOf(Throwable.class);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest).block())
.satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("invalid_token_response"))
.withMessageContaining("[invalid_token_response]")
.withMessageContaining("An error occurred parsing the Access Token response")
.withCauseInstanceOf(Throwable.class);
}
@Test
@ -164,10 +163,10 @@ public class WebClientReactivePasswordTokenResponseClientTests {
this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
this.clientRegistrationBuilder.build(), this.username, this.password);
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest).block())
.isInstanceOfSatisfying(OAuth2AuthorizationException.class,
(e) -> assertThat(e.getError().getErrorCode()).isEqualTo("unauthorized_client"))
.hasMessageContaining("[unauthorized_client]");
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest).block())
.satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("unauthorized_client"))
.withMessageContaining("[unauthorized_client]");
}
@Test
@ -175,11 +174,11 @@ public class WebClientReactivePasswordTokenResponseClientTests {
this.server.enqueue(new MockResponse().setResponseCode(500));
OAuth2PasswordGrantRequest passwordGrantRequest = new OAuth2PasswordGrantRequest(
this.clientRegistrationBuilder.build(), this.username, this.password);
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest).block())
.isInstanceOfSatisfying(OAuth2AuthorizationException.class,
(e) -> assertThat(e.getError().getErrorCode()).isEqualTo("invalid_token_response"))
.hasMessageContaining("[invalid_token_response]")
.hasMessageContaining("Empty OAuth 2.0 Access Token Response");
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(passwordGrantRequest).block())
.satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("invalid_token_response"))
.withMessageContaining("[invalid_token_response]")
.withMessageContaining("Empty OAuth 2.0 Access Token Response");
}
private MockResponse jsonResponse(String json) {

View File

@ -40,7 +40,8 @@ import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
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.assertThatIllegalArgumentException;
/**
* Tests for {@link WebClientReactiveRefreshTokenTokenResponseClient}.
@ -76,14 +77,12 @@ public class WebClientReactiveRefreshTokenTokenResponseClientTests {
@Test
public void setWebClientWhenClientIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.tokenResponseClient.setWebClient(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.setWebClient(null));
}
@Test
public void getTokenResponseWhenRequestIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(null).block())
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null).block());
}
@Test
@ -138,10 +137,11 @@ public class WebClientReactiveRefreshTokenTokenResponseClientTests {
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block())
.isInstanceOf(OAuth2AuthorizationException.class).hasMessageContaining("[invalid_token_response]")
.hasMessageContaining("An error occurred parsing the Access Token response")
.hasCauseInstanceOf(Throwable.class);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block())
.withMessageContaining("[invalid_token_response]")
.withMessageContaining("An error occurred parsing the Access Token response")
.withCauseInstanceOf(Throwable.class);
}
@Test
@ -167,10 +167,10 @@ public class WebClientReactiveRefreshTokenTokenResponseClientTests {
this.server.enqueue(jsonResponse(accessTokenErrorResponse).setResponseCode(400));
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block())
.isInstanceOfSatisfying(OAuth2AuthorizationException.class,
(e) -> assertThat(e.getError().getErrorCode()).isEqualTo("unauthorized_client"))
.hasMessageContaining("[unauthorized_client]");
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block())
.satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("unauthorized_client"))
.withMessageContaining("[unauthorized_client]");
}
@Test
@ -178,11 +178,11 @@ public class WebClientReactiveRefreshTokenTokenResponseClientTests {
this.server.enqueue(new MockResponse().setResponseCode(500));
OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(
this.clientRegistrationBuilder.build(), this.accessToken, this.refreshToken);
assertThatThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block())
.isInstanceOfSatisfying(OAuth2AuthorizationException.class,
(e) -> assertThat(e.getError().getErrorCode()).isEqualTo("invalid_token_response"))
.hasMessageContaining("[invalid_token_response]")
.hasMessageContaining("Empty OAuth 2.0 Access Token Response");
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(refreshTokenGrantRequest).block())
.satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("invalid_token_response"))
.withMessageContaining("[invalid_token_response]")
.withMessageContaining("Empty OAuth 2.0 Access Token Response");
}
private MockResponse jsonResponse(String json) {

View File

@ -23,7 +23,7 @@ import org.springframework.http.HttpStatus;
import org.springframework.mock.http.client.MockClientHttpResponse;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link OAuth2ErrorResponseErrorHandler}.
@ -39,9 +39,9 @@ public class OAuth2ErrorResponseErrorHandlerTests {
String errorResponse = "{\n" + " \"error\": \"unauthorized_client\",\n"
+ " \"error_description\": \"The client is not authorized\"\n" + "}\n";
MockClientHttpResponse response = new MockClientHttpResponse(errorResponse.getBytes(), HttpStatus.BAD_REQUEST);
assertThatThrownBy(() -> this.errorHandler.handleError(response))
.isInstanceOf(OAuth2AuthorizationException.class)
.hasMessage("[unauthorized_client] The client is not authorized");
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.errorHandler.handleError(response))
.withMessage("[unauthorized_client] The client is not authorized");
}
@Test
@ -49,9 +49,9 @@ public class OAuth2ErrorResponseErrorHandlerTests {
String wwwAuthenticateHeader = "Bearer realm=\"auth-realm\" error=\"insufficient_scope\" error_description=\"The access token expired\"";
MockClientHttpResponse response = new MockClientHttpResponse(new byte[0], HttpStatus.BAD_REQUEST);
response.getHeaders().add(HttpHeaders.WWW_AUTHENTICATE, wwwAuthenticateHeader);
assertThatThrownBy(() -> this.errorHandler.handleError(response))
.isInstanceOf(OAuth2AuthorizationException.class)
.hasMessage("[insufficient_scope] The access token expired");
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.errorHandler.handleError(response))
.withMessage("[insufficient_scope] The access token expired");
}
}

View File

@ -27,7 +27,7 @@ import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link OAuth2AuthenticationExceptionMixin}.
@ -68,8 +68,8 @@ public class OAuth2AuthenticationExceptionMixinTests {
@Test
public void deserializeWhenMixinNotRegisteredThenThrowJsonProcessingException() {
String json = asJson(new OAuth2AuthenticationException(new OAuth2Error("[authorization_request_not_found]")));
assertThatThrownBy(() -> new ObjectMapper().readValue(json, OAuth2AuthenticationException.class))
.isInstanceOf(JsonProcessingException.class);
assertThatExceptionOfType(JsonProcessingException.class)
.isThrownBy(() -> new ObjectMapper().readValue(json, OAuth2AuthenticationException.class));
}
@Test

View File

@ -48,7 +48,7 @@ import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link OAuth2AuthenticationTokenMixin}.
@ -95,8 +95,8 @@ public class OAuth2AuthenticationTokenMixinTests {
public void deserializeWhenMixinNotRegisteredThenThrowJsonProcessingException() {
OAuth2AuthenticationToken authentication = TestOAuth2AuthenticationTokens.oidcAuthenticated();
String json = asJson(authentication);
assertThatThrownBy(() -> new ObjectMapper().readValue(json, OAuth2AuthenticationToken.class))
.isInstanceOf(JsonProcessingException.class);
assertThatExceptionOfType(JsonProcessingException.class)
.isThrownBy(() -> new ObjectMapper().readValue(json, OAuth2AuthenticationToken.class));
}
@Test

View File

@ -34,7 +34,7 @@ import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link OAuth2AuthorizationRequestMixin}.
@ -79,8 +79,8 @@ public class OAuth2AuthorizationRequestMixinTests {
@Test
public void deserializeWhenMixinNotRegisteredThenThrowJsonProcessingException() {
String json = asJson(this.authorizationRequestBuilder.build());
assertThatThrownBy(() -> new ObjectMapper().readValue(json, OAuth2AuthorizationRequest.class))
.isInstanceOf(JsonProcessingException.class);
assertThatExceptionOfType(JsonProcessingException.class)
.isThrownBy(() -> new ObjectMapper().readValue(json, OAuth2AuthorizationRequest.class));
}
@Test
@ -128,8 +128,9 @@ public class OAuth2AuthorizationRequestMixinTests {
public void deserializeWhenInvalidAuthorizationGrantTypeThenThrowJsonParseException() {
OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestBuilder.build();
String json = asJson(authorizationRequest).replace("authorization_code", "client_credentials");
assertThatThrownBy(() -> this.mapper.readValue(json, OAuth2AuthorizationRequest.class))
.isInstanceOf(JsonParseException.class).hasMessageContaining("Invalid authorizationGrantType");
assertThatExceptionOfType(JsonParseException.class)
.isThrownBy(() -> this.mapper.readValue(json, OAuth2AuthorizationRequest.class))
.withMessageContaining("Invalid authorizationGrantType");
}
private static String asJson(OAuth2AuthorizationRequest authorizationRequest) {

View File

@ -40,7 +40,7 @@ import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link OAuth2AuthorizedClientMixin}.
@ -99,8 +99,8 @@ public class OAuth2AuthorizedClientMixinTests {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistrationBuilder.build(),
this.principalName, this.accessToken);
String json = asJson(authorizedClient);
assertThatThrownBy(() -> new ObjectMapper().readValue(json, OAuth2AuthorizedClient.class))
.isInstanceOf(JsonProcessingException.class);
assertThatExceptionOfType(JsonProcessingException.class)
.isThrownBy(() -> new ObjectMapper().readValue(json, OAuth2AuthorizedClient.class));
}
@Test

View File

@ -66,8 +66,8 @@ import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder;
import org.springframework.security.oauth2.jwt.TestJwts;
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.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.BDDMockito.given;
@ -113,25 +113,27 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests {
@Test
public void constructorWhenNullAccessTokenResponseClientThenIllegalArgumentException() {
this.accessTokenResponseClient = null;
assertThatThrownBy(() -> new OidcAuthorizationCodeReactiveAuthenticationManager(this.accessTokenResponseClient,
this.userService)).isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> new OidcAuthorizationCodeReactiveAuthenticationManager(this.accessTokenResponseClient,
this.userService));
}
@Test
public void constructorWhenNullUserServiceThenIllegalArgumentException() {
this.userService = null;
assertThatThrownBy(() -> new OidcAuthorizationCodeReactiveAuthenticationManager(this.accessTokenResponseClient,
this.userService)).isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> new OidcAuthorizationCodeReactiveAuthenticationManager(this.accessTokenResponseClient,
this.userService));
}
@Test
public void setJwtDecoderFactoryWhenNullThenIllegalArgumentException() {
assertThatThrownBy(() -> this.manager.setJwtDecoderFactory(null)).isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.manager.setJwtDecoderFactory(null));
}
@Test
public void setAuthoritiesMapperWhenAuthoritiesMapperIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.manager.setAuthoritiesMapper(null)).isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.manager.setAuthoritiesMapper(null));
}
@Test
@ -139,8 +141,8 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests {
// we didn't do anything because it should cause a ClassCastException (as verified
// below)
TestingAuthenticationToken token = new TestingAuthenticationToken("a", "b");
assertThatCode(() -> this.manager.authenticate(token)).doesNotThrowAnyException();
assertThatThrownBy(() -> this.manager.authenticate(token).block()).isInstanceOf(Throwable.class);
this.manager.authenticate(token);
assertThatExceptionOfType(Throwable.class).isThrownBy(() -> this.manager.authenticate(token).block());
}
@Test
@ -152,15 +154,15 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests {
@Test
public void authenticationWhenErrorThenOAuth2AuthenticationException() {
this.authorizationResponseBldr = OAuth2AuthorizationResponse.error("error").state("state");
assertThatThrownBy(() -> this.manager.authenticate(loginToken()).block())
.isInstanceOf(OAuth2AuthenticationException.class);
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.manager.authenticate(loginToken()).block());
}
@Test
public void authenticationWhenStateDoesNotMatchThenOAuth2AuthenticationException() {
this.authorizationResponseBldr.state("notmatch");
assertThatThrownBy(() -> this.manager.authenticate(loginToken()).block())
.isInstanceOf(OAuth2AuthenticationException.class);
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.manager.authenticate(loginToken()).block());
}
@Test
@ -172,9 +174,9 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests {
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
given(this.jwtDecoder.decode(any())).willThrow(new JwtException("ID Token Validation Error"));
this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
assertThatThrownBy(() -> this.manager.authenticate(loginToken()).block())
.isInstanceOf(OAuth2AuthenticationException.class)
.hasMessageContaining("[invalid_id_token] ID Token Validation Error");
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.manager.authenticate(loginToken()).block())
.withMessageContaining("[invalid_id_token] ID Token Validation Error");
}
@Test
@ -193,8 +195,9 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests {
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken));
this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
assertThatThrownBy(() -> this.manager.authenticate(authorizationCodeAuthentication).block())
.isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining("[invalid_nonce]");
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.manager.authenticate(authorizationCodeAuthentication).block())
.withMessageContaining("[invalid_nonce]");
}
@Test

View File

@ -36,7 +36,8 @@ import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.jwt.Jwt;
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.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -76,33 +77,30 @@ public class OidcIdTokenDecoderFactoryTests {
@Test
public void setJwtValidatorFactoryWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.idTokenDecoderFactory.setJwtValidatorFactory(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.idTokenDecoderFactory.setJwtValidatorFactory(null));
}
@Test
public void setJwsAlgorithmResolverWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.idTokenDecoderFactory.setJwsAlgorithmResolver(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.idTokenDecoderFactory.setJwsAlgorithmResolver(null));
}
@Test
public void setClaimTypeConverterFactoryWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.idTokenDecoderFactory.setClaimTypeConverterFactory(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> this.idTokenDecoderFactory.setClaimTypeConverterFactory(null));
}
@Test
public void createDecoderWhenClientRegistrationNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(null));
}
@Test
public void createDecoderWhenJwsAlgorithmDefaultAndJwkSetUriEmptyThenThrowOAuth2AuthenticationException() {
assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.jwkSetUri(null).build()))
.isInstanceOf(OAuth2AuthenticationException.class)
.hasMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.jwkSetUri(null).build()))
.withMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
+ "for Client Registration: 'registration-id'. "
+ "Check to ensure you have configured the JwkSet URI.");
}
@ -110,9 +108,9 @@ public class OidcIdTokenDecoderFactoryTests {
@Test
public void createDecoderWhenJwsAlgorithmEcAndJwkSetUriEmptyThenThrowOAuth2AuthenticationException() {
this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> SignatureAlgorithm.ES256);
assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.jwkSetUri(null).build()))
.isInstanceOf(OAuth2AuthenticationException.class)
.hasMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.jwkSetUri(null).build()))
.withMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
+ "for Client Registration: 'registration-id'. "
+ "Check to ensure you have configured the JwkSet URI.");
}
@ -120,9 +118,10 @@ public class OidcIdTokenDecoderFactoryTests {
@Test
public void createDecoderWhenJwsAlgorithmHmacAndClientSecretNullThenThrowOAuth2AuthenticationException() {
this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> MacAlgorithm.HS256);
assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.clientSecret(null).build()))
.isInstanceOf(OAuth2AuthenticationException.class)
.hasMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.idTokenDecoderFactory.createDecoder(this.registration.clientSecret(null).build()))
.withMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
+ "for Client Registration: 'registration-id'. "
+ "Check to ensure you have configured the client secret.");
}
@ -130,9 +129,9 @@ public class OidcIdTokenDecoderFactoryTests {
@Test
public void createDecoderWhenJwsAlgorithmNullThenThrowOAuth2AuthenticationException() {
this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> null);
assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.build()))
.isInstanceOf(OAuth2AuthenticationException.class)
.hasMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.build()))
.withMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
+ "for Client Registration: 'registration-id'. "
+ "Check to ensure you have configured a valid JWS Algorithm: 'null'");
}

View File

@ -35,7 +35,7 @@ import org.springframework.security.oauth2.jose.jws.JwsAlgorithms;
import org.springframework.security.oauth2.jwt.Jwt;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author Rob Winch
@ -72,20 +72,19 @@ public class OidcIdTokenValidatorTests {
@Test
public void setClockSkewWhenNullThenThrowIllegalArgumentException() {
OidcIdTokenValidator idTokenValidator = new OidcIdTokenValidator(this.registration.build());
assertThatThrownBy(() -> idTokenValidator.setClockSkew(null)).isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> idTokenValidator.setClockSkew(null));
}
@Test
public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() {
OidcIdTokenValidator idTokenValidator = new OidcIdTokenValidator(this.registration.build());
assertThatThrownBy(() -> idTokenValidator.setClockSkew(Duration.ofSeconds(-1)))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> idTokenValidator.setClockSkew(Duration.ofSeconds(-1)));
}
@Test
public void setClockWhenNullThenThrowIllegalArgumentException() {
OidcIdTokenValidator idTokenValidator = new OidcIdTokenValidator(this.registration.build());
assertThatThrownBy(() -> idTokenValidator.setClock(null)).isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> idTokenValidator.setClock(null));
}
@Test

View File

@ -36,7 +36,8 @@ import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.jwt.Jwt;
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.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -76,33 +77,30 @@ public class ReactiveOidcIdTokenDecoderFactoryTests {
@Test
public void setJwtValidatorFactoryWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.idTokenDecoderFactory.setJwtValidatorFactory(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.idTokenDecoderFactory.setJwtValidatorFactory(null));
}
@Test
public void setJwsAlgorithmResolverWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.idTokenDecoderFactory.setJwsAlgorithmResolver(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.idTokenDecoderFactory.setJwsAlgorithmResolver(null));
}
@Test
public void setClaimTypeConverterFactoryWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.idTokenDecoderFactory.setClaimTypeConverterFactory(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> this.idTokenDecoderFactory.setClaimTypeConverterFactory(null));
}
@Test
public void createDecoderWhenClientRegistrationNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(null));
}
@Test
public void createDecoderWhenJwsAlgorithmDefaultAndJwkSetUriEmptyThenThrowOAuth2AuthenticationException() {
assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.jwkSetUri(null).build()))
.isInstanceOf(OAuth2AuthenticationException.class)
.hasMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.jwkSetUri(null).build()))
.withMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
+ "for Client Registration: 'registration-id'. "
+ "Check to ensure you have configured the JwkSet URI.");
}
@ -110,9 +108,9 @@ public class ReactiveOidcIdTokenDecoderFactoryTests {
@Test
public void createDecoderWhenJwsAlgorithmEcAndJwkSetUriEmptyThenThrowOAuth2AuthenticationException() {
this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> SignatureAlgorithm.ES256);
assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.jwkSetUri(null).build()))
.isInstanceOf(OAuth2AuthenticationException.class)
.hasMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.jwkSetUri(null).build()))
.withMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
+ "for Client Registration: 'registration-id'. "
+ "Check to ensure you have configured the JwkSet URI.");
}
@ -120,9 +118,10 @@ public class ReactiveOidcIdTokenDecoderFactoryTests {
@Test
public void createDecoderWhenJwsAlgorithmHmacAndClientSecretNullThenThrowOAuth2AuthenticationException() {
this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> MacAlgorithm.HS256);
assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.clientSecret(null).build()))
.isInstanceOf(OAuth2AuthenticationException.class)
.hasMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.idTokenDecoderFactory.createDecoder(this.registration.clientSecret(null).build()))
.withMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
+ "for Client Registration: 'registration-id'. "
+ "Check to ensure you have configured the client secret.");
}
@ -130,9 +129,9 @@ public class ReactiveOidcIdTokenDecoderFactoryTests {
@Test
public void createDecoderWhenJwsAlgorithmNullThenThrowOAuth2AuthenticationException() {
this.idTokenDecoderFactory.setJwsAlgorithmResolver((clientRegistration) -> null);
assertThatThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.build()))
.isInstanceOf(OAuth2AuthenticationException.class)
.hasMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.idTokenDecoderFactory.createDecoder(this.registration.build()))
.withMessage("[missing_signature_verifier] Failed to find a Signature Verifier "
+ "for Client Registration: 'registration-id'. "
+ "Check to ensure you have configured a valid JWS Algorithm: 'null'");
}

View File

@ -53,8 +53,8 @@ import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2UserAuthority;
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.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.BDDMockito.given;
@ -97,8 +97,7 @@ public class OidcReactiveOAuth2UserServiceTests {
@Test
public void setClaimTypeConverterFactoryWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.userService.setClaimTypeConverterFactory(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.userService.setClaimTypeConverterFactory(null));
}
@Test
@ -120,8 +119,8 @@ public class OidcReactiveOAuth2UserServiceTests {
OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"),
Collections.singletonMap("user", "rob"), "user");
given(this.oauth2UserService.loadUser(any())).willReturn(Mono.just(oauth2User));
assertThatCode(() -> this.userService.loadUser(userRequest()).block())
.isInstanceOf(OAuth2AuthenticationException.class);
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.userService.loadUser(userRequest()).block());
}
@Test
@ -132,8 +131,8 @@ public class OidcReactiveOAuth2UserServiceTests {
OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), attributes,
"user");
given(this.oauth2UserService.loadUser(any())).willReturn(Mono.just(oauth2User));
assertThatCode(() -> this.userService.loadUser(userRequest()).block())
.isInstanceOf(OAuth2AuthenticationException.class);
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.userService.loadUser(userRequest()).block());
}
@Test

View File

@ -32,7 +32,7 @@ import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.TestOidcIdTokens;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link OidcUserRequest}.
@ -62,20 +62,20 @@ public class OidcUserRequestTests {
@Test
public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OidcUserRequest(null, this.accessToken, this.idToken))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> new OidcUserRequest(null, this.accessToken, this.idToken));
}
@Test
public void constructorWhenAccessTokenIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OidcUserRequest(this.clientRegistration, null, this.idToken))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> new OidcUserRequest(this.clientRegistration, null, this.idToken));
}
@Test
public void constructorWhenIdTokenIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> new OidcUserRequest(this.clientRegistration, this.accessToken, null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> new OidcUserRequest(this.clientRegistration, this.accessToken, null));
}
@Test

View File

@ -56,7 +56,7 @@ import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority;
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.hamcrest.CoreMatchers.containsString;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.BDDMockito.given;
@ -113,20 +113,17 @@ public class OidcUserServiceTests {
@Test
public void setOauth2UserServiceWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.userService.setOauth2UserService(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.userService.setOauth2UserService(null));
}
@Test
public void setClaimTypeConverterFactoryWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.userService.setClaimTypeConverterFactory(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.userService.setClaimTypeConverterFactory(null));
}
@Test
public void setAccessibleScopesWhenNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> this.userService.setAccessibleScopes(null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.userService.setAccessibleScopes(null));
}
@Test

View File

@ -40,7 +40,7 @@ import org.springframework.security.oauth2.core.oidc.user.TestOidcUsers;
import org.springframework.security.oauth2.core.user.TestOAuth2Users;
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.mockito.Mockito.mock;
/**
@ -137,14 +137,12 @@ public class OidcClientInitiatedLogoutSuccessHandlerTests {
@Test
public void setPostLogoutRedirectUriWhenGivenNullThenThrowsException() {
assertThatThrownBy(() -> this.handler.setPostLogoutRedirectUri((URI) null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setPostLogoutRedirectUri((URI) null));
}
@Test
public void setPostLogoutRedirectUriTemplateWhenGivenNullThenThrowsException() {
assertThatThrownBy(() -> this.handler.setPostLogoutRedirectUri((String) null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setPostLogoutRedirectUri((String) null));
}
}

View File

@ -42,7 +42,7 @@ import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilterChain;
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.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ -149,14 +149,12 @@ public class OidcClientInitiatedServerLogoutSuccessHandlerTests {
@Test
public void setPostLogoutRedirectUriWhenGivenNullThenThrowsException() {
assertThatThrownBy(() -> this.handler.setPostLogoutRedirectUri((URI) null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setPostLogoutRedirectUri((URI) null));
}
@Test
public void setPostLogoutRedirectUriTemplateWhenGivenNullThenThrowsException() {
assertThatThrownBy(() -> this.handler.setPostLogoutRedirectUri((String) null))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setPostLogoutRedirectUri((String) null));
}
private String redirectedUrl(ServerWebExchange exchange) {

View File

@ -30,7 +30,7 @@ import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link ClientRegistration}.
@ -364,18 +364,17 @@ public class ClientRegistrationTests {
@Test
public void buildWhenClientCredentialsGrantRegistrationIdIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> ClientRegistration.withRegistrationId(null).clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET).clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).tokenUri(TOKEN_URI).build())
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> ClientRegistration.withRegistrationId(null).clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET).clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).tokenUri(TOKEN_URI).build());
}
@Test
public void buildWhenClientCredentialsGrantClientIdIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> ClientRegistration.withRegistrationId(REGISTRATION_ID).clientId(null)
.clientSecret(CLIENT_SECRET).clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).tokenUri(TOKEN_URI).build())
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(null).clientSecret(CLIENT_SECRET).clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).tokenUri(TOKEN_URI).build());
}
@Test
@ -396,23 +395,23 @@ public class ClientRegistrationTests {
@Test
public void buildWhenClientCredentialsGrantTokenUriIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> ClientRegistration.withRegistrationId(REGISTRATION_ID).clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET).clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).tokenUri(null).build())
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> ClientRegistration.withRegistrationId(REGISTRATION_ID).clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET).clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).tokenUri(null).build());
}
// gh-6256
@Test
public void buildWhenScopesContainASpaceThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> TestClientRegistrations.clientCredentials().scope("openid profile email").build())
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> TestClientRegistrations.clientCredentials().scope("openid profile email").build());
}
@Test
public void buildWhenScopesContainAnInvalidCharacterThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> TestClientRegistrations.clientCredentials().scope("an\"invalid\"scope").build())
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> TestClientRegistrations.clientCredentials().scope("an\"invalid\"scope").build());
}
@Test
@ -433,18 +432,17 @@ public class ClientRegistrationTests {
@Test
public void buildWhenPasswordGrantRegistrationIdIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> ClientRegistration.withRegistrationId(null).clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET).clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
.authorizationGrantType(AuthorizationGrantType.PASSWORD).tokenUri(TOKEN_URI).build())
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> ClientRegistration.withRegistrationId(null).clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET).clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
.authorizationGrantType(AuthorizationGrantType.PASSWORD).tokenUri(TOKEN_URI).build());
}
@Test
public void buildWhenPasswordGrantClientIdIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> ClientRegistration.withRegistrationId(REGISTRATION_ID).clientId(null)
.clientSecret(CLIENT_SECRET).clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
.authorizationGrantType(AuthorizationGrantType.PASSWORD).tokenUri(TOKEN_URI).build())
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(null).clientSecret(CLIENT_SECRET).clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
.authorizationGrantType(AuthorizationGrantType.PASSWORD).tokenUri(TOKEN_URI).build());
}
@Test
@ -465,10 +463,10 @@ public class ClientRegistrationTests {
@Test
public void buildWhenPasswordGrantTokenUriIsNullThenThrowIllegalArgumentException() {
assertThatThrownBy(() -> ClientRegistration.withRegistrationId(REGISTRATION_ID).clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET).clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
.authorizationGrantType(AuthorizationGrantType.PASSWORD).tokenUri(null).build())
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> ClientRegistration.withRegistrationId(REGISTRATION_ID).clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET).clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
.authorizationGrantType(AuthorizationGrantType.PASSWORD).tokenUri(null).build());
}
@Test

View File

@ -35,7 +35,8 @@ import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
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
@ -142,17 +143,16 @@ public class ClientRegistrationsTests {
@Test
public void issuerWhenResponseMissingJwksUriThenThrowsIllegalArgumentException() throws Exception {
this.response.remove("jwks_uri");
assertThatThrownBy(() -> registration("").build()).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("The public JWK set URI must not be null");
assertThatIllegalArgumentException().isThrownBy(() -> registration("").build())
.withMessageContaining("The public JWK set URI must not be null");
}
// gh-7512
@Test
public void issuerWhenOidcFallbackResponseMissingJwksUriThenThrowsIllegalArgumentException() throws Exception {
this.response.remove("jwks_uri");
assertThatThrownBy(() -> registrationOidcFallback("issuer1", null).build())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("The public JWK set URI must not be null");
assertThatIllegalArgumentException().isThrownBy(() -> registrationOidcFallback("issuer1", null).build())
.withMessageContaining("The public JWK set URI must not be null");
}
// gh-7512
@ -239,16 +239,16 @@ public class ClientRegistrationsTests {
@Test
public void issuerWhenGrantTypesSupportedInvalidThenException() {
this.response.put("grant_types_supported", Arrays.asList("implicit"));
assertThatThrownBy(() -> registration("")).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Only AuthorizationGrantType.AUTHORIZATION_CODE is supported. The issuer \""
assertThatIllegalArgumentException().isThrownBy(() -> registration(""))
.withMessageContaining("Only AuthorizationGrantType.AUTHORIZATION_CODE is supported. The issuer \""
+ this.issuer + "\" returned a configuration of [implicit]");
}
@Test
public void issuerWhenOAuth2GrantTypesSupportedInvalidThenException() {
this.response.put("grant_types_supported", Arrays.asList("implicit"));
assertThatThrownBy(() -> registrationOAuth2("", null)).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Only AuthorizationGrantType.AUTHORIZATION_CODE is supported. The issuer \""
assertThatIllegalArgumentException().isThrownBy(() -> registrationOAuth2("", null))
.withMessageContaining("Only AuthorizationGrantType.AUTHORIZATION_CODE is supported. The issuer \""
+ this.issuer + "\" returned a configuration of [implicit]");
}
@ -301,30 +301,31 @@ public class ClientRegistrationsTests {
@Test
public void issuerWhenTokenEndpointAuthMethodsInvalidThenException() {
this.response.put("token_endpoint_auth_methods_supported", Arrays.asList("tls_client_auth"));
assertThatThrownBy(() -> registration("")).isInstanceOf(IllegalArgumentException.class).hasMessageContaining(
"Only ClientAuthenticationMethod.BASIC, ClientAuthenticationMethod.POST and ClientAuthenticationMethod.NONE are supported. The issuer \""
+ this.issuer + "\" returned a configuration of [tls_client_auth]");
assertThatIllegalArgumentException().isThrownBy(() -> registration(""))
.withMessageContaining("Only ClientAuthenticationMethod.BASIC, ClientAuthenticationMethod.POST and "
+ "ClientAuthenticationMethod.NONE are supported. The issuer \"" + this.issuer
+ "\" returned a configuration of [tls_client_auth]");
}
@Test
public void issuerWhenOAuth2TokenEndpointAuthMethodsInvalidThenException() {
this.response.put("token_endpoint_auth_methods_supported", Arrays.asList("tls_client_auth"));
assertThatThrownBy(() -> registrationOAuth2("", null)).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining(
"Only ClientAuthenticationMethod.BASIC, ClientAuthenticationMethod.POST and ClientAuthenticationMethod.NONE are supported. The issuer \""
+ this.issuer + "\" returned a configuration of [tls_client_auth]");
assertThatIllegalArgumentException().isThrownBy(() -> registrationOAuth2("", null))
.withMessageContaining("Only ClientAuthenticationMethod.BASIC, ClientAuthenticationMethod.POST and "
+ "ClientAuthenticationMethod.NONE are supported. The issuer \"" + this.issuer
+ "\" returned a configuration of [tls_client_auth]");
}
@Test
public void issuerWhenOAuth2EmptyStringThenMeaningfulErrorMessage() {
assertThatThrownBy(() -> ClientRegistrations.fromIssuerLocation(""))
.hasMessageContaining("issuer cannot be empty");
assertThatIllegalArgumentException().isThrownBy(() -> ClientRegistrations.fromIssuerLocation(""))
.withMessageContaining("issuer cannot be empty");
}
@Test
public void issuerWhenEmptyStringThenMeaningfulErrorMessage() {
assertThatThrownBy(() -> ClientRegistrations.fromOidcIssuerLocation(""))
.hasMessageContaining("issuer cannot be empty");
assertThatIllegalArgumentException().isThrownBy(() -> ClientRegistrations.fromOidcIssuerLocation(""))
.withMessageContaining("issuer cannot be empty");
}
@Test
@ -334,9 +335,9 @@ public class ClientRegistrationsTests {
MockResponse mockResponse = new MockResponse().setBody(body).setHeader(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_JSON_VALUE);
this.server.enqueue(mockResponse);
assertThatThrownBy(() -> ClientRegistrations.fromOidcIssuerLocation(this.issuer)).hasMessageContaining(
"The Issuer \"https://example.com\" provided in the configuration metadata did not match the requested issuer \""
+ this.issuer + "\"");
assertThatIllegalStateException().isThrownBy(() -> ClientRegistrations.fromOidcIssuerLocation(this.issuer))
.withMessageContaining("The Issuer \"https://example.com\" provided in the configuration metadata did "
+ "not match the requested issuer \"" + this.issuer + "\"");
}
@Test
@ -346,9 +347,9 @@ public class ClientRegistrationsTests {
MockResponse mockResponse = new MockResponse().setBody(body).setHeader(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_JSON_VALUE);
this.server.enqueue(mockResponse);
assertThatThrownBy(() -> ClientRegistrations.fromIssuerLocation(this.issuer)).hasMessageContaining(
"The Issuer \"https://example.com\" provided in the configuration metadata did not match the requested issuer \""
+ this.issuer + "\"");
assertThatIllegalStateException().isThrownBy(() -> ClientRegistrations.fromIssuerLocation(this.issuer))
.withMessageContaining("The Issuer \"https://example.com\" provided in the configuration metadata "
+ "did not match the requested issuer \"" + this.issuer + "\"");
}
private ClientRegistration.Builder registration(String path) throws Exception {

View File

@ -24,7 +24,7 @@ import org.junit.Test;
import reactor.test.StepVerifier;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author Rob Winch
@ -43,22 +43,21 @@ public class InMemoryReactiveClientRegistrationRepositoryTests {
@Test
public void constructorWhenZeroVarArgsThenIllegalArgumentException() {
assertThatThrownBy(() -> new InMemoryReactiveClientRegistrationRepository())
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException().isThrownBy(() -> new InMemoryReactiveClientRegistrationRepository());
}
@Test
public void constructorWhenClientRegistrationArrayThenIllegalArgumentException() {
ClientRegistration[] registrations = null;
assertThatThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registrations))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registrations));
}
@Test
public void constructorWhenClientRegistrationListThenIllegalArgumentException() {
List<ClientRegistration> registrations = null;
assertThatThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registrations))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registrations));
}
@Test(expected = IllegalStateException.class)
@ -70,8 +69,8 @@ public class InMemoryReactiveClientRegistrationRepositoryTests {
@Test
public void constructorWhenClientRegistrationIsNullThenIllegalArgumentException() {
ClientRegistration registration = null;
assertThatThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registration))
.isInstanceOf(IllegalArgumentException.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registration));
}
@Test

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