1
0
mirror of synced 2026-08-05 09:47:05 +00:00

Replace ExpectedException @Rules with AssertJ

Replace JUnit ExpectedException @Rules with AssertJ calls.
This commit is contained in:
Phillip Webb
2020-09-10 18:40:27 -07:00
committed by Josh Cummings
parent 910b81928f
commit 20baa7d409
24 changed files with 383 additions and 543 deletions
@@ -25,9 +25,7 @@ import java.util.Map;
import java.util.Set;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.ArgumentCaptor;
import org.mockito.stubbing.Answer;
@@ -52,7 +50,8 @@ import org.springframework.security.oauth2.core.endpoint.TestOAuth2Authorization
import org.springframework.security.oauth2.core.user.OAuth2User;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.containsString;
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;
@@ -79,9 +78,6 @@ public class OAuth2LoginAuthenticationProviderTests {
private OAuth2LoginAuthenticationProvider authenticationProvider;
@Rule
public ExpectedException exception = ExpectedException.none();
@Before
@SuppressWarnings("unchecked")
public void setUp() {
@@ -98,20 +94,19 @@ public class OAuth2LoginAuthenticationProviderTests {
@Test
public void constructorWhenAccessTokenResponseClientIsNullThenThrowIllegalArgumentException() {
this.exception.expect(IllegalArgumentException.class);
new OAuth2LoginAuthenticationProvider(null, this.userService);
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2LoginAuthenticationProvider(null, this.userService));
}
@Test
public void constructorWhenUserServiceIsNullThenThrowIllegalArgumentException() {
this.exception.expect(IllegalArgumentException.class);
new OAuth2LoginAuthenticationProvider(this.accessTokenResponseClient, null);
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2LoginAuthenticationProvider(this.accessTokenResponseClient, null));
}
@Test
public void setAuthoritiesMapperWhenAuthoritiesMapperIsNullThenThrowIllegalArgumentException() {
this.exception.expect(IllegalArgumentException.class);
this.authenticationProvider.setAuthoritiesMapper(null);
assertThatIllegalArgumentException().isThrownBy(() -> this.authenticationProvider.setAuthoritiesMapper(null));
}
@Test
@@ -132,26 +127,26 @@ public class OAuth2LoginAuthenticationProviderTests {
@Test
public void authenticateWhenAuthorizationErrorResponseThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString(OAuth2ErrorCodes.INVALID_REQUEST));
OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.error()
.errorCode(OAuth2ErrorCodes.INVALID_REQUEST).build();
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
authorizationResponse);
this.authenticationProvider
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(
new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange)))
.withMessageContaining(OAuth2ErrorCodes.INVALID_REQUEST);
}
@Test
public void authenticateWhenAuthorizationResponseStateNotEqualAuthorizationRequestStateThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString("invalid_state_parameter"));
OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.success().state("67890")
.build();
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
authorizationResponse);
this.authenticationProvider
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(
new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange)))
.withMessageContaining("invalid_state_parameter");
}
@Test
@@ -21,9 +21,7 @@ import java.time.Instant;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
@@ -40,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.hamcrest.CoreMatchers.containsString;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link NimbusAuthorizationCodeTokenResponseClient}.
@@ -59,9 +58,6 @@ public class NimbusAuthorizationCodeTokenResponseClientTests {
private NimbusAuthorizationCodeTokenResponseClient tokenResponseClient = new NimbusAuthorizationCodeTokenResponseClient();
@Rule
public ExpectedException exception = ExpectedException.none();
@Before
public void setUp() {
this.clientRegistrationBuilder = TestClientRegistrations.clientRegistration()
@@ -109,29 +105,27 @@ public class NimbusAuthorizationCodeTokenResponseClientTests {
@Test
public void getTokenResponseWhenRedirectUriMalformedThenThrowIllegalArgumentException() {
this.exception.expect(IllegalArgumentException.class);
String redirectUri = "http:\\example.com";
OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request()
.redirectUri(redirectUri).build();
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest,
this.authorizationResponse);
this.tokenResponseClient.getTokenResponse(
new OAuth2AuthorizationCodeGrantRequest(this.clientRegistrationBuilder.build(), authorizationExchange));
assertThatIllegalArgumentException()
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
this.clientRegistrationBuilder.build(), authorizationExchange)));
}
@Test
public void getTokenResponseWhenTokenUriMalformedThenThrowIllegalArgumentException() {
this.exception.expect(IllegalArgumentException.class);
String tokenUri = "http:\\provider.com\\oauth2\\token";
this.clientRegistrationBuilder.tokenUri(tokenUri);
this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
this.clientRegistrationBuilder.build(), this.authorizationExchange));
assertThatIllegalArgumentException()
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
this.clientRegistrationBuilder.build(), this.authorizationExchange)));
}
@Test
public void getTokenResponseWhenSuccessResponseInvalidThenThrowOAuth2AuthorizationException() throws Exception {
this.exception.expect(OAuth2AuthorizationException.class);
this.exception.expectMessage(containsString("invalid_token_response"));
MockWebServer server = new MockWebServer();
// @formatter:off
String accessTokenSuccessResponse = "{\n"
@@ -149,8 +143,10 @@ public class NimbusAuthorizationCodeTokenResponseClientTests {
String tokenUri = server.url("/oauth2/token").toString();
this.clientRegistrationBuilder.tokenUri(tokenUri);
try {
this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
this.clientRegistrationBuilder.build(), this.authorizationExchange));
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
this.clientRegistrationBuilder.build(), this.authorizationExchange)))
.withMessageContaining("invalid_token_response");
}
finally {
server.shutdown();
@@ -159,17 +155,15 @@ public class NimbusAuthorizationCodeTokenResponseClientTests {
@Test
public void getTokenResponseWhenTokenUriInvalidThenThrowOAuth2AuthorizationException() {
this.exception.expect(OAuth2AuthorizationException.class);
String tokenUri = "https://invalid-provider.com/oauth2/token";
this.clientRegistrationBuilder.tokenUri(tokenUri);
this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
this.clientRegistrationBuilder.build(), this.authorizationExchange));
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
this.clientRegistrationBuilder.build(), this.authorizationExchange)));
}
@Test
public void getTokenResponseWhenErrorResponseThenThrowOAuth2AuthorizationException() throws Exception {
this.exception.expect(OAuth2AuthorizationException.class);
this.exception.expectMessage(containsString("unauthorized_client"));
MockWebServer server = new MockWebServer();
// @formatter:off
String accessTokenErrorResponse = "{\n"
@@ -182,8 +176,10 @@ public class NimbusAuthorizationCodeTokenResponseClientTests {
String tokenUri = server.url("/oauth2/token").toString();
this.clientRegistrationBuilder.tokenUri(tokenUri);
try {
this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
this.clientRegistrationBuilder.build(), this.authorizationExchange));
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
this.clientRegistrationBuilder.build(), this.authorizationExchange)))
.withMessageContaining("unauthorized_client");
}
finally {
server.shutdown();
@@ -193,16 +189,16 @@ public class NimbusAuthorizationCodeTokenResponseClientTests {
// gh-5594
@Test
public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationException() throws Exception {
this.exception.expect(OAuth2AuthorizationException.class);
this.exception.expectMessage(containsString("server_error"));
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse().setResponseCode(500));
server.start();
String tokenUri = server.url("/oauth2/token").toString();
this.clientRegistrationBuilder.tokenUri(tokenUri);
try {
this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
this.clientRegistrationBuilder.build(), this.authorizationExchange));
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
this.clientRegistrationBuilder.build(), this.authorizationExchange)))
.withMessageContaining("server_error");
}
finally {
server.shutdown();
@@ -212,8 +208,6 @@ public class NimbusAuthorizationCodeTokenResponseClientTests {
@Test
public void getTokenResponseWhenSuccessResponseAndNotBearerTokenTypeThenThrowOAuth2AuthorizationException()
throws Exception {
this.exception.expect(OAuth2AuthorizationException.class);
this.exception.expectMessage(containsString("invalid_token_response"));
MockWebServer server = new MockWebServer();
// @formatter:off
String accessTokenSuccessResponse = "{\n"
@@ -228,8 +222,10 @@ public class NimbusAuthorizationCodeTokenResponseClientTests {
String tokenUri = server.url("/oauth2/token").toString();
this.clientRegistrationBuilder.tokenUri(tokenUri);
try {
this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
this.clientRegistrationBuilder.build(), this.authorizationExchange));
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(
this.clientRegistrationBuilder.build(), this.authorizationExchange)))
.withMessageContaining("invalid_token_response");
}
finally {
server.shutdown();
@@ -28,9 +28,7 @@ import java.util.Map;
import java.util.Set;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.ArgumentCaptor;
import org.mockito.stubbing.Answer;
@@ -64,7 +62,8 @@ import org.springframework.security.oauth2.jwt.JwtException;
import org.springframework.security.oauth2.jwt.TestJwts;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.containsString;
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.ArgumentMatchers.anyString;
@@ -100,9 +99,6 @@ public class OidcAuthorizationCodeAuthenticationProviderTests {
private String nonceHash;
@Rule
public ExpectedException exception = ExpectedException.none();
@Before
@SuppressWarnings("unchecked")
public void setUp() {
@@ -138,26 +134,24 @@ public class OidcAuthorizationCodeAuthenticationProviderTests {
@Test
public void constructorWhenAccessTokenResponseClientIsNullThenThrowIllegalArgumentException() {
this.exception.expect(IllegalArgumentException.class);
new OidcAuthorizationCodeAuthenticationProvider(null, this.userService);
assertThatIllegalArgumentException()
.isThrownBy(() -> new OidcAuthorizationCodeAuthenticationProvider(null, this.userService));
}
@Test
public void constructorWhenUserServiceIsNullThenThrowIllegalArgumentException() {
this.exception.expect(IllegalArgumentException.class);
new OidcAuthorizationCodeAuthenticationProvider(this.accessTokenResponseClient, null);
assertThatIllegalArgumentException().isThrownBy(
() -> new OidcAuthorizationCodeAuthenticationProvider(this.accessTokenResponseClient, null));
}
@Test
public void setJwtDecoderFactoryWhenNullThenThrowIllegalArgumentException() {
this.exception.expect(IllegalArgumentException.class);
this.authenticationProvider.setJwtDecoderFactory(null);
assertThatIllegalArgumentException().isThrownBy(() -> this.authenticationProvider.setJwtDecoderFactory(null));
}
@Test
public void setAuthoritiesMapperWhenAuthoritiesMapperIsNullThenThrowIllegalArgumentException() {
this.exception.expect(IllegalArgumentException.class);
this.authenticationProvider.setAuthoritiesMapper(null);
assertThatIllegalArgumentException().isThrownBy(() -> this.authenticationProvider.setAuthoritiesMapper(null));
}
@Test
@@ -181,8 +175,6 @@ public class OidcAuthorizationCodeAuthenticationProviderTests {
@Test
public void authenticateWhenAuthorizationErrorResponseThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString(OAuth2ErrorCodes.INVALID_SCOPE));
// @formatter:off
OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.error()
.errorCode(OAuth2ErrorCodes.INVALID_SCOPE)
@@ -190,14 +182,14 @@ public class OidcAuthorizationCodeAuthenticationProviderTests {
// @formatter:on
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
authorizationResponse);
this.authenticationProvider
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(
new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange)))
.withMessageContaining(OAuth2ErrorCodes.INVALID_SCOPE);
}
@Test
public void authenticateWhenAuthorizationResponseStateNotEqualAuthorizationRequestStateThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString("invalid_state_parameter"));
// @formatter:off
OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.success()
.state("89012")
@@ -205,14 +197,14 @@ public class OidcAuthorizationCodeAuthenticationProviderTests {
// @formatter:on
OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest,
authorizationResponse);
this.authenticationProvider
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(
new OAuth2LoginAuthenticationToken(this.clientRegistration, authorizationExchange)))
.withMessageContaining("invalid_state_parameter");
}
@Test
public void authenticateWhenTokenResponseDoesNotContainIdTokenThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString("invalid_id_token"));
// @formatter:off
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse
.withResponse(this.accessTokenSuccessResponse())
@@ -220,38 +212,38 @@ public class OidcAuthorizationCodeAuthenticationProviderTests {
.build();
// @formatter:on
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
this.authenticationProvider
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(
new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange)))
.withMessageContaining("invalid_id_token");
}
@Test
public void authenticateWhenJwkSetUriNotSetThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString("missing_signature_verifier"));
// @formatter:off
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
.jwkSetUri(null)
.build();
// @formatter:on
this.authenticationProvider
.authenticate(new OAuth2LoginAuthenticationToken(clientRegistration, this.authorizationExchange));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(
new OAuth2LoginAuthenticationToken(clientRegistration, this.authorizationExchange)))
.withMessageContaining("missing_signature_verifier");
}
@Test
public void authenticateWhenIdTokenValidationErrorThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString("[invalid_id_token] ID Token Validation Error"));
JwtDecoder jwtDecoder = mock(JwtDecoder.class);
given(jwtDecoder.decode(anyString())).willThrow(new JwtException("ID Token Validation Error"));
this.authenticationProvider.setJwtDecoderFactory((registration) -> jwtDecoder);
this.authenticationProvider
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(
new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange)))
.withMessageContaining("[invalid_id_token] ID Token Validation Error");
}
@Test
public void authenticateWhenIdTokenInvalidNonceThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString("[invalid_nonce]"));
Map<String, Object> claims = new HashMap<>();
claims.put(IdTokenClaimNames.ISS, "https://provider.com");
claims.put(IdTokenClaimNames.SUB, "subject1");
@@ -259,8 +251,10 @@ public class OidcAuthorizationCodeAuthenticationProviderTests {
claims.put(IdTokenClaimNames.AZP, "client1");
claims.put(IdTokenClaimNames.NONCE, "invalid-nonce-hash");
this.setUpIdToken(claims);
this.authenticationProvider
.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.authenticationProvider.authenticate(
new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange)))
.withMessageContaining("[invalid_nonce]");
}
@Test
@@ -29,9 +29,7 @@ import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
@@ -56,8 +54,8 @@ 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.assertThatExceptionOfType;
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;
import static org.mockito.Mockito.mock;
@@ -80,9 +78,6 @@ public class OidcUserServiceTests {
private MockWebServer server;
@Rule
public ExpectedException exception = ExpectedException.none();
@Before
public void setup() throws Exception {
this.server = new MockWebServer();
@@ -133,8 +128,7 @@ public class OidcUserServiceTests {
@Test
public void loadUserWhenUserRequestIsNullThenThrowIllegalArgumentException() {
this.exception.expect(IllegalArgumentException.class);
this.userService.loadUser(null);
assertThatIllegalArgumentException().isThrownBy(() -> this.userService.loadUser(null));
}
@Test
@@ -260,8 +254,6 @@ public class OidcUserServiceTests {
// gh-5447
@Test
public void loadUserWhenUserInfoSuccessResponseAndUserInfoSubjectIsNullThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString("invalid_user_info_response"));
// @formatter:off
String userInfoResponse = "{\n"
+ " \"email\": \"full_name@provider.com\",\n"
@@ -272,25 +264,26 @@ public class OidcUserServiceTests {
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userNameAttributeName(StandardClaimNames.EMAIL).build();
this.userService.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.userService
.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken)))
.withMessageContaining("invalid_user_info_response");
}
@Test
public void loadUserWhenUserInfoSuccessResponseAndUserInfoSubjectNotSameAsIdTokenSubjectThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString("invalid_user_info_response"));
String userInfoResponse = "{\n" + " \"sub\": \"other-subject\"\n" + "}\n";
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri).build();
this.userService.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.userService
.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken)))
.withMessageContaining("invalid_user_info_response");
}
@Test
public void loadUserWhenUserInfoSuccessResponseInvalidThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource"));
// @formatter:off
String userInfoResponse = "{\n"
+ " \"sub\": \"subject1\",\n"
@@ -304,28 +297,34 @@ public class OidcUserServiceTests {
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri).build();
this.userService.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.userService
.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource");
}
@Test
public void loadUserWhenServerErrorThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource: 500 Server Error"));
this.server.enqueue(new MockResponse().setResponseCode(500));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri).build();
this.userService.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.userService
.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource: 500 Server Error");
}
@Test
public void loadUserWhenUserInfoUriInvalidThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource"));
String userInfoUri = "https://invalid-provider.com/user";
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri).build();
this.userService.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.userService
.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource");
}
@Test
@@ -26,9 +26,7 @@ import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
@@ -43,7 +41,8 @@ import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.user.OAuth2User;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.containsString;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link CustomUserTypesOAuth2UserService}.
@@ -61,9 +60,6 @@ public class CustomUserTypesOAuth2UserServiceTests {
private MockWebServer server;
@Rule
public ExpectedException exception = ExpectedException.none();
@Before
public void setUp() throws Exception {
this.server = new MockWebServer();
@@ -86,32 +82,28 @@ public class CustomUserTypesOAuth2UserServiceTests {
@Test
public void constructorWhenCustomUserTypesIsNullThenThrowIllegalArgumentException() {
this.exception.expect(IllegalArgumentException.class);
new CustomUserTypesOAuth2UserService(null);
assertThatIllegalArgumentException().isThrownBy(() -> new CustomUserTypesOAuth2UserService(null));
}
@Test
public void constructorWhenCustomUserTypesIsEmptyThenThrowIllegalArgumentException() {
this.exception.expect(IllegalArgumentException.class);
new CustomUserTypesOAuth2UserService(Collections.emptyMap());
assertThatIllegalArgumentException()
.isThrownBy(() -> new CustomUserTypesOAuth2UserService(Collections.emptyMap()));
}
@Test
public void setRequestEntityConverterWhenNullThenThrowIllegalArgumentException() {
this.exception.expect(IllegalArgumentException.class);
this.userService.setRequestEntityConverter(null);
assertThatIllegalArgumentException().isThrownBy(() -> this.userService.setRequestEntityConverter(null));
}
@Test
public void setRestOperationsWhenNullThenThrowIllegalArgumentException() {
this.exception.expect(IllegalArgumentException.class);
this.userService.setRestOperations(null);
assertThatIllegalArgumentException().isThrownBy(() -> this.userService.setRestOperations(null));
}
@Test
public void loadUserWhenUserRequestIsNullThenThrowIllegalArgumentException() {
this.exception.expect(IllegalArgumentException.class);
this.userService.loadUser(null);
assertThatIllegalArgumentException().isThrownBy(() -> this.userService.loadUser(null));
}
@Test
@@ -151,9 +143,6 @@ public class CustomUserTypesOAuth2UserServiceTests {
@Test
public void loadUserWhenUserInfoSuccessResponseInvalidThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource"));
// @formatter:off
String userInfoResponse = "{\n"
+ " \"id\": \"12345\",\n"
@@ -166,28 +155,34 @@ public class CustomUserTypesOAuth2UserServiceTests {
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri).build();
this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource");
}
@Test
public void loadUserWhenServerErrorThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource: 500 Server Error"));
this.server.enqueue(new MockResponse().setResponseCode(500));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri).build();
this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource: 500 Server Error");
}
@Test
public void loadUserWhenUserInfoUriInvalidThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource"));
String userInfoUri = "https://invalid-provider.com/user";
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri).build();
this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource");
}
private ClientRegistration.Builder withRegistrationId(String registrationId) {
@@ -26,9 +26,7 @@ import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.convert.converter.Converter;
@@ -51,7 +49,8 @@ import org.springframework.security.oauth2.core.user.OAuth2UserAuthority;
import org.springframework.web.client.RestOperations;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.containsString;
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.nullable;
import static org.mockito.BDDMockito.given;
@@ -73,9 +72,6 @@ public class DefaultOAuth2UserServiceTests {
private MockWebServer server;
@Rule
public ExpectedException exception = ExpectedException.none();
@Before
public void setup() throws Exception {
this.server = new MockWebServer();
@@ -95,40 +91,39 @@ public class DefaultOAuth2UserServiceTests {
@Test
public void setRequestEntityConverterWhenNullThenThrowIllegalArgumentException() {
this.exception.expect(IllegalArgumentException.class);
this.userService.setRequestEntityConverter(null);
assertThatIllegalArgumentException().isThrownBy(() -> this.userService.setRequestEntityConverter(null));
}
@Test
public void setRestOperationsWhenNullThenThrowIllegalArgumentException() {
this.exception.expect(IllegalArgumentException.class);
this.userService.setRestOperations(null);
assertThatIllegalArgumentException().isThrownBy(() -> this.userService.setRestOperations(null));
}
@Test
public void loadUserWhenUserRequestIsNullThenThrowIllegalArgumentException() {
this.exception.expect(IllegalArgumentException.class);
this.userService.loadUser(null);
assertThatIllegalArgumentException().isThrownBy(() -> this.userService.loadUser(null));
}
@Test
public void loadUserWhenUserInfoUriIsNullThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString("missing_user_info_uri"));
ClientRegistration clientRegistration = this.clientRegistrationBuilder.build();
this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining("missing_user_info_uri");
}
@Test
public void loadUserWhenUserNameAttributeNameIsNullThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString("missing_user_name_attribute"));
// @formatter:off
ClientRegistration clientRegistration = this.clientRegistrationBuilder
.userInfoUri("https://provider.com/user")
.build();
// @formatter:on
this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining("missing_user_name_attribute");
}
@Test
@@ -165,9 +160,6 @@ public class DefaultOAuth2UserServiceTests {
@Test
public void loadUserWhenUserInfoSuccessResponseInvalidThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource"));
// @formatter:off
String userInfoResponse = "{\n"
+ " \"user-name\": \"user1\",\n"
@@ -182,16 +174,15 @@ public class DefaultOAuth2UserServiceTests {
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource");
}
@Test
public void loadUserWhenUserInfoErrorResponseWwwAuthenticateHeaderThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource"));
this.exception.expectMessage(
containsString("Error Code: insufficient_scope, Error Description: The access token expired"));
String wwwAuthenticateHeader = "Bearer realm=\"auth-realm\" error=\"insufficient_scope\" error_description=\"The access token expired\"";
MockResponse response = new MockResponse();
response.setHeader(HttpHeaders.WWW_AUTHENTICATE, wwwAuthenticateHeader);
@@ -200,15 +191,16 @@ public class DefaultOAuth2UserServiceTests {
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource")
.withMessageContaining("Error Code: insufficient_scope, Error Description: The access token expired");
}
@Test
public void loadUserWhenUserInfoErrorResponseThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource"));
this.exception.expectMessage(containsString("Error Code: invalid_token"));
// @formatter:off
String userInfoErrorResponse = "{\n"
+ " \"error\": \"invalid_token\"\n"
@@ -218,30 +210,37 @@ public class DefaultOAuth2UserServiceTests {
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource")
.withMessageContaining("Error Code: invalid_token");
}
@Test
public void loadUserWhenServerErrorThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource: 500 Server Error"));
this.server.enqueue(new MockResponse().setResponseCode(500));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource: 500 Server Error");
}
@Test
public void loadUserWhenUserInfoUriInvalidThenThrowOAuth2AuthenticationException() {
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource"));
String userInfoUri = "https://invalid-provider.com/user";
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource");
}
// gh-5294
@@ -348,17 +347,18 @@ public class DefaultOAuth2UserServiceTests {
@Test
public void loadUserWhenUserInfoSuccessResponseInvalidContentTypeThenThrowOAuth2AuthenticationException() {
String userInfoUri = this.server.url("/user").toString();
this.exception.expect(OAuth2AuthenticationException.class);
this.exception.expectMessage(containsString(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource "
+ "from '" + userInfoUri + "': response contains invalid content type 'text/plain'."));
MockResponse response = new MockResponse();
response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE);
response.setBody("invalid content type");
this.server.enqueue(response);
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource "
+ "from '" + userInfoUri + "': response contains invalid content type 'text/plain'.");
}
private DefaultOAuth2UserService withMockResponse(Map<String, Object> response) {