From 00e7d6703dd5a4897bf3a2983922fa2b15df0210 Mon Sep 17 00:00:00 2001 From: Joe Grandja <10884212+jgrandja@users.noreply.github.com> Date: Sun, 19 May 2024 07:33:12 -0400 Subject: [PATCH] Fix checkstyle violations for test module Issue gh-1624 --- ...Auth2AuthorizationConsentServiceTests.java | 36 ++- .../JdbcOAuth2AuthorizationServiceTests.java | 269 ++++++++---------- .../OAuth2AuthorizationConsentTests.java | 2 +- ...Auth2AuthorizationServerMetadataTests.java | 18 +- .../TestOAuth2Authorizations.java | 5 +- ...ientSecretAuthenticationProviderTests.java | 90 +++--- ...tAssertionAuthenticationProviderTests.java | 54 ++-- ...JwtClientAssertionDecoderFactoryTests.java | 12 +- ...h2AccessTokenAuthenticationTokenTests.java | 10 +- ...zationCodeAuthenticationProviderTests.java | 118 ++++---- ...odeRequestAuthenticationProviderTests.java | 156 +++++----- ...tionConsentAuthenticationContextTests.java | 2 +- ...ionConsentAuthenticationProviderTests.java | 158 +++++----- ...redentialsAuthenticationProviderTests.java | 22 +- ...ionConsentAuthenticationProviderTests.java | 67 +++-- ...ionRequestAuthenticationProviderTests.java | 18 +- ...DeviceCodeAuthenticationProviderTests.java | 62 ++-- ...rificationAuthenticationProviderTests.java | 40 +-- ...freshTokenAuthenticationProviderTests.java | 100 +++---- ...rospectionAuthenticationProviderTests.java | 30 +- ...RevocationAuthenticationProviderTests.java | 18 +- ...blicClientAuthenticationProviderTests.java | 84 +++--- .../JdbcRegisteredClientRepositoryTests.java | 8 +- .../client/RegisteredClientTests.java | 95 +++---- .../client/TestRegisteredClients.java | 5 +- ...RegisterMissingBeanPostProcessorTests.java | 2 +- .../web/configurers/JwkSetTests.java | 4 +- .../OAuth2AuthorizationCodeGrantTests.java | 66 ++--- ...Auth2AuthorizationServerMetadataTests.java | 12 +- .../OAuth2ClientCredentialsGrantTests.java | 41 ++- .../OAuth2DeviceCodeGrantTests.java | 6 +- .../OAuth2RefreshTokenGrantTests.java | 6 +- .../OAuth2TokenIntrospectionTests.java | 20 +- .../OAuth2TokenRevocationTests.java | 20 +- .../OidcClientRegistrationTests.java | 75 ++--- .../OidcProviderConfigurationTests.java | 12 +- .../annotation/web/configurers/OidcTests.java | 14 +- .../web/configurers/OidcUserInfoTests.java | 46 +-- .../TestAuthorizationServerContext.java | 2 +- ...rverMetadataHttpMessageConverterTests.java | 4 +- ...ntrospectionHttpMessageConverterTests.java | 4 +- .../oidc/OidcClientRegistrationTests.java | 10 +- .../oidc/OidcProviderConfigurationTests.java | 16 +- ...figurationAuthenticationProviderTests.java | 56 ++-- ...gistrationAuthenticationProviderTests.java | 92 +++--- ...OidcLogoutAuthenticationProviderTests.java | 124 ++++---- ...dcUserInfoAuthenticationProviderTests.java | 30 +- ...RegistrationHttpMessageConverterTests.java | 56 ++-- ...onfigurationHttpMessageConverterTests.java | 4 +- ...OidcUserInfoHttpMessageConverterTests.java | 4 +- ...ClientRegistrationEndpointFilterTests.java | 27 +- .../web/OidcLogoutEndpointFilterTests.java | 33 ++- ...viderConfigurationEndpointFilterTests.java | 1 - .../web/OidcUserInfoEndpointFilterTests.java | 19 +- .../AuthorizationServerSettingsTests.java | 2 +- .../settings/ClientSettingsTests.java | 2 +- .../settings/TokenSettingsTests.java | 2 +- .../authorization/test/SpringTestContext.java | 8 +- .../DelegatingOAuth2TokenGeneratorTests.java | 4 +- .../token/JwtEncodingContextTests.java | 2 +- .../token/OAuth2TokenClaimsContextTests.java | 2 +- .../token/OAuth2TokenClaimsSetTests.java | 4 +- .../web/NimbusJwkSetEndpointFilterTests.java | 7 +- ...Auth2AuthorizationEndpointFilterTests.java | 101 ++++--- ...tionServerMetadataEndpointFilterTests.java | 1 - ...OAuth2ClientAuthenticationFilterTests.java | 33 +-- ...eviceAuthorizationEndpointFilterTests.java | 32 +-- ...DeviceVerificationEndpointFilterTests.java | 39 ++- .../web/OAuth2TokenEndpointFilterTests.java | 32 ++- ...TokenIntrospectionEndpointFilterTests.java | 15 +- ...th2TokenRevocationEndpointFilterTests.java | 21 +- ...cretBasicAuthenticationConverterTests.java | 6 +- ...ecretPostAuthenticationConverterTests.java | 4 +- ...AssertionAuthenticationConverterTests.java | 2 +- ...onConsentAuthenticationConverterTests.java | 7 +- ...onRequestAuthenticationConverterTests.java | 7 +- ...eviceCodeAuthenticationConverterTests.java | 7 +- ...ificationAuthenticationConverterTests.java | 7 +- ...licClientAuthenticationConverterTests.java | 6 +- 79 files changed, 1320 insertions(+), 1318 deletions(-) diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationConsentServiceTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationConsentServiceTests.java index de6c4868..f104c905 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationConsentServiceTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationConsentServiceTests.java @@ -45,10 +45,10 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * Tests for {@link JdbcOAuth2AuthorizationConsentService}. @@ -150,7 +150,8 @@ public class JdbcOAuth2AuthorizationConsentServiceTests { RegisteredClient newRegisteredClient = TestRegisteredClients.registeredClient().id("new-client").build(); - when(this.registeredClientRepository.findById(eq(newRegisteredClient.getId()))).thenReturn(newRegisteredClient); + given(this.registeredClientRepository.findById(eq(newRegisteredClient.getId()))) + .willReturn(newRegisteredClient); this.authorizationConsentService.save(expectedAuthorizationConsent); @@ -164,7 +165,7 @@ public class JdbcOAuth2AuthorizationConsentServiceTests { OAuth2AuthorizationConsent expectedAuthorizationConsent = OAuth2AuthorizationConsent.from(AUTHORIZATION_CONSENT) .authority(new SimpleGrantedAuthority("new.authority")) .build(); - when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).thenReturn(REGISTERED_CLIENT); + given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT); this.authorizationConsentService.save(expectedAuthorizationConsent); @@ -176,8 +177,7 @@ public class JdbcOAuth2AuthorizationConsentServiceTests { @Test public void saveLoadAuthorizationConsentWhenCustomStrategiesSetThenCalled() throws Exception { - when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))) - .thenReturn(REGISTERED_CLIENT); + given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT); JdbcOAuth2AuthorizationConsentService.OAuth2AuthorizationConsentRowMapper authorizationConsentRowMapper = spy( new JdbcOAuth2AuthorizationConsentService.OAuth2AuthorizationConsentRowMapper( @@ -188,8 +188,8 @@ public class JdbcOAuth2AuthorizationConsentServiceTests { this.authorizationConsentService.setAuthorizationConsentParametersMapper(authorizationConsentParametersMapper); this.authorizationConsentService.save(AUTHORIZATION_CONSENT); - OAuth2AuthorizationConsent authorizationConsent = this.authorizationConsentService.findById( - AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName()); + OAuth2AuthorizationConsent authorizationConsent = this.authorizationConsentService + .findById(AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName()); assertThat(authorizationConsent).isEqualTo(AUTHORIZATION_CONSENT); verify(authorizationConsentRowMapper).mapRow(any(), anyInt()); verify(authorizationConsentParametersMapper).apply(any()); @@ -225,12 +225,11 @@ public class JdbcOAuth2AuthorizationConsentServiceTests { @Test public void findByIdWhenAuthorizationConsentExistsThenFound() { - when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))) - .thenReturn(REGISTERED_CLIENT); + given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT); this.authorizationConsentService.save(AUTHORIZATION_CONSENT); - OAuth2AuthorizationConsent authorizationConsent = this.authorizationConsentService.findById( - AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName()); + OAuth2AuthorizationConsent authorizationConsent = this.authorizationConsentService + .findById(AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName()); assertThat(authorizationConsent).isNotNull(); } @@ -243,19 +242,18 @@ public class JdbcOAuth2AuthorizationConsentServiceTests { @Test public void tableDefinitionWhenCustomThenAbleToOverride() { - when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))) - .thenReturn(REGISTERED_CLIENT); + given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT); EmbeddedDatabase db = createDb(CUSTOM_OAUTH2_AUTHORIZATION_CONSENT_SCHEMA_SQL_RESOURCE); - OAuth2AuthorizationConsentService authorizationConsentService = - new CustomJdbcOAuth2AuthorizationConsentService(new JdbcTemplate(db), this.registeredClientRepository); + OAuth2AuthorizationConsentService authorizationConsentService = new CustomJdbcOAuth2AuthorizationConsentService( + new JdbcTemplate(db), this.registeredClientRepository); authorizationConsentService.save(AUTHORIZATION_CONSENT); - OAuth2AuthorizationConsent foundAuthorizationConsent1 = authorizationConsentService.findById( - AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName()); + OAuth2AuthorizationConsent foundAuthorizationConsent1 = authorizationConsentService + .findById(AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName()); assertThat(foundAuthorizationConsent1).isEqualTo(AUTHORIZATION_CONSENT); authorizationConsentService.remove(AUTHORIZATION_CONSENT); - OAuth2AuthorizationConsent foundAuthorizationConsent2 = authorizationConsentService.findById( - AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName()); + OAuth2AuthorizationConsent foundAuthorizationConsent2 = authorizationConsentService + .findById(AUTHORIZATION_CONSENT.getRegisteredClientId(), AUTHORIZATION_CONSENT.getPrincipalName()); assertThat(foundAuthorizationConsent2).isNull(); db.shutdown(); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationServiceTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationServiceTests.java index 37052d06..ff9b69ab 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationServiceTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationServiceTests.java @@ -63,10 +63,10 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * Tests for {@link JdbcOAuth2AuthorizationService}. @@ -182,14 +182,13 @@ public class JdbcOAuth2AuthorizationServiceTests { @Test public void saveWhenAuthorizationNewThenSaved() { - when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))) - .thenReturn(REGISTERED_CLIENT); + given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT); OAuth2Authorization expectedAuthorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT) - .id(ID) - .principalName(PRINCIPAL_NAME) - .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) - .token(AUTHORIZATION_CODE) - .build(); + .id(ID) + .principalName(PRINCIPAL_NAME) + .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) + .token(AUTHORIZATION_CODE) + .build(); this.authorizationService.save(expectedAuthorization); OAuth2Authorization authorization = this.authorizationService.findById(ID); @@ -198,53 +197,47 @@ public class JdbcOAuth2AuthorizationServiceTests { @Test public void saveWhenAuthorizationExistsThenUpdated() { - when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))) - .thenReturn(REGISTERED_CLIENT); + given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT); OAuth2Authorization originalAuthorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT) - .id(ID) - .principalName(PRINCIPAL_NAME) - .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) - .token(AUTHORIZATION_CODE) - .build(); + .id(ID) + .principalName(PRINCIPAL_NAME) + .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) + .token(AUTHORIZATION_CODE) + .build(); this.authorizationService.save(originalAuthorization); - OAuth2Authorization authorization = this.authorizationService.findById( - originalAuthorization.getId()); + OAuth2Authorization authorization = this.authorizationService.findById(originalAuthorization.getId()); assertThat(authorization).isEqualTo(originalAuthorization); OAuth2Authorization updatedAuthorization = OAuth2Authorization.from(authorization) - .attribute("custom-name-1", "custom-value-1") - .build(); + .attribute("custom-name-1", "custom-value-1") + .build(); this.authorizationService.save(updatedAuthorization); - authorization = this.authorizationService.findById( - updatedAuthorization.getId()); + authorization = this.authorizationService.findById(updatedAuthorization.getId()); assertThat(authorization).isEqualTo(updatedAuthorization); assertThat(authorization).isNotEqualTo(originalAuthorization); } @Test public void saveLoadAuthorizationWhenCustomStrategiesSetThenCalled() throws Exception { - when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))) - .thenReturn(REGISTERED_CLIENT); + given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT); OAuth2Authorization originalAuthorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT) - .id(ID) - .principalName(PRINCIPAL_NAME) - .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) - .token(AUTHORIZATION_CODE) - .build(); + .id(ID) + .principalName(PRINCIPAL_NAME) + .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) + .token(AUTHORIZATION_CODE) + .build(); RowMapper authorizationRowMapper = spy( - new JdbcOAuth2AuthorizationService.OAuth2AuthorizationRowMapper( - this.registeredClientRepository)); + new JdbcOAuth2AuthorizationService.OAuth2AuthorizationRowMapper(this.registeredClientRepository)); this.authorizationService.setAuthorizationRowMapper(authorizationRowMapper); Function> authorizationParametersMapper = spy( new JdbcOAuth2AuthorizationService.OAuth2AuthorizationParametersMapper()); this.authorizationService.setAuthorizationParametersMapper(authorizationParametersMapper); this.authorizationService.save(originalAuthorization); - OAuth2Authorization authorization = this.authorizationService.findById( - originalAuthorization.getId()); + OAuth2Authorization authorization = this.authorizationService.findById(originalAuthorization.getId()); assertThat(authorization).isEqualTo(originalAuthorization); verify(authorizationRowMapper).mapRow(any(), anyInt()); verify(authorizationParametersMapper).apply(any()); @@ -261,23 +254,22 @@ public class JdbcOAuth2AuthorizationServiceTests { @Test public void removeWhenAuthorizationProvidedThenRemoved() { - when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))) - .thenReturn(REGISTERED_CLIENT); + given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT); OAuth2Authorization expectedAuthorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT) - .id(ID) - .principalName(PRINCIPAL_NAME) - .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) - .token(AUTHORIZATION_CODE) - .build(); + .id(ID) + .principalName(PRINCIPAL_NAME) + .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) + .token(AUTHORIZATION_CODE) + .build(); this.authorizationService.save(expectedAuthorization); - OAuth2Authorization authorization = this.authorizationService.findByToken( - AUTHORIZATION_CODE.getTokenValue(), AUTHORIZATION_CODE_TOKEN_TYPE); + OAuth2Authorization authorization = this.authorizationService.findByToken(AUTHORIZATION_CODE.getTokenValue(), + AUTHORIZATION_CODE_TOKEN_TYPE); assertThat(authorization).isEqualTo(expectedAuthorization); this.authorizationService.remove(authorization); - authorization = this.authorizationService.findByToken( - AUTHORIZATION_CODE.getTokenValue(), AUTHORIZATION_CODE_TOKEN_TYPE); + authorization = this.authorizationService.findByToken(AUTHORIZATION_CODE.getTokenValue(), + AUTHORIZATION_CODE_TOKEN_TYPE); assertThat(authorization).isNull(); } @@ -310,19 +302,17 @@ public class JdbcOAuth2AuthorizationServiceTests { @Test public void findByTokenWhenStateExistsThenFound() { - when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))) - .thenReturn(REGISTERED_CLIENT); + given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT); String state = "state"; OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT) - .id(ID) - .principalName(PRINCIPAL_NAME) - .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) - .attribute(OAuth2ParameterNames.STATE, state) - .build(); + .id(ID) + .principalName(PRINCIPAL_NAME) + .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) + .attribute(OAuth2ParameterNames.STATE, state) + .build(); this.authorizationService.save(authorization); - OAuth2Authorization result = this.authorizationService.findByToken( - state, STATE_TOKEN_TYPE); + OAuth2Authorization result = this.authorizationService.findByToken(state, STATE_TOKEN_TYPE); assertThat(authorization).isEqualTo(result); result = this.authorizationService.findByToken(state, null); assertThat(authorization).isEqualTo(result); @@ -330,18 +320,17 @@ public class JdbcOAuth2AuthorizationServiceTests { @Test public void findByTokenWhenAuthorizationCodeExistsThenFound() { - when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))) - .thenReturn(REGISTERED_CLIENT); + given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT); OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT) - .id(ID) - .principalName(PRINCIPAL_NAME) - .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) - .token(AUTHORIZATION_CODE) - .build(); + .id(ID) + .principalName(PRINCIPAL_NAME) + .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) + .token(AUTHORIZATION_CODE) + .build(); this.authorizationService.save(authorization); - OAuth2Authorization result = this.authorizationService.findByToken( - AUTHORIZATION_CODE.getTokenValue(), AUTHORIZATION_CODE_TOKEN_TYPE); + OAuth2Authorization result = this.authorizationService.findByToken(AUTHORIZATION_CODE.getTokenValue(), + AUTHORIZATION_CODE_TOKEN_TYPE); assertThat(authorization).isEqualTo(result); result = this.authorizationService.findByToken(AUTHORIZATION_CODE.getTokenValue(), null); assertThat(authorization).isEqualTo(result); @@ -349,21 +338,21 @@ public class JdbcOAuth2AuthorizationServiceTests { @Test public void findByTokenWhenAccessTokenExistsThenFound() { - when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))) - .thenReturn(REGISTERED_CLIENT); - OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, - "access-token", Instant.now().minusSeconds(60).truncatedTo(ChronoUnit.MILLIS), Instant.now().truncatedTo(ChronoUnit.MILLIS)); + given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT); + OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token", + Instant.now().minusSeconds(60).truncatedTo(ChronoUnit.MILLIS), + Instant.now().truncatedTo(ChronoUnit.MILLIS)); OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT) - .id(ID) - .principalName(PRINCIPAL_NAME) - .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) - .token(AUTHORIZATION_CODE) - .accessToken(accessToken) - .build(); + .id(ID) + .principalName(PRINCIPAL_NAME) + .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) + .token(AUTHORIZATION_CODE) + .accessToken(accessToken) + .build(); this.authorizationService.save(authorization); - OAuth2Authorization result = this.authorizationService.findByToken( - accessToken.getTokenValue(), OAuth2TokenType.ACCESS_TOKEN); + OAuth2Authorization result = this.authorizationService.findByToken(accessToken.getTokenValue(), + OAuth2TokenType.ACCESS_TOKEN); assertThat(authorization).isEqualTo(result); result = this.authorizationService.findByToken(accessToken.getTokenValue(), null); assertThat(authorization).isEqualTo(result); @@ -371,25 +360,24 @@ public class JdbcOAuth2AuthorizationServiceTests { @Test public void findByTokenWhenIdTokenExistsThenFound() { - when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))) - .thenReturn(REGISTERED_CLIENT); - OidcIdToken idToken = OidcIdToken.withTokenValue("id-token") - .issuer("https://provider.com") - .subject("subject") - .issuedAt(Instant.now().minusSeconds(60).truncatedTo(ChronoUnit.MILLIS)) - .expiresAt(Instant.now().truncatedTo(ChronoUnit.MILLIS)) - .build(); + given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT); + OidcIdToken idToken = OidcIdToken.withTokenValue("id-token") + .issuer("https://provider.com") + .subject("subject") + .issuedAt(Instant.now().minusSeconds(60).truncatedTo(ChronoUnit.MILLIS)) + .expiresAt(Instant.now().truncatedTo(ChronoUnit.MILLIS)) + .build(); OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT) - .id(ID) - .principalName(PRINCIPAL_NAME) - .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) - .token(idToken, (metadata) -> - metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims())) - .build(); + .id(ID) + .principalName(PRINCIPAL_NAME) + .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) + .token(idToken, + (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims())) + .build(); this.authorizationService.save(authorization); - OAuth2Authorization result = this.authorizationService.findByToken( - idToken.getTokenValue(), ID_TOKEN_TOKEN_TYPE); + OAuth2Authorization result = this.authorizationService.findByToken(idToken.getTokenValue(), + ID_TOKEN_TOKEN_TYPE); assertThat(authorization).isEqualTo(result); result = this.authorizationService.findByToken(idToken.getTokenValue(), null); assertThat(authorization).isEqualTo(result); @@ -397,21 +385,20 @@ public class JdbcOAuth2AuthorizationServiceTests { @Test public void findByTokenWhenRefreshTokenExistsThenFound() { - when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))) - .thenReturn(REGISTERED_CLIENT); + given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT); OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", Instant.now().truncatedTo(ChronoUnit.MILLIS), Instant.now().plus(5, ChronoUnit.MINUTES).truncatedTo(ChronoUnit.MILLIS)); OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT) - .id(ID) - .principalName(PRINCIPAL_NAME) - .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) - .refreshToken(refreshToken) - .build(); + .id(ID) + .principalName(PRINCIPAL_NAME) + .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) + .refreshToken(refreshToken) + .build(); this.authorizationService.save(authorization); - OAuth2Authorization result = this.authorizationService.findByToken( - refreshToken.getTokenValue(), OAuth2TokenType.REFRESH_TOKEN); + OAuth2Authorization result = this.authorizationService.findByToken(refreshToken.getTokenValue(), + OAuth2TokenType.REFRESH_TOKEN); assertThat(authorization).isEqualTo(result); result = this.authorizationService.findByToken(refreshToken.getTokenValue(), null); assertThat(authorization).isEqualTo(result); @@ -419,21 +406,19 @@ public class JdbcOAuth2AuthorizationServiceTests { @Test public void findByTokenWhenDeviceCodeExistsThenFound() { - when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))) - .thenReturn(REGISTERED_CLIENT); - OAuth2DeviceCode deviceCode = new OAuth2DeviceCode("device-code", - Instant.now().truncatedTo(ChronoUnit.MILLIS), + given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT); + OAuth2DeviceCode deviceCode = new OAuth2DeviceCode("device-code", Instant.now().truncatedTo(ChronoUnit.MILLIS), Instant.now().plus(5, ChronoUnit.MINUTES).truncatedTo(ChronoUnit.MILLIS)); OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT) - .id(ID) - .principalName(PRINCIPAL_NAME) - .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) - .token(deviceCode) - .build(); + .id(ID) + .principalName(PRINCIPAL_NAME) + .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) + .token(deviceCode) + .build(); this.authorizationService.save(authorization); - OAuth2Authorization result = this.authorizationService.findByToken( - deviceCode.getTokenValue(), DEVICE_CODE_TOKEN_TYPE); + OAuth2Authorization result = this.authorizationService.findByToken(deviceCode.getTokenValue(), + DEVICE_CODE_TOKEN_TYPE); assertThat(authorization).isEqualTo(result); result = this.authorizationService.findByToken(deviceCode.getTokenValue(), null); assertThat(authorization).isEqualTo(result); @@ -441,21 +426,19 @@ public class JdbcOAuth2AuthorizationServiceTests { @Test public void findByTokenWhenUserCodeExistsThenFound() { - when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))) - .thenReturn(REGISTERED_CLIENT); - OAuth2UserCode userCode = new OAuth2UserCode("user-code", - Instant.now().truncatedTo(ChronoUnit.MILLIS), + given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT); + OAuth2UserCode userCode = new OAuth2UserCode("user-code", Instant.now().truncatedTo(ChronoUnit.MILLIS), Instant.now().plus(5, ChronoUnit.MINUTES).truncatedTo(ChronoUnit.MILLIS)); OAuth2Authorization authorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT) - .id(ID) - .principalName(PRINCIPAL_NAME) - .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) - .token(userCode) - .build(); + .id(ID) + .principalName(PRINCIPAL_NAME) + .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) + .token(userCode) + .build(); this.authorizationService.save(authorization); - OAuth2Authorization result = this.authorizationService.findByToken( - userCode.getTokenValue(), USER_CODE_TOKEN_TYPE); + OAuth2Authorization result = this.authorizationService.findByToken(userCode.getTokenValue(), + USER_CODE_TOKEN_TYPE); assertThat(authorization).isEqualTo(result); result = this.authorizationService.findByToken(userCode.getTokenValue(), null); assertThat(authorization).isEqualTo(result); @@ -487,20 +470,19 @@ public class JdbcOAuth2AuthorizationServiceTests { @Test public void tableDefinitionWhenCustomThenAbleToOverride() { - when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))) - .thenReturn(REGISTERED_CLIENT); + given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT); EmbeddedDatabase db = createDb(CUSTOM_OAUTH2_AUTHORIZATION_SCHEMA_SQL_RESOURCE); - OAuth2AuthorizationService authorizationService = - new CustomJdbcOAuth2AuthorizationService(new JdbcTemplate(db), this.registeredClientRepository); + OAuth2AuthorizationService authorizationService = new CustomJdbcOAuth2AuthorizationService(new JdbcTemplate(db), + this.registeredClientRepository); String state = "state"; OAuth2Authorization originalAuthorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT) - .id(ID) - .principalName(PRINCIPAL_NAME) - .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) - .attribute(OAuth2ParameterNames.STATE, state) - .token(AUTHORIZATION_CODE) - .build(); + .id(ID) + .principalName(PRINCIPAL_NAME) + .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) + .attribute(OAuth2ParameterNames.STATE, state) + .token(AUTHORIZATION_CODE) + .build(); authorizationService.save(originalAuthorization); OAuth2Authorization foundAuthorization1 = authorizationService.findById(originalAuthorization.getId()); assertThat(foundAuthorization1).isEqualTo(originalAuthorization); @@ -511,31 +493,28 @@ public class JdbcOAuth2AuthorizationServiceTests { @Test public void tableDefinitionWhenClobSqlTypeThenAuthorizationUpdated() { - when(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))) - .thenReturn(REGISTERED_CLIENT); + given(this.registeredClientRepository.findById(eq(REGISTERED_CLIENT.getId()))).willReturn(REGISTERED_CLIENT); EmbeddedDatabase db = createDb(OAUTH2_AUTHORIZATION_SCHEMA_CLOB_DATA_TYPE_SQL_RESOURCE); - OAuth2AuthorizationService authorizationService = - new JdbcOAuth2AuthorizationService(new JdbcTemplate(db), this.registeredClientRepository); + OAuth2AuthorizationService authorizationService = new JdbcOAuth2AuthorizationService(new JdbcTemplate(db), + this.registeredClientRepository); OAuth2Authorization originalAuthorization = OAuth2Authorization.withRegisteredClient(REGISTERED_CLIENT) - .id(ID) - .principalName(PRINCIPAL_NAME) - .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) - .token(AUTHORIZATION_CODE) - .build(); + .id(ID) + .principalName(PRINCIPAL_NAME) + .authorizationGrantType(AUTHORIZATION_GRANT_TYPE) + .token(AUTHORIZATION_CODE) + .build(); authorizationService.save(originalAuthorization); - OAuth2Authorization authorization = authorizationService.findById( - originalAuthorization.getId()); + OAuth2Authorization authorization = authorizationService.findById(originalAuthorization.getId()); assertThat(authorization).isEqualTo(originalAuthorization); OAuth2Authorization updatedAuthorization = OAuth2Authorization.from(authorization) - .attribute("custom-name-1", "custom-value-1") - .build(); + .attribute("custom-name-1", "custom-value-1") + .build(); authorizationService.save(updatedAuthorization); - authorization = authorizationService.findById( - updatedAuthorization.getId()); + authorization = authorizationService.findById(updatedAuthorization.getId()); assertThat(authorization).isEqualTo(updatedAuthorization); assertThat(authorization).isNotEqualTo(originalAuthorization); db.shutdown(); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsentTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsentTests.java index 53080165..256ba86a 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsentTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsentTests.java @@ -92,7 +92,7 @@ public class OAuth2AuthorizationConsentTests { public void authoritiesThenCustomizesAuthorities() { OAuth2AuthorizationConsent authorizationConsent = OAuth2AuthorizationConsent.withId("some-client", "some-user") .authority(new SimpleGrantedAuthority("some.authority")) - .authorities(authorities -> { + .authorities((authorities) -> { authorities.clear(); authorities.add(new SimpleGrantedAuthority("other.authority")); }) diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadataTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadataTests.java index af59e98a..b8961137 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadataTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationServerMetadataTests.java @@ -294,7 +294,7 @@ public class OAuth2AuthorizationServerMetadataTests { public void buildWhenTokenEndpointAuthenticationMethodsAddingOrRemovingThenCorrectValues() { OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder .tokenEndpointAuthenticationMethod("should-be-removed") - .tokenEndpointAuthenticationMethods(authMethods -> { + .tokenEndpointAuthenticationMethods((authMethods) -> { authMethods.clear(); authMethods.add("some-authentication-method"); }) @@ -332,7 +332,7 @@ public class OAuth2AuthorizationServerMetadataTests { @Test public void buildWhenScopesAddingOrRemovingThenCorrectValues() { OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder.scope("should-be-removed") - .scopes(scopes -> { + .scopes((scopes) -> { scopes.clear(); scopes.add("some-scope"); }) @@ -370,7 +370,7 @@ public class OAuth2AuthorizationServerMetadataTests { public void buildWhenResponseTypesAddingOrRemovingThenCorrectValues() { OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder .responseType("should-be-removed") - .responseTypes(responseTypes -> { + .responseTypes((responseTypes) -> { responseTypes.clear(); responseTypes.add("some-response-type"); }) @@ -382,8 +382,8 @@ public class OAuth2AuthorizationServerMetadataTests { @Test public void buildWhenResponseTypesNotPresentAndAddingThenCorrectValues() { OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder - .claims(claims -> claims.remove(OAuth2AuthorizationServerMetadataClaimNames.RESPONSE_TYPES_SUPPORTED)) - .responseTypes(responseTypes -> responseTypes.add("some-response-type")) + .claims((claims) -> claims.remove(OAuth2AuthorizationServerMetadataClaimNames.RESPONSE_TYPES_SUPPORTED)) + .responseTypes((responseTypes) -> responseTypes.add("some-response-type")) .build(); assertThat(authorizationServerMetadata.getResponseTypes()).containsExactly("some-response-type"); @@ -410,7 +410,7 @@ public class OAuth2AuthorizationServerMetadataTests { public void buildWhenGrantTypesAddingOrRemovingThenCorrectValues() { OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder .grantType("should-be-removed") - .grantTypes(grantTypes -> { + .grantTypes((grantTypes) -> { grantTypes.clear(); grantTypes.add("some-grant-type"); }) @@ -450,7 +450,7 @@ public class OAuth2AuthorizationServerMetadataTests { public void buildWhenTokenRevocationEndpointAuthenticationMethodsAddingOrRemovingThenCorrectValues() { OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder .tokenRevocationEndpointAuthenticationMethod("should-be-removed") - .tokenRevocationEndpointAuthenticationMethods(authMethods -> { + .tokenRevocationEndpointAuthenticationMethods((authMethods) -> { authMethods.clear(); authMethods.add("some-authentication-method"); }) @@ -492,7 +492,7 @@ public class OAuth2AuthorizationServerMetadataTests { public void buildWhenTokenIntrospectionEndpointAuthenticationMethodsAddingOrRemovingThenCorrectValues() { OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder .tokenIntrospectionEndpointAuthenticationMethod("should-be-removed") - .tokenIntrospectionEndpointAuthenticationMethods(authMethods -> { + .tokenIntrospectionEndpointAuthenticationMethods((authMethods) -> { authMethods.clear(); authMethods.add("some-authentication-method"); }) @@ -525,7 +525,7 @@ public class OAuth2AuthorizationServerMetadataTests { public void buildWhenCodeChallengeMethodsAddingOrRemovingThenCorrectValues() { OAuth2AuthorizationServerMetadata authorizationServerMetadata = this.minimalBuilder .codeChallengeMethod("should-be-removed") - .codeChallengeMethods(codeChallengeMethods -> { + .codeChallengeMethods((codeChallengeMethods) -> { codeChallengeMethods.clear(); codeChallengeMethods.add("some-authentication-method"); }) diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/TestOAuth2Authorizations.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/TestOAuth2Authorizations.java index eee09c21..bc8d17fa 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/TestOAuth2Authorizations.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/TestOAuth2Authorizations.java @@ -36,7 +36,10 @@ import org.springframework.util.CollectionUtils; * @author Joe Grandja * @author Daniel Garnier-Moiroux */ -public class TestOAuth2Authorizations { +public final class TestOAuth2Authorizations { + + private TestOAuth2Authorizations() { + } public static OAuth2Authorization.Builder authorization() { return authorization(TestRegisteredClients.registeredClient().build()); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/ClientSecretAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/ClientSecretAuthenticationProviderTests.java index bfd3506d..4d41cf99 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/ClientSecretAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/ClientSecretAuthenticationProviderTests.java @@ -43,10 +43,10 @@ import static org.assertj.core.api.Assertions.assertThat; 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; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * Tests for {@link ClientSecretAuthenticationProvider}. @@ -129,16 +129,16 @@ public class ClientSecretAuthenticationProviderTests { @Test public void authenticateWhenInvalidClientIdThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken( registeredClient.getClientId() + "-invalid", ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret(), null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); assertThat(error.getDescription()).contains(OAuth2ParameterNames.CLIENT_ID); }); @@ -147,16 +147,16 @@ public class ClientSecretAuthenticationProviderTests { @Test public void authenticateWhenUnsupportedClientAuthenticationMethodThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken( registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_POST, registeredClient.getClientSecret(), null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); assertThat(error.getDescription()).contains("authentication_method"); }); @@ -165,15 +165,15 @@ public class ClientSecretAuthenticationProviderTests { @Test public void authenticateWhenClientSecretNotProvidedThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken( registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC, null, null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); assertThat(error.getDescription()).contains("credentials"); }); @@ -182,16 +182,16 @@ public class ClientSecretAuthenticationProviderTests { @Test public void authenticateWhenInvalidClientSecretThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken( registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret() + "-invalid", null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); assertThat(error.getDescription()).contains(OAuth2ParameterNames.CLIENT_SECRET); }); @@ -203,16 +203,16 @@ public class ClientSecretAuthenticationProviderTests { RegisteredClient registeredClient = TestRegisteredClients.registeredClient() .clientSecretExpiresAt(Instant.now().minus(1, ChronoUnit.HOURS).truncatedTo(ChronoUnit.SECONDS)) .build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken( registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret(), null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); assertThat(error.getDescription()).contains("client_secret_expires_at"); }); @@ -222,8 +222,8 @@ public class ClientSecretAuthenticationProviderTests { @Test public void authenticateWhenValidCredentialsThenAuthenticated() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken( registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC, @@ -241,8 +241,8 @@ public class ClientSecretAuthenticationProviderTests { @Test public void authenticateWhenValidCredentialsAndRequiresUpgradingThenClientSecretUpgraded() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken( registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC, @@ -263,11 +263,11 @@ public class ClientSecretAuthenticationProviderTests { @Test public void authenticateWhenAuthorizationCodeGrantAndValidCredentialsThenAuthenticated() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(TestOAuth2Authorizations.authorization().build()); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(TestOAuth2Authorizations.authorization().build()); OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken( registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret(), createAuthorizationCodeTokenParameters()); @@ -285,14 +285,14 @@ public class ClientSecretAuthenticationProviderTests { @Test public void authenticateWhenPkceAndInvalidCodeThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, createPkceAuthorizationParametersS256()) .build(); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(authorization); Map parameters = createPkceTokenParameters(S256_CODE_VERIFIER); parameters.put(OAuth2ParameterNames.CODE, "invalid-code"); @@ -303,8 +303,8 @@ public class ClientSecretAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); assertThat(error.getDescription()).contains(OAuth2ParameterNames.CODE); }); @@ -313,14 +313,14 @@ public class ClientSecretAuthenticationProviderTests { @Test public void authenticateWhenPkceAndMissingCodeVerifierThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, createPkceAuthorizationParametersS256()) .build(); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(authorization); Map parameters = createAuthorizationCodeTokenParameters(); @@ -330,8 +330,8 @@ public class ClientSecretAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); assertThat(error.getDescription()).contains(PkceParameterNames.CODE_VERIFIER); }); @@ -340,14 +340,14 @@ public class ClientSecretAuthenticationProviderTests { @Test public void authenticateWhenPkceAndValidCodeVerifierThenAuthenticated() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, createPkceAuthorizationParametersS256()) .build(); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(authorization); Map parameters = createPkceTokenParameters(S256_CODE_VERIFIER); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionAuthenticationProviderTests.java index d2179944..b9cb6c66 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionAuthenticationProviderTests.java @@ -65,9 +65,9 @@ import org.springframework.web.util.UriComponentsBuilder; import static org.assertj.core.api.Assertions.assertThat; 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; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * Tests for {@link JwtClientAssertionAuthenticationProvider}. @@ -144,16 +144,16 @@ public class JwtClientAssertionAuthenticationProviderTests { .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT) .build(); // @formatter:on - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken( registeredClient.getClientId() + "-invalid", JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD, "jwt-assertion", null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); assertThat(error.getDescription()).contains(OAuth2ParameterNames.CLIENT_ID); }); @@ -162,15 +162,15 @@ public class JwtClientAssertionAuthenticationProviderTests { @Test public void authenticateWhenUnsupportedClientAuthenticationMethodThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken( registeredClient.getClientId(), JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD, "jwt-assertion", null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); assertThat(error.getDescription()).contains("authentication_method"); }); @@ -183,15 +183,15 @@ public class JwtClientAssertionAuthenticationProviderTests { .clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT) .build(); // @formatter:on - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken( registeredClient.getClientId(), JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD, null, null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); assertThat(error.getDescription()).contains("credentials"); }); @@ -210,8 +210,8 @@ public class JwtClientAssertionAuthenticationProviderTests { ) .build(); // @formatter:on - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken( registeredClient.getClientId(), JWT_CLIENT_ASSERTION_AUTHENTICATION_METHOD, "invalid-jwt-assertion", @@ -219,8 +219,8 @@ public class JwtClientAssertionAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) .hasCauseInstanceOf(BadJwtException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); assertThat(error.getDescription()).contains(OAuth2ParameterNames.CLIENT_ASSERTION); }); @@ -239,8 +239,8 @@ public class JwtClientAssertionAuthenticationProviderTests { ) .build(); // @formatter:on - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); // @formatter:off JwsHeader jwsHeader = JwsHeader.with(MacAlgorithm.HS256) @@ -261,8 +261,8 @@ public class JwtClientAssertionAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) .hasCauseInstanceOf(JwtValidationException.class) - .extracting(ex -> (OAuth2AuthenticationException) ex) - .satisfies(ex -> { + .extracting((ex) -> (OAuth2AuthenticationException) ex) + .satisfies((ex) -> { assertThat(ex.getError().getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); assertThat(ex.getError().getDescription()).contains(OAuth2ParameterNames.CLIENT_ASSERTION); JwtValidationException jwtValidationException = (JwtValidationException) ex.getCause(); @@ -284,8 +284,8 @@ public class JwtClientAssertionAuthenticationProviderTests { ) .build(); // @formatter:on - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); // @formatter:off JwsHeader jwsHeader = JwsHeader.with(MacAlgorithm.HS256) @@ -324,14 +324,14 @@ public class JwtClientAssertionAuthenticationProviderTests { ) .build(); // @formatter:on - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, createPkceAuthorizationParametersS256()) .build(); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(authorization); Map parameters = createPkceTokenParameters(S256_CODE_VERIFIER); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionDecoderFactoryTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionDecoderFactoryTests.java index d44777da..8c543f46 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionDecoderFactoryTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/JwtClientAssertionDecoderFactoryTests.java @@ -60,8 +60,8 @@ public class JwtClientAssertionDecoderFactoryTests { assertThatThrownBy(() -> this.jwtDecoderFactory.createDecoder(registeredClient)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); assertThat(error.getDescription()).isEqualTo("Failed to find a Signature Verifier for Client: '" + registeredClient.getId() + "'. Check to ensure you have configured the JWK Set URL."); @@ -84,8 +84,8 @@ public class JwtClientAssertionDecoderFactoryTests { assertThatThrownBy(() -> this.jwtDecoderFactory.createDecoder(registeredClient)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); assertThat(error.getDescription()).isEqualTo("Failed to find a Signature Verifier for Client: '" + registeredClient.getId() + "'. Check to ensure you have configured the client secret."); @@ -102,8 +102,8 @@ public class JwtClientAssertionDecoderFactoryTests { assertThatThrownBy(() -> this.jwtDecoderFactory.createDecoder(registeredClient)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); assertThat(error.getDescription()) .isEqualTo("Failed to find a Signature Verifier for Client: '" + registeredClient.getId() diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AccessTokenAuthenticationTokenTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AccessTokenAuthenticationTokenTests.java index ee6be4cd..f95a55d3 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AccessTokenAuthenticationTokenTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AccessTokenAuthenticationTokenTests.java @@ -15,6 +15,11 @@ */ package org.springframework.security.oauth2.server.authorization.authentication; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Collections; +import java.util.Map; + import org.junit.jupiter.api.Test; import org.springframework.security.oauth2.core.ClientAuthenticationMethod; @@ -23,11 +28,6 @@ import org.springframework.security.oauth2.core.OAuth2RefreshToken; import org.springframework.security.oauth2.server.authorization.client.RegisteredClient; import org.springframework.security.oauth2.server.authorization.client.TestRegisteredClients; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.Collections; -import java.util.Map; - import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationProviderTests.java index e302f645..3a928980 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeAuthenticationProviderTests.java @@ -83,13 +83,13 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doAnswer; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * Tests for {@link OAuth2AuthorizationCodeAuthenticationProvider}. @@ -187,7 +187,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { AUTHORIZATION_CODE, clientPrincipal, null, null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); } @@ -202,7 +202,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { AUTHORIZATION_CODE, clientPrincipal, null, null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); } @@ -216,7 +216,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { AUTHORIZATION_CODE, clientPrincipal, null, null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); } @@ -224,8 +224,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @Test public void authenticateWhenCodeIssuedToAnotherClientThenThrowOAuth2AuthenticationException() { OAuth2Authorization authorization = TestOAuth2Authorizations.authorization().build(); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(authorization); RegisteredClient registeredClient = TestRegisteredClients.registeredClient2().build(); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, @@ -234,7 +234,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { AUTHORIZATION_CODE, clientPrincipal, null, null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); @@ -250,8 +250,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { public void authenticateWhenInvalidRedirectUriThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -261,7 +261,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri() + "-invalid", null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); } @@ -275,8 +275,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { .token(authorizationCode, (metadata) -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true)) .build(); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -287,7 +287,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); @@ -308,8 +308,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { .token(authorizationCode, (metadata) -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true)) .build(); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -320,7 +320,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); @@ -336,8 +336,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient) .token(authorizationCode) .build(); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -348,7 +348,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); } @@ -357,8 +357,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { public void authenticateWhenAccessTokenNotGeneratedThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -367,7 +367,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken( AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null); - doAnswer(answer -> { + willAnswer((answer) -> { OAuth2TokenContext context = answer.getArgument(0); if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) { return null; @@ -375,12 +375,12 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { else { return answer.callRealMethod(); } - }).when(this.tokenGenerator).generate(any()); + }).given(this.tokenGenerator).generate(any()); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR); assertThat(error.getDescription()).contains("The token generator failed to generate the access token."); }); @@ -390,8 +390,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { public void authenticateWhenRefreshTokenNotGeneratedThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -400,9 +400,9 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken( AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null); - when(this.jwtEncoder.encode(any())).thenReturn(createJwt()); + given(this.jwtEncoder.encode(any())).willReturn(createJwt()); - doAnswer(answer -> { + willAnswer((answer) -> { OAuth2TokenContext context = answer.getArgument(0); if (OAuth2TokenType.REFRESH_TOKEN.equals(context.getTokenType())) { return null; @@ -410,12 +410,12 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { else { return answer.callRealMethod(); } - }).when(this.tokenGenerator).generate(any()); + }).given(this.tokenGenerator).generate(any()); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR); assertThat(error.getDescription()) .contains("The token generator failed to generate the refresh token."); @@ -426,8 +426,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { public void authenticateWhenIdTokenNotGeneratedThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scope(OidcScopes.OPENID).build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -436,9 +436,9 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken( AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null); - when(this.jwtEncoder.encode(any())).thenReturn(createJwt()); + given(this.jwtEncoder.encode(any())).willReturn(createJwt()); - doAnswer(answer -> { + willAnswer((answer) -> { OAuth2TokenContext context = answer.getArgument(0); if (OidcParameterNames.ID_TOKEN.equals(context.getTokenType().getValue())) { return null; @@ -446,12 +446,12 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { else { return answer.callRealMethod(); } - }).when(this.tokenGenerator).generate(any()); + }).given(this.tokenGenerator).generate(any()); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR); assertThat(error.getDescription()).contains("The token generator failed to generate the ID token."); }); @@ -461,8 +461,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { public void authenticateWhenValidCodeThenReturnAccessToken() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -471,7 +471,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken( AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null); - when(this.jwtEncoder.encode(any())).thenReturn(createJwt()); + given(this.jwtEncoder.encode(any())).willReturn(createJwt()); OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider .authenticate(authentication); @@ -526,8 +526,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { Instant.now().plusSeconds(120)); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient, authorizationCode) .build(); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -536,7 +536,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken( AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null); - when(this.jwtEncoder.encode(any())).thenReturn(createJwt()); + given(this.jwtEncoder.encode(any())).willReturn(createJwt()); Authentication principal = authorization.getAttribute(Principal.class.getName()); @@ -547,7 +547,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { sessions.add(new SessionInformation(principal.getPrincipal(), "session1", Date.from(Instant.now().minus(2, ChronoUnit.HOURS)))); SessionInformation expectedSession = sessions.get(0); // Most recent - when(this.sessionRegistry.getAllSessions(eq(principal.getPrincipal()), eq(false))).thenReturn(sessions); + given(this.sessionRegistry.getAllSessions(eq(principal.getPrincipal()), eq(false))).willReturn(sessions); OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider .authenticate(authentication); @@ -620,8 +620,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN) .build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.NONE, null); @@ -630,7 +630,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken( AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null); - when(this.jwtEncoder.encode(any())).thenReturn(createJwt()); + given(this.jwtEncoder.encode(any())).willReturn(createJwt()); OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider .authenticate(authentication); @@ -688,8 +688,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { .build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -700,7 +700,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { Instant accessTokenIssuedAt = Instant.now(); Instant accessTokenExpiresAt = accessTokenIssuedAt.plus(accessTokenTTL); - when(this.jwtEncoder.encode(any())).thenReturn(createJwt(accessTokenIssuedAt, accessTokenExpiresAt)); + given(this.jwtEncoder.encode(any())).willReturn(createJwt(accessTokenIssuedAt, accessTokenExpiresAt)); OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider .authenticate(authentication); @@ -729,12 +729,12 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @Test public void authenticateWhenRefreshTokenGrantNotConfiguredThenRefreshTokenNotIssued() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient() - .authorizationGrantTypes(grantTypes -> grantTypes.remove(AuthorizationGrantType.REFRESH_TOKEN)) + .authorizationGrantTypes((grantTypes) -> grantTypes.remove(AuthorizationGrantType.REFRESH_TOKEN)) .build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -743,7 +743,7 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken( AUTHORIZATION_CODE, clientPrincipal, authorizationRequest.getRedirectUri(), null); - when(this.jwtEncoder.encode(any())).thenReturn(createJwt()); + given(this.jwtEncoder.encode(any())).willReturn(createJwt()); OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider .authenticate(authentication); @@ -761,8 +761,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { .build(); // @formatter:on OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationProviderTests.java index 4fac15c6..3fddd987 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationCodeRequestAuthenticationProviderTests.java @@ -54,9 +54,9 @@ import static org.assertj.core.api.Assertions.assertThat; 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; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * Tests for {@link OAuth2AuthorizationCodeRequestAuthenticationProvider}. @@ -147,11 +147,11 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[1]; OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE, registeredClient.getScopes(), null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class) - .satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, + .satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.CLIENT_ID, null)); } @@ -159,14 +159,14 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @Test public void authenticateWhenInvalidRedirectUriHostThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, "https:///invalid", STATE, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, "https:///invalid", STATE, registeredClient.getScopes(), null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class) - .satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, + .satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI, null)); } @@ -174,28 +174,28 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @Test public void authenticateWhenInvalidRedirectUriFragmentThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, "https://example.com#fragment", STATE, - registeredClient.getScopes(), null); + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, "https://example.com#fragment", + STATE, registeredClient.getScopes(), null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class) - .satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, + .satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI, null)); } @Test public void authenticateWhenUnregisteredRedirectUriThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, "https://invalid-example.com", STATE, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, "https://invalid-example.com", STATE, registeredClient.getScopes(), null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class) - .satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, + .satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI, null)); } @@ -205,10 +205,10 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { RegisteredClient registeredClient = TestRegisteredClients.registeredClient() .redirectUri("https://127.0.0.1:8080") .build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, "https://127.0.0.1:5000", STATE, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, "https://127.0.0.1:5000", STATE, registeredClient.getScopes(), null); OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider @@ -224,10 +224,10 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { RegisteredClient registeredClient = TestRegisteredClients.registeredClient() .redirectUri("https://[::1]:8080") .build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, "https://[::1]:5000", STATE, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, "https://[::1]:5000", STATE, registeredClient.getScopes(), null); OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider @@ -242,14 +242,14 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { RegisteredClient registeredClient = TestRegisteredClients.registeredClient() .redirectUri("https://example2.com") .build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, null, STATE, registeredClient.getScopes(), - null); + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, null, STATE, + registeredClient.getScopes(), null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class) - .satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, + .satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI, null)); } @@ -257,14 +257,14 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { public void authenticateWhenAuthenticationRequestMissingRedirectUriThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() { // redirect_uri is REQUIRED for OpenID Connect requests RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scope(OidcScopes.OPENID).build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, null, STATE, registeredClient.getScopes(), - null); + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, null, STATE, + registeredClient.getScopes(), null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class) - .satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, + .satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.REDIRECT_URI, null)); } @@ -274,15 +274,15 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { .authorizationGrantTypes(Set::clear) .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS) .build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[1]; OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE, registeredClient.getScopes(), null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class) - .satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, + .satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, OAuth2ErrorCodes.UNAUTHORIZED_CLIENT, OAuth2ParameterNames.CLIENT_ID, authentication.getRedirectUri())); } @@ -290,15 +290,15 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @Test public void authenticateWhenInvalidScopeThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[2]; OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE, Collections.singleton("invalid-scope"), null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class) - .satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, + .satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, OAuth2ErrorCodes.INVALID_SCOPE, OAuth2ParameterNames.SCOPE, authentication.getRedirectUri())); } @@ -307,15 +307,15 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { RegisteredClient registeredClient = TestRegisteredClients.registeredClient() .clientSettings(ClientSettings.builder().requireProofKey(true).build()) .build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[2]; OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE, registeredClient.getScopes(), null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class) - .satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, + .satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, OAuth2ErrorCodes.INVALID_REQUEST, PkceParameterNames.CODE_CHALLENGE, authentication.getRedirectUri())); } @@ -323,18 +323,18 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @Test public void authenticateWhenPkceUnsupportedCodeChallengeMethodThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[0]; Map additionalParameters = new HashMap<>(); additionalParameters.put(PkceParameterNames.CODE_CHALLENGE, "code-challenge"); additionalParameters.put(PkceParameterNames.CODE_CHALLENGE_METHOD, "unsupported"); OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE, registeredClient.getScopes(), additionalParameters); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class) - .satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, + .satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, OAuth2ErrorCodes.INVALID_REQUEST, PkceParameterNames.CODE_CHALLENGE_METHOD, authentication.getRedirectUri())); } @@ -343,17 +343,17 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @Test public void authenticateWhenPkceMissingCodeChallengeMethodThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[2]; Map additionalParameters = new HashMap<>(); additionalParameters.put(PkceParameterNames.CODE_CHALLENGE, "code-challenge"); OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE, registeredClient.getScopes(), additionalParameters); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class) - .satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, + .satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, OAuth2ErrorCodes.INVALID_REQUEST, PkceParameterNames.CODE_CHALLENGE_METHOD, authentication.getRedirectUri())); } @@ -361,13 +361,13 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @Test public void authenticateWhenPrincipalNotAuthenticatedThenReturnAuthorizationCodeRequest() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); this.principal.setAuthenticated(false); String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[1]; OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE, registeredClient.getScopes(), null); OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider @@ -382,12 +382,12 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { RegisteredClient registeredClient = TestRegisteredClients.registeredClient() .clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build()) .build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[0]; OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE, registeredClient.getScopes(), null); OAuth2AuthorizationConsentAuthenticationToken authenticationResult = (OAuth2AuthorizationConsentAuthenticationToken) this.authenticationProvider @@ -428,17 +428,17 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { public void authenticateWhenRequireAuthorizationConsentAndOnlyOpenidScopeRequestedThenAuthorizationConsentNotRequired() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient() .clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build()) - .scopes(scopes -> { + .scopes((scopes) -> { scopes.clear(); scopes.add(OidcScopes.OPENID); }) .build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[1]; OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE, registeredClient.getScopes(), null); OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider @@ -453,19 +453,19 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { RegisteredClient registeredClient = TestRegisteredClients.registeredClient() .clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build()) .build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2AuthorizationConsent.Builder builder = OAuth2AuthorizationConsent.withId(registeredClient.getId(), this.principal.getName()); registeredClient.getScopes().forEach(builder::scope); OAuth2AuthorizationConsent previousAuthorizationConsent = builder.build(); - when(this.authorizationConsentService.findById(eq(registeredClient.getId()), eq(this.principal.getName()))) - .thenReturn(previousAuthorizationConsent); + given(this.authorizationConsentService.findById(eq(registeredClient.getId()), eq(this.principal.getName()))) + .willReturn(previousAuthorizationConsent); String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[2]; OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE, registeredClient.getScopes(), null); OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider @@ -478,15 +478,15 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @Test public void authenticateWhenAuthorizationCodeRequestValidThenReturnAuthorizationCode() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[0]; Map additionalParameters = new HashMap<>(); additionalParameters.put(PkceParameterNames.CODE_CHALLENGE, "code-challenge"); additionalParameters.put(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256"); OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE, registeredClient.getScopes(), additionalParameters); OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider @@ -499,8 +499,8 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @Test public void authenticateWhenAuthorizationCodeNotGeneratedThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); @SuppressWarnings("unchecked") OAuth2TokenGenerator authorizationCodeGenerator = mock(OAuth2TokenGenerator.class); @@ -508,13 +508,13 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[1]; OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE, registeredClient.getScopes(), null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class) - .extracting(ex -> ((OAuth2AuthorizationCodeRequestAuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthorizationCodeRequestAuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR); assertThat(error.getDescription()) .contains("The token generator failed to generate the authorization code."); @@ -524,8 +524,8 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { @Test public void authenticateWhenCustomAuthenticationValidatorThenUsed() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); @SuppressWarnings("unchecked") Consumer authenticationValidator = mock(Consumer.class); @@ -533,7 +533,7 @@ public class OAuth2AuthorizationCodeRequestAuthenticationProviderTests { String redirectUri = registeredClient.getRedirectUris().toArray(new String[0])[2]; OAuth2AuthorizationCodeRequestAuthenticationToken authentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, redirectUri, STATE, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, redirectUri, STATE, registeredClient.getScopes(), null); OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationContextTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationContextTests.java index 43887dd4..af745991 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationContextTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationContextTests.java @@ -107,7 +107,7 @@ public class OAuth2AuthorizationConsentAuthenticationContextTests { .authorization(this.authorization) .authorizationRequest(this.authorizationRequest) .put("custom-key-1", "custom-value-1") - .context(ctx -> ctx.put("custom-key-2", "custom-value-2")) + .context((ctx) -> ctx.put("custom-key-2", "custom-value-2")) .build(); assertThat(context.getAuthentication()).isEqualTo(this.authorizationConsentAuthentication); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationProviderTests.java index a2687abf..cb51847e 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2AuthorizationConsentAuthenticationProviderTests.java @@ -49,10 +49,10 @@ import static org.assertj.core.api.Assertions.assertThat; 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; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * Tests for {@link OAuth2AuthorizationConsentAuthenticationProvider}. @@ -141,14 +141,14 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { public void authenticateWhenInvalidStateThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, registeredClient.getScopes(), + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, registeredClient.getScopes(), null); - when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE))) - .thenReturn(null); + given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE))) + .willReturn(null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class) - .satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, + .satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.STATE, null)); } @@ -159,15 +159,15 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { .principalName(this.principal.getName()) .build(); OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, registeredClient.getScopes(), + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, registeredClient.getScopes(), null); - when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE))) + .willReturn(authorization); this.principal.setAuthenticated(false); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class) - .satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, + .satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.STATE, null)); } @@ -178,14 +178,14 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { .principalName(this.principal.getName().concat("-other")) .build(); OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, registeredClient.getScopes(), + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, registeredClient.getScopes(), null); - when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE))) + .willReturn(authorization); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class) - .satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, + .satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.STATE, null)); } @@ -195,43 +195,43 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient) .principalName(this.principal.getName()) .build(); - when(this.authorizationService.findByToken(eq("state"), eq(STATE_TOKEN_TYPE))).thenReturn(authorization); + given(this.authorizationService.findByToken(eq("state"), eq(STATE_TOKEN_TYPE))).willReturn(authorization); RegisteredClient otherRegisteredClient = TestRegisteredClients.registeredClient2().build(); OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken( - AUTHORIZATION_URI, otherRegisteredClient.getClientId(), principal, STATE, registeredClient.getScopes(), - null); + AUTHORIZATION_URI, otherRegisteredClient.getClientId(), this.principal, STATE, + registeredClient.getScopes(), null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class) - .satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, + .satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.CLIENT_ID, null)); } @Test public void authenticateWhenDoesNotMatchClientThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); RegisteredClient otherRegisteredClient = TestRegisteredClients.registeredClient2().build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(otherRegisteredClient) .principalName(this.principal.getName()) .build(); - when(this.authorizationService.findByToken(eq("state"), eq(STATE_TOKEN_TYPE))).thenReturn(authorization); + given(this.authorizationService.findByToken(eq("state"), eq(STATE_TOKEN_TYPE))).willReturn(authorization); OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, registeredClient.getScopes(), + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, registeredClient.getScopes(), null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class) - .satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, + .satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ParameterNames.CLIENT_ID, null)); } @Test public void authenticateWhenScopeNotRequestedThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient) .principalName(this.principal.getName()) .build(); @@ -240,37 +240,37 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { Set authorizedScopes = new HashSet<>(authorizationRequest.getScopes()); authorizedScopes.add("scope-not-requested"); OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, authorizedScopes, null); - when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE))) - .thenReturn(authorization); + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, authorizedScopes, null); + given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE))) + .willReturn(authorization); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class) - .satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, + .satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, OAuth2ErrorCodes.INVALID_SCOPE, OAuth2ParameterNames.SCOPE, authorizationRequest.getRedirectUri())); } @Test public void authenticateWhenNotApprovedThenThrowOAuth2AuthorizationCodeRequestAuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient) .principalName(this.principal.getName()) .build(); OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, new HashSet<>(), null); // No - // scopes - // approved - when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE))) - .thenReturn(authorization); + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, new HashSet<>(), null); // No + // scopes + // approved + given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE))) + .willReturn(authorization); OAuth2AuthorizationRequest authorizationRequest = authorization .getAttribute(OAuth2AuthorizationRequest.class.getName()); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class) - .satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, + .satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, OAuth2ErrorCodes.ACCESS_DENIED, OAuth2ParameterNames.CLIENT_ID, authorizationRequest.getRedirectUri())); @@ -280,8 +280,8 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { @Test public void authenticateWhenApproveAllThenReturnAuthorizationCode() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient) .principalName(this.principal.getName()) .build(); @@ -289,11 +289,11 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { .getAttribute(OAuth2AuthorizationRequest.class.getName()); Set authorizedScopes = authorizationRequest.getScopes(); OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, authorizedScopes, null); // Approve - // all - // scopes - when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE))) - .thenReturn(authorization); + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, authorizedScopes, null); // Approve + // all + // scopes + given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE))) + .willReturn(authorization); OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider .authenticate(authentication); @@ -305,8 +305,8 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { @Test public void authenticateWhenCustomAuthorizationConsentCustomizerThenUsed() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient) .principalName(this.principal.getName()) .build(); @@ -314,11 +314,11 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { .getAttribute(OAuth2AuthorizationRequest.class.getName()); Set authorizedScopes = authorizationRequest.getScopes(); OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, authorizedScopes, null); // Approve - // all - // scopes - when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE))) - .thenReturn(authorization); + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, authorizedScopes, null); // Approve + // all + // scopes + given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE))) + .willReturn(authorization); @SuppressWarnings("unchecked") Consumer authorizationConsentCustomizer = mock(Consumer.class); @@ -391,31 +391,31 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { public void authenticateWhenApproveNoneAndRevokePreviouslyApprovedThenAuthorizationConsentRemoved() { String previouslyApprovedScope = "message.read"; String requestedScope = "message.write"; - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(scopes -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> { scopes.clear(); scopes.add(previouslyApprovedScope); scopes.add(requestedScope); }).build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient) .principalName(this.principal.getName()) .build(); OAuth2AuthorizationRequest authorizationRequest = authorization .getAttribute(OAuth2AuthorizationRequest.class.getName()); OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, new HashSet<>(), null); // No - // scopes - // approved - when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE))) - .thenReturn(authorization); + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, new HashSet<>(), null); // No + // scopes + // approved + given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE))) + .willReturn(authorization); OAuth2AuthorizationConsent previousAuthorizationConsent = OAuth2AuthorizationConsent .withId(authorization.getRegisteredClientId(), authorization.getPrincipalName()) .scope(previouslyApprovedScope) .build(); - when(this.authorizationConsentService.findById(eq(authorization.getRegisteredClientId()), + given(this.authorizationConsentService.findById(eq(authorization.getRegisteredClientId()), eq(authorization.getPrincipalName()))) - .thenReturn(previousAuthorizationConsent); + .willReturn(previousAuthorizationConsent); // Revoke all (including previously approved) this.authenticationProvider.setAuthorizationConsentCustomizer( @@ -424,7 +424,7 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthorizationCodeRequestAuthenticationException.class) - .satisfies(ex -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, + .satisfies((ex) -> assertAuthenticationException((OAuth2AuthorizationCodeRequestAuthenticationException) ex, OAuth2ErrorCodes.ACCESS_DENIED, OAuth2ParameterNames.CLIENT_ID, authorizationRequest.getRedirectUri())); @@ -437,13 +437,13 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { String previouslyApprovedScope = "message.read"; String requestedScope = "message.write"; String otherPreviouslyApprovedScope = "other.scope"; - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(scopes -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> { scopes.clear(); scopes.add(previouslyApprovedScope); scopes.add(requestedScope); }).build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient) .principalName(this.principal.getName()) .build(); @@ -451,17 +451,17 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { .getAttribute(OAuth2AuthorizationRequest.class.getName()); Set requestedScopes = authorizationRequest.getScopes(); OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, requestedScopes, null); - when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE))) - .thenReturn(authorization); + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, requestedScopes, null); + given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE))) + .willReturn(authorization); OAuth2AuthorizationConsent previousAuthorizationConsent = OAuth2AuthorizationConsent .withId(authorization.getRegisteredClientId(), authorization.getPrincipalName()) .scope(previouslyApprovedScope) .scope(otherPreviouslyApprovedScope) .build(); - when(this.authorizationConsentService.findById(eq(authorization.getRegisteredClientId()), + given(this.authorizationConsentService.findById(eq(authorization.getRegisteredClientId()), eq(authorization.getPrincipalName()))) - .thenReturn(previousAuthorizationConsent); + .willReturn(previousAuthorizationConsent); OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider .authenticate(authentication); @@ -489,29 +489,29 @@ public class OAuth2AuthorizationConsentAuthenticationProviderTests { public void authenticateWhenApproveNoneAndPreviouslyApprovedThenAuthorizationConsentNotUpdated() { String previouslyApprovedScope = "message.read"; String requestedScope = "message.write"; - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(scopes -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> { scopes.clear(); scopes.add(previouslyApprovedScope); scopes.add(requestedScope); }).build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient) .principalName(this.principal.getName()) .build(); OAuth2AuthorizationConsentAuthenticationToken authentication = new OAuth2AuthorizationConsentAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, new HashSet<>(), null); // No - // scopes - // approved - when(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE))) - .thenReturn(authorization); + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, new HashSet<>(), null); // No + // scopes + // approved + given(this.authorizationService.findByToken(eq(authentication.getState()), eq(STATE_TOKEN_TYPE))) + .willReturn(authorization); OAuth2AuthorizationConsent previousAuthorizationConsent = OAuth2AuthorizationConsent .withId(authorization.getRegisteredClientId(), authorization.getPrincipalName()) .scope(previouslyApprovedScope) .build(); - when(this.authorizationConsentService.findById(eq(authorization.getRegisteredClientId()), + given(this.authorizationConsentService.findById(eq(authorization.getRegisteredClientId()), eq(authorization.getPrincipalName()))) - .thenReturn(previousAuthorizationConsent); + .willReturn(previousAuthorizationConsent); OAuth2AuthorizationCodeRequestAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeRequestAuthenticationToken) this.authenticationProvider .authenticate(authentication); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationProviderTests.java index 076d541c..1029dd7f 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientCredentialsAuthenticationProviderTests.java @@ -59,11 +59,11 @@ import org.springframework.security.oauth2.server.authorization.token.OAuth2Toke import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * Tests for {@link OAuth2ClientCredentialsAuthenticationProvider}. @@ -151,7 +151,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); } @@ -167,7 +167,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); } @@ -175,7 +175,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests { @Test public void authenticateWhenClientNotAuthorizedToRequestTokenThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient2() - .authorizationGrantTypes(grantTypes -> grantTypes.remove(AuthorizationGrantType.CLIENT_CREDENTIALS)) + .authorizationGrantTypes((grantTypes) -> grantTypes.remove(AuthorizationGrantType.CLIENT_CREDENTIALS)) .build(); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -184,7 +184,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT); } @@ -199,7 +199,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_SCOPE); } @@ -213,7 +213,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests { OAuth2ClientCredentialsAuthenticationToken authentication = new OAuth2ClientCredentialsAuthenticationToken( clientPrincipal, requestedScope, null); - when(this.jwtEncoder.encode(any())).thenReturn(createJwt(Collections.singleton("mapped-scoped"))); + given(this.jwtEncoder.encode(any())).willReturn(createJwt(Collections.singleton("mapped-scoped"))); OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider .authenticate(authentication); @@ -228,7 +228,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests { OAuth2ClientCredentialsAuthenticationToken authentication = new OAuth2ClientCredentialsAuthenticationToken( clientPrincipal, null, null); - when(this.jwtEncoder.encode(any())).thenReturn(createJwt(Collections.singleton("mapped-scoped"))); + given(this.jwtEncoder.encode(any())).willReturn(createJwt(Collections.singleton("mapped-scoped"))); OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider .authenticate(authentication); @@ -247,8 +247,8 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR); assertThat(error.getDescription()).contains("The token generator failed to generate the access token."); }); @@ -262,7 +262,7 @@ public class OAuth2ClientCredentialsAuthenticationProviderTests { OAuth2ClientCredentialsAuthenticationToken authentication = new OAuth2ClientCredentialsAuthenticationToken( clientPrincipal, null, null); - when(this.jwtEncoder.encode(any())).thenReturn(createJwt(registeredClient.getScopes())); + given(this.jwtEncoder.encode(any())).willReturn(createJwt(registeredClient.getScopes())); OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider .authenticate(authentication); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationProviderTests.java index 8f279d9d..86e900af 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationConsentAuthenticationProviderTests.java @@ -52,12 +52,11 @@ 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.anyString; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; -import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE; /** * Tests for {@link OAuth2DeviceAuthorizationConsentAuthenticationProvider}. @@ -149,7 +148,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { .isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); // @formatter:on - verify(this.authorizationService).findByToken(STATE, STATE_TOKEN_TYPE); + verify(this.authorizationService).findByToken(STATE, + OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE); verifyNoInteractions(this.registeredClientRepository, this.authorizationConsentService); } @@ -157,7 +157,7 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { public void authenticateWhenPrincipalIsNotAuthenticatedThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2Authorization authorization = createAuthorization(registeredClient); - when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization); + given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization); TestingAuthenticationToken principal = new TestingAuthenticationToken(authorization.getPrincipalName(), null); Authentication authentication = new OAuth2DeviceAuthorizationConsentAuthenticationToken(AUTHORIZATION_URI, registeredClient.getClientId(), principal, USER_CODE, STATE, null, Collections.emptyMap()); @@ -170,7 +170,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { .isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); // @formatter:on - verify(this.authorizationService).findByToken(STATE, STATE_TOKEN_TYPE); + verify(this.authorizationService).findByToken(STATE, + OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE); verifyNoInteractions(this.registeredClientRepository, this.authorizationConsentService); } @@ -178,7 +179,7 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { public void authenticateWhenPrincipalNameDoesNotMatchThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2Authorization authorization = createAuthorization(registeredClient); - when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization); + given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization); TestingAuthenticationToken principal = new TestingAuthenticationToken("invalid", null, Collections.emptyList()); Authentication authentication = new OAuth2DeviceAuthorizationConsentAuthenticationToken(AUTHORIZATION_URI, registeredClient.getClientId(), principal, USER_CODE, STATE, null, Collections.emptyMap()); @@ -191,7 +192,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { .isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); // @formatter:on - verify(this.authorizationService).findByToken(STATE, STATE_TOKEN_TYPE); + verify(this.authorizationService).findByToken(STATE, + OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE); verifyNoInteractions(this.registeredClientRepository, this.authorizationConsentService); } @@ -199,7 +201,7 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { public void authenticateWhenRegisteredClientNotFoundThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2Authorization authorization = createAuthorization(registeredClient); - when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization); + given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization); Authentication authentication = createAuthentication(registeredClient); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) @@ -211,7 +213,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { // @formatter:on verify(this.registeredClientRepository).findByClientId(registeredClient.getClientId()); - verify(this.authorizationService).findByToken(STATE, STATE_TOKEN_TYPE); + verify(this.authorizationService).findByToken(STATE, + OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE); verifyNoMoreInteractions(this.registeredClientRepository, this.authorizationService); verifyNoInteractions(this.authorizationConsentService); } @@ -221,8 +224,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); RegisteredClient registeredClient2 = TestRegisteredClients.registeredClient2().build(); OAuth2Authorization authorization = createAuthorization(registeredClient2); - when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization); - when(this.registeredClientRepository.findByClientId(anyString())).thenReturn(registeredClient); + given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization); + given(this.registeredClientRepository.findByClientId(anyString())).willReturn(registeredClient); Authentication authentication = createAuthentication(registeredClient); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) @@ -234,7 +237,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { // @formatter:on verify(this.registeredClientRepository).findByClientId(registeredClient.getClientId()); - verify(this.authorizationService).findByToken(STATE, STATE_TOKEN_TYPE); + verify(this.authorizationService).findByToken(STATE, + OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE); verifyNoMoreInteractions(this.registeredClientRepository, this.authorizationService); verifyNoInteractions(this.authorizationConsentService); } @@ -247,8 +251,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { .scope("invalid") .build(); OAuth2Authorization authorization = createAuthorization(registeredClient); - when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization); - when(this.registeredClientRepository.findByClientId(anyString())).thenReturn(registeredClient); + given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization); + given(this.registeredClientRepository.findByClientId(anyString())).willReturn(registeredClient); Authentication authentication = createAuthentication(registeredClient2); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) @@ -260,7 +264,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { // @formatter:on verify(this.registeredClientRepository).findByClientId(registeredClient.getClientId()); - verify(this.authorizationService).findByToken(STATE, STATE_TOKEN_TYPE); + verify(this.authorizationService).findByToken(STATE, + OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE); verifyNoMoreInteractions(this.registeredClientRepository, this.authorizationService); verifyNoInteractions(this.authorizationConsentService); } @@ -271,8 +276,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { RegisteredClient registeredClient2 = TestRegisteredClients.registeredClient().scopes(Set::clear).build(); OAuth2Authorization authorization = createAuthorization(registeredClient2); Authentication authentication = createAuthentication(registeredClient2); - when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization); - when(this.registeredClientRepository.findByClientId(anyString())).thenReturn(registeredClient); + given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization); + given(this.registeredClientRepository.findByClientId(anyString())).willReturn(registeredClient); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> this.authenticationProvider.authenticate(authentication)) @@ -282,7 +287,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { // @formatter:on ArgumentCaptor authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class); - verify(this.authorizationService).findByToken(STATE, STATE_TOKEN_TYPE); + verify(this.authorizationService).findByToken(STATE, + OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE); verify(this.registeredClientRepository).findByClientId(registeredClient.getClientId()); verify(this.authorizationConsentService).findById(registeredClient.getId(), authentication.getName()); verify(this.authorizationService).save(authorizationCaptor.capture()); @@ -305,8 +311,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { public void authenticateWhenAuthoritiesIsNotEmptyThenAuthorizationConsentSaved() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2Authorization authorization = createAuthorization(registeredClient); - when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization); - when(this.registeredClientRepository.findByClientId(anyString())).thenReturn(registeredClient); + given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization); + given(this.registeredClientRepository.findByClientId(anyString())).willReturn(registeredClient); Authentication authentication = createAuthentication(registeredClient); OAuth2DeviceVerificationAuthenticationToken authenticationResult = (OAuth2DeviceVerificationAuthenticationToken) this.authenticationProvider @@ -317,7 +323,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { assertThat(authenticationResult.getUserCode()).isEqualTo(USER_CODE); ArgumentCaptor authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class); - verify(this.authorizationService).findByToken(STATE, STATE_TOKEN_TYPE); + verify(this.authorizationService).findByToken(STATE, + OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE); verify(this.registeredClientRepository).findByClientId(registeredClient.getClientId()); verify(this.authorizationConsentService).findById(registeredClient.getId(), authentication.getName()); verify(this.authorizationConsentService).save(any(OAuth2AuthorizationConsent.class)); @@ -354,9 +361,9 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { OAuth2AuthorizationConsent.withId(registeredClient.getId(), authentication.getName()) .scope("scope1").build(); // @formatter:on - when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization); - when(this.registeredClientRepository.findByClientId(anyString())).thenReturn(registeredClient); - when(this.authorizationConsentService.findById(anyString(), anyString())).thenReturn(authorizationConsent); + given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization); + given(this.registeredClientRepository.findByClientId(anyString())).willReturn(registeredClient); + given(this.authorizationConsentService.findById(anyString(), anyString())).willReturn(authorizationConsent); OAuth2DeviceVerificationAuthenticationToken authenticationResult = (OAuth2DeviceVerificationAuthenticationToken) this.authenticationProvider .authenticate(authentication); @@ -367,7 +374,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { ArgumentCaptor authorizationConsentCaptor = ArgumentCaptor .forClass(OAuth2AuthorizationConsent.class); - verify(this.authorizationService).findByToken(STATE, STATE_TOKEN_TYPE); + verify(this.authorizationService).findByToken(STATE, + OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE); verify(this.registeredClientRepository).findByClientId(registeredClient.getClientId()); verify(this.authorizationConsentService).findById(registeredClient.getId(), authentication.getName()); verify(this.authorizationConsentService).save(authorizationConsentCaptor.capture()); @@ -390,9 +398,9 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(Set::clear).build(); OAuth2Authorization authorization = createAuthorization(registeredClient); Authentication authentication = createAuthentication(registeredClient); - when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization); - when(this.registeredClientRepository.findByClientId(anyString())).thenReturn(registeredClient); - when(this.authorizationConsentService.findById(anyString(), anyString())).thenReturn(null); + given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization); + given(this.registeredClientRepository.findByClientId(anyString())).willReturn(registeredClient); + given(this.authorizationConsentService.findById(anyString(), anyString())).willReturn(null); OAuth2DeviceVerificationAuthenticationToken authenticationResult = (OAuth2DeviceVerificationAuthenticationToken) this.authenticationProvider .authenticate(authentication); @@ -403,7 +411,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationProviderTests { ArgumentCaptor authorizationConsentCaptor = ArgumentCaptor .forClass(OAuth2AuthorizationConsent.class); - verify(this.authorizationService).findByToken(STATE, STATE_TOKEN_TYPE); + verify(this.authorizationService).findByToken(STATE, + OAuth2DeviceAuthorizationConsentAuthenticationProvider.STATE_TOKEN_TYPE); verify(this.registeredClientRepository).findByClientId(registeredClient.getClientId()); verify(this.authorizationConsentService).findById(registeredClient.getId(), authentication.getName()); verify(this.authorizationConsentService).save(authorizationConsentCaptor.capture()); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationProviderTests.java index 3719da77..81b038f6 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceAuthorizationRequestAuthenticationProviderTests.java @@ -48,13 +48,11 @@ 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.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; -import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2DeviceAuthorizationRequestAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE; -import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2DeviceAuthorizationRequestAuthenticationProvider.USER_CODE_TOKEN_TYPE; /** * Tests for {@link OAuth2DeviceAuthorizationRequestAuthenticationProvider}. @@ -171,7 +169,7 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationProviderTests { public void authenticateWhenDeviceCodeIsNullThenThrowOAuth2AuthenticationException() { @SuppressWarnings("unchecked") OAuth2TokenGenerator deviceCodeGenerator = mock(OAuth2TokenGenerator.class); - when(deviceCodeGenerator.generate(any(OAuth2TokenContext.class))).thenReturn(null); + given(deviceCodeGenerator.generate(any(OAuth2TokenContext.class))).willReturn(null); this.authenticationProvider.setDeviceCodeGenerator(deviceCodeGenerator); RegisteredClient registeredClient = TestRegisteredClients.registeredClient() @@ -196,7 +194,7 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationProviderTests { public void authenticateWhenUserCodeIsNullThenThrowOAuth2AuthenticationException() { @SuppressWarnings("unchecked") OAuth2TokenGenerator userCodeGenerator = mock(OAuth2TokenGenerator.class); - when(userCodeGenerator.generate(any(OAuth2TokenContext.class))).thenReturn(null); + given(userCodeGenerator.generate(any(OAuth2TokenContext.class))).willReturn(null); this.authenticationProvider.setUserCodeGenerator(userCodeGenerator); RegisteredClient registeredClient = TestRegisteredClients.registeredClient() .authorizationGrantType(AuthorizationGrantType.DEVICE_CODE) @@ -277,7 +275,7 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationProviderTests { public void authenticateWhenDeviceCodeGeneratorSetThenUsed() { @SuppressWarnings("unchecked") OAuth2TokenGenerator deviceCodeGenerator = mock(OAuth2TokenGenerator.class); - when(deviceCodeGenerator.generate(any(OAuth2TokenContext.class))).thenReturn(createDeviceCode()); + given(deviceCodeGenerator.generate(any(OAuth2TokenContext.class))).willReturn(createDeviceCode()); this.authenticationProvider.setDeviceCodeGenerator(deviceCodeGenerator); RegisteredClient registeredClient = TestRegisteredClients.registeredClient() @@ -303,14 +301,15 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationProviderTests { assertThat(tokenContext.getAuthorizationServerContext()).isNotNull(); assertThat(tokenContext.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.DEVICE_CODE); assertThat(tokenContext.getAuthorizationGrant()).isEqualTo(authentication); - assertThat(tokenContext.getTokenType()).isEqualTo(DEVICE_CODE_TOKEN_TYPE); + assertThat(tokenContext.getTokenType()) + .isEqualTo(OAuth2DeviceAuthorizationRequestAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE); } @Test public void authenticateWhenUserCodeGeneratorSetThenUsed() { @SuppressWarnings("unchecked") OAuth2TokenGenerator userCodeGenerator = mock(OAuth2TokenGenerator.class); - when(userCodeGenerator.generate(any(OAuth2TokenContext.class))).thenReturn(createUserCode()); + given(userCodeGenerator.generate(any(OAuth2TokenContext.class))).willReturn(createUserCode()); this.authenticationProvider.setUserCodeGenerator(userCodeGenerator); RegisteredClient registeredClient = TestRegisteredClients.registeredClient() @@ -335,7 +334,8 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationProviderTests { assertThat(tokenContext.getAuthorizationServerContext()).isNotNull(); assertThat(tokenContext.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.DEVICE_CODE); assertThat(tokenContext.getAuthorizationGrant()).isEqualTo(authentication); - assertThat(tokenContext.getTokenType()).isEqualTo(USER_CODE_TOKEN_TYPE); + assertThat(tokenContext.getTokenType()) + .isEqualTo(OAuth2DeviceAuthorizationRequestAuthenticationProvider.USER_CODE_TOKEN_TYPE); } private static void mockAuthorizationServerContext() { diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceCodeAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceCodeAuthenticationProviderTests.java index ac445ff5..0c37bb16 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceCodeAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceCodeAuthenticationProviderTests.java @@ -55,15 +55,12 @@ 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.anyString; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; -import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2DeviceCodeAuthenticationProvider.AUTHORIZATION_PENDING; -import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2DeviceCodeAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE; -import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2DeviceCodeAuthenticationProvider.EXPIRED_TOKEN; /** * Tests for {@link OAuth2DeviceCodeAuthenticationProvider}. @@ -142,7 +139,7 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { public void authenticateWhenAuthorizationNotFoundThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); Authentication authentication = createAuthentication(registeredClient); - when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(null); + given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(null); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> this.authenticationProvider.authenticate(authentication)) @@ -151,7 +148,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { .isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); // @formatter:on - verify(this.authorizationService).findByToken(DEVICE_CODE, DEVICE_CODE_TOKEN_TYPE); + verify(this.authorizationService).findByToken(DEVICE_CODE, + OAuth2DeviceCodeAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE); verifyNoMoreInteractions(this.authorizationService); verifyNoInteractions(this.tokenGenerator); } @@ -164,7 +162,7 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient2) .token(createDeviceCode()) .build(); - when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization); + given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> this.authenticationProvider.authenticate(authentication)) @@ -174,7 +172,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { // @formatter:on ArgumentCaptor authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class); - verify(this.authorizationService).findByToken(DEVICE_CODE, DEVICE_CODE_TOKEN_TYPE); + verify(this.authorizationService).findByToken(DEVICE_CODE, + OAuth2DeviceCodeAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE); verify(this.authorizationService).save(authorizationCaptor.capture()); verifyNoMoreInteractions(this.authorizationService); verifyNoInteractions(this.tokenGenerator); @@ -194,16 +193,17 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient) .token(createUserCode()) .build(); - when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization); + given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .extracting(OAuth2AuthenticationException::getError) .extracting(OAuth2Error::getErrorCode) - .isEqualTo(AUTHORIZATION_PENDING); + .isEqualTo(OAuth2DeviceCodeAuthenticationProvider.AUTHORIZATION_PENDING); // @formatter:on - verify(this.authorizationService).findByToken(DEVICE_CODE, DEVICE_CODE_TOKEN_TYPE); + verify(this.authorizationService).findByToken(DEVICE_CODE, + OAuth2DeviceCodeAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE); verifyNoMoreInteractions(this.authorizationService); verifyNoInteractions(this.tokenGenerator); } @@ -216,7 +216,7 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { .token(createDeviceCode(), withInvalidated()) .token(createUserCode(), withInvalidated()) .build(); - when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization); + given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> this.authenticationProvider.authenticate(authentication)) @@ -225,7 +225,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { .isEqualTo(OAuth2ErrorCodes.ACCESS_DENIED); // @formatter:on - verify(this.authorizationService).findByToken(DEVICE_CODE, DEVICE_CODE_TOKEN_TYPE); + verify(this.authorizationService).findByToken(DEVICE_CODE, + OAuth2DeviceCodeAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE); verifyNoMoreInteractions(this.authorizationService); verifyNoInteractions(this.tokenGenerator); } @@ -238,17 +239,18 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { .token(createExpiredDeviceCode()) .token(createUserCode(), withInvalidated()) .build(); - when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization); + given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .extracting(OAuth2AuthenticationException::getError) .extracting(OAuth2Error::getErrorCode) - .isEqualTo(EXPIRED_TOKEN); + .isEqualTo(OAuth2DeviceCodeAuthenticationProvider.EXPIRED_TOKEN); // @formatter:on ArgumentCaptor authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class); - verify(this.authorizationService).findByToken(DEVICE_CODE, DEVICE_CODE_TOKEN_TYPE); + verify(this.authorizationService).findByToken(DEVICE_CODE, + OAuth2DeviceCodeAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE); verify(this.authorizationService).save(authorizationCaptor.capture()); verifyNoMoreInteractions(this.authorizationService); verifyNoInteractions(this.tokenGenerator); @@ -272,8 +274,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { .attribute(Principal.class.getName(), authentication.getPrincipal()) .build(); // @formatter:on - when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization); - when(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).thenReturn(null); + given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization); + given(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).willReturn(null); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> this.authenticationProvider.authenticate(authentication)) @@ -283,7 +285,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { .isEqualTo(OAuth2ErrorCodes.SERVER_ERROR); // @formatter:on - verify(this.authorizationService).findByToken(DEVICE_CODE, DEVICE_CODE_TOKEN_TYPE); + verify(this.authorizationService).findByToken(DEVICE_CODE, + OAuth2DeviceCodeAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE); verify(this.tokenGenerator).generate(any(OAuth2TokenContext.class)); verifyNoMoreInteractions(this.authorizationService, this.tokenGenerator); } @@ -299,8 +302,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { .attribute(Principal.class.getName(), authentication.getPrincipal()) .build(); // @formatter:on - when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization); - when(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).thenReturn(createAccessToken(), + given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization); + given(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).willReturn(createAccessToken(), (OAuth2RefreshToken) null); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) @@ -311,7 +314,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { .isEqualTo(OAuth2ErrorCodes.SERVER_ERROR); // @formatter:on - verify(this.authorizationService).findByToken(DEVICE_CODE, DEVICE_CODE_TOKEN_TYPE); + verify(this.authorizationService).findByToken(DEVICE_CODE, + OAuth2DeviceCodeAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE); verify(this.tokenGenerator, times(2)).generate(any(OAuth2TokenContext.class)); verifyNoMoreInteractions(this.authorizationService, this.tokenGenerator); } @@ -327,9 +331,9 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { .attribute(Principal.class.getName(), authentication.getPrincipal()) .build(); // @formatter:on - when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization); + given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization); OAuth2AccessToken accessToken = createAccessToken(); - when(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).thenReturn(accessToken, accessToken); + given(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).willReturn(accessToken, accessToken); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> this.authenticationProvider.authenticate(authentication)) @@ -339,7 +343,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { .isEqualTo(OAuth2ErrorCodes.SERVER_ERROR); // @formatter:on - verify(this.authorizationService).findByToken(DEVICE_CODE, DEVICE_CODE_TOKEN_TYPE); + verify(this.authorizationService).findByToken(DEVICE_CODE, + OAuth2DeviceCodeAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE); verify(this.tokenGenerator, times(2)).generate(any(OAuth2TokenContext.class)); verifyNoMoreInteractions(this.authorizationService, this.tokenGenerator); } @@ -355,10 +360,10 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { .attribute(Principal.class.getName(), authentication.getPrincipal()) .build(); // @formatter:on - when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization); + given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization); OAuth2AccessToken accessToken = createAccessToken(); OAuth2RefreshToken refreshToken = createRefreshToken(); - when(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).thenReturn(accessToken, refreshToken); + given(this.tokenGenerator.generate(any(OAuth2TokenContext.class))).willReturn(accessToken, refreshToken); OAuth2AccessTokenAuthenticationToken authenticationResult = (OAuth2AccessTokenAuthenticationToken) this.authenticationProvider .authenticate(authentication); assertThat(authenticationResult.getRegisteredClient()).isEqualTo(registeredClient); @@ -368,7 +373,8 @@ public class OAuth2DeviceCodeAuthenticationProviderTests { ArgumentCaptor authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class); ArgumentCaptor tokenContextCaptor = ArgumentCaptor.forClass(OAuth2TokenContext.class); - verify(this.authorizationService).findByToken(DEVICE_CODE, DEVICE_CODE_TOKEN_TYPE); + verify(this.authorizationService).findByToken(DEVICE_CODE, + OAuth2DeviceCodeAuthenticationProvider.DEVICE_CODE_TOKEN_TYPE); verify(this.authorizationService).save(authorizationCaptor.capture()); verify(this.tokenGenerator, times(2)).generate(tokenContextCaptor.capture()); verifyNoMoreInteractions(this.authorizationService, this.tokenGenerator); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationProviderTests.java index 3e97029d..a0f3d12b 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2DeviceVerificationAuthenticationProviderTests.java @@ -55,12 +55,11 @@ 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.anyString; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; -import static org.springframework.security.oauth2.server.authorization.authentication.OAuth2DeviceVerificationAuthenticationProvider.USER_CODE_TOKEN_TYPE; /** * Tests for {@link OAuth2DeviceVerificationAuthenticationProvider}. @@ -130,7 +129,7 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests { @Test public void authenticateWhenAuthorizationNotFoundThenThrowOAuth2AuthenticationException() { - when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(null); + given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(null); Authentication authentication = createAuthentication(); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) @@ -140,7 +139,8 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests { .isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); // @formatter:on - verify(this.authorizationService).findByToken(USER_CODE, USER_CODE_TOKEN_TYPE); + verify(this.authorizationService).findByToken(USER_CODE, + OAuth2DeviceVerificationAuthenticationProvider.USER_CODE_TOKEN_TYPE); verifyNoMoreInteractions(this.authorizationService); verifyNoInteractions(this.registeredClientRepository, this.authorizationConsentService); } @@ -152,14 +152,15 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests { TestingAuthenticationToken principal = new TestingAuthenticationToken("user", null); Authentication authentication = new OAuth2DeviceVerificationAuthenticationToken(principal, USER_CODE, Collections.emptyMap()); - when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization); + given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization); OAuth2DeviceVerificationAuthenticationToken authenticationResult = (OAuth2DeviceVerificationAuthenticationToken) this.authenticationProvider .authenticate(authentication); assertThat(authenticationResult).isEqualTo(authentication); assertThat(authenticationResult.isAuthenticated()).isFalse(); - verify(this.authorizationService).findByToken(USER_CODE, USER_CODE_TOKEN_TYPE); + verify(this.authorizationService).findByToken(USER_CODE, + OAuth2DeviceVerificationAuthenticationProvider.USER_CODE_TOKEN_TYPE); verifyNoMoreInteractions(this.authorizationService); verifyNoInteractions(this.registeredClientRepository, this.authorizationConsentService); } @@ -175,9 +176,9 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests { .build(); // @formatter:on Authentication authentication = createAuthentication(); - when(this.registeredClientRepository.findById(anyString())).thenReturn(registeredClient); - when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization); - when(this.authorizationConsentService.findById(anyString(), anyString())).thenReturn(null); + given(this.registeredClientRepository.findById(anyString())).willReturn(registeredClient); + given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization); + given(this.authorizationConsentService.findById(anyString(), anyString())).willReturn(null); OAuth2DeviceAuthorizationConsentAuthenticationToken authenticationResult = (OAuth2DeviceAuthorizationConsentAuthenticationToken) this.authenticationProvider .authenticate(authentication); @@ -191,7 +192,8 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests { assertThat(authenticationResult.getScopes()).isEmpty(); ArgumentCaptor authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class); - verify(this.authorizationService).findByToken(USER_CODE, USER_CODE_TOKEN_TYPE); + verify(this.authorizationService).findByToken(USER_CODE, + OAuth2DeviceVerificationAuthenticationProvider.USER_CODE_TOKEN_TYPE); verify(this.registeredClientRepository).findById(authorization.getRegisteredClientId()); verify(this.authorizationService).save(authorizationCaptor.capture()); verify(this.authorizationConsentService).findById(registeredClient.getId(), authentication.getName()); @@ -222,9 +224,9 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests { .scope(registeredClient.getScopes().iterator().next()) .build(); // @formatter:on - when(this.registeredClientRepository.findById(anyString())).thenReturn(registeredClient); - when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization); - when(this.authorizationConsentService.findById(anyString(), anyString())).thenReturn(authorizationConsent); + given(this.registeredClientRepository.findById(anyString())).willReturn(registeredClient); + given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization); + given(this.authorizationConsentService.findById(anyString(), anyString())).willReturn(authorizationConsent); OAuth2DeviceVerificationAuthenticationToken authenticationResult = (OAuth2DeviceVerificationAuthenticationToken) this.authenticationProvider .authenticate(authentication); @@ -234,7 +236,8 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests { assertThat(authenticationResult.getUserCode()).isEqualTo(USER_CODE); ArgumentCaptor authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class); - verify(this.authorizationService).findByToken(USER_CODE, USER_CODE_TOKEN_TYPE); + verify(this.authorizationService).findByToken(USER_CODE, + OAuth2DeviceVerificationAuthenticationProvider.USER_CODE_TOKEN_TYPE); verify(this.registeredClientRepository).findById(authorization.getRegisteredClientId()); verify(this.authorizationService).save(authorizationCaptor.capture()); verify(this.authorizationConsentService).findById(registeredClient.getId(), authentication.getName()); @@ -276,9 +279,9 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests { .scope("previous") .build(); // @formatter:on - when(this.registeredClientRepository.findById(anyString())).thenReturn(registeredClient); - when(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).thenReturn(authorization); - when(this.authorizationConsentService.findById(anyString(), anyString())).thenReturn(authorizationConsent); + given(this.registeredClientRepository.findById(anyString())).willReturn(registeredClient); + given(this.authorizationService.findByToken(anyString(), any(OAuth2TokenType.class))).willReturn(authorization); + given(this.authorizationConsentService.findById(anyString(), anyString())).willReturn(authorizationConsent); OAuth2DeviceAuthorizationConsentAuthenticationToken authenticationResult = (OAuth2DeviceAuthorizationConsentAuthenticationToken) this.authenticationProvider .authenticate(authentication); @@ -292,7 +295,8 @@ public class OAuth2DeviceVerificationAuthenticationProviderTests { assertThat(authenticationResult.getScopes()).containsExactly("previous"); ArgumentCaptor authorizationCaptor = ArgumentCaptor.forClass(OAuth2Authorization.class); - verify(this.authorizationService).findByToken(USER_CODE, USER_CODE_TOKEN_TYPE); + verify(this.authorizationService).findByToken(USER_CODE, + OAuth2DeviceVerificationAuthenticationProvider.USER_CODE_TOKEN_TYPE); verify(this.registeredClientRepository).findById(authorization.getRegisteredClientId()); verify(this.authorizationService).save(authorizationCaptor.capture()); verify(this.authorizationConsentService).findById(registeredClient.getId(), authentication.getName()); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2RefreshTokenAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2RefreshTokenAuthenticationProviderTests.java index 311f78ab..beb2b00a 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2RefreshTokenAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2RefreshTokenAuthenticationProviderTests.java @@ -73,12 +73,12 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doAnswer; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * Tests for {@link OAuth2RefreshTokenAuthenticationProvider}. @@ -106,7 +106,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { public void setUp() { this.authorizationService = mock(OAuth2AuthorizationService.class); this.jwtEncoder = mock(JwtEncoder.class); - when(this.jwtEncoder.encode(any())).thenReturn(createJwt(Collections.singleton("scope1"))); + given(this.jwtEncoder.encode(any())).willReturn(createJwt(Collections.singleton("scope1"))); this.jwtCustomizer = mock(OAuth2TokenCustomizer.class); JwtGenerator jwtGenerator = new JwtGenerator(this.jwtEncoder); jwtGenerator.setJwtCustomizer(this.jwtCustomizer); @@ -165,9 +165,9 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { public void authenticateWhenValidRefreshTokenThenReturnAccessToken() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -222,9 +222,9 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient) .token(authorizedIdToken) .build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -296,9 +296,9 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { .tokenSettings(TokenSettings.builder().reuseRefreshTokens(false).build()) .build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -324,9 +324,9 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { .scope("scope3") .build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -346,9 +346,9 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { public void authenticateWhenRequestedScopesNotAuthorizedThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -360,7 +360,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_SCOPE); } @@ -375,7 +375,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); } @@ -390,7 +390,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); } @@ -406,7 +406,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); } @@ -415,9 +415,9 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { public void authenticateWhenRefreshTokenIssuedToAnotherClientThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); RegisteredClient registeredClient2 = TestRegisteredClients.registeredClient2().build(); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient2, @@ -427,7 +427,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); } @@ -435,12 +435,12 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { @Test public void authenticateWhenClientNotAuthorizedToRefreshTokenThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient() - .authorizationGrantTypes(grantTypes -> grantTypes.remove(AuthorizationGrantType.REFRESH_TOKEN)) + .authorizationGrantTypes((grantTypes) -> grantTypes.remove(AuthorizationGrantType.REFRESH_TOKEN)) .build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -449,7 +449,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT); } @@ -461,9 +461,9 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { OAuth2RefreshToken expiredRefreshToken = new OAuth2RefreshToken("expired-refresh-token", Instant.now().minusSeconds(120), Instant.now().minusSeconds(60)); authorization = OAuth2Authorization.from(authorization).token(expiredRefreshToken).build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -472,7 +472,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); } @@ -485,9 +485,9 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient) .token(refreshToken, (metadata) -> metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true)) .build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -496,7 +496,7 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); } @@ -505,16 +505,16 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { public void authenticateWhenAccessTokenNotGeneratedThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken( authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, null, null); - doAnswer(answer -> { + willAnswer((answer) -> { OAuth2TokenContext context = answer.getArgument(0); if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) { return null; @@ -522,12 +522,12 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { else { return answer.callRealMethod(); } - }).when(this.tokenGenerator).generate(any()); + }).given(this.tokenGenerator).generate(any()); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR); assertThat(error.getDescription()).contains("The token generator failed to generate the access token."); }); @@ -539,16 +539,16 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { .tokenSettings(TokenSettings.builder().reuseRefreshTokens(false).build()) .build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken( authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, null, null); - doAnswer(answer -> { + willAnswer((answer) -> { OAuth2TokenContext context = answer.getArgument(0); if (OAuth2TokenType.REFRESH_TOKEN.equals(context.getTokenType())) { return null; @@ -556,12 +556,12 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { else { return answer.callRealMethod(); } - }).when(this.tokenGenerator).generate(any()); + }).given(this.tokenGenerator).generate(any()); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR); assertThat(error.getDescription()) .contains("The token generator failed to generate the refresh token."); @@ -572,16 +572,16 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { public void authenticateWhenIdTokenNotGeneratedThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scope(OidcScopes.OPENID).build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); OAuth2RefreshTokenAuthenticationToken authentication = new OAuth2RefreshTokenAuthenticationToken( authorization.getRefreshToken().getToken().getTokenValue(), clientPrincipal, null, null); - doAnswer(answer -> { + willAnswer((answer) -> { OAuth2TokenContext context = answer.getArgument(0); if (OidcParameterNames.ID_TOKEN.equals(context.getTokenType().getValue())) { return null; @@ -589,12 +589,12 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { else { return answer.callRealMethod(); } - }).when(this.tokenGenerator).generate(any()); + }).given(this.tokenGenerator).generate(any()); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR); assertThat(error.getDescription()).contains("The token generator failed to generate the ID token."); }); @@ -610,9 +610,9 @@ public class OAuth2RefreshTokenAuthenticationProviderTests { .build(); // @formatter:on OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), eq(OAuth2TokenType.REFRESH_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenIntrospectionAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenIntrospectionAuthenticationProviderTests.java index 95c9d848..3ff0b62f 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenIntrospectionAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenIntrospectionAuthenticationProviderTests.java @@ -46,9 +46,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * Tests for {@link OAuth2TokenIntrospectionAuthenticationProvider}. @@ -103,7 +103,7 @@ public class OAuth2TokenIntrospectionAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); } @@ -120,7 +120,7 @@ public class OAuth2TokenIntrospectionAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); } @@ -148,8 +148,8 @@ public class OAuth2TokenIntrospectionAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); OAuth2AccessToken accessToken = authorization.getAccessToken().getToken(); authorization = OAuth2AuthenticationProviderUtils.invalidate(authorization, accessToken); - when(this.authorizationService.findByToken(eq(accessToken.getTokenValue()), isNull())) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(accessToken.getTokenValue()), isNull())) + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -174,8 +174,8 @@ public class OAuth2TokenIntrospectionAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient) .token(accessToken) .build(); - when(this.authorizationService.findByToken(eq(accessToken.getTokenValue()), isNull())) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(accessToken.getTokenValue()), isNull())) + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -202,8 +202,8 @@ public class OAuth2TokenIntrospectionAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, accessToken, accessTokenClaims) .build(); - when(this.authorizationService.findByToken(eq(accessToken.getTokenValue()), isNull())) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(accessToken.getTokenValue()), isNull())) + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -243,9 +243,9 @@ public class OAuth2TokenIntrospectionAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(authorizedClient, accessToken, claimsSet.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(accessToken.getTokenValue()), isNull())) - .thenReturn(authorization); - when(this.registeredClientRepository.findById(eq(authorizedClient.getId()))).thenReturn(authorizedClient); + given(this.authorizationService.findByToken(eq(accessToken.getTokenValue()), isNull())) + .willReturn(authorization); + given(this.registeredClientRepository.findById(eq(authorizedClient.getId()))).willReturn(authorizedClient); RegisteredClient registeredClient = TestRegisteredClients.registeredClient2().build(); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -278,9 +278,9 @@ public class OAuth2TokenIntrospectionAuthenticationProviderTests { RegisteredClient authorizedClient = TestRegisteredClients.registeredClient().build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization().build(); OAuth2RefreshToken refreshToken = authorization.getRefreshToken().getToken(); - when(this.authorizationService.findByToken(eq(refreshToken.getTokenValue()), isNull())) - .thenReturn(authorization); - when(this.registeredClientRepository.findById(eq(authorizedClient.getId()))).thenReturn(authorizedClient); + given(this.authorizationService.findByToken(eq(refreshToken.getTokenValue()), isNull())) + .willReturn(authorization); + given(this.registeredClientRepository.findById(eq(authorizedClient.getId()))).willReturn(authorizedClient); RegisteredClient registeredClient = TestRegisteredClients.registeredClient2().build(); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenRevocationAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenRevocationAuthenticationProviderTests.java index e1560cde..27f77748 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenRevocationAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2TokenRevocationAuthenticationProviderTests.java @@ -37,10 +37,10 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * Tests for {@link OAuth2TokenRevocationAuthenticationProvider}. @@ -81,7 +81,7 @@ public class OAuth2TokenRevocationAuthenticationProviderTests { clientPrincipal, OAuth2TokenType.ACCESS_TOKEN.getValue()); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); } @@ -96,7 +96,7 @@ public class OAuth2TokenRevocationAuthenticationProviderTests { clientPrincipal, OAuth2TokenType.ACCESS_TOKEN.getValue()); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); } @@ -120,7 +120,7 @@ public class OAuth2TokenRevocationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(TestRegisteredClients.registeredClient2().build()) .build(); - when(this.authorizationService.findByToken(eq("token"), isNull())).thenReturn(authorization); + given(this.authorizationService.findByToken(eq("token"), isNull())).willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -129,7 +129,7 @@ public class OAuth2TokenRevocationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); } @@ -138,9 +138,9 @@ public class OAuth2TokenRevocationAuthenticationProviderTests { public void authenticateWhenValidRefreshTokenThenRevoked() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getRefreshToken().getToken().getTokenValue()), isNull())) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); @@ -166,9 +166,9 @@ public class OAuth2TokenRevocationAuthenticationProviderTests { public void authenticateWhenValidAccessTokenThenRevoked() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(authorization.getAccessToken().getToken().getTokenValue()), + given(this.authorizationService.findByToken(eq(authorization.getAccessToken().getToken().getTokenValue()), isNull())) - .thenReturn(authorization); + .willReturn(authorization); OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/PublicClientAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/PublicClientAuthenticationProviderTests.java index 062043f0..36095a7d 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/PublicClientAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/authentication/PublicClientAuthenticationProviderTests.java @@ -38,8 +38,8 @@ import org.springframework.security.oauth2.server.authorization.client.TestRegis import static org.assertj.core.api.Assertions.assertThat; 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; -import static org.mockito.Mockito.when; /** * Tests for {@link PublicClientAuthenticationProvider}. @@ -95,15 +95,15 @@ public class PublicClientAuthenticationProviderTests { @Test public void authenticateWhenInvalidClientIdThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken( registeredClient.getClientId() + "-invalid", ClientAuthenticationMethod.NONE, null, null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); assertThat(error.getDescription()).contains(OAuth2ParameterNames.CLIENT_ID); }); @@ -112,15 +112,15 @@ public class PublicClientAuthenticationProviderTests { @Test public void authenticateWhenUnsupportedClientAuthenticationMethodThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2ClientAuthenticationToken authentication = new OAuth2ClientAuthenticationToken( registeredClient.getClientId(), ClientAuthenticationMethod.NONE, null, null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); assertThat(error.getDescription()).contains("authentication_method"); }); @@ -129,14 +129,14 @@ public class PublicClientAuthenticationProviderTests { @Test public void authenticateWhenInvalidCodeThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, createPkceAuthorizationParametersS256()) .build(); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(authorization); Map parameters = createPkceTokenParameters(S256_CODE_VERIFIER); parameters.put(OAuth2ParameterNames.CODE, "invalid-code"); @@ -146,8 +146,8 @@ public class PublicClientAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); assertThat(error.getDescription()).contains(OAuth2ParameterNames.CODE); }); @@ -156,12 +156,12 @@ public class PublicClientAuthenticationProviderTests { @Test public void authenticateWhenMissingCodeChallengeThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(authorization); Map parameters = createPkceTokenParameters(S256_CODE_VERIFIER); @@ -170,8 +170,8 @@ public class PublicClientAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); assertThat(error.getDescription()).contains(PkceParameterNames.CODE_CHALLENGE); }); @@ -180,14 +180,14 @@ public class PublicClientAuthenticationProviderTests { @Test public void authenticateWhenMissingCodeVerifierThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, createPkceAuthorizationParametersS256()) .build(); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(authorization); Map parameters = createAuthorizationCodeTokenParameters(); @@ -196,8 +196,8 @@ public class PublicClientAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); assertThat(error.getDescription()).contains(PkceParameterNames.CODE_VERIFIER); }); @@ -206,14 +206,14 @@ public class PublicClientAuthenticationProviderTests { @Test public void authenticateWhenS256MethodAndInvalidCodeVerifierThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, createPkceAuthorizationParametersS256()) .build(); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(authorization); Map parameters = createPkceTokenParameters("invalid-code-verifier"); @@ -222,8 +222,8 @@ public class PublicClientAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); assertThat(error.getDescription()).contains(PkceParameterNames.CODE_VERIFIER); }); @@ -232,14 +232,14 @@ public class PublicClientAuthenticationProviderTests { @Test public void authenticateWhenS256MethodAndValidCodeVerifierThenAuthenticated() { RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, createPkceAuthorizationParametersS256()) .build(); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(authorization); Map parameters = createPkceTokenParameters(S256_CODE_VERIFIER); @@ -257,8 +257,8 @@ public class PublicClientAuthenticationProviderTests { @Test public void authenticateWhenUnsupportedCodeChallengeMethodThenThrowOAuth2AuthenticationException() { RegisteredClient registeredClient = TestRegisteredClients.registeredPublicClient().build(); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); Map authorizationRequestAdditionalParameters = createPkceAuthorizationParametersS256(); // This should never happen: the Authorization endpoint should not allow it @@ -267,8 +267,8 @@ public class PublicClientAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, authorizationRequestAdditionalParameters) .build(); - when(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(AUTHORIZATION_CODE), eq(AUTHORIZATION_CODE_TOKEN_TYPE))) + .willReturn(authorization); Map parameters = createPkceTokenParameters(S256_CODE_VERIFIER); @@ -277,7 +277,7 @@ public class PublicClientAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_GRANT); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/client/JdbcRegisteredClientRepositoryTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/client/JdbcRegisteredClientRepositoryTests.java index 2b46f1c7..e5d8c795 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/client/JdbcRegisteredClientRepositoryTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/client/JdbcRegisteredClientRepositoryTests.java @@ -374,15 +374,15 @@ public class JdbcRegisteredClientRepositoryTests { // @formatter:off RegisteredClient.Builder builder = RegisteredClient.withId(rs.getString("id")) .clientId(rs.getString("clientId")) - .clientIdIssuedAt(clientIdIssuedAt != null ? clientIdIssuedAt.toInstant() : null) + .clientIdIssuedAt((clientIdIssuedAt != null) ? clientIdIssuedAt.toInstant() : null) .clientSecret(rs.getString("clientSecret")) - .clientSecretExpiresAt(clientSecretExpiresAt != null ? clientSecretExpiresAt.toInstant() : null) + .clientSecretExpiresAt((clientSecretExpiresAt != null) ? clientSecretExpiresAt.toInstant() : null) .clientName(rs.getString("clientName")) .clientAuthenticationMethods((authenticationMethods) -> - clientAuthenticationMethods.forEach(authenticationMethod -> + clientAuthenticationMethods.forEach((authenticationMethod) -> authenticationMethods.add(resolveClientAuthenticationMethod(authenticationMethod)))) .authorizationGrantTypes((grantTypes) -> - authorizationGrantTypes.forEach(grantType -> + authorizationGrantTypes.forEach((grantType) -> grantTypes.add(resolveAuthorizationGrantType(grantType)))) .redirectUris((uris) -> uris.addAll(redirectUris)) .postLogoutRedirectUris((uris) -> uris.addAll(postLogoutRedirectUris)) diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/client/RegisteredClientTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/client/RegisteredClientTests.java index 91d36e33..c7c75942 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/client/RegisteredClientTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/client/RegisteredClientTests.java @@ -59,8 +59,8 @@ public class RegisteredClientTests { assertThatThrownBy(() -> RegisteredClient.withId(ID) .clientId(CLIENT_ID) .clientSecret(CLIENT_SECRET) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) - .scopes(scopes -> scopes.addAll(SCOPES)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .build()).isInstanceOf(IllegalArgumentException.class); } @@ -77,9 +77,10 @@ public class RegisteredClientTests { .clientName("client-name") .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) - .postLogoutRedirectUris(postLogoutRedirectUris -> postLogoutRedirectUris.addAll(POST_LOGOUT_REDIRECT_URIS)) - .scopes(scopes -> scopes.addAll(SCOPES)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) + .postLogoutRedirectUris( + (postLogoutRedirectUris) -> postLogoutRedirectUris.addAll(POST_LOGOUT_REDIRECT_URIS)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build(); assertThat(registration.getId()).isEqualTo(ID); @@ -108,8 +109,8 @@ public class RegisteredClientTests { .clientSecret(CLIENT_SECRET) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) - .scopes(scopes -> scopes.addAll(SCOPES)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build()).isInstanceOf(IllegalArgumentException.class); } @@ -120,7 +121,7 @@ public class RegisteredClientTests { .clientSecret(CLIENT_SECRET) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .scopes(scopes -> scopes.addAll(SCOPES)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build()).isInstanceOf(IllegalArgumentException.class); } @@ -133,7 +134,7 @@ public class RegisteredClientTests { .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .redirectUri("https://example.com") .redirectUris(Set::clear) - .scopes(scopes -> scopes.addAll(SCOPES)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build()).isInstanceOf(IllegalArgumentException.class); } @@ -143,8 +144,8 @@ public class RegisteredClientTests { .clientId(CLIENT_ID) .clientSecret(CLIENT_SECRET) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) - .scopes(scopes -> scopes.addAll(SCOPES)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build(); assertThat(registration.getClientAuthenticationMethods()) @@ -158,7 +159,7 @@ public class RegisteredClientTests { .clientSecret(CLIENT_SECRET) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) .build(); } @@ -169,8 +170,8 @@ public class RegisteredClientTests { .clientSecret(CLIENT_SECRET) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) - .scopes(scopes -> scopes.addAll(SCOPES)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build(); assertThat(registration.getScopes()).isEqualTo(SCOPES); @@ -182,7 +183,7 @@ public class RegisteredClientTests { .clientId(CLIENT_ID) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) .scope("openid profile") .build()).isInstanceOf(IllegalArgumentException.class); } @@ -194,7 +195,7 @@ public class RegisteredClientTests { .clientSecret(CLIENT_SECRET) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) .scope("an\"invalid\"scope") .build()).isInstanceOf(IllegalArgumentException.class); } @@ -207,7 +208,7 @@ public class RegisteredClientTests { .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .redirectUri("invalid URI") - .scopes(scopes -> scopes.addAll(SCOPES)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build()).isInstanceOf(IllegalArgumentException.class); } @@ -219,7 +220,7 @@ public class RegisteredClientTests { .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .redirectUri("https://example.com/page#fragment") - .scopes(scopes -> scopes.addAll(SCOPES)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build()).isInstanceOf(IllegalArgumentException.class); } @@ -230,7 +231,7 @@ public class RegisteredClientTests { .clientSecret(CLIENT_SECRET) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) .postLogoutRedirectUri("invalid URI") .build()).isInstanceOf(IllegalArgumentException.class); } @@ -244,7 +245,7 @@ public class RegisteredClientTests { .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .redirectUri("https://example.com") .postLogoutRedirectUri("https://example.com/index#fragment") - .scopes(scopes -> scopes.addAll(SCOPES)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build()).isInstanceOf(IllegalArgumentException.class); } @@ -256,8 +257,8 @@ public class RegisteredClientTests { .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) - .scopes(scopes -> scopes.addAll(SCOPES)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build(); assertThat(registration.getAuthorizationGrantTypes()).containsExactlyInAnyOrder( @@ -269,13 +270,13 @@ public class RegisteredClientTests { RegisteredClient registration = RegisteredClient.withId(ID) .clientId(CLIENT_ID) .clientSecret(CLIENT_SECRET) - .authorizationGrantTypes(authorizationGrantTypes -> { + .authorizationGrantTypes((authorizationGrantTypes) -> { authorizationGrantTypes.add(AuthorizationGrantType.AUTHORIZATION_CODE); authorizationGrantTypes.add(AuthorizationGrantType.CLIENT_CREDENTIALS); }) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) - .scopes(scopes -> scopes.addAll(SCOPES)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build(); assertThat(registration.getAuthorizationGrantTypes()).containsExactlyInAnyOrder( @@ -284,17 +285,15 @@ public class RegisteredClientTests { @Test public void buildWhenAuthorizationGrantTypesConsumerClearsSetThenThrowIllegalArgumentException() { - assertThatThrownBy(() -> { - RegisteredClient.withId(ID) - .clientId(CLIENT_ID) - .clientSecret(CLIENT_SECRET) - .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) - .authorizationGrantTypes(Set::clear) - .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) - .scopes(scopes -> scopes.addAll(SCOPES)) - .build(); - }).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> RegisteredClient.withId(ID) + .clientId(CLIENT_ID) + .clientSecret(CLIENT_SECRET) + .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) + .authorizationGrantTypes(Set::clear) + .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) + .scopes((scopes) -> scopes.addAll(SCOPES)) + .build()).isInstanceOf(IllegalArgumentException.class); } @Test @@ -305,8 +304,8 @@ public class RegisteredClientTests { .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) - .scopes(scopes -> scopes.addAll(SCOPES)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build(); assertThat(registration.getClientAuthenticationMethods()).containsExactlyInAnyOrder( @@ -319,12 +318,12 @@ public class RegisteredClientTests { .clientId(CLIENT_ID) .clientSecret(CLIENT_SECRET) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) - .clientAuthenticationMethods(clientAuthenticationMethods -> { + .clientAuthenticationMethods((clientAuthenticationMethods) -> { clientAuthenticationMethods.add(ClientAuthenticationMethod.CLIENT_SECRET_BASIC); clientAuthenticationMethods.add(ClientAuthenticationMethod.CLIENT_SECRET_POST); }) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) - .scopes(scopes -> scopes.addAll(SCOPES)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build(); assertThat(registration.getClientAuthenticationMethods()).containsExactlyInAnyOrder( @@ -340,8 +339,8 @@ public class RegisteredClientTests { .clientSecret(CLIENT_SECRET) .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) - .scopes(scopes -> scopes.addAll(SCOPES)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build(); assertThat(registration.getId()).isEqualTo(overriddenId); @@ -385,15 +384,15 @@ public class RegisteredClientTests { RegisteredClient updated = RegisteredClient.from(registration) .clientName(newName) .clientSecret(newSecret) - .scopes(scopes -> { + .scopes((scopes) -> { scopes.clear(); scopes.add(newScope); }) - .redirectUris(redirectUris -> { + .redirectUris((redirectUris) -> { redirectUris.clear(); redirectUris.add(newRedirectUri); }) - .postLogoutRedirectUris(postLogoutRedirectUris -> { + .postLogoutRedirectUris((postLogoutRedirectUris) -> { postLogoutRedirectUris.clear(); postLogoutRedirectUris.add(newPostLogoutRedirectUri); }) @@ -420,8 +419,8 @@ public class RegisteredClientTests { .clientName("client-name") .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .clientAuthenticationMethod(ClientAuthenticationMethod.NONE) - .redirectUris(redirectUris -> redirectUris.addAll(REDIRECT_URIS)) - .scopes(scopes -> scopes.addAll(SCOPES)) + .redirectUris((redirectUris) -> redirectUris.addAll(REDIRECT_URIS)) + .scopes((scopes) -> scopes.addAll(SCOPES)) .build(); assertThat(registration.getId()).isEqualTo(ID); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/client/TestRegisteredClients.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/client/TestRegisteredClients.java index 208f0ccb..e08851d3 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/client/TestRegisteredClients.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/client/TestRegisteredClients.java @@ -25,7 +25,10 @@ import org.springframework.security.oauth2.server.authorization.settings.ClientS /** * @author Anoop Garlapati */ -public class TestRegisteredClients { +public final class TestRegisteredClients { + + private TestRegisteredClients() { + } public static RegisteredClient.Builder registeredClient() { return RegisteredClient.withId("registration-1") diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configuration/RegisterMissingBeanPostProcessorTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configuration/RegisterMissingBeanPostProcessorTests.java index 7cada95e..e637698f 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configuration/RegisterMissingBeanPostProcessorTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configuration/RegisterMissingBeanPostProcessorTests.java @@ -104,7 +104,7 @@ public class RegisterMissingBeanPostProcessorTests { } private String getField() { - return field; + return this.field; } } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/JwkSetTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/JwkSetTests.java index 51d19c9e..677c13d9 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/JwkSetTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/JwkSetTests.java @@ -93,8 +93,8 @@ public class JwkSetTests { @AfterEach public void tearDown() { - jdbcOperations.update("truncate table oauth2_authorization"); - jdbcOperations.update("truncate table oauth2_registered_client"); + this.jdbcOperations.update("truncate table oauth2_authorization"); + this.jdbcOperations.update("truncate table oauth2_registered_client"); } @AfterAll diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationCodeGrantTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationCodeGrantTests.java index 9e18413a..7b00e671 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationCodeGrantTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationCodeGrantTests.java @@ -134,12 +134,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.containsString; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @@ -259,9 +259,9 @@ public class OAuth2AuthorizationCodeGrantTests { @AfterEach public void tearDown() { - jdbcOperations.update("truncate table oauth2_authorization"); - jdbcOperations.update("truncate table oauth2_authorization_consent"); - jdbcOperations.update("truncate table oauth2_registered_client"); + this.jdbcOperations.update("truncate table oauth2_authorization"); + this.jdbcOperations.update("truncate table oauth2_authorization_consent"); + this.jdbcOperations.update("truncate table oauth2_registered_client"); } @AfterAll @@ -311,7 +311,7 @@ public class OAuth2AuthorizationCodeGrantTests { } private void assertAuthorizationRequestRedirectsToClient(String authorizationEndpointUri) throws Exception { - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().redirectUris(redirectUris -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().redirectUris((redirectUris) -> { redirectUris.clear(); redirectUris.add("https://example.com/callback-1?param=encoded%20parameter%20value"); // gh-1011 }).build(); @@ -499,7 +499,7 @@ public class OAuth2AuthorizationCodeGrantTests { this.spring.register(AuthorizationServerConfiguration.class).autowire(); String redirectUri = "https://example.com/callback-1?param=encoded%20parameter%20value"; - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().redirectUris(redirectUris -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().redirectUris((redirectUris) -> { redirectUris.clear(); redirectUris.add(redirectUri); }).clientSettings(ClientSettings.builder().requireProofKey(true).build()).build(); @@ -576,7 +576,7 @@ public class OAuth2AuthorizationCodeGrantTests { public void requestWhenRequiresConsentThenDisplaysConsentPage() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(scopes -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> { scopes.clear(); scopes.add("message.read"); scopes.add("message.write"); @@ -601,7 +601,7 @@ public class OAuth2AuthorizationCodeGrantTests { public void requestWhenConsentRequestThenReturnAccessTokenResponse() throws Exception { this.spring.register(AuthorizationServerConfiguration.class).autowire(); - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(scopes -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> { scopes.clear(); scopes.add("message.read"); scopes.add("message.write"); @@ -658,7 +658,7 @@ public class OAuth2AuthorizationCodeGrantTests { public void requestWhenCustomConsentPageConfiguredThenRedirect() throws Exception { this.spring.register(AuthorizationServerConfigurationCustomConsentPage.class).autowire(); - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(scopes -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> { scopes.clear(); scopes.add("message.read"); scopes.add("message.write"); @@ -739,7 +739,7 @@ public class OAuth2AuthorizationCodeGrantTests { .andExpect(jsonPath("$.access_token").value(new AssertionMatcher() { @Override public void assertion(String accessToken) throws AssertionError { - Jwt jwt = jwtDecoder.decode(accessToken); + Jwt jwt = OAuth2AuthorizationCodeGrantTests.this.jwtDecoder.decode(accessToken); assertThat(jwt.getClaimAsStringList(AUTHORITIES_CLAIM)).containsExactlyInAnyOrder("authority-1", "authority-2"); } @@ -763,11 +763,11 @@ public class OAuth2AuthorizationCodeGrantTests { "https://provider.com/oauth2/authorize", registeredClient.getClientId(), principal, authorizationCode, registeredClient.getRedirectUris().iterator().next(), STATE_URL_UNENCODED, registeredClient.getScopes()); - when(authorizationRequestConverter.convert(any())).thenReturn(authorizationCodeRequestAuthenticationResult); - when(authorizationRequestAuthenticationProvider - .supports(eq(OAuth2AuthorizationCodeRequestAuthenticationToken.class))).thenReturn(true); - when(authorizationRequestAuthenticationProvider.authenticate(any())) - .thenReturn(authorizationCodeRequestAuthenticationResult); + given(authorizationRequestConverter.convert(any())).willReturn(authorizationCodeRequestAuthenticationResult); + given(authorizationRequestAuthenticationProvider + .supports(eq(OAuth2AuthorizationCodeRequestAuthenticationToken.class))).willReturn(true); + given(authorizationRequestAuthenticationProvider.authenticate(any())) + .willReturn(authorizationCodeRequestAuthenticationResult); this.mvc .perform(get(DEFAULT_AUTHORIZATION_ENDPOINT_URI).params(getAuthorizationRequestParameters(registeredClient)) @@ -940,7 +940,7 @@ public class OAuth2AuthorizationCodeGrantTests { @Bean OAuth2TokenCustomizer jwtCustomizer() { - return context -> { + return (context) -> { if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(context.getAuthorizationGrantType()) && OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) { Authentication principal = context.getPrincipal(); @@ -985,18 +985,18 @@ public class OAuth2AuthorizationCodeGrantTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); RequestMatcher endpointsMatcher = authorizationServerConfigurer.getEndpointsMatcher(); http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) - .securityContext(securityContext -> + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .securityContext((securityContext) -> securityContext.securityContextRepository(securityContextRepository)) .apply(authorizationServerConfigurer); return http.build(); @@ -1048,20 +1048,20 @@ public class OAuth2AuthorizationCodeGrantTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); authorizationServerConfigurer - .authorizationEndpoint(authorizationEndpoint -> + .authorizationEndpoint((authorizationEndpoint) -> authorizationEndpoint.consentPage(consentPage)); RequestMatcher endpointsMatcher = authorizationServerConfigurer.getEndpointsMatcher(); http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) .apply(authorizationServerConfigurer); return http.build(); } @@ -1078,20 +1078,20 @@ public class OAuth2AuthorizationCodeGrantTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); authorizationServerConfigurer - .authorizationEndpoint(authorizationEndpoint -> + .authorizationEndpoint((authorizationEndpoint) -> authorizationEndpoint.authenticationProviders(configureAuthenticationProviders())); RequestMatcher endpointsMatcher = authorizationServerConfigurer.getEndpointsMatcher(); http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) .apply(authorizationServerConfigurer); return http.build(); } @@ -1100,7 +1100,7 @@ public class OAuth2AuthorizationCodeGrantTests { @Bean @Override OAuth2TokenCustomizer jwtCustomizer() { - return context -> { + return (context) -> { if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(context.getAuthorizationGrantType()) && OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) { OAuth2AuthorizationConsent authorizationConsent = this.authorizationConsentService @@ -1167,11 +1167,11 @@ public class OAuth2AuthorizationCodeGrantTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); authorizationServerConfigurer - .authorizationEndpoint(authorizationEndpoint -> + .authorizationEndpoint((authorizationEndpoint) -> authorizationEndpoint .authorizationRequestConverter(authorizationRequestConverter) .authorizationRequestConverters(authorizationRequestConvertersConsumer) @@ -1183,10 +1183,10 @@ public class OAuth2AuthorizationCodeGrantTests { http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) .apply(authorizationServerConfigurer); return http.build(); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationServerMetadataTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationServerMetadataTests.java index 6824ee53..4b0aa93d 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationServerMetadataTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2AuthorizationServerMetadataTests.java @@ -96,8 +96,8 @@ public class OAuth2AuthorizationServerMetadataTests { @AfterEach public void tearDown() { - jdbcOperations.update("truncate table oauth2_authorization"); - jdbcOperations.update("truncate table oauth2_registered_client"); + this.jdbcOperations.update("truncate table oauth2_authorization"); + this.jdbcOperations.update("truncate table oauth2_registered_client"); } @AfterAll @@ -173,13 +173,13 @@ public class OAuth2AuthorizationServerMetadataTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); http.apply(authorizationServerConfigurer); authorizationServerConfigurer - .authorizationServerMetadataEndpoint(authorizationServerMetadataEndpoint -> + .authorizationServerMetadataEndpoint((authorizationServerMetadataEndpoint) -> authorizationServerMetadataEndpoint .authorizationServerMetadataCustomizer(authorizationServerMetadataCustomizer())); @@ -187,10 +187,10 @@ public class OAuth2AuthorizationServerMetadataTests { http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)); + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)); return http.build(); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2ClientCredentialsGrantTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2ClientCredentialsGrantTests.java index b3b63d0f..c6b86af5 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2ClientCredentialsGrantTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2ClientCredentialsGrantTests.java @@ -24,13 +24,12 @@ import java.util.Base64; import java.util.List; import java.util.function.Consumer; -import jakarta.servlet.ServletException; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - import com.nimbusds.jose.jwk.JWKSet; import com.nimbusds.jose.jwk.source.JWKSource; import com.nimbusds.jose.proc.SecurityContext; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; @@ -105,11 +104,11 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -188,8 +187,8 @@ public class OAuth2ClientCredentialsGrantTests { @AfterEach public void tearDown() { - jdbcOperations.update("truncate table oauth2_authorization"); - jdbcOperations.update("truncate table oauth2_registered_client"); + this.jdbcOperations.update("truncate table oauth2_authorization"); + this.jdbcOperations.update("truncate table oauth2_registered_client"); } @AfterAll @@ -285,14 +284,14 @@ public class OAuth2ClientCredentialsGrantTests { ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); OAuth2ClientCredentialsAuthenticationToken clientCredentialsAuthentication = new OAuth2ClientCredentialsAuthenticationToken( clientPrincipal, null, null); - when(authenticationConverter.convert(any())).thenReturn(clientCredentialsAuthentication); + given(authenticationConverter.convert(any())).willReturn(clientCredentialsAuthentication); OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", Instant.now(), Instant.now().plus(Duration.ofHours(1))); OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = new OAuth2AccessTokenAuthenticationToken( registeredClient, clientPrincipal, accessToken); - when(authenticationProvider.supports(eq(OAuth2ClientCredentialsAuthenticationToken.class))).thenReturn(true); - when(authenticationProvider.authenticate(any())).thenReturn(accessTokenAuthentication); + given(authenticationProvider.supports(eq(OAuth2ClientCredentialsAuthenticationToken.class))).willReturn(true); + given(authenticationProvider.authenticate(any())).willReturn(accessTokenAuthentication); this.mvc .perform(post(DEFAULT_TOKEN_ENDPOINT_URI) @@ -339,9 +338,9 @@ public class OAuth2ClientCredentialsGrantTests { OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, new ClientAuthenticationMethod("custom"), null); - when(authenticationConverter.convert(any())).thenReturn(clientPrincipal); - when(authenticationProvider.supports(eq(OAuth2ClientAuthenticationToken.class))).thenReturn(true); - when(authenticationProvider.authenticate(any())).thenReturn(clientPrincipal); + given(authenticationConverter.convert(any())).willReturn(clientPrincipal); + given(authenticationProvider.supports(eq(OAuth2ClientAuthenticationToken.class))).willReturn(true); + given(authenticationProvider.authenticate(any())).willReturn(clientPrincipal); this.mvc .perform(post(DEFAULT_TOKEN_ENDPOINT_URI).param(OAuth2ParameterNames.GRANT_TYPE, @@ -453,11 +452,11 @@ public class OAuth2ClientCredentialsGrantTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); authorizationServerConfigurer - .tokenEndpoint(tokenEndpoint -> + .tokenEndpoint((tokenEndpoint) -> tokenEndpoint .accessTokenRequestConverter(authenticationConverter) .accessTokenRequestConverters(authenticationConvertersConsumer) @@ -469,10 +468,10 @@ public class OAuth2ClientCredentialsGrantTests { http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) .apply(authorizationServerConfigurer); return http.build(); } @@ -497,13 +496,13 @@ public class OAuth2ClientCredentialsGrantTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { authenticationSuccessHandler = spy(authenticationSuccessHandler()); OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); authorizationServerConfigurer - .clientAuthentication(clientAuthentication -> + .clientAuthentication((clientAuthentication) -> clientAuthentication .authenticationConverter(authenticationConverter) .authenticationConverters(authenticationConvertersConsumer) @@ -515,10 +514,10 @@ public class OAuth2ClientCredentialsGrantTests { http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) .apply(authorizationServerConfigurer); return http.build(); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2DeviceCodeGrantTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2DeviceCodeGrantTests.java index 88450aa9..f3edae28 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2DeviceCodeGrantTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2DeviceCodeGrantTests.java @@ -151,9 +151,9 @@ public class OAuth2DeviceCodeGrantTests { @AfterEach public void tearDown() { - jdbcOperations.update("truncate table oauth2_authorization"); - jdbcOperations.update("truncate table oauth2_authorization_consent"); - jdbcOperations.update("truncate table oauth2_registered_client"); + this.jdbcOperations.update("truncate table oauth2_authorization"); + this.jdbcOperations.update("truncate table oauth2_authorization_consent"); + this.jdbcOperations.update("truncate table oauth2_registered_client"); } @AfterAll diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2RefreshTokenGrantTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2RefreshTokenGrantTests.java index c9a2b5c3..f478599b 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2RefreshTokenGrantTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2RefreshTokenGrantTests.java @@ -142,8 +142,8 @@ public class OAuth2RefreshTokenGrantTests { @AfterEach public void tearDown() { - jdbcOperations.update("truncate table oauth2_authorization"); - jdbcOperations.update("truncate table oauth2_registered_client"); + this.jdbcOperations.update("truncate table oauth2_authorization"); + this.jdbcOperations.update("truncate table oauth2_registered_client"); } @AfterAll @@ -282,7 +282,7 @@ public class OAuth2RefreshTokenGrantTests { @Bean OAuth2TokenCustomizer jwtCustomizer() { - return context -> { + return (context) -> { if (AuthorizationGrantType.REFRESH_TOKEN.equals(context.getAuthorizationGrantType())) { Authentication principal = context.getPrincipal(); Set authorities = new HashSet<>(); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenIntrospectionTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenIntrospectionTests.java index dc53cc78..434c91db 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenIntrospectionTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenIntrospectionTests.java @@ -106,9 +106,9 @@ import org.springframework.util.MultiValueMap; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -180,8 +180,8 @@ public class OAuth2TokenIntrospectionTests { @AfterEach public void tearDown() { - jdbcOperations.update("truncate table oauth2_authorization"); - jdbcOperations.update("truncate table oauth2_registered_client"); + this.jdbcOperations.update("truncate table oauth2_authorization"); + this.jdbcOperations.update("truncate table oauth2_registered_client"); } @AfterAll @@ -375,9 +375,9 @@ public class OAuth2TokenIntrospectionTests { OAuth2TokenIntrospectionAuthenticationToken tokenIntrospectionAuthentication = new OAuth2TokenIntrospectionAuthenticationToken( accessToken.getTokenValue(), clientPrincipal, null, null); - when(authenticationConverter.convert(any())).thenReturn(tokenIntrospectionAuthentication); - when(authenticationProvider.supports(eq(OAuth2TokenIntrospectionAuthenticationToken.class))).thenReturn(true); - when(authenticationProvider.authenticate(any())).thenReturn(tokenIntrospectionAuthentication); + given(authenticationConverter.convert(any())).willReturn(tokenIntrospectionAuthentication); + given(authenticationProvider.supports(eq(OAuth2TokenIntrospectionAuthenticationToken.class))).willReturn(true); + given(authenticationProvider.authenticate(any())).willReturn(tokenIntrospectionAuthentication); // @formatter:off this.mvc.perform(post(authorizationServerSettings.getTokenIntrospectionEndpoint()) @@ -528,11 +528,11 @@ public class OAuth2TokenIntrospectionTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); authorizationServerConfigurer - .tokenIntrospectionEndpoint(tokenIntrospectionEndpoint -> + .tokenIntrospectionEndpoint((tokenIntrospectionEndpoint) -> tokenIntrospectionEndpoint .introspectionRequestConverter(authenticationConverter) .introspectionRequestConverters(authenticationConvertersConsumer) @@ -544,10 +544,10 @@ public class OAuth2TokenIntrospectionTests { http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) .apply(authorizationServerConfigurer); return http.build(); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenRevocationTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenRevocationTests.java index 67cec39d..441945a2 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenRevocationTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OAuth2TokenRevocationTests.java @@ -84,9 +84,9 @@ import org.springframework.util.MultiValueMap; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -151,8 +151,8 @@ public class OAuth2TokenRevocationTests { @AfterEach public void tearDown() { - jdbcOperations.update("truncate table oauth2_authorization"); - jdbcOperations.update("truncate table oauth2_registered_client"); + this.jdbcOperations.update("truncate table oauth2_authorization"); + this.jdbcOperations.update("truncate table oauth2_registered_client"); } @AfterAll @@ -229,9 +229,9 @@ public class OAuth2TokenRevocationTests { OAuth2TokenRevocationAuthenticationToken tokenRevocationAuthentication = new OAuth2TokenRevocationAuthenticationToken( token, clientPrincipal); - when(authenticationConverter.convert(any())).thenReturn(tokenRevocationAuthentication); - when(authenticationProvider.supports(eq(OAuth2TokenRevocationAuthenticationToken.class))).thenReturn(true); - when(authenticationProvider.authenticate(any())).thenReturn(tokenRevocationAuthentication); + given(authenticationConverter.convert(any())).willReturn(tokenRevocationAuthentication); + given(authenticationProvider.supports(eq(OAuth2TokenRevocationAuthenticationToken.class))).willReturn(true); + given(authenticationProvider.authenticate(any())).willReturn(tokenRevocationAuthentication); this.mvc .perform(post(DEFAULT_TOKEN_REVOCATION_ENDPOINT_URI) @@ -344,11 +344,11 @@ public class OAuth2TokenRevocationTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); authorizationServerConfigurer - .tokenRevocationEndpoint(tokenRevocationEndpoint -> + .tokenRevocationEndpoint((tokenRevocationEndpoint) -> tokenRevocationEndpoint .revocationRequestConverter(authenticationConverter) .revocationRequestConverters(authenticationConvertersConsumer) @@ -360,10 +360,10 @@ public class OAuth2TokenRevocationTests { http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) .apply(authorizationServerConfigurer); return http.build(); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcClientRegistrationTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcClientRegistrationTests.java index 7afac8fb..75f79fc7 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcClientRegistrationTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcClientRegistrationTests.java @@ -114,12 +114,12 @@ import org.springframework.web.util.UriComponentsBuilder; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.containsString; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doAnswer; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -216,14 +216,14 @@ public class OidcClientRegistrationTests { .setBody(clientJwkSet.toString()); // @formatter:on this.server.enqueue(response); - when(authenticationProvider.supports(OidcClientRegistrationAuthenticationToken.class)).thenReturn(true); + given(authenticationProvider.supports(OidcClientRegistrationAuthenticationToken.class)).willReturn(true); } @AfterEach public void tearDown() throws Exception { this.server.shutdown(); - jdbcOperations.update("truncate table oauth2_authorization"); - jdbcOperations.update("truncate table oauth2_registered_client"); + this.jdbcOperations.update("truncate table oauth2_authorization"); + this.jdbcOperations.update("truncate table oauth2_registered_client"); reset(authenticationConverter); reset(authenticationConvertersConsumer); reset(authenticationProvider); @@ -343,13 +343,13 @@ public class OidcClientRegistrationTests { .build(); // @formatter:on - doAnswer(invocation -> { + willAnswer((invocation) -> { HttpServletResponse response = invocation.getArgument(1, HttpServletResponse.class); ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response); httpResponse.setStatusCode(HttpStatus.CREATED); new OidcClientRegistrationHttpMessageConverter().write(clientRegistration, null, httpResponse); return null; - }).when(authenticationSuccessHandler).onAuthenticationSuccess(any(), any(), any()); + }).given(authenticationSuccessHandler).onAuthenticationSuccess(any(), any(), any()); registerClient(clientRegistration); @@ -359,7 +359,7 @@ public class OidcClientRegistrationTests { verify(authenticationConvertersConsumer).accept(authenticationConvertersCaptor.capture()); List authenticationConverters = authenticationConvertersCaptor.getValue(); assertThat(authenticationConverters).hasSize(2) - .allMatch(converter -> converter == authenticationConverter + .allMatch((converter) -> converter == authenticationConverter || converter instanceof OidcClientRegistrationAuthenticationConverter); verify(authenticationProvider).authenticate(any()); @@ -368,7 +368,7 @@ public class OidcClientRegistrationTests { verify(authenticationProvidersConsumer).accept(authenticationProvidersCaptor.capture()); List authenticationProviders = authenticationProvidersCaptor.getValue(); assertThat(authenticationProviders).hasSize(3) - .allMatch(provider -> provider == authenticationProvider + .allMatch((provider) -> provider == authenticationProvider || provider instanceof OidcClientRegistrationAuthenticationProvider || provider instanceof OidcClientConfigurationAuthenticationProvider); @@ -381,7 +381,7 @@ public class OidcClientRegistrationTests { throws Exception { this.spring.register(CustomClientRegistrationConfiguration.class).autowire(); - when(authenticationProvider.authenticate(any())).thenThrow(new OAuth2AuthenticationException("error")); + given(authenticationProvider.authenticate(any())).willThrow(new OAuth2AuthenticationException("error")); this.mvc .perform(get(DEFAULT_OIDC_CLIENT_REGISTRATION_ENDPOINT_URI).param(OAuth2ParameterNames.CLIENT_ID, "invalid") @@ -611,9 +611,9 @@ public class OidcClientRegistrationTests { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); authorizationServerConfigurer - .oidc(oidc -> + .oidc((oidc) -> oidc - .clientRegistrationEndpoint(clientRegistration -> + .clientRegistrationEndpoint((clientRegistration) -> clientRegistration .clientRegistrationRequestConverter(authenticationConverter) .clientRegistrationRequestConverters(authenticationConvertersConsumer) @@ -627,11 +627,11 @@ public class OidcClientRegistrationTests { http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) - .oauth2ResourceServer(resourceServer -> + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .oauth2ResourceServer((resourceServer) -> resourceServer.jwt(Customizer.withDefaults()) ) .apply(authorizationServerConfigurer); @@ -652,9 +652,9 @@ public class OidcClientRegistrationTests { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); authorizationServerConfigurer - .oidc(oidc -> + .oidc((oidc) -> oidc - .clientRegistrationEndpoint(clientRegistration -> + .clientRegistrationEndpoint((clientRegistration) -> clientRegistration .authenticationProviders(configureRegisteredClientConverter()) ) @@ -663,11 +663,11 @@ public class OidcClientRegistrationTests { http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) - .oauth2ResourceServer(resourceServer -> + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .oauth2ResourceServer((resourceServer) -> resourceServer.jwt(Customizer.withDefaults()) ) .apply(authorizationServerConfigurer); @@ -711,31 +711,35 @@ public class OidcClientRegistrationTests { builder .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST) .clientSecret(CLIENT_SECRET_GENERATOR.generateKey()); - } else if (ClientAuthenticationMethod.CLIENT_SECRET_JWT.getValue().equals(clientRegistration.getTokenEndpointAuthenticationMethod())) { + } + else if (ClientAuthenticationMethod.CLIENT_SECRET_JWT.getValue().equals(clientRegistration.getTokenEndpointAuthenticationMethod())) { builder .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_JWT) .clientSecret(CLIENT_SECRET_GENERATOR.generateKey()); - } else if (ClientAuthenticationMethod.PRIVATE_KEY_JWT.getValue().equals(clientRegistration.getTokenEndpointAuthenticationMethod())) { + } + else if (ClientAuthenticationMethod.PRIVATE_KEY_JWT.getValue().equals(clientRegistration.getTokenEndpointAuthenticationMethod())) { builder.clientAuthenticationMethod(ClientAuthenticationMethod.PRIVATE_KEY_JWT); - } else { + } + else { builder .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .clientSecret(CLIENT_SECRET_GENERATOR.generateKey()); } - builder.redirectUris(redirectUris -> + builder.redirectUris((redirectUris) -> redirectUris.addAll(clientRegistration.getRedirectUris())); if (!CollectionUtils.isEmpty(clientRegistration.getPostLogoutRedirectUris())) { - builder.postLogoutRedirectUris(postLogoutRedirectUris -> + builder.postLogoutRedirectUris((postLogoutRedirectUris) -> postLogoutRedirectUris.addAll(clientRegistration.getPostLogoutRedirectUris())); } if (!CollectionUtils.isEmpty(clientRegistration.getGrantTypes())) { - builder.authorizationGrantTypes(authorizationGrantTypes -> - clientRegistration.getGrantTypes().forEach(grantType -> + builder.authorizationGrantTypes((authorizationGrantTypes) -> + clientRegistration.getGrantTypes().forEach((grantType) -> authorizationGrantTypes.add(new AuthorizationGrantType(grantType)))); - } else { + } + else { builder.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE); } if (CollectionUtils.isEmpty(clientRegistration.getResponseTypes()) || @@ -744,7 +748,7 @@ public class OidcClientRegistrationTests { } if (!CollectionUtils.isEmpty(clientRegistration.getScopes())) { - builder.scopes(scopes -> + builder.scopes((scopes) -> scopes.addAll(clientRegistration.getScopes())); } @@ -758,7 +762,8 @@ public class OidcClientRegistrationTests { macAlgorithm = MacAlgorithm.HS256; } clientSettingsBuilder.tokenEndpointAuthenticationSigningAlgorithm(macAlgorithm); - } else if (ClientAuthenticationMethod.PRIVATE_KEY_JWT.getValue().equals(clientRegistration.getTokenEndpointAuthenticationMethod())) { + } + else if (ClientAuthenticationMethod.PRIVATE_KEY_JWT.getValue().equals(clientRegistration.getTokenEndpointAuthenticationMethod())) { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.from(clientRegistration.getTokenEndpointAuthenticationSigningAlgorithm()); if (signatureAlgorithm == null) { signatureAlgorithm = SignatureAlgorithm.RS256; @@ -794,21 +799,21 @@ public class OidcClientRegistrationTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); authorizationServerConfigurer - .oidc(oidc -> + .oidc((oidc) -> oidc.clientRegistrationEndpoint(Customizer.withDefaults())); RequestMatcher endpointsMatcher = authorizationServerConfigurer.getEndpointsMatcher(); http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) - .oauth2ResourceServer(resourceServer -> + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .oauth2ResourceServer((resourceServer) -> resourceServer.jwt(Customizer.withDefaults()) ) .apply(authorizationServerConfigurer); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcProviderConfigurationTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcProviderConfigurationTests.java index 096cf87d..dbabeacb 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcProviderConfigurationTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcProviderConfigurationTests.java @@ -225,14 +225,14 @@ public class OidcProviderConfigurationTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); http.apply(authorizationServerConfigurer); authorizationServerConfigurer - .oidc(oidc -> - oidc.providerConfigurationEndpoint(providerConfigurationEndpoint -> + .oidc((oidc) -> + oidc.providerConfigurationEndpoint((providerConfigurationEndpoint) -> providerConfigurationEndpoint .providerConfigurationCustomizer(providerConfigurationCustomizer()))); @@ -240,10 +240,10 @@ public class OidcProviderConfigurationTests { http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)); + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)); return http.build(); } @@ -268,7 +268,7 @@ public class OidcProviderConfigurationTests { http.apply(authorizationServerConfigurer); authorizationServerConfigurer - .oidc(oidc -> + .oidc((oidc) -> oidc.clientRegistrationEndpoint(Customizer.withDefaults()) ); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcTests.java index b9f21bdc..ff414080 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcTests.java @@ -179,9 +179,9 @@ public class OidcTests { @AfterEach public void tearDown() { - if (jdbcOperations != null) { - jdbcOperations.update("truncate table oauth2_authorization"); - jdbcOperations.update("truncate table oauth2_registered_client"); + if (this.jdbcOperations != null) { + this.jdbcOperations.update("truncate table oauth2_authorization"); + this.jdbcOperations.update("truncate table oauth2_registered_client"); } } @@ -552,7 +552,7 @@ public class OidcTests { @Bean OAuth2TokenCustomizer jwtCustomizer() { - return context -> { + return (context) -> { if (context.getTokenType().getValue().equals(OidcParameterNames.ID_TOKEN)) { Authentication principal = context.getPrincipal(); Set authorities = new HashSet<>(); @@ -605,7 +605,7 @@ public class OidcTests { // @formatter:off @Bean - public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); http.apply(authorizationServerConfigurer); @@ -619,10 +619,10 @@ public class OidcTests { http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)); + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)); return http.build(); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcUserInfoTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcUserInfoTests.java index bdc58a11..c43af61b 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcUserInfoTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/config/annotation/web/configurers/OidcUserInfoTests.java @@ -87,13 +87,13 @@ import org.springframework.test.web.servlet.ResultMatcher; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doAnswer; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; @@ -202,7 +202,7 @@ public class OidcUserInfoTests { OAuth2Authorization authorization = createAuthorization(); this.authorizationService.save(authorization); - when(userInfoMapper.apply(any())).thenReturn(createUserInfo()); + given(userInfoMapper.apply(any())).willReturn(createUserInfo()); OAuth2AccessToken accessToken = authorization.getAccessToken().getToken(); // @formatter:off @@ -221,7 +221,7 @@ public class OidcUserInfoTests { verify(authenticationProvidersConsumer).accept(authenticationProvidersCaptor.capture()); List authenticationProviders = authenticationProvidersCaptor.getValue(); assertThat(authenticationProviders).hasSize(2) - .allMatch(provider -> provider == authenticationProvider + .allMatch((provider) -> provider == authenticationProvider || provider instanceof OidcUserInfoAuthenticationProvider); ArgumentCaptor> authenticationConvertersCaptor = ArgumentCaptor @@ -238,12 +238,12 @@ public class OidcUserInfoTests { OAuth2Authorization authorization = createAuthorization(); this.authorizationService.save(authorization); - when(authenticationProvider.supports(eq(OidcUserInfoAuthenticationToken.class))).thenReturn(true); + given(authenticationProvider.supports(eq(OidcUserInfoAuthenticationToken.class))).willReturn(true); String tokenValue = authorization.getAccessToken().getToken().getTokenValue(); Jwt jwt = this.jwtDecoder.decode(tokenValue); OidcUserInfoAuthenticationToken oidcUserInfoAuthentication = new OidcUserInfoAuthenticationToken( new JwtAuthenticationToken(jwt), createUserInfo()); - when(authenticationProvider.authenticate(any())).thenReturn(oidcUserInfoAuthentication); + given(authenticationProvider.authenticate(any())).willReturn(oidcUserInfoAuthentication); OAuth2AccessToken accessToken = authorization.getAccessToken().getToken(); // @formatter:off @@ -262,13 +262,13 @@ public class OidcUserInfoTests { public void requestWhenUserInfoEndpointCustomizedWithAuthenticationFailureHandlerThenUsed() throws Exception { this.spring.register(CustomUserInfoConfiguration.class).autowire(); - when(userInfoMapper.apply(any())).thenReturn(createUserInfo()); - doAnswer(invocation -> { + given(userInfoMapper.apply(any())).willReturn(createUserInfo()); + willAnswer((invocation) -> { HttpServletResponse response = invocation.getArgument(1); response.setStatus(HttpStatus.UNAUTHORIZED.value()); response.getWriter().write("unauthorized"); return null; - }).when(authenticationFailureHandler).onAuthenticationFailure(any(), any(), any()); + }).given(authenticationFailureHandler).onAuthenticationFailure(any(), any(), any()); OAuth2AccessToken accessToken = createAuthorization().getAccessToken().getToken(); // @formatter:off @@ -336,7 +336,7 @@ public class OidcUserInfoTests { JwsHeader headers = JwsHeader.with(SignatureAlgorithm.RS256).build(); // @formatter:off JwtClaimsSet claimSet = JwtClaimsSet.builder() - .claims(claims -> claims.putAll(createUserInfo().getClaims())) + .claims((claims) -> claims.putAll(createUserInfo().getClaims())) .build(); // @formatter:on Jwt jwt = this.jwtEncoder.encode(JwtEncoderParameters.from(headers, claimSet)); @@ -347,7 +347,7 @@ public class OidcUserInfoTests { OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, jwt.getTokenValue(), now, now.plusSeconds(300), scopes); OidcIdToken idToken = OidcIdToken.withTokenValue("id-token") - .claims(claims -> claims.putAll(createUserInfo().getClaims())) + .claims((claims) -> claims.putAll(createUserInfo().getClaims())) .build(); return TestOAuth2Authorizations.authorization().accessToken(accessToken).token(idToken).build(); @@ -393,16 +393,16 @@ public class OidcUserInfoTests { // @formatter:off http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) - .oauth2ResourceServer(resourceServer -> + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .oauth2ResourceServer((resourceServer) -> resourceServer.jwt(Customizer.withDefaults()) ) .apply(authorizationServerConfigurer) - .oidc(oidc -> oidc - .userInfoEndpoint(userInfo -> userInfo + .oidc((oidc) -> oidc + .userInfoEndpoint((userInfo) -> userInfo .userInfoRequestConverter(authenticationConverter) .userInfoRequestConverters(authenticationConvertersConsumer) .authenticationProvider(authenticationProvider) @@ -435,14 +435,14 @@ public class OidcUserInfoTests { // @formatter:off http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) - .oauth2ResourceServer(resourceServer -> + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .oauth2ResourceServer((resourceServer) -> resourceServer.jwt(Customizer.withDefaults()) ) - .securityContext(securityContext -> + .securityContext((securityContext) -> securityContext.securityContextRepository(securityContextRepository)) .apply(authorizationServerConfigurer); // @formatter:on @@ -466,11 +466,11 @@ public class OidcUserInfoTests { // @formatter:off http .securityMatcher(endpointsMatcher) - .authorizeHttpRequests(authorize -> + .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ) - .csrf(csrf -> csrf.ignoringRequestMatchers(endpointsMatcher)) - .oauth2ResourceServer(resourceServer -> + .csrf((csrf) -> csrf.ignoringRequestMatchers(endpointsMatcher)) + .oauth2ResourceServer((resourceServer) -> resourceServer.jwt(Customizer.withDefaults()) ) .apply(authorizationServerConfigurer); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/context/TestAuthorizationServerContext.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/context/TestAuthorizationServerContext.java index fc406ac2..e7c14db4 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/context/TestAuthorizationServerContext.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/context/TestAuthorizationServerContext.java @@ -37,7 +37,7 @@ public class TestAuthorizationServerContext implements AuthorizationServerContex @Override public String getIssuer() { - return this.issuerSupplier != null ? this.issuerSupplier.get() : getAuthorizationServerSettings().getIssuer(); + return (this.issuerSupplier != null) ? this.issuerSupplier.get() : getAuthorizationServerSettings().getIssuer(); } @Override diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/http/converter/OAuth2AuthorizationServerMetadataHttpMessageConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/http/converter/OAuth2AuthorizationServerMetadataHttpMessageConverterTests.java index 7c291e2d..f7f205d6 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/http/converter/OAuth2AuthorizationServerMetadataHttpMessageConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/http/converter/OAuth2AuthorizationServerMetadataHttpMessageConverterTests.java @@ -148,7 +148,7 @@ public class OAuth2AuthorizationServerMetadataHttpMessageConverterTests { @Test public void readInternalWhenFailingConverterThenThrowException() { String errorMessage = "this is not a valid converter"; - this.messageConverter.setAuthorizationServerMetadataConverter(source -> { + this.messageConverter.setAuthorizationServerMetadataConverter((source) -> { throw new RuntimeException(errorMessage); }); MockClientHttpResponse response = new MockClientHttpResponse("{}".getBytes(), HttpStatus.OK); @@ -224,7 +224,7 @@ public class OAuth2AuthorizationServerMetadataHttpMessageConverterTests { @Test public void writeInternalWhenWriteFailsThenThrowException() { String errorMessage = "this is not a valid converter"; - Converter> failingConverter = source -> { + Converter> failingConverter = (source) -> { throw new RuntimeException(errorMessage); }; this.messageConverter.setAuthorizationServerMetadataParametersConverter(failingConverter); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/http/converter/OAuth2TokenIntrospectionHttpMessageConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/http/converter/OAuth2TokenIntrospectionHttpMessageConverterTests.java index ddf06789..3866f0cb 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/http/converter/OAuth2TokenIntrospectionHttpMessageConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/http/converter/OAuth2TokenIntrospectionHttpMessageConverterTests.java @@ -105,7 +105,7 @@ public class OAuth2TokenIntrospectionHttpMessageConverterTests { @Test public void readInternalWhenFailingConverterThenThrowException() { String errorMessage = "this is not a valid converter"; - this.messageConverter.setTokenIntrospectionConverter(source -> { + this.messageConverter.setTokenIntrospectionConverter((source) -> { throw new RuntimeException(errorMessage); }); MockClientHttpResponse response = new MockClientHttpResponse("{}".getBytes(), HttpStatus.OK); @@ -156,7 +156,7 @@ public class OAuth2TokenIntrospectionHttpMessageConverterTests { @Test public void writeInternalWhenWriteFailsThenThrowsException() { String errorMessage = "this is not a valid converter"; - Converter> failingConverter = source -> { + Converter> failingConverter = (source) -> { throw new RuntimeException(errorMessage); }; this.messageConverter.setTokenIntrospectionParametersConverter(failingConverter); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/OidcClientRegistrationTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/OidcClientRegistrationTests.java index 5ae9279f..96ce6cef 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/OidcClientRegistrationTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/OidcClientRegistrationTests.java @@ -252,7 +252,7 @@ public class OidcClientRegistrationTests { // @formatter:off OidcClientRegistration clientRegistration = this.minimalBuilder .redirectUri("https://client1.example.com") - .redirectUris(redirectUris -> { + .redirectUris((redirectUris) -> { redirectUris.clear(); redirectUris.add("https://client2.example.com"); }) @@ -285,7 +285,7 @@ public class OidcClientRegistrationTests { // @formatter:off OidcClientRegistration clientRegistration = this.minimalBuilder .postLogoutRedirectUri("https://client1.example.com/oidc-post-logout") - .postLogoutRedirectUris(postLogoutRedirectUris -> { + .postLogoutRedirectUris((postLogoutRedirectUris) -> { postLogoutRedirectUris.clear(); postLogoutRedirectUris.add("https://client2.example.com/oidc-post-logout"); }) @@ -318,7 +318,7 @@ public class OidcClientRegistrationTests { // @formatter:off OidcClientRegistration clientRegistration = this.minimalBuilder .grantType("authorization_code") - .grantTypes(grantTypes -> { + .grantTypes((grantTypes) -> { grantTypes.clear(); grantTypes.add("client_credentials"); }) @@ -350,7 +350,7 @@ public class OidcClientRegistrationTests { // @formatter:off OidcClientRegistration clientRegistration = this.minimalBuilder .responseType("token") - .responseTypes(responseTypes -> { + .responseTypes((responseTypes) -> { responseTypes.clear(); responseTypes.add("code"); }) @@ -382,7 +382,7 @@ public class OidcClientRegistrationTests { // @formatter:off OidcClientRegistration clientRegistration = this.minimalBuilder .scope("should-be-removed") - .scopes(scopes -> { + .scopes((scopes) -> { scopes.clear(); scopes.add("scope1"); }) diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/OidcProviderConfigurationTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/OidcProviderConfigurationTests.java index 0ff05965..cd6e33bc 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/OidcProviderConfigurationTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/OidcProviderConfigurationTests.java @@ -404,7 +404,7 @@ public class OidcProviderConfigurationTests { @Test public void responseTypesWhenAddingOrRemovingThenCorrectValues() { OidcProviderConfiguration configuration = this.minimalConfigurationBuilder.responseType("should-be-removed") - .responseTypes(responseTypes -> { + .responseTypes((responseTypes) -> { responseTypes.clear(); responseTypes.add("some-response-type"); }) @@ -416,8 +416,8 @@ public class OidcProviderConfigurationTests { @Test public void responseTypesWhenNotPresentAndAddingThenCorrectValues() { OidcProviderConfiguration configuration = this.minimalConfigurationBuilder - .claims(claims -> claims.remove(OidcProviderMetadataClaimNames.RESPONSE_TYPES_SUPPORTED)) - .responseTypes(responseTypes -> responseTypes.add("some-response-type")) + .claims((claims) -> claims.remove(OidcProviderMetadataClaimNames.RESPONSE_TYPES_SUPPORTED)) + .responseTypes((responseTypes) -> responseTypes.add("some-response-type")) .build(); assertThat(configuration.getResponseTypes()).containsExactly("some-response-type"); @@ -426,7 +426,7 @@ public class OidcProviderConfigurationTests { @Test public void subjectTypesWhenAddingOrRemovingThenCorrectValues() { OidcProviderConfiguration configuration = this.minimalConfigurationBuilder.subjectType("should-be-removed") - .subjectTypes(subjectTypes -> { + .subjectTypes((subjectTypes) -> { subjectTypes.clear(); subjectTypes.add("some-subject-type"); }) @@ -439,7 +439,7 @@ public class OidcProviderConfigurationTests { public void idTokenSigningAlgorithmsWhenAddingOrRemovingThenCorrectValues() { OidcProviderConfiguration configuration = this.minimalConfigurationBuilder .idTokenSigningAlgorithm("should-be-removed") - .idTokenSigningAlgorithms(signingAlgorithms -> { + .idTokenSigningAlgorithms((signingAlgorithms) -> { signingAlgorithms.clear(); signingAlgorithms.add("ES256"); }) @@ -451,7 +451,7 @@ public class OidcProviderConfigurationTests { @Test public void scopesWhenAddingOrRemovingThenCorrectValues() { OidcProviderConfiguration configuration = this.minimalConfigurationBuilder.scope("should-be-removed") - .scopes(scopes -> { + .scopes((scopes) -> { scopes.clear(); scopes.add("some-scope"); }) @@ -463,7 +463,7 @@ public class OidcProviderConfigurationTests { @Test public void grantTypesWhenAddingOrRemovingThenCorrectValues() { OidcProviderConfiguration configuration = this.minimalConfigurationBuilder.grantType("should-be-removed") - .grantTypes(grantTypes -> { + .grantTypes((grantTypes) -> { grantTypes.clear(); grantTypes.add("some-grant-type"); }) @@ -476,7 +476,7 @@ public class OidcProviderConfigurationTests { public void tokenEndpointAuthenticationMethodsWhenAddingOrRemovingThenCorrectValues() { OidcProviderConfiguration configuration = this.minimalConfigurationBuilder .tokenEndpointAuthenticationMethod("should-be-removed") - .tokenEndpointAuthenticationMethods(authMethods -> { + .tokenEndpointAuthenticationMethods((authMethods) -> { authMethods.clear(); authMethods.add("some-authentication-method"); }) diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcClientConfigurationAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcClientConfigurationAuthenticationProviderTests.java index d7899341..364b0d9c 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcClientConfigurationAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcClientConfigurationAuthenticationProviderTests.java @@ -60,10 +60,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; 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; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * Tests for {@link OidcClientConfigurationAuthenticationProvider}. @@ -125,7 +125,7 @@ public class OidcClientConfigurationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); } @@ -139,7 +139,7 @@ public class OidcClientConfigurationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); } @@ -155,7 +155,7 @@ public class OidcClientConfigurationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); verify(this.authorizationService).findByToken(eq(jwt.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN)); @@ -171,9 +171,9 @@ public class OidcClientConfigurationAuthenticationProviderTests { .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); authorization = OidcAuthenticationProviderUtils.invalidate(authorization, jwtAccessToken); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.read")); @@ -183,7 +183,7 @@ public class OidcClientConfigurationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); verify(this.authorizationService).findByToken(eq(jwtAccessToken.getTokenValue()), @@ -199,9 +199,9 @@ public class OidcClientConfigurationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_unauthorized.scope")); @@ -211,7 +211,7 @@ public class OidcClientConfigurationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INSUFFICIENT_SCOPE); verify(this.authorizationService).findByToken(eq(jwtAccessToken.getTokenValue()), @@ -227,9 +227,9 @@ public class OidcClientConfigurationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.read", "SCOPE_scope1")); @@ -239,7 +239,7 @@ public class OidcClientConfigurationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); verify(this.authorizationService).findByToken(eq(jwtAccessToken.getTokenValue()), @@ -255,9 +255,9 @@ public class OidcClientConfigurationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.read")); @@ -267,7 +267,7 @@ public class OidcClientConfigurationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); verify(this.authorizationService).findByToken(eq(jwtAccessToken.getTokenValue()), @@ -288,11 +288,11 @@ public class OidcClientConfigurationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(authorizedRegisteredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + .willReturn(authorization); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.read")); @@ -302,7 +302,7 @@ public class OidcClientConfigurationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_CLIENT); verify(this.authorizationService).findByToken(eq(jwtAccessToken.getTokenValue()), @@ -328,11 +328,11 @@ public class OidcClientConfigurationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); - when(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) - .thenReturn(registeredClient); + .willReturn(authorization); + given(this.registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) + .willReturn(registeredClient); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.read")); @@ -363,7 +363,7 @@ public class OidcClientConfigurationAuthenticationProviderTests { List grantTypes = new ArrayList<>(); registeredClient.getAuthorizationGrantTypes() - .forEach(authorizationGrantType -> grantTypes.add(authorizationGrantType.getValue())); + .forEach((authorizationGrantType) -> grantTypes.add(authorizationGrantType.getValue())); assertThat(clientRegistrationResult.getGrantTypes()).containsExactlyInAnyOrderElementsOf(grantTypes); assertThat(clientRegistrationResult.getResponseTypes()) @@ -403,8 +403,8 @@ public class OidcClientConfigurationAuthenticationProviderTests { .claim(OAuth2ParameterNames.SCOPE, scopes) .build(); Jwt jwt = Jwt.withTokenValue("jwt-access-token") - .headers(headers -> headers.putAll(jwsHeader.getHeaders())) - .claims(claims -> claims.putAll(jwtClaimsSet.getClaims())) + .headers((headers) -> headers.putAll(jwsHeader.getHeaders())) + .claims((claims) -> claims.putAll(jwtClaimsSet.getClaims())) .build(); // @formatter:on return jwt; diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcClientRegistrationAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcClientRegistrationAuthenticationProviderTests.java index a7e5d3e6..bd932e51 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcClientRegistrationAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcClientRegistrationAuthenticationProviderTests.java @@ -71,6 +71,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException 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; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; @@ -78,7 +79,6 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; /** * Tests for {@link OidcClientRegistrationAuthenticationProvider}. @@ -193,7 +193,7 @@ public class OidcClientRegistrationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); } @@ -210,7 +210,7 @@ public class OidcClientRegistrationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); } @@ -229,7 +229,7 @@ public class OidcClientRegistrationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); verify(this.authorizationService).findByToken(eq(jwt.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN)); @@ -245,9 +245,9 @@ public class OidcClientRegistrationAuthenticationProviderTests { .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); authorization = OidcAuthenticationProviderUtils.invalidate(authorization, jwtAccessToken); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.create")); @@ -260,7 +260,7 @@ public class OidcClientRegistrationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); verify(this.authorizationService).findByToken(eq(jwtAccessToken.getTokenValue()), @@ -276,9 +276,9 @@ public class OidcClientRegistrationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_unauthorized.scope")); @@ -291,7 +291,7 @@ public class OidcClientRegistrationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INSUFFICIENT_SCOPE); verify(this.authorizationService).findByToken(eq(jwtAccessToken.getTokenValue()), @@ -307,9 +307,9 @@ public class OidcClientRegistrationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.create", "SCOPE_scope1")); @@ -322,7 +322,7 @@ public class OidcClientRegistrationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); verify(this.authorizationService).findByToken(eq(jwtAccessToken.getTokenValue()), @@ -338,9 +338,9 @@ public class OidcClientRegistrationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.create")); @@ -355,8 +355,8 @@ public class OidcClientRegistrationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_REDIRECT_URI); assertThat(error.getDescription()).contains(OidcClientMetadataClaimNames.REDIRECT_URIS); }); @@ -373,9 +373,9 @@ public class OidcClientRegistrationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.create")); @@ -390,8 +390,8 @@ public class OidcClientRegistrationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_REDIRECT_URI); assertThat(error.getDescription()).contains(OidcClientMetadataClaimNames.REDIRECT_URIS); }); @@ -408,9 +408,9 @@ public class OidcClientRegistrationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.create")); @@ -426,8 +426,8 @@ public class OidcClientRegistrationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo("invalid_client_metadata"); assertThat(error.getDescription()).contains(OidcClientMetadataClaimNames.POST_LOGOUT_REDIRECT_URIS); }); @@ -444,9 +444,9 @@ public class OidcClientRegistrationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.create")); @@ -462,8 +462,8 @@ public class OidcClientRegistrationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo("invalid_client_metadata"); assertThat(error.getDescription()).contains(OidcClientMetadataClaimNames.POST_LOGOUT_REDIRECT_URIS); }); @@ -480,9 +480,9 @@ public class OidcClientRegistrationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.create")); @@ -544,8 +544,8 @@ public class OidcClientRegistrationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(errorCode); assertThat(error.getDescription()).contains(errorDescription); }); @@ -560,10 +560,10 @@ public class OidcClientRegistrationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); - when(this.jwtEncoder.encode(any())).thenReturn(createJwtClientConfiguration()); + .willReturn(authorization); + given(this.jwtEncoder.encode(any())).willReturn(createJwtClientConfiguration()); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.create")); @@ -611,9 +611,9 @@ public class OidcClientRegistrationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + .willReturn(authorization); doReturn(null).when(this.tokenGenerator).generate(any()); @@ -635,8 +635,8 @@ public class OidcClientRegistrationAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.SERVER_ERROR); assertThat(error.getDescription()) .contains("The token generator failed to generate the registration access token."); @@ -652,10 +652,10 @@ public class OidcClientRegistrationAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations .authorization(registeredClient, jwtAccessToken, jwt.getClaims()) .build(); - when(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), + given(this.authorizationService.findByToken(eq(jwtAccessToken.getTokenValue()), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); - when(this.jwtEncoder.encode(any())).thenReturn(createJwtClientConfiguration()); + .willReturn(authorization); + given(this.jwtEncoder.encode(any())).willReturn(createJwtClientConfiguration()); JwtAuthenticationToken principal = new JwtAuthenticationToken(jwt, AuthorityUtils.createAuthorityList("SCOPE_client.create")); @@ -734,7 +734,7 @@ public class OidcClientRegistrationAuthenticationProviderTests { List grantTypes = new ArrayList<>(); registeredClientResult.getAuthorizationGrantTypes() - .forEach(authorizationGrantType -> grantTypes.add(authorizationGrantType.getValue())); + .forEach((authorizationGrantType) -> grantTypes.add(authorizationGrantType.getValue())); assertThat(clientRegistrationResult.getGrantTypes()).containsExactlyInAnyOrderElementsOf(grantTypes); assertThat(clientRegistrationResult.getResponseTypes()) @@ -774,8 +774,8 @@ public class OidcClientRegistrationAuthenticationProviderTests { .claim(OAuth2ParameterNames.SCOPE, scopes) .build(); Jwt jwt = Jwt.withTokenValue("jwt-access-token") - .headers(headers -> headers.putAll(jwsHeader.getHeaders())) - .claims(claims -> claims.putAll(jwtClaimsSet.getClaims())) + .headers((headers) -> headers.putAll(jwsHeader.getHeaders())) + .claims((claims) -> claims.putAll(jwtClaimsSet.getClaims())) .build(); // @formatter:on return jwt; diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcLogoutAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcLogoutAuthenticationProviderTests.java index 99019391..b7f91b80 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcLogoutAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcLogoutAuthenticationProviderTests.java @@ -54,9 +54,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; 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; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; /** * Tests for {@link OidcLogoutAuthenticationProvider}. @@ -132,8 +132,8 @@ public class OidcLogoutAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); assertThat(error.getDescription()).contains("id_token_hint"); }); @@ -158,16 +158,16 @@ public class OidcLogoutAuthenticationProviderTests { metadata.put(OAuth2Authorization.Token.INVALIDATED_METADATA_NAME, true); }) .build(); - when(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) + .willReturn(authorization); OidcLogoutAuthenticationToken authentication = new OidcLogoutAuthenticationToken(idToken.getTokenValue(), principal, "session-1", null, null, null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); assertThat(error.getDescription()).contains("id_token_hint"); }); @@ -190,18 +190,18 @@ public class OidcLogoutAuthenticationProviderTests { .token(idToken, (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims())) .build(); - when(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) - .thenReturn(authorization); - when(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) - .thenReturn(registeredClient); + given(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) + .willReturn(authorization); + given(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) + .willReturn(registeredClient); OidcLogoutAuthenticationToken authentication = new OidcLogoutAuthenticationToken(idToken.getTokenValue(), principal, "session-1", null, null, null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); assertThat(error.getDescription()).contains(IdTokenClaimNames.AUD); }); @@ -225,18 +225,18 @@ public class OidcLogoutAuthenticationProviderTests { .token(idToken, (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims())) .build(); - when(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) - .thenReturn(authorization); - when(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) - .thenReturn(registeredClient); + given(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) + .willReturn(authorization); + given(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) + .willReturn(registeredClient); OidcLogoutAuthenticationToken authentication = new OidcLogoutAuthenticationToken(idToken.getTokenValue(), principal, "session-1", null, null, null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); assertThat(error.getDescription()).contains(IdTokenClaimNames.AUD); }); @@ -260,18 +260,18 @@ public class OidcLogoutAuthenticationProviderTests { .token(idToken, (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims())) .build(); - when(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) - .thenReturn(authorization); - when(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) - .thenReturn(registeredClient); + given(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) + .willReturn(authorization); + given(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) + .willReturn(registeredClient); OidcLogoutAuthenticationToken authentication = new OidcLogoutAuthenticationToken(idToken.getTokenValue(), principal, "session-1", registeredClient.getClientId() + "-invalid", null, null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); assertThat(error.getDescription()).contains(OAuth2ParameterNames.CLIENT_ID); }); @@ -295,18 +295,18 @@ public class OidcLogoutAuthenticationProviderTests { .token(idToken, (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims())) .build(); - when(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) - .thenReturn(authorization); - when(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) - .thenReturn(registeredClient); + given(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) + .willReturn(authorization); + given(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) + .willReturn(registeredClient); OidcLogoutAuthenticationToken authentication = new OidcLogoutAuthenticationToken(idToken.getTokenValue(), principal, "session-1", registeredClient.getClientId(), "https://example.com/callback-1-invalid", null); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); assertThat(error.getDescription()).contains("post_logout_redirect_uri"); }); @@ -329,10 +329,10 @@ public class OidcLogoutAuthenticationProviderTests { .token(idToken, (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims())) .build(); - when(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) - .thenReturn(authorization); - when(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) - .thenReturn(registeredClient); + given(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) + .willReturn(authorization); + given(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) + .willReturn(registeredClient); principal.setAuthenticated(true); @@ -341,8 +341,8 @@ public class OidcLogoutAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); assertThat(error.getDescription()).contains("sub"); }); @@ -367,10 +367,10 @@ public class OidcLogoutAuthenticationProviderTests { .token(idToken, (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims())) .build(); - when(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) - .thenReturn(authorization); - when(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) - .thenReturn(registeredClient); + given(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) + .willReturn(authorization); + given(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) + .willReturn(registeredClient); principal.setAuthenticated(true); @@ -382,8 +382,8 @@ public class OidcLogoutAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); assertThat(error.getDescription()).contains("sub"); }); @@ -407,15 +407,15 @@ public class OidcLogoutAuthenticationProviderTests { .token(idToken, (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims())) .build(); - when(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) - .thenReturn(authorization); - when(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) - .thenReturn(registeredClient); + given(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) + .willReturn(authorization); + given(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) + .willReturn(registeredClient); String sessionId = "session-1"; List sessions = Collections .singletonList(new SessionInformation(principal.getPrincipal(), sessionId, Date.from(Instant.now()))); - when(this.sessionRegistry.getAllSessions(eq(principal.getPrincipal()), eq(true))).thenReturn(sessions); + given(this.sessionRegistry.getAllSessions(eq(principal.getPrincipal()), eq(true))).willReturn(sessions); principal.setAuthenticated(true); @@ -424,8 +424,8 @@ public class OidcLogoutAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); assertThat(error.getDescription()).contains("sid"); }); @@ -450,15 +450,15 @@ public class OidcLogoutAuthenticationProviderTests { .token(idToken, (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims())) .build(); - when(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) - .thenReturn(authorization); - when(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) - .thenReturn(registeredClient); + given(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) + .willReturn(authorization); + given(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) + .willReturn(registeredClient); String sessionId = "session-1"; List sessions = Collections .singletonList(new SessionInformation(principal.getPrincipal(), sessionId, Date.from(Instant.now()))); - when(this.sessionRegistry.getAllSessions(eq(principal.getPrincipal()), eq(true))).thenReturn(sessions); + given(this.sessionRegistry.getAllSessions(eq(principal.getPrincipal()), eq(true))).willReturn(sessions); principal.setAuthenticated(true); @@ -467,8 +467,8 @@ public class OidcLogoutAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); assertThat(error.getDescription()).contains("sid"); }); @@ -516,15 +516,15 @@ public class OidcLogoutAuthenticationProviderTests { .token(idToken, (metadata) -> metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, idToken.getClaims())) .build(); - when(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) - .thenReturn(authorization); - when(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) - .thenReturn(registeredClient); + given(this.authorizationService.findByToken(eq(idToken.getTokenValue()), eq(ID_TOKEN_TOKEN_TYPE))) + .willReturn(authorization); + given(this.registeredClientRepository.findById(eq(authorization.getRegisteredClientId()))) + .willReturn(registeredClient); SessionInformation sessionInformation = new SessionInformation(principal.getPrincipal(), sessionId, Date.from(Instant.now())); List sessions = Collections.singletonList(sessionInformation); - when(this.sessionRegistry.getAllSessions(eq(principal.getPrincipal()), eq(true))).thenReturn(sessions); + given(this.sessionRegistry.getAllSessions(eq(principal.getPrincipal()), eq(true))).willReturn(sessions); principal.setAuthenticated(true); String postLogoutRedirectUri = registeredClient.getPostLogoutRedirectUris().toArray(new String[0])[0]; diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcUserInfoAuthenticationProviderTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcUserInfoAuthenticationProviderTests.java index 2cc36973..ffeb823b 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcUserInfoAuthenticationProviderTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/authentication/OidcUserInfoAuthenticationProviderTests.java @@ -45,10 +45,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; 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; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; /** * Tests for {@link OidcUserInfoAuthenticationProvider}. @@ -91,7 +91,7 @@ public class OidcUserInfoAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); @@ -107,7 +107,7 @@ public class OidcUserInfoAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); @@ -122,7 +122,7 @@ public class OidcUserInfoAuthenticationProviderTests { assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); @@ -135,15 +135,15 @@ public class OidcUserInfoAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations.authorization().build(); authorization = OidcAuthenticationProviderUtils.invalidate(authorization, authorization.getAccessToken().getToken()); - when(this.authorizationService.findByToken(eq(tokenValue), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(tokenValue), eq(OAuth2TokenType.ACCESS_TOKEN))) + .willReturn(authorization); JwtAuthenticationToken principal = createJwtAuthenticationToken(tokenValue); OidcUserInfoAuthenticationToken authentication = new OidcUserInfoAuthenticationToken(principal); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); @@ -153,15 +153,15 @@ public class OidcUserInfoAuthenticationProviderTests { @Test public void authenticateWhenAccessTokenNotAuthorizedThenThrowOAuth2AuthenticationException() { String tokenValue = "token"; - when(this.authorizationService.findByToken(eq(tokenValue), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(TestOAuth2Authorizations.authorization().build()); + given(this.authorizationService.findByToken(eq(tokenValue), eq(OAuth2TokenType.ACCESS_TOKEN))) + .willReturn(TestOAuth2Authorizations.authorization().build()); JwtAuthenticationToken principal = createJwtAuthenticationToken(tokenValue); OidcUserInfoAuthenticationToken authentication = new OidcUserInfoAuthenticationToken(principal); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INSUFFICIENT_SCOPE); @@ -174,15 +174,15 @@ public class OidcUserInfoAuthenticationProviderTests { OAuth2Authorization authorization = TestOAuth2Authorizations.authorization() .token(createAuthorization(tokenValue).getAccessToken().getToken()) .build(); - when(this.authorizationService.findByToken(eq(tokenValue), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(authorization); + given(this.authorizationService.findByToken(eq(tokenValue), eq(OAuth2TokenType.ACCESS_TOKEN))) + .willReturn(authorization); JwtAuthenticationToken principal = createJwtAuthenticationToken(tokenValue); OidcUserInfoAuthenticationToken authentication = new OidcUserInfoAuthenticationToken(principal); assertThatThrownBy(() -> this.authenticationProvider.authenticate(authentication)) .isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN); @@ -192,8 +192,8 @@ public class OidcUserInfoAuthenticationProviderTests { @Test public void authenticateWhenValidAccessTokenThenReturnUserInfo() { String tokenValue = "access-token"; - when(this.authorizationService.findByToken(eq(tokenValue), eq(OAuth2TokenType.ACCESS_TOKEN))) - .thenReturn(createAuthorization(tokenValue)); + given(this.authorizationService.findByToken(eq(tokenValue), eq(OAuth2TokenType.ACCESS_TOKEN))) + .willReturn(createAuthorization(tokenValue)); JwtAuthenticationToken principal = createJwtAuthenticationToken(tokenValue); OidcUserInfoAuthenticationToken authentication = new OidcUserInfoAuthenticationToken(principal); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcClientRegistrationHttpMessageConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcClientRegistrationHttpMessageConverterTests.java index 24821401..60d70e1d 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcClientRegistrationHttpMessageConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcClientRegistrationHttpMessageConverterTests.java @@ -92,31 +92,31 @@ public class OidcClientRegistrationHttpMessageConverterTests { public void readInternalWhenValidParametersThenSuccess() throws Exception { // @formatter:off String clientRegistrationRequest = "{\n" - +" \"client_id\": \"client-id\",\n" - +" \"client_id_issued_at\": 1607633867,\n" - +" \"client_secret\": \"client-secret\",\n" - +" \"client_secret_expires_at\": 1607637467,\n" - +" \"client_name\": \"client-name\",\n" - +" \"redirect_uris\": [\n" + + " \"client_id\": \"client-id\",\n" + + " \"client_id_issued_at\": 1607633867,\n" + + " \"client_secret\": \"client-secret\",\n" + + " \"client_secret_expires_at\": 1607637467,\n" + + " \"client_name\": \"client-name\",\n" + + " \"redirect_uris\": [\n" + " \"https://client.example.com\"\n" + " ],\n" - +" \"post_logout_redirect_uris\": [\n" + + " \"post_logout_redirect_uris\": [\n" + " \"https://client.example.com/oidc-post-logout\"\n" + " ],\n" - +" \"token_endpoint_auth_method\": \"client_secret_jwt\",\n" - +" \"token_endpoint_auth_signing_alg\": \"HS256\",\n" - +" \"grant_types\": [\n" - +" \"authorization_code\",\n" - +" \"client_credentials\"\n" - +" ],\n" - +" \"response_types\":[\n" - +" \"code\"\n" - +" ],\n" - +" \"scope\": \"scope1 scope2\",\n" - +" \"jwks_uri\": \"https://client.example.com/jwks\",\n" - +" \"id_token_signed_response_alg\": \"RS256\",\n" - +" \"a-claim\": \"a-value\"\n" - +"}\n"; + + " \"token_endpoint_auth_method\": \"client_secret_jwt\",\n" + + " \"token_endpoint_auth_signing_alg\": \"HS256\",\n" + + " \"grant_types\": [\n" + + " \"authorization_code\",\n" + + " \"client_credentials\"\n" + + " ],\n" + + " \"response_types\":[\n" + + " \"code\"\n" + + " ],\n" + + " \"scope\": \"scope1 scope2\",\n" + + " \"jwks_uri\": \"https://client.example.com/jwks\",\n" + + " \"id_token_signed_response_alg\": \"RS256\",\n" + + " \"a-claim\": \"a-value\"\n" + + "}\n"; // @formatter:on MockClientHttpResponse response = new MockClientHttpResponse(clientRegistrationRequest.getBytes(), HttpStatus.OK); @@ -148,13 +148,13 @@ public class OidcClientRegistrationHttpMessageConverterTests { public void readInternalWhenClientSecretNoExpiryThenSuccess() { // @formatter:off String clientRegistrationRequest = "{\n" - +" \"client_id\": \"client-id\",\n" - +" \"client_secret\": \"client-secret\",\n" - +" \"client_secret_expires_at\": 0,\n" - +" \"redirect_uris\": [\n" + + " \"client_id\": \"client-id\",\n" + + " \"client_secret\": \"client-secret\",\n" + + " \"client_secret_expires_at\": 0,\n" + + " \"redirect_uris\": [\n" + " \"https://client.example.com\"\n" + " ]\n" - +"}\n"; + + "}\n"; // @formatter:on MockClientHttpResponse response = new MockClientHttpResponse(clientRegistrationRequest.getBytes(), HttpStatus.OK); @@ -171,7 +171,7 @@ public class OidcClientRegistrationHttpMessageConverterTests { @Test public void readInternalWhenFailingConverterThenThrowException() { String errorMessage = "this is not a valid converter"; - this.messageConverter.setClientRegistrationConverter(source -> { + this.messageConverter.setClientRegistrationConverter((source) -> { throw new RuntimeException(errorMessage); }); MockClientHttpResponse response = new MockClientHttpResponse("{}".getBytes(), HttpStatus.OK); @@ -257,7 +257,7 @@ public class OidcClientRegistrationHttpMessageConverterTests { @Test public void writeInternalWhenWriteFailsThenThrowException() { String errorMessage = "this is not a valid converter"; - Converter> failingConverter = source -> { + Converter> failingConverter = (source) -> { throw new RuntimeException(errorMessage); }; this.messageConverter.setClientRegistrationParametersConverter(failingConverter); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcProviderConfigurationHttpMessageConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcProviderConfigurationHttpMessageConverterTests.java index c5cfc17a..f0eef0ca 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcProviderConfigurationHttpMessageConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcProviderConfigurationHttpMessageConverterTests.java @@ -137,7 +137,7 @@ public class OidcProviderConfigurationHttpMessageConverterTests { @Test public void readInternalWhenFailingConverterThenThrowException() { String errorMessage = "this is not a valid converter"; - this.messageConverter.setProviderConfigurationConverter(source -> { + this.messageConverter.setProviderConfigurationConverter((source) -> { throw new RuntimeException(errorMessage); }); MockClientHttpResponse response = new MockClientHttpResponse("{}".getBytes(), HttpStatus.OK); @@ -204,7 +204,7 @@ public class OidcProviderConfigurationHttpMessageConverterTests { @Test public void writeInternalWhenWriteFailsThenThrowsException() { String errorMessage = "this is not a valid converter"; - Converter> failingConverter = source -> { + Converter> failingConverter = (source) -> { throw new RuntimeException(errorMessage); }; this.messageConverter.setProviderConfigurationParametersConverter(failingConverter); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcUserInfoHttpMessageConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcUserInfoHttpMessageConverterTests.java index b77bcf7d..a469dbc9 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcUserInfoHttpMessageConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/http/converter/OidcUserInfoHttpMessageConverterTests.java @@ -126,7 +126,7 @@ public class OidcUserInfoHttpMessageConverterTests { @Test public void readInternalWhenFailingConverterThenThrowException() { String errorMessage = "this is not a valid converter"; - this.messageConverter.setUserInfoConverter(source -> { + this.messageConverter.setUserInfoConverter((source) -> { throw new RuntimeException(errorMessage); }); MockClientHttpResponse response = new MockClientHttpResponse("{}".getBytes(), HttpStatus.OK); @@ -185,7 +185,7 @@ public class OidcUserInfoHttpMessageConverterTests { @Test public void writeInternalWhenWriteFailsThenThrowsException() { String errorMessage = "this is not a valid converter"; - Converter> failingConverter = source -> { + Converter> failingConverter = (source) -> { throw new RuntimeException(errorMessage); }; this.messageConverter.setUserInfoParametersConverter(failingConverter); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcClientRegistrationEndpointFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcClientRegistrationEndpointFilterTests.java index 95b43404..5b57705f 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcClientRegistrationEndpointFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcClientRegistrationEndpointFilterTests.java @@ -23,7 +23,6 @@ import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -67,10 +66,10 @@ import static org.assertj.core.api.Assertions.assertThat; 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; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; /** * Tests for {@link OidcClientRegistrationEndpointFilter}. @@ -199,7 +198,7 @@ public class OidcClientRegistrationEndpointFilterTests { securityContext.setAuthentication(principal); SecurityContextHolder.setContext(securityContext); - when(this.authenticationManager.authenticate(any())).thenThrow(new OAuth2AuthenticationException(errorCode)); + given(this.authenticationManager.authenticate(any())).willThrow(new OAuth2AuthenticationException(errorCode)); // @formatter:off OidcClientRegistration clientRegistrationRequest = OidcClientRegistration.builder() @@ -235,9 +234,9 @@ public class OidcClientRegistrationEndpointFilterTests { OidcClientRegistration clientRegistrationRequest = OidcClientRegistration.builder() .clientName(expectedClientRegistrationResponse.getClientName()) - .redirectUris(redirectUris -> redirectUris.addAll(expectedClientRegistrationResponse.getRedirectUris())) - .grantTypes(grantTypes -> grantTypes.addAll(expectedClientRegistrationResponse.getGrantTypes())) - .scopes(scopes -> scopes.addAll(expectedClientRegistrationResponse.getScopes())) + .redirectUris((redirectUris) -> redirectUris.addAll(expectedClientRegistrationResponse.getRedirectUris())) + .grantTypes((grantTypes) -> grantTypes.addAll(expectedClientRegistrationResponse.getGrantTypes())) + .scopes((scopes) -> scopes.addAll(expectedClientRegistrationResponse.getScopes())) .build(); // @formatter:on @@ -248,7 +247,7 @@ public class OidcClientRegistrationEndpointFilterTests { OidcClientRegistrationAuthenticationToken clientRegistrationAuthenticationResult = new OidcClientRegistrationAuthenticationToken( principal, expectedClientRegistrationResponse); - when(this.authenticationManager.authenticate(any())).thenReturn(clientRegistrationAuthenticationResult); + given(this.authenticationManager.authenticate(any())).willReturn(clientRegistrationAuthenticationResult); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(principal); @@ -384,7 +383,7 @@ public class OidcClientRegistrationEndpointFilterTests { securityContext.setAuthentication(principal); SecurityContextHolder.setContext(securityContext); - when(this.authenticationManager.authenticate(any())).thenThrow(new OAuth2AuthenticationException(errorCode)); + given(this.authenticationManager.authenticate(any())).willThrow(new OAuth2AuthenticationException(errorCode)); String requestUri = DEFAULT_OIDC_CLIENT_REGISTRATION_ENDPOINT_URI; MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); @@ -414,7 +413,7 @@ public class OidcClientRegistrationEndpointFilterTests { OidcClientRegistrationAuthenticationToken clientConfigurationAuthenticationResult = new OidcClientRegistrationAuthenticationToken( principal, expectedClientRegistrationResponse); - when(this.authenticationManager.authenticate(any())).thenReturn(clientConfigurationAuthenticationResult); + given(this.authenticationManager.authenticate(any())).willReturn(clientConfigurationAuthenticationResult); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(principal); @@ -489,7 +488,7 @@ public class OidcClientRegistrationEndpointFilterTests { OidcClientRegistrationAuthenticationToken clientRegistrationAuthenticationResult = new OidcClientRegistrationAuthenticationToken( principal, expectedClientRegistrationResponse); - when(this.authenticationManager.authenticate(any())).thenReturn(clientRegistrationAuthenticationResult); + given(this.authenticationManager.authenticate(any())).willReturn(clientRegistrationAuthenticationResult); AuthenticationSuccessHandler successHandler = mock(AuthenticationSuccessHandler.class); this.filter.setAuthenticationSuccessHandler(successHandler); @@ -516,8 +515,8 @@ public class OidcClientRegistrationEndpointFilterTests { AuthenticationFailureHandler authenticationFailureHandler = mock(AuthenticationFailureHandler.class); this.filter.setAuthenticationFailureHandler(authenticationFailureHandler); - when(this.authenticationManager.authenticate(any())) - .thenThrow(new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_TOKEN)); + given(this.authenticationManager.authenticate(any())) + .willThrow(new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_TOKEN)); String requestUri = DEFAULT_OIDC_CLIENT_REGISTRATION_ENDPOINT_URI; MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); @@ -593,8 +592,8 @@ public class OidcClientRegistrationEndpointFilterTests { .claim(OAuth2ParameterNames.SCOPE, Collections.singleton(scope)) .build(); Jwt jwt = Jwt.withTokenValue("jwt-access-token") - .headers(headers -> headers.putAll(jwsHeader.getHeaders())) - .claims(claims -> claims.putAll(jwtClaimsSet.getClaims())) + .headers((headers) -> headers.putAll(jwsHeader.getHeaders())) + .claims((claims) -> claims.putAll(jwtClaimsSet.getClaims())) .build(); // @formatter:on return jwt; diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcLogoutEndpointFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcLogoutEndpointFilterTests.java index 2b5417c4..ff52a429 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcLogoutEndpointFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcLogoutEndpointFilterTests.java @@ -20,7 +20,6 @@ import java.util.function.Consumer; import jakarta.servlet.FilterChain; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -51,10 +50,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.same; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; /** * Tests for {@link OidcLogoutEndpointFilter}. @@ -138,14 +137,14 @@ public class OidcLogoutEndpointFilterTests { public void doFilterWhenLogoutRequestMissingIdTokenHintThenInvalidRequestError() throws Exception { doFilterWhenRequestInvalidParameterThenError( createLogoutRequest(TestRegisteredClients.registeredClient().build()), "id_token_hint", - OAuth2ErrorCodes.INVALID_REQUEST, request -> request.removeParameter("id_token_hint")); + OAuth2ErrorCodes.INVALID_REQUEST, (request) -> request.removeParameter("id_token_hint")); } @Test public void doFilterWhenLogoutRequestMultipleIdTokenHintThenInvalidRequestError() throws Exception { doFilterWhenRequestInvalidParameterThenError( createLogoutRequest(TestRegisteredClients.registeredClient().build()), "id_token_hint", - OAuth2ErrorCodes.INVALID_REQUEST, request -> request.addParameter("id_token_hint", "id-token-2")); + OAuth2ErrorCodes.INVALID_REQUEST, (request) -> request.addParameter("id_token_hint", "id-token-2")); } @Test @@ -153,7 +152,7 @@ public class OidcLogoutEndpointFilterTests { doFilterWhenRequestInvalidParameterThenError( createLogoutRequest(TestRegisteredClients.registeredClient().build()), OAuth2ParameterNames.CLIENT_ID, OAuth2ErrorCodes.INVALID_REQUEST, - request -> request.addParameter(OAuth2ParameterNames.CLIENT_ID, "client-2")); + (request) -> request.addParameter(OAuth2ParameterNames.CLIENT_ID, "client-2")); } @Test @@ -161,7 +160,7 @@ public class OidcLogoutEndpointFilterTests { doFilterWhenRequestInvalidParameterThenError( createLogoutRequest(TestRegisteredClients.registeredClient().build()), "post_logout_redirect_uri", OAuth2ErrorCodes.INVALID_REQUEST, - request -> request.addParameter("post_logout_redirect_uri", "https://example.com/callback-4")); + (request) -> request.addParameter("post_logout_redirect_uri", "https://example.com/callback-4")); } @Test @@ -169,7 +168,7 @@ public class OidcLogoutEndpointFilterTests { doFilterWhenRequestInvalidParameterThenError( createLogoutRequest(TestRegisteredClients.registeredClient().build()), OAuth2ParameterNames.STATE, OAuth2ErrorCodes.INVALID_REQUEST, - request -> request.addParameter(OAuth2ParameterNames.STATE, "state-2")); + (request) -> request.addParameter(OAuth2ParameterNames.STATE, "state-2")); } private void doFilterWhenRequestInvalidParameterThenError(MockHttpServletRequest request, String parameterName, @@ -191,7 +190,7 @@ public class OidcLogoutEndpointFilterTests { @Test public void doFilterWhenLogoutRequestAuthenticationExceptionThenErrorResponse() throws Exception { OAuth2Error error = new OAuth2Error("errorCode", "errorDescription", "errorUri"); - when(this.authenticationManager.authenticate(any())).thenThrow(new OAuth2AuthenticationException(error)); + given(this.authenticationManager.authenticate(any())).willThrow(new OAuth2AuthenticationException(error)); MockHttpServletRequest request = createLogoutRequest(TestRegisteredClients.registeredClient().build()); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -213,10 +212,10 @@ public class OidcLogoutEndpointFilterTests { null, null, null, null); AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); - when(authenticationConverter.convert(any())).thenReturn(authentication); + given(authenticationConverter.convert(any())).willReturn((authentication)); this.filter.setAuthenticationConverter(authenticationConverter); - when(this.authenticationManager.authenticate(any())).thenReturn(authentication); + given(this.authenticationManager.authenticate(any())).willReturn((authentication)); MockHttpServletRequest request = createLogoutRequest(TestRegisteredClients.registeredClient().build()); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -237,7 +236,7 @@ public class OidcLogoutEndpointFilterTests { AuthenticationSuccessHandler authenticationSuccessHandler = mock(AuthenticationSuccessHandler.class); this.filter.setAuthenticationSuccessHandler(authenticationSuccessHandler); - when(this.authenticationManager.authenticate(any())).thenReturn(authentication); + given(this.authenticationManager.authenticate(any())).willReturn((authentication)); MockHttpServletRequest request = createLogoutRequest(TestRegisteredClients.registeredClient().build()); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -255,8 +254,8 @@ public class OidcLogoutEndpointFilterTests { AuthenticationFailureHandler authenticationFailureHandler = mock(AuthenticationFailureHandler.class); this.filter.setAuthenticationFailureHandler(authenticationFailureHandler); - when(this.authenticationManager.authenticate(any())) - .thenThrow(new AuthenticationServiceException("AuthenticationServiceException")); + given(this.authenticationManager.authenticate(any())) + .willThrow(new AuthenticationServiceException("AuthenticationServiceException")); MockHttpServletRequest request = createLogoutRequest(TestRegisteredClients.registeredClient().build()); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -272,8 +271,8 @@ public class OidcLogoutEndpointFilterTests { verifyNoInteractions(filterChain); assertThat(authenticationExceptionCaptor.getValue()).isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) - .satisfies(error -> { + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) + .satisfies((error) -> { assertThat(error.getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); assertThat(error.getDescription()).contains("AuthenticationServiceException"); }); @@ -287,7 +286,7 @@ public class OidcLogoutEndpointFilterTests { OidcLogoutAuthenticationToken authentication = new OidcLogoutAuthenticationToken("id-token", this.principal, session.getId(), null, null, null); - when(this.authenticationManager.authenticate(any())).thenReturn(authentication); + given(this.authenticationManager.authenticate(any())).willReturn((authentication)); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); @@ -316,7 +315,7 @@ public class OidcLogoutEndpointFilterTests { session.getId(), registeredClient.getClientId(), postLogoutRedirectUri, state); authentication.setAuthenticated(true); - when(this.authenticationManager.authenticate(any())).thenReturn(authentication); + given(this.authenticationManager.authenticate(any())).willReturn((authentication)); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcProviderConfigurationEndpointFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcProviderConfigurationEndpointFilterTests.java index 47922017..729930ae 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcProviderConfigurationEndpointFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcProviderConfigurationEndpointFilterTests.java @@ -18,7 +18,6 @@ package org.springframework.security.oauth2.server.authorization.oidc.web; import jakarta.servlet.FilterChain; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcUserInfoEndpointFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcUserInfoEndpointFilterTests.java index 323595e1..d53eca48 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcUserInfoEndpointFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/oidc/web/OidcUserInfoEndpointFilterTests.java @@ -19,7 +19,6 @@ import java.time.Instant; import java.util.Collections; import jakarta.servlet.FilterChain; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -51,10 +50,10 @@ import org.springframework.security.web.authentication.AuthenticationSuccessHand import static org.assertj.core.api.Assertions.assertThat; 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; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; /** * Tests for {@link OidcUserInfoEndpointFilter}. @@ -151,7 +150,7 @@ public class OidcUserInfoEndpointFilterTests { OidcUserInfoAuthenticationToken authentication = new OidcUserInfoAuthenticationToken(principal, createUserInfo()); - when(this.authenticationManager.authenticate(any())).thenReturn(authentication); + given(this.authenticationManager.authenticate(any())).willReturn(authentication); String requestUri = DEFAULT_OIDC_USER_INFO_ENDPOINT_URI; MockHttpServletRequest request = new MockHttpServletRequest(httpMethod, requestUri); @@ -183,8 +182,8 @@ public class OidcUserInfoEndpointFilterTests { Authentication principal = new TestingAuthenticationToken("principal", "credentials"); SecurityContextHolder.getContext().setAuthentication(principal); - when(this.authenticationManager.authenticate(any())) - .thenThrow(new OAuth2AuthenticationException(oauth2ErrorCode)); + given(this.authenticationManager.authenticate(any())) + .willThrow(new OAuth2AuthenticationException(oauth2ErrorCode)); String requestUri = DEFAULT_OIDC_USER_INFO_ENDPOINT_URI; MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); @@ -208,9 +207,9 @@ public class OidcUserInfoEndpointFilterTests { AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); this.filter.setAuthenticationConverter(authenticationConverter); - when(authenticationConverter.convert(any())).thenReturn(authentication); - when(this.authenticationManager.authenticate(any())) - .thenReturn(new OidcUserInfoAuthenticationToken(principal, createUserInfo())); + given(authenticationConverter.convert(any())).willReturn(authentication); + given(this.authenticationManager.authenticate(any())) + .willReturn(new OidcUserInfoAuthenticationToken(principal, createUserInfo())); String requestUri = DEFAULT_OIDC_USER_INFO_ENDPOINT_URI; MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); @@ -236,7 +235,7 @@ public class OidcUserInfoEndpointFilterTests { OidcUserInfoAuthenticationToken authentication = new OidcUserInfoAuthenticationToken(principal, createUserInfo()); - when(this.authenticationManager.authenticate(any())).thenReturn(authentication); + given(this.authenticationManager.authenticate(any())).willReturn(authentication); String requestUri = DEFAULT_OIDC_USER_INFO_ENDPOINT_URI; MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); @@ -260,7 +259,7 @@ public class OidcUserInfoEndpointFilterTests { OAuth2AuthenticationException authenticationException = new OAuth2AuthenticationException( OAuth2ErrorCodes.INVALID_TOKEN); - when(this.authenticationManager.authenticate(any())).thenThrow(authenticationException); + given(this.authenticationManager.authenticate(any())).willThrow(authenticationException); String requestUri = DEFAULT_OIDC_USER_INFO_ENDPOINT_URI; MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/settings/AuthorizationServerSettingsTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/settings/AuthorizationServerSettingsTests.java index caf6b536..60bb9d95 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/settings/AuthorizationServerSettingsTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/settings/AuthorizationServerSettingsTests.java @@ -84,7 +84,7 @@ public class AuthorizationServerSettingsTests { public void settingWhenCustomThenSet() { AuthorizationServerSettings authorizationServerSettings = AuthorizationServerSettings.builder() .setting("name1", "value1") - .settings(settings -> settings.put("name2", "value2")) + .settings((settings) -> settings.put("name2", "value2")) .build(); assertThat(authorizationServerSettings.getSettings()).hasSize(12); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/settings/ClientSettingsTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/settings/ClientSettingsTests.java index 20a20445..5981589d 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/settings/ClientSettingsTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/settings/ClientSettingsTests.java @@ -66,7 +66,7 @@ public class ClientSettingsTests { public void settingWhenCustomThenSet() { ClientSettings clientSettings = ClientSettings.builder() .setting("name1", "value1") - .settings(settings -> settings.put("name2", "value2")) + .settings((settings) -> settings.put("name2", "value2")) .build(); assertThat(clientSettings.getSettings()).hasSize(4); assertThat(clientSettings.getSetting("name1")).isEqualTo("value1"); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/settings/TokenSettingsTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/settings/TokenSettingsTests.java index a3e1b97a..6e952738 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/settings/TokenSettingsTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/settings/TokenSettingsTests.java @@ -154,7 +154,7 @@ public class TokenSettingsTests { public void settingWhenCustomThenSet() { TokenSettings tokenSettings = TokenSettings.builder() .setting("name1", "value1") - .settings(settings -> settings.put("name2", "value2")) + .settings((settings) -> settings.put("name2", "value2")) .build(); assertThat(tokenSettings.getSettings()).hasSize(9); assertThat(tokenSettings.getSetting("name1")).isEqualTo("value1"); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/test/SpringTestContext.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/test/SpringTestContext.java index 06b377e5..f0464a11 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/test/SpringTestContext.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/test/SpringTestContext.java @@ -27,6 +27,7 @@ import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor; import org.springframework.mock.web.MockServletConfig; import org.springframework.mock.web.MockServletContext; +import org.springframework.security.config.BeanIds; import org.springframework.test.context.web.GenericXmlWebContextLoader; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.RequestPostProcessor; @@ -39,7 +40,6 @@ import org.springframework.web.context.support.AnnotationConfigWebApplicationCon import org.springframework.web.context.support.XmlWebApplicationContext; import org.springframework.web.filter.OncePerRequestFilter; -import static org.springframework.security.config.BeanIds.SPRING_SECURITY_FILTER_CHAIN; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; /** @@ -62,7 +62,7 @@ public class SpringTestContext implements Closeable { try { this.context.close(); } - catch (Exception e) { + catch (Exception ex) { } } @@ -120,7 +120,7 @@ public class SpringTestContext implements Closeable { this.context.setServletConfig(new MockServletConfig()); this.context.refresh(); - if (this.context.containsBean(SPRING_SECURITY_FILTER_CHAIN)) { + if (this.context.containsBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN)) { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(springSecurity()) .apply(new AddFilter()) @@ -133,7 +133,7 @@ public class SpringTestContext implements Closeable { bpp.processInjection(this.test); } - private class AddFilter implements MockMvcConfigurer { + public class AddFilter implements MockMvcConfigurer { public RequestPostProcessor beforeMockMvcCreated(ConfigurableMockMvcBuilder builder, WebApplicationContext context) { diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/DelegatingOAuth2TokenGeneratorTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/DelegatingOAuth2TokenGeneratorTests.java index 03267b35..7ca1c6b7 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/DelegatingOAuth2TokenGeneratorTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/DelegatingOAuth2TokenGeneratorTests.java @@ -25,8 +25,8 @@ import org.springframework.security.oauth2.core.OAuth2Token; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; /** * Tests for {@link DelegatingOAuth2TokenGenerator}. @@ -60,7 +60,7 @@ public class DelegatingOAuth2TokenGeneratorTests { OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token", Instant.now(), Instant.now().plusSeconds(300)); - when(tokenGenerator3.generate(any())).thenReturn(accessToken); + given(tokenGenerator3.generate(any())).willReturn(accessToken); DelegatingOAuth2TokenGenerator delegatingTokenGenerator = new DelegatingOAuth2TokenGenerator(tokenGenerator1, tokenGenerator2, tokenGenerator3); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/JwtEncodingContextTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/JwtEncodingContextTests.java index c40b7199..6625f94b 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/JwtEncodingContextTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/JwtEncodingContextTests.java @@ -94,7 +94,7 @@ public class JwtEncodingContextTests { .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .authorizationGrant(authorizationGrant) .put("custom-key-1", "custom-value-1") - .context(ctx -> ctx.put("custom-key-2", "custom-value-2")) + .context((ctx) -> ctx.put("custom-key-2", "custom-value-2")) .build(); assertThat(context.getJwsHeader()).isEqualTo(headers); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenClaimsContextTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenClaimsContextTests.java index 78ff3dfa..cd5a1658 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenClaimsContextTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenClaimsContextTests.java @@ -96,7 +96,7 @@ public class OAuth2TokenClaimsContextTests { .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .authorizationGrant(authorizationGrant) .put("custom-key-1", "custom-value-1") - .context(ctx -> ctx.put("custom-key-2", "custom-value-2")) + .context((ctx) -> ctx.put("custom-key-2", "custom-value-2")) .build(); // @formatter:on diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenClaimsSetTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenClaimsSetTests.java index e51616dc..ea88dfea 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenClaimsSetTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/token/OAuth2TokenClaimsSetTests.java @@ -53,7 +53,7 @@ public class OAuth2TokenClaimsSetTests { .notBefore(issuedAt) .expiresAt(expiresAt) .id("id") - .claims(claims -> claims.put(customClaimName, customClaimValue)) + .claims((claims) -> claims.put(customClaimName, customClaimValue)) .build(); OAuth2TokenClaimsSet claimsSet = OAuth2TokenClaimsSet.builder() @@ -64,7 +64,7 @@ public class OAuth2TokenClaimsSetTests { .notBefore(expectedClaimsSet.getNotBefore()) .expiresAt(expectedClaimsSet.getExpiresAt()) .id(expectedClaimsSet.getId()) - .claims(claims -> claims.put(customClaimName, expectedClaimsSet.getClaim(customClaimName))) + .claims((claims) -> claims.put(customClaimName, expectedClaimsSet.getClaim(customClaimName))) .build(); // @formatter:on diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/NimbusJwkSetEndpointFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/NimbusJwkSetEndpointFilterTests.java index baf17936..d15b4d56 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/NimbusJwkSetEndpointFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/NimbusJwkSetEndpointFilterTests.java @@ -18,10 +18,6 @@ package org.springframework.security.oauth2.server.authorization.web; import java.util.ArrayList; import java.util.List; -import jakarta.servlet.FilterChain; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - import com.nimbusds.jose.jwk.ECKey; import com.nimbusds.jose.jwk.JWK; import com.nimbusds.jose.jwk.JWKSet; @@ -30,6 +26,9 @@ import com.nimbusds.jose.jwk.OctetSequenceKey; import com.nimbusds.jose.jwk.RSAKey; import com.nimbusds.jose.jwk.source.JWKSource; import com.nimbusds.jose.proc.SecurityContext; +import jakarta.servlet.FilterChain; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2AuthorizationEndpointFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2AuthorizationEndpointFilterTests.java index 8fc31afd..ba89f50b 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2AuthorizationEndpointFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2AuthorizationEndpointFilterTests.java @@ -27,7 +27,7 @@ import java.util.function.Consumer; import jakarta.servlet.FilterChain; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; - +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -64,13 +64,12 @@ import org.springframework.web.util.UriComponentsBuilder; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.InstanceOfAssertFactories.type; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.same; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; /** * Tests for {@link OAuth2AuthorizationEndpointFilter}. @@ -185,7 +184,7 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthorizationRequestMissingResponseTypeThenInvalidRequestError() throws Exception { doFilterWhenAuthorizationRequestInvalidParameterThenError(TestRegisteredClients.registeredClient().build(), - OAuth2ParameterNames.RESPONSE_TYPE, OAuth2ErrorCodes.INVALID_REQUEST, request -> { + OAuth2ParameterNames.RESPONSE_TYPE, OAuth2ErrorCodes.INVALID_REQUEST, (request) -> { request.removeParameter(OAuth2ParameterNames.RESPONSE_TYPE); updateQueryString(request); }); @@ -194,7 +193,7 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthorizationRequestMultipleResponseTypeThenInvalidRequestError() throws Exception { doFilterWhenAuthorizationRequestInvalidParameterThenError(TestRegisteredClients.registeredClient().build(), - OAuth2ParameterNames.RESPONSE_TYPE, OAuth2ErrorCodes.INVALID_REQUEST, request -> { + OAuth2ParameterNames.RESPONSE_TYPE, OAuth2ErrorCodes.INVALID_REQUEST, (request) -> { request.addParameter(OAuth2ParameterNames.RESPONSE_TYPE, "id_token"); updateQueryString(request); }); @@ -203,7 +202,7 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthorizationRequestInvalidResponseTypeThenUnsupportedResponseTypeError() throws Exception { doFilterWhenAuthorizationRequestInvalidParameterThenError(TestRegisteredClients.registeredClient().build(), - OAuth2ParameterNames.RESPONSE_TYPE, OAuth2ErrorCodes.UNSUPPORTED_RESPONSE_TYPE, request -> { + OAuth2ParameterNames.RESPONSE_TYPE, OAuth2ErrorCodes.UNSUPPORTED_RESPONSE_TYPE, (request) -> { request.setParameter(OAuth2ParameterNames.RESPONSE_TYPE, "id_token"); updateQueryString(request); }); @@ -212,7 +211,7 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthorizationRequestMissingClientIdThenInvalidRequestError() throws Exception { doFilterWhenAuthorizationRequestInvalidParameterThenError(TestRegisteredClients.registeredClient().build(), - OAuth2ParameterNames.CLIENT_ID, OAuth2ErrorCodes.INVALID_REQUEST, request -> { + OAuth2ParameterNames.CLIENT_ID, OAuth2ErrorCodes.INVALID_REQUEST, (request) -> { request.removeParameter(OAuth2ParameterNames.CLIENT_ID); updateQueryString(request); }); @@ -221,7 +220,7 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthorizationRequestMultipleClientIdThenInvalidRequestError() throws Exception { doFilterWhenAuthorizationRequestInvalidParameterThenError(TestRegisteredClients.registeredClient().build(), - OAuth2ParameterNames.CLIENT_ID, OAuth2ErrorCodes.INVALID_REQUEST, request -> { + OAuth2ParameterNames.CLIENT_ID, OAuth2ErrorCodes.INVALID_REQUEST, (request) -> { request.addParameter(OAuth2ParameterNames.CLIENT_ID, "client-2"); updateQueryString(request); }); @@ -230,7 +229,7 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthorizationRequestMultipleRedirectUriThenInvalidRequestError() throws Exception { doFilterWhenAuthorizationRequestInvalidParameterThenError(TestRegisteredClients.registeredClient().build(), - OAuth2ParameterNames.REDIRECT_URI, OAuth2ErrorCodes.INVALID_REQUEST, request -> { + OAuth2ParameterNames.REDIRECT_URI, OAuth2ErrorCodes.INVALID_REQUEST, (request) -> { request.addParameter(OAuth2ParameterNames.REDIRECT_URI, "https://example2.com"); updateQueryString(request); }); @@ -239,7 +238,7 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthorizationRequestMultipleScopeThenInvalidRequestError() throws Exception { doFilterWhenAuthorizationRequestInvalidParameterThenError(TestRegisteredClients.registeredClient().build(), - OAuth2ParameterNames.SCOPE, OAuth2ErrorCodes.INVALID_REQUEST, request -> { + OAuth2ParameterNames.SCOPE, OAuth2ErrorCodes.INVALID_REQUEST, (request) -> { request.addParameter(OAuth2ParameterNames.SCOPE, "scope2"); updateQueryString(request); }); @@ -248,7 +247,7 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthorizationRequestMultipleStateThenInvalidRequestError() throws Exception { doFilterWhenAuthorizationRequestInvalidParameterThenError(TestRegisteredClients.registeredClient().build(), - OAuth2ParameterNames.STATE, OAuth2ErrorCodes.INVALID_REQUEST, request -> { + OAuth2ParameterNames.STATE, OAuth2ErrorCodes.INVALID_REQUEST, (request) -> { request.addParameter(OAuth2ParameterNames.STATE, "state2"); updateQueryString(request); }); @@ -258,7 +257,7 @@ public class OAuth2AuthorizationEndpointFilterTests { public void doFilterWhenAuthorizationConsentRequestMissingStateThenInvalidRequestError() throws Exception { doFilterWhenAuthorizationConsentRequestInvalidParameterThenError( TestRegisteredClients.registeredClient().build(), OAuth2ParameterNames.STATE, - OAuth2ErrorCodes.INVALID_REQUEST, request -> request.removeParameter(OAuth2ParameterNames.STATE)); + OAuth2ErrorCodes.INVALID_REQUEST, (request) -> request.removeParameter(OAuth2ParameterNames.STATE)); } @Test @@ -266,13 +265,13 @@ public class OAuth2AuthorizationEndpointFilterTests { doFilterWhenAuthorizationConsentRequestInvalidParameterThenError( TestRegisteredClients.registeredClient().build(), OAuth2ParameterNames.STATE, OAuth2ErrorCodes.INVALID_REQUEST, - request -> request.addParameter(OAuth2ParameterNames.STATE, "state2")); + (request) -> request.addParameter(OAuth2ParameterNames.STATE, "state2")); } @Test public void doFilterWhenAuthorizationRequestMultipleCodeChallengeThenInvalidRequestError() throws Exception { doFilterWhenAuthorizationRequestInvalidParameterThenError(TestRegisteredClients.registeredClient().build(), - PkceParameterNames.CODE_CHALLENGE, OAuth2ErrorCodes.INVALID_REQUEST, request -> { + PkceParameterNames.CODE_CHALLENGE, OAuth2ErrorCodes.INVALID_REQUEST, (request) -> { request.addParameter(PkceParameterNames.CODE_CHALLENGE, "code-challenge"); request.addParameter(PkceParameterNames.CODE_CHALLENGE, "another-code-challenge"); updateQueryString(request); @@ -282,7 +281,7 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthorizationRequestMultipleCodeChallengeMethodThenInvalidRequestError() throws Exception { doFilterWhenAuthorizationRequestInvalidParameterThenError(TestRegisteredClients.registeredClient().build(), - PkceParameterNames.CODE_CHALLENGE_METHOD, OAuth2ErrorCodes.INVALID_REQUEST, request -> { + PkceParameterNames.CODE_CHALLENGE_METHOD, OAuth2ErrorCodes.INVALID_REQUEST, (request) -> { request.addParameter(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256"); request.addParameter(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256"); updateQueryString(request); @@ -291,17 +290,17 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthorizationRequestAuthenticationExceptionThenErrorResponse() throws Exception { - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().redirectUris(redirectUris -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().redirectUris((redirectUris) -> { redirectUris.clear(); redirectUris.add("https://example.com?param=encoded%20parameter%20value"); }).build(); OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, registeredClient.getRedirectUris().iterator().next(), "client state", registeredClient.getScopes(), null); OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST, "error description", "error uri"); - when(this.authenticationManager.authenticate(any())) - .thenThrow(new OAuth2AuthorizationCodeRequestAuthenticationException(error, + given(this.authenticationManager.authenticate(any())) + .willThrow(new OAuth2AuthorizationCodeRequestAuthenticationException(error, authorizationCodeRequestAuthentication)); MockHttpServletRequest request = createAuthorizationRequest(registeredClient); @@ -323,14 +322,14 @@ public class OAuth2AuthorizationEndpointFilterTests { public void doFilterWhenCustomAuthenticationConverterThenUsed() throws Exception { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, registeredClient.getRedirectUris().iterator().next(), STATE, registeredClient.getScopes(), null); AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); - when(authenticationConverter.convert(any())).thenReturn(authorizationCodeRequestAuthentication); + given(authenticationConverter.convert(any())).willReturn(authorizationCodeRequestAuthentication); this.filter.setAuthenticationConverter(authenticationConverter); - when(this.authenticationManager.authenticate(any())).thenReturn(authorizationCodeRequestAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(authorizationCodeRequestAuthentication); MockHttpServletRequest request = createAuthorizationRequest(registeredClient); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -347,10 +346,10 @@ public class OAuth2AuthorizationEndpointFilterTests { public void doFilterWhenCustomAuthenticationSuccessHandlerThenUsed() throws Exception { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthenticationResult = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, this.authorizationCode, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, this.authorizationCode, registeredClient.getRedirectUris().iterator().next(), STATE, registeredClient.getScopes()); authorizationCodeRequestAuthenticationResult.setAuthenticated(true); - when(this.authenticationManager.authenticate(any())).thenReturn(authorizationCodeRequestAuthenticationResult); + given(this.authenticationManager.authenticate(any())).willReturn(authorizationCodeRequestAuthenticationResult); AuthenticationSuccessHandler authenticationSuccessHandler = mock(AuthenticationSuccessHandler.class); this.filter.setAuthenticationSuccessHandler(authenticationSuccessHandler); @@ -371,12 +370,12 @@ public class OAuth2AuthorizationEndpointFilterTests { public void doFilterWhenCustomAuthenticationFailureHandlerThenUsed() throws Exception { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, registeredClient.getRedirectUris().iterator().next(), STATE, registeredClient.getScopes(), null); OAuth2Error error = new OAuth2Error("errorCode", "errorDescription", "errorUri"); OAuth2AuthorizationCodeRequestAuthenticationException authenticationException = new OAuth2AuthorizationCodeRequestAuthenticationException( error, authorizationCodeRequestAuthentication); - when(this.authenticationManager.authenticate(any())).thenThrow(authenticationException); + given(this.authenticationManager.authenticate(any())).willThrow(authenticationException); AuthenticationFailureHandler authenticationFailureHandler = mock(AuthenticationFailureHandler.class); this.filter.setAuthenticationFailureHandler(authenticationFailureHandler); @@ -396,10 +395,10 @@ public class OAuth2AuthorizationEndpointFilterTests { public void doFilterWhenCustomSessionAuthenticationStrategyThenUsed() throws Exception { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthenticationResult = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, this.authorizationCode, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, this.authorizationCode, registeredClient.getRedirectUris().iterator().next(), STATE, registeredClient.getScopes()); authorizationCodeRequestAuthenticationResult.setAuthenticated(true); - when(this.authenticationManager.authenticate(any())).thenReturn(authorizationCodeRequestAuthenticationResult); + given(this.authenticationManager.authenticate(any())).willReturn(authorizationCodeRequestAuthenticationResult); SessionAuthenticationStrategy sessionAuthenticationStrategy = mock(SessionAuthenticationStrategy.class); this.filter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy); @@ -420,17 +419,17 @@ public class OAuth2AuthorizationEndpointFilterTests { public void doFilterWhenCustomAuthenticationDetailsSourceThenUsed() throws Exception { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthentication = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, registeredClient.getRedirectUris().iterator().next(), STATE, registeredClient.getScopes(), null); MockHttpServletRequest request = createAuthorizationRequest(registeredClient); AuthenticationDetailsSource authenticationDetailsSource = mock( AuthenticationDetailsSource.class); WebAuthenticationDetails webAuthenticationDetails = new WebAuthenticationDetails(request); - when(authenticationDetailsSource.buildDetails(request)).thenReturn(webAuthenticationDetails); + given(authenticationDetailsSource.buildDetails(request)).willReturn(webAuthenticationDetails); this.filter.setAuthenticationDetailsSource(authenticationDetailsSource); - when(this.authenticationManager.authenticate(any())).thenReturn(authorizationCodeRequestAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(authorizationCodeRequestAuthentication); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); @@ -447,10 +446,10 @@ public class OAuth2AuthorizationEndpointFilterTests { this.principal.setAuthenticated(false); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthenticationResult = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, registeredClient.getRedirectUris().iterator().next(), STATE, registeredClient.getScopes(), null); authorizationCodeRequestAuthenticationResult.setAuthenticated(false); - when(this.authenticationManager.authenticate(any())).thenReturn(authorizationCodeRequestAuthenticationResult); + given(this.authenticationManager.authenticate(any())).willReturn(authorizationCodeRequestAuthenticationResult); MockHttpServletRequest request = createAuthorizationRequest(registeredClient); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -466,15 +465,15 @@ public class OAuth2AuthorizationEndpointFilterTests { public void doFilterWhenAuthorizationRequestConsentRequiredWithCustomConsentUriThenRedirectConsentResponse() throws Exception { Set requestedScopes = new HashSet<>(Arrays.asList("scope1", "scope2")); - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(scopes -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> { scopes.clear(); scopes.addAll(requestedScopes); }).build(); // No scopes previously approved OAuth2AuthorizationConsentAuthenticationToken authorizationConsentAuthenticationResult = new OAuth2AuthorizationConsentAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, new HashSet<>(), null); + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, new HashSet<>(), null); authorizationConsentAuthenticationResult.setAuthenticated(true); - when(this.authenticationManager.authenticate(any())).thenReturn(authorizationConsentAuthenticationResult); + given(this.authenticationManager.authenticate(any())).willReturn(authorizationConsentAuthenticationResult); MockHttpServletRequest request = createAuthorizationRequest(registeredClient); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -494,15 +493,15 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthorizationRequestConsentRequiredThenConsentResponse() throws Exception { Set requestedScopes = new HashSet<>(Arrays.asList("scope1", "scope2")); - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(scopes -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> { scopes.clear(); scopes.addAll(requestedScopes); }).build(); // No scopes previously approved OAuth2AuthorizationConsentAuthenticationToken authorizationConsentAuthenticationResult = new OAuth2AuthorizationConsentAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, new HashSet<>(), null); + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, new HashSet<>(), null); authorizationConsentAuthenticationResult.setAuthenticated(true); - when(this.authenticationManager.authenticate(any())).thenReturn(authorizationConsentAuthenticationResult); + given(this.authenticationManager.authenticate(any())).willReturn(authorizationConsentAuthenticationResult); MockHttpServletRequest request = createAuthorizationRequest(registeredClient); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -525,15 +524,15 @@ public class OAuth2AuthorizationEndpointFilterTests { throws Exception { Set approvedScopes = new HashSet<>(Arrays.asList("scope1", "scope2")); Set requestedScopes = new HashSet<>(Arrays.asList("scope3", "scope4")); - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(scopes -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> { scopes.clear(); scopes.addAll(approvedScopes); scopes.addAll(requestedScopes); }).build(); OAuth2AuthorizationConsentAuthenticationToken authorizationConsentAuthenticationResult = new OAuth2AuthorizationConsentAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, STATE, approvedScopes, null); + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, STATE, approvedScopes, null); authorizationConsentAuthenticationResult.setAuthenticated(true); - when(this.authenticationManager.authenticate(any())).thenReturn(authorizationConsentAuthenticationResult); + given(this.authenticationManager.authenticate(any())).willReturn(authorizationConsentAuthenticationResult); MockHttpServletRequest request = createAuthorizationRequest(registeredClient); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -556,15 +555,15 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthorizationRequestAuthenticatedThenAuthorizationResponse() throws Exception { - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().redirectUris(redirectUris -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().redirectUris((redirectUris) -> { redirectUris.clear(); redirectUris.add("https://example.com?param=encoded%20parameter%20value"); }).build(); OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthenticationResult = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, this.authorizationCode, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, this.authorizationCode, registeredClient.getRedirectUris().iterator().next(), "client state", registeredClient.getScopes()); authorizationCodeRequestAuthenticationResult.setAuthenticated(true); - when(this.authenticationManager.authenticate(any())).thenReturn(authorizationCodeRequestAuthenticationResult); + given(this.authenticationManager.authenticate(any())).willReturn(authorizationCodeRequestAuthenticationResult); MockHttpServletRequest request = createAuthorizationRequest(registeredClient); request.addParameter("custom-param", "custom-value-1", "custom-value-2"); @@ -581,14 +580,14 @@ public class OAuth2AuthorizationEndpointFilterTests { verifyNoInteractions(filterChain); assertThat(authorizationCodeRequestAuthenticationCaptor.getValue().getDetails()) - .asInstanceOf(type(WebAuthenticationDetails.class)) + .asInstanceOf(InstanceOfAssertFactories.type(WebAuthenticationDetails.class)) .extracting(WebAuthenticationDetails::getRemoteAddress) .isEqualTo(REMOTE_ADDRESS); // Assert that multi-valued request parameters are preserved assertThat(authorizationCodeRequestAuthenticationCaptor.getValue().getAdditionalParameters()) - .extracting(params -> params.get("custom-param")) - .asInstanceOf(type(String[].class)) + .extracting((params) -> params.get("custom-param")) + .asInstanceOf(InstanceOfAssertFactories.type(String[].class)) .isEqualTo(new String[] { "custom-value-1", "custom-value-2" }); assertThat(response.getStatus()).isEqualTo(HttpStatus.FOUND.value()); assertThat(response.getRedirectedUrl()) @@ -598,15 +597,15 @@ public class OAuth2AuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthenticationRequestAuthenticatedThenAuthorizationResponse() throws Exception { // Setup OpenID Connect request - RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes(scopes -> { + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().scopes((scopes) -> { scopes.clear(); scopes.add(OidcScopes.OPENID); }).build(); OAuth2AuthorizationCodeRequestAuthenticationToken authorizationCodeRequestAuthenticationResult = new OAuth2AuthorizationCodeRequestAuthenticationToken( - AUTHORIZATION_URI, registeredClient.getClientId(), principal, this.authorizationCode, + AUTHORIZATION_URI, registeredClient.getClientId(), this.principal, this.authorizationCode, registeredClient.getRedirectUris().iterator().next(), STATE, registeredClient.getScopes()); authorizationCodeRequestAuthenticationResult.setAuthenticated(true); - when(this.authenticationManager.authenticate(any())).thenReturn(authorizationCodeRequestAuthenticationResult); + given(this.authenticationManager.authenticate(any())).willReturn(authorizationCodeRequestAuthenticationResult); MockHttpServletRequest request = createAuthorizationRequest(registeredClient); request.setMethod("POST"); // OpenID Connect supports POST method diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2AuthorizationServerMetadataEndpointFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2AuthorizationServerMetadataEndpointFilterTests.java index f3e5dbc0..fed24e8c 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2AuthorizationServerMetadataEndpointFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2AuthorizationServerMetadataEndpointFilterTests.java @@ -18,7 +18,6 @@ package org.springframework.security.oauth2.server.authorization.web; import jakarta.servlet.FilterChain; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2ClientAuthenticationFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2ClientAuthenticationFilterTests.java index 918b9d6b..97dc1750 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2ClientAuthenticationFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2ClientAuthenticationFilterTests.java @@ -20,7 +20,7 @@ import java.nio.charset.StandardCharsets; import jakarta.servlet.FilterChain; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; - +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -51,12 +51,11 @@ import org.springframework.security.web.util.matcher.RequestMatcher; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.InstanceOfAssertFactories.type; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; /** * Tests for {@link OAuth2ClientAuthenticationFilter}. @@ -156,8 +155,8 @@ public class OAuth2ClientAuthenticationFilterTests { @Test public void doFilterWhenRequestMatchesAndInvalidCredentialsThenInvalidRequestError() throws Exception { - when(this.authenticationConverter.convert(any(HttpServletRequest.class))).thenThrow( - new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST)); + given(this.authenticationConverter.convert(any(HttpServletRequest.class))) + .willThrow(new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST)); MockHttpServletRequest request = new MockHttpServletRequest("POST", this.filterProcessesUrl); request.setServletPath(this.filterProcessesUrl); @@ -196,8 +195,9 @@ public class OAuth2ClientAuthenticationFilterTests { } private void assertWhenInvalidClientIdThenInvalidRequestError(String clientId) throws Exception { - when(this.authenticationConverter.convert(any(HttpServletRequest.class))).thenReturn( - new OAuth2ClientAuthenticationToken(clientId, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, "secret", null)); + given(this.authenticationConverter.convert(any(HttpServletRequest.class))) + .willReturn(new OAuth2ClientAuthenticationToken(clientId, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, + "secret", null)); MockHttpServletRequest request = new MockHttpServletRequest("POST", this.filterProcessesUrl); request.setServletPath(this.filterProcessesUrl); @@ -217,10 +217,11 @@ public class OAuth2ClientAuthenticationFilterTests { @Test public void doFilterWhenRequestMatchesAndBadCredentialsThenInvalidClientError() throws Exception { - when(this.authenticationConverter.convert(any(HttpServletRequest.class))).thenReturn( - new OAuth2ClientAuthenticationToken("clientId", ClientAuthenticationMethod.CLIENT_SECRET_BASIC, "invalid-secret", null)); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenThrow( - new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT)); + given(this.authenticationConverter.convert(any(HttpServletRequest.class))) + .willReturn(new OAuth2ClientAuthenticationToken("clientId", ClientAuthenticationMethod.CLIENT_SECRET_BASIC, + "invalid-secret", null)); + given(this.authenticationManager.authenticate(any(Authentication.class))) + .willThrow(new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_CLIENT)); MockHttpServletRequest request = new MockHttpServletRequest("POST", this.filterProcessesUrl); request.setServletPath(this.filterProcessesUrl); @@ -243,11 +244,11 @@ public class OAuth2ClientAuthenticationFilterTests { final String remoteAddress = "remote-address"; RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); - when(this.authenticationConverter.convert(any(HttpServletRequest.class))) - .thenReturn(new OAuth2ClientAuthenticationToken(registeredClient.getClientId(), + given(this.authenticationConverter.convert(any(HttpServletRequest.class))) + .willReturn(new OAuth2ClientAuthenticationToken(registeredClient.getClientId(), ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret(), null)); - when(this.authenticationManager.authenticate(any(Authentication.class))) - .thenReturn(new OAuth2ClientAuthenticationToken(registeredClient, + given(this.authenticationManager.authenticate(any(Authentication.class))) + .willReturn(new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret())); MockHttpServletRequest request = new MockHttpServletRequest("POST", this.filterProcessesUrl); @@ -270,7 +271,7 @@ public class OAuth2ClientAuthenticationFilterTests { verify(this.authenticationManager).authenticate(authenticationRequestCaptor.capture()); assertThat(authenticationRequestCaptor).extracting(ArgumentCaptor::getValue) .extracting(OAuth2ClientAuthenticationToken::getDetails) - .asInstanceOf(type(WebAuthenticationDetails.class)) + .asInstanceOf(InstanceOfAssertFactories.type(WebAuthenticationDetails.class)) .extracting(WebAuthenticationDetails::getRemoteAddress) .isEqualTo(remoteAddress); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2DeviceAuthorizationEndpointFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2DeviceAuthorizationEndpointFilterTests.java index 3a27e2b6..2d39cff7 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2DeviceAuthorizationEndpointFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2DeviceAuthorizationEndpointFilterTests.java @@ -18,9 +18,11 @@ package org.springframework.security.oauth2.server.authorization.web; import java.io.IOException; import java.time.Instant; import java.time.temporal.ChronoUnit; +import java.util.Map; import jakarta.servlet.FilterChain; import jakarta.servlet.http.HttpServletRequest; +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -56,15 +58,13 @@ import org.springframework.security.web.authentication.AuthenticationFailureHand import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.authentication.WebAuthenticationDetails; -import static java.util.Map.entry; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.assertj.core.api.InstanceOfAssertFactories.type; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; /** * Tests for {@link OAuth2DeviceAuthorizationEndpointFilter}. @@ -195,7 +195,7 @@ public class OAuth2DeviceAuthorizationEndpointFilterTests { @Test public void doFilterWhenDeviceAuthorizationRequestThenDeviceAuthorizationResponse() throws Exception { Authentication authenticationResult = createAuthentication(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authenticationResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authenticationResult); Authentication clientPrincipal = (Authentication) authenticationResult.getPrincipal(); mockSecurityContext(clientPrincipal); @@ -219,11 +219,11 @@ public class OAuth2DeviceAuthorizationEndpointFilterTests { assertThat(deviceAuthorizationRequestAuthentication.getPrincipal()).isEqualTo(clientPrincipal); assertThat(deviceAuthorizationRequestAuthentication.getScopes()).isEmpty(); assertThat(deviceAuthorizationRequestAuthentication.getAdditionalParameters()).containsExactly( - entry("custom-param-1", "custom-value-1"), - entry("custom-param-2", new String[] { "custom-value-1", "custom-value-2" })); + Map.entry("custom-param-1", "custom-value-1"), + Map.entry("custom-param-2", new String[] { "custom-value-1", "custom-value-2" })); // @formatter:off assertThat(deviceAuthorizationRequestAuthentication.getDetails()) - .asInstanceOf(type(WebAuthenticationDetails.class)) + .asInstanceOf(InstanceOfAssertFactories.type(WebAuthenticationDetails.class)) .extracting(WebAuthenticationDetails::getRemoteAddress) .isEqualTo(REMOTE_ADDRESS); // @formatter:on @@ -246,7 +246,7 @@ public class OAuth2DeviceAuthorizationEndpointFilterTests { AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); OAuth2AuthenticationException authenticationException = new OAuth2AuthenticationException( new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST, "Invalid request", "error-uri")); - when(authenticationConverter.convert(any(HttpServletRequest.class))).thenThrow(authenticationException); + given(authenticationConverter.convert(any(HttpServletRequest.class))).willThrow(authenticationException); this.filter.setAuthenticationConverter(authenticationConverter); MockHttpServletRequest request = createRequest(); @@ -267,7 +267,7 @@ public class OAuth2DeviceAuthorizationEndpointFilterTests { @Test public void doFilterWhenCustomDeviceAuthorizationEndpointUriThenUsed() throws Exception { Authentication authenticationResult = createAuthentication(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authenticationResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authenticationResult); Authentication clientPrincipal = (Authentication) authenticationResult.getPrincipal(); mockSecurityContext(clientPrincipal); @@ -288,7 +288,7 @@ public class OAuth2DeviceAuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthenticationConverterSetThenUsed() throws Exception { Authentication authenticationResult = createAuthentication(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authenticationResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authenticationResult); Authentication clientPrincipal = (Authentication) authenticationResult.getPrincipal(); mockSecurityContext(clientPrincipal); @@ -296,7 +296,7 @@ public class OAuth2DeviceAuthorizationEndpointFilterTests { AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); OAuth2DeviceAuthorizationRequestAuthenticationToken authenticationRequest = new OAuth2DeviceAuthorizationRequestAuthenticationToken( clientPrincipal, AUTHORIZATION_URI, null, null); - when(authenticationConverter.convert(any(HttpServletRequest.class))).thenReturn(authenticationRequest); + given(authenticationConverter.convert(any(HttpServletRequest.class))).willReturn(authenticationRequest); this.filter.setAuthenticationConverter(authenticationConverter); MockHttpServletRequest request = createRequest(); @@ -313,7 +313,7 @@ public class OAuth2DeviceAuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthenticationDetailsSourceSetThenUsed() throws Exception { Authentication authenticationResult = createAuthentication(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authenticationResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authenticationResult); Authentication clientPrincipal = (Authentication) authenticationResult.getPrincipal(); mockSecurityContext(clientPrincipal); @@ -325,8 +325,8 @@ public class OAuth2DeviceAuthorizationEndpointFilterTests { @SuppressWarnings("unchecked") AuthenticationDetailsSource authenticationDetailsSource = mock( AuthenticationDetailsSource.class); - when(authenticationDetailsSource.buildDetails(any(HttpServletRequest.class))) - .thenReturn(new WebAuthenticationDetails(request)); + given(authenticationDetailsSource.buildDetails(any(HttpServletRequest.class))) + .willReturn(new WebAuthenticationDetails(request)); this.filter.setAuthenticationDetailsSource(authenticationDetailsSource); this.filter.doFilter(request, response, filterChain); @@ -340,7 +340,7 @@ public class OAuth2DeviceAuthorizationEndpointFilterTests { @Test public void doFilterWhenAuthenticationSuccessHandlerSetThenUsed() throws Exception { Authentication authenticationResult = createAuthentication(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authenticationResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authenticationResult); Authentication clientPrincipal = (Authentication) authenticationResult.getPrincipal(); mockSecurityContext(clientPrincipal); @@ -363,7 +363,7 @@ public class OAuth2DeviceAuthorizationEndpointFilterTests { public void doFilterWhenAuthenticationFailureHandlerSetThenUsed() throws Exception { OAuth2AuthenticationException authenticationException = new OAuth2AuthenticationException( OAuth2ErrorCodes.INVALID_REQUEST); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenThrow(authenticationException); + given(this.authenticationManager.authenticate(any(Authentication.class))).willThrow(authenticationException); Authentication clientPrincipal = (Authentication) createAuthentication().getPrincipal(); mockSecurityContext(clientPrincipal); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2DeviceVerificationEndpointFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2DeviceVerificationEndpointFilterTests.java index fcabda39..f755e75c 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2DeviceVerificationEndpointFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2DeviceVerificationEndpointFilterTests.java @@ -19,11 +19,11 @@ import java.nio.charset.StandardCharsets; import java.text.MessageFormat; import java.util.Collections; import java.util.HashSet; +import java.util.Map; import java.util.Set; import jakarta.servlet.FilterChain; import jakarta.servlet.http.HttpServletRequest; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -55,14 +55,13 @@ import org.springframework.security.web.authentication.AuthenticationSuccessHand import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.web.util.UriComponentsBuilder; -import static java.util.Map.entry; import static org.assertj.core.api.Assertions.assertThat; 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; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; /** * Tests for {@link OAuth2DeviceVerificationEndpointFilter}. @@ -169,7 +168,7 @@ public class OAuth2DeviceVerificationEndpointFilterTests { @Test public void doFilterWhenUnauthenticatedThenPassThrough() throws Exception { TestingAuthenticationToken unauthenticatedResult = new TestingAuthenticationToken("user", null); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(unauthenticatedResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(unauthenticatedResult); MockHttpServletRequest request = createRequest(); request.addParameter(OAuth2ParameterNames.USER_CODE, USER_CODE); @@ -184,7 +183,7 @@ public class OAuth2DeviceVerificationEndpointFilterTests { @Test public void doFilterWhenDeviceAuthorizationConsentRequestThenSuccess() throws Exception { Authentication authenticationResult = createDeviceVerificationAuthentication(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authenticationResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authenticationResult); Authentication clientPrincipal = (Authentication) authenticationResult.getPrincipal(); mockSecurityContext(clientPrincipal); @@ -218,14 +217,14 @@ public class OAuth2DeviceVerificationEndpointFilterTests { assertThat(deviceAuthorizationConsentAuthentication.getUserCode()).isEqualTo(USER_CODE); assertThat(deviceAuthorizationConsentAuthentication.getScopes()).containsExactly("scope-1", "scope-2"); assertThat(deviceAuthorizationConsentAuthentication.getAdditionalParameters()).containsExactly( - entry("custom-param-1", "custom-value-1"), - entry("custom-param-2", new String[] { "custom-value-1", "custom-value-2" })); + Map.entry("custom-param-1", "custom-value-1"), + Map.entry("custom-param-2", new String[] { "custom-value-1", "custom-value-2" })); } @Test public void doFilterWhenDeviceVerificationRequestAndConsentNotRequiredThenSuccess() throws Exception { Authentication authenticationResult = createDeviceVerificationAuthentication(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authenticationResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authenticationResult); Authentication clientPrincipal = (Authentication) authenticationResult.getPrincipal(); mockSecurityContext(clientPrincipal); @@ -249,13 +248,13 @@ public class OAuth2DeviceVerificationEndpointFilterTests { assertThat(deviceVerificationAuthentication.getPrincipal()).isInstanceOf(TestingAuthenticationToken.class); assertThat(deviceVerificationAuthentication.getUserCode()).isEqualTo(USER_CODE); assertThat(deviceVerificationAuthentication.getAdditionalParameters()) - .containsExactly(entry("custom-param-1", "custom-value-1")); + .containsExactly(Map.entry("custom-param-1", "custom-value-1")); } @Test public void doFilterWhenDeviceVerificationRequestAndConsentRequiredThenConsentScreen() throws Exception { Authentication authenticationResult = createDeviceAuthorizationConsentAuthentication(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authenticationResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authenticationResult); MockHttpServletRequest request = createRequest(); request.addParameter(OAuth2ParameterNames.USER_CODE, USER_CODE); @@ -277,7 +276,7 @@ public class OAuth2DeviceVerificationEndpointFilterTests { public void doFilterWhenDeviceVerificationRequestAndConsentRequiredWithPreviouslyApprovedThenConsentScreen() throws Exception { Authentication authenticationResult = createDeviceAuthorizationConsentAuthenticationWithAuthorizedScopes(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authenticationResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authenticationResult); MockHttpServletRequest request = createRequest(); request.addParameter(OAuth2ParameterNames.USER_CODE, USER_CODE); @@ -299,7 +298,7 @@ public class OAuth2DeviceVerificationEndpointFilterTests { public void doFilterWhenDeviceVerificationRequestAndConsentRequiredAndConsentPageSetThenRedirect() throws Exception { Authentication authentication = createDeviceAuthorizationConsentAuthentication(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authentication); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authentication); MockHttpServletRequest request = createRequest(); request.setScheme("https"); @@ -327,13 +326,13 @@ public class OAuth2DeviceVerificationEndpointFilterTests { @Test public void doFilterWhenAuthenticationConverterSetThenUsed() throws Exception { Authentication authenticationResult = createDeviceVerificationAuthentication(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authenticationResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authenticationResult); AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); OAuth2DeviceVerificationAuthenticationToken deviceVerificationAuthentication = new OAuth2DeviceVerificationAuthenticationToken( (Authentication) authenticationResult.getPrincipal(), USER_CODE, Collections.emptyMap()); - when(authenticationConverter.convert(any(HttpServletRequest.class))) - .thenReturn(deviceVerificationAuthentication); + given(authenticationConverter.convert(any(HttpServletRequest.class))) + .willReturn(deviceVerificationAuthentication); this.filter.setAuthenticationConverter(authenticationConverter); MockHttpServletRequest request = createRequest(); @@ -353,7 +352,7 @@ public class OAuth2DeviceVerificationEndpointFilterTests { @Test public void doFilterWhenAuthenticationDetailsSourceSetThenUsed() throws Exception { Authentication authenticationResult = createDeviceVerificationAuthentication(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authenticationResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authenticationResult); MockHttpServletRequest request = createRequest(); request.addParameter(OAuth2ParameterNames.USER_CODE, USER_CODE); @@ -364,8 +363,8 @@ public class OAuth2DeviceVerificationEndpointFilterTests { @SuppressWarnings("unchecked") AuthenticationDetailsSource authenticationDetailsSource = mock( AuthenticationDetailsSource.class); - when(authenticationDetailsSource.buildDetails(any(HttpServletRequest.class))) - .thenReturn(new WebAuthenticationDetails(request)); + given(authenticationDetailsSource.buildDetails(any(HttpServletRequest.class))) + .willReturn(new WebAuthenticationDetails(request)); this.filter.setAuthenticationDetailsSource(authenticationDetailsSource); this.filter.doFilter(request, response, filterChain); @@ -380,7 +379,7 @@ public class OAuth2DeviceVerificationEndpointFilterTests { @Test public void doFilterWhenAuthenticationSuccessHandlerSetThenUsed() throws Exception { Authentication authenticationResult = createDeviceVerificationAuthentication(); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(authenticationResult); + given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authenticationResult); AuthenticationSuccessHandler authenticationSuccessHandler = mock(AuthenticationSuccessHandler.class); this.filter.setAuthenticationSuccessHandler(authenticationSuccessHandler); @@ -402,7 +401,7 @@ public class OAuth2DeviceVerificationEndpointFilterTests { public void doFilterWhenAuthenticationFailureHandlerSetThenUsed() throws Exception { OAuth2AuthenticationException authenticationException = new OAuth2AuthenticationException( OAuth2ErrorCodes.INVALID_REQUEST); - when(this.authenticationManager.authenticate(any(Authentication.class))).thenThrow(authenticationException); + given(this.authenticationManager.authenticate(any(Authentication.class))).willThrow(authenticationException); AuthenticationFailureHandler authenticationFailureHandler = mock(AuthenticationFailureHandler.class); this.filter.setAuthenticationFailureHandler(authenticationFailureHandler); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenEndpointFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenEndpointFilterTests.java index 21cc8f56..fc3bce20 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenEndpointFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenEndpointFilterTests.java @@ -21,11 +21,11 @@ import java.util.Arrays; import java.util.HashSet; import java.util.Map; +import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.FilterChain; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; - -import com.fasterxml.jackson.databind.ObjectMapper; +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -67,12 +67,11 @@ 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.entry; -import static org.assertj.core.api.InstanceOfAssertFactories.type; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; /** * Tests for {@link OAuth2TokenEndpointFilter}. @@ -247,7 +246,7 @@ public class OAuth2TokenEndpointFilterTests { OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = new OAuth2AccessTokenAuthenticationToken( registeredClient, clientPrincipal, accessToken, refreshToken); - when(this.authenticationManager.authenticate(any())).thenReturn(accessTokenAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(accessTokenAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); @@ -275,7 +274,8 @@ public class OAuth2TokenEndpointFilterTests { assertThat(authorizationCodeAuthentication.getAdditionalParameters()).containsExactly( entry("custom-param-1", "custom-value-1"), entry("custom-param-2", new String[] { "custom-value-1", "custom-value-2" })); - assertThat(authorizationCodeAuthentication.getDetails()).asInstanceOf(type(WebAuthenticationDetails.class)) + assertThat(authorizationCodeAuthentication.getDetails()) + .asInstanceOf(InstanceOfAssertFactories.type(WebAuthenticationDetails.class)) .extracting(WebAuthenticationDetails::getRemoteAddress) .isEqualTo(REMOTE_ADDRESS); @@ -314,7 +314,7 @@ public class OAuth2TokenEndpointFilterTests { OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = new OAuth2AccessTokenAuthenticationToken( registeredClient, clientPrincipal, accessToken); - when(this.authenticationManager.authenticate(any())).thenReturn(accessTokenAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(accessTokenAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); @@ -339,7 +339,8 @@ public class OAuth2TokenEndpointFilterTests { assertThat(clientCredentialsAuthentication.getAdditionalParameters()).containsExactly( entry("custom-param-1", "custom-value-1"), entry("custom-param-2", new String[] { "custom-value-1", "custom-value-2" })); - assertThat(clientCredentialsAuthentication.getDetails()).asInstanceOf(type(WebAuthenticationDetails.class)) + assertThat(clientCredentialsAuthentication.getDetails()) + .asInstanceOf(InstanceOfAssertFactories.type(WebAuthenticationDetails.class)) .extracting(WebAuthenticationDetails::getRemoteAddress) .isEqualTo(REMOTE_ADDRESS); @@ -401,7 +402,7 @@ public class OAuth2TokenEndpointFilterTests { OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = new OAuth2AccessTokenAuthenticationToken( registeredClient, clientPrincipal, accessToken, refreshToken); - when(this.authenticationManager.authenticate(any())).thenReturn(accessTokenAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(accessTokenAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); @@ -427,7 +428,8 @@ public class OAuth2TokenEndpointFilterTests { assertThat(refreshTokenAuthenticationToken.getAdditionalParameters()).containsExactly( entry("custom-param-1", "custom-value-1"), entry("custom-param-2", new String[] { "custom-value-1", "custom-value-2" })); - assertThat(refreshTokenAuthenticationToken.getDetails()).asInstanceOf(type(WebAuthenticationDetails.class)) + assertThat(refreshTokenAuthenticationToken.getDetails()) + .asInstanceOf(InstanceOfAssertFactories.type(WebAuthenticationDetails.class)) .extracting(WebAuthenticationDetails::getRemoteAddress) .isEqualTo(REMOTE_ADDRESS); @@ -458,7 +460,7 @@ public class OAuth2TokenEndpointFilterTests { AuthenticationDetailsSource authenticationDetailsSource = mock( AuthenticationDetailsSource.class); WebAuthenticationDetails webAuthenticationDetails = new WebAuthenticationDetails(request); - when(authenticationDetailsSource.buildDetails(any())).thenReturn(webAuthenticationDetails); + given(authenticationDetailsSource.buildDetails(any())).willReturn(webAuthenticationDetails); this.filter.setAuthenticationDetailsSource(authenticationDetailsSource); OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", @@ -467,7 +469,7 @@ public class OAuth2TokenEndpointFilterTests { OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = new OAuth2AccessTokenAuthenticationToken( registeredClient, clientPrincipal, accessToken); - when(this.authenticationManager.authenticate(any())).thenReturn(accessTokenAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(accessTokenAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); @@ -491,7 +493,7 @@ public class OAuth2TokenEndpointFilterTests { "code", clientPrincipal, null, null); AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); - when(authenticationConverter.convert(any())).thenReturn(authorizationCodeAuthentication); + given(authenticationConverter.convert(any())).willReturn(authorizationCodeAuthentication); this.filter.setAuthenticationConverter(authenticationConverter); OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", @@ -500,7 +502,7 @@ public class OAuth2TokenEndpointFilterTests { OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = new OAuth2AccessTokenAuthenticationToken( registeredClient, clientPrincipal, accessToken); - when(this.authenticationManager.authenticate(any())).thenReturn(accessTokenAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(accessTokenAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); @@ -529,7 +531,7 @@ public class OAuth2TokenEndpointFilterTests { OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = new OAuth2AccessTokenAuthenticationToken( registeredClient, clientPrincipal, accessToken); - when(this.authenticationManager.authenticate(any())).thenReturn(accessTokenAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(accessTokenAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenIntrospectionEndpointFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenIntrospectionEndpointFilterTests.java index 4a90ed80..37fc4b86 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenIntrospectionEndpointFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenIntrospectionEndpointFilterTests.java @@ -23,7 +23,6 @@ import java.util.HashSet; import jakarta.servlet.FilterChain; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -60,10 +59,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; /** * Tests for {@link OAuth2TokenIntrospectionEndpointFilter}. @@ -199,7 +198,7 @@ public class OAuth2TokenIntrospectionEndpointFilterTests { .username("authorizing-username") .issuedAt(accessToken.getIssuedAt()) .expiresAt(accessToken.getExpiresAt()) - .scopes(scopes -> scopes.addAll(accessToken.getScopes())) + .scopes((scopes) -> scopes.addAll(accessToken.getScopes())) .tokenType(accessToken.getTokenType().getValue()) .notBefore(accessToken.getIssuedAt()) .subject("authorizing-subject") @@ -211,7 +210,7 @@ public class OAuth2TokenIntrospectionEndpointFilterTests { OAuth2TokenIntrospectionAuthenticationToken tokenIntrospectionAuthenticationResult = new OAuth2TokenIntrospectionAuthenticationToken( accessToken.getTokenValue(), clientPrincipal, tokenClaims); - when(this.authenticationManager.authenticate(any())).thenReturn(tokenIntrospectionAuthenticationResult); + given(this.authenticationManager.authenticate(any())).willReturn(tokenIntrospectionAuthenticationResult); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); @@ -269,10 +268,10 @@ public class OAuth2TokenIntrospectionEndpointFilterTests { accessToken.getTokenValue(), clientPrincipal, OAuth2TokenType.ACCESS_TOKEN.getValue(), null); AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); - when(authenticationConverter.convert(any())).thenReturn(tokenIntrospectionAuthentication); + given(authenticationConverter.convert(any())).willReturn(tokenIntrospectionAuthentication); this.filter.setAuthenticationConverter(authenticationConverter); - when(this.authenticationManager.authenticate(any())).thenReturn(tokenIntrospectionAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(tokenIntrospectionAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); @@ -302,7 +301,7 @@ public class OAuth2TokenIntrospectionEndpointFilterTests { AuthenticationSuccessHandler authenticationSuccessHandler = mock(AuthenticationSuccessHandler.class); this.filter.setAuthenticationSuccessHandler(authenticationSuccessHandler); - when(this.authenticationManager.authenticate(any())).thenReturn(tokenIntrospectionAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(tokenIntrospectionAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); @@ -330,7 +329,7 @@ public class OAuth2TokenIntrospectionEndpointFilterTests { AuthenticationFailureHandler authenticationFailureHandler = mock(AuthenticationFailureHandler.class); this.filter.setAuthenticationFailureHandler(authenticationFailureHandler); - when(this.authenticationManager.authenticate(any())).thenThrow(OAuth2AuthenticationException.class); + given(this.authenticationManager.authenticate(any())).willThrow(OAuth2AuthenticationException.class); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenRevocationEndpointFilterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenRevocationEndpointFilterTests.java index 5940e3a2..6b5bbb6b 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenRevocationEndpointFilterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenRevocationEndpointFilterTests.java @@ -24,7 +24,6 @@ import java.util.function.Consumer; import jakarta.servlet.FilterChain; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; - import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -57,10 +56,10 @@ import org.springframework.security.web.authentication.AuthenticationSuccessHand import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; /** * Tests for {@link OAuth2TokenRevocationEndpointFilter}. @@ -153,21 +152,21 @@ public class OAuth2TokenRevocationEndpointFilterTests { @Test public void doFilterWhenTokenRevocationRequestMissingTokenThenInvalidRequestError() throws Exception { doFilterWhenTokenRevocationRequestInvalidParameterThenError(OAuth2ParameterNames.TOKEN, - OAuth2ErrorCodes.INVALID_REQUEST, request -> request.removeParameter(OAuth2ParameterNames.TOKEN)); + OAuth2ErrorCodes.INVALID_REQUEST, (request) -> request.removeParameter(OAuth2ParameterNames.TOKEN)); } @Test public void doFilterWhenTokenRevocationRequestMultipleTokenThenInvalidRequestError() throws Exception { doFilterWhenTokenRevocationRequestInvalidParameterThenError(OAuth2ParameterNames.TOKEN, OAuth2ErrorCodes.INVALID_REQUEST, - request -> request.addParameter(OAuth2ParameterNames.TOKEN, "token-2")); + (request) -> request.addParameter(OAuth2ParameterNames.TOKEN, "token-2")); } @Test public void doFilterWhenTokenRevocationRequestMultipleTokenTypeHintThenInvalidRequestError() throws Exception { doFilterWhenTokenRevocationRequestInvalidParameterThenError(OAuth2ParameterNames.TOKEN_TYPE_HINT, - OAuth2ErrorCodes.INVALID_REQUEST, request -> request.addParameter(OAuth2ParameterNames.TOKEN_TYPE_HINT, - OAuth2TokenType.ACCESS_TOKEN.getValue())); + OAuth2ErrorCodes.INVALID_REQUEST, (request) -> request + .addParameter(OAuth2ParameterNames.TOKEN_TYPE_HINT, OAuth2TokenType.ACCESS_TOKEN.getValue())); } @Test @@ -181,7 +180,7 @@ public class OAuth2TokenRevocationEndpointFilterTests { OAuth2TokenRevocationAuthenticationToken tokenRevocationAuthentication = new OAuth2TokenRevocationAuthenticationToken( accessToken, clientPrincipal); - when(this.authenticationManager.authenticate(any())).thenReturn(tokenRevocationAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(tokenRevocationAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); @@ -211,10 +210,10 @@ public class OAuth2TokenRevocationEndpointFilterTests { accessToken, clientPrincipal); AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); - when(authenticationConverter.convert(any())).thenReturn(tokenRevocationAuthentication); + given(authenticationConverter.convert(any())).willReturn(tokenRevocationAuthentication); this.filter.setAuthenticationConverter(authenticationConverter); - when(this.authenticationManager.authenticate(any())).thenReturn(tokenRevocationAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(tokenRevocationAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); @@ -243,7 +242,7 @@ public class OAuth2TokenRevocationEndpointFilterTests { AuthenticationSuccessHandler authenticationSuccessHandler = mock(AuthenticationSuccessHandler.class); this.filter.setAuthenticationSuccessHandler(authenticationSuccessHandler); - when(this.authenticationManager.authenticate(any())).thenReturn(tokenRevocationAuthentication); + given(this.authenticationManager.authenticate(any())).willReturn(tokenRevocationAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); @@ -267,7 +266,7 @@ public class OAuth2TokenRevocationEndpointFilterTests { AuthenticationFailureHandler authenticationFailureHandler = mock(AuthenticationFailureHandler.class); this.filter.setAuthenticationFailureHandler(authenticationFailureHandler); - when(this.authenticationManager.authenticate(any())).thenThrow(OAuth2AuthenticationException.class); + given(this.authenticationManager.authenticate(any())).willThrow(OAuth2AuthenticationException.class); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/ClientSecretBasicAuthenticationConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/ClientSecretBasicAuthenticationConverterTests.java index 028abe14..133ffd39 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/ClientSecretBasicAuthenticationConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/ClientSecretBasicAuthenticationConverterTests.java @@ -66,7 +66,7 @@ public class ClientSecretBasicAuthenticationConverterTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(HttpHeaders.AUTHORIZATION, "Basic "); assertThatThrownBy(() -> this.converter.convert(request)).isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); } @@ -76,7 +76,7 @@ public class ClientSecretBasicAuthenticationConverterTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(HttpHeaders.AUTHORIZATION, "Basic clientId:secret"); assertThatThrownBy(() -> this.converter.convert(request)).isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); } @@ -87,7 +87,7 @@ public class ClientSecretBasicAuthenticationConverterTests { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodeBasicAuth("clientId", "")); assertThatThrownBy(() -> this.converter.convert(request)).isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/ClientSecretPostAuthenticationConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/ClientSecretPostAuthenticationConverterTests.java index e1d91eca..95148b90 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/ClientSecretPostAuthenticationConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/ClientSecretPostAuthenticationConverterTests.java @@ -53,7 +53,7 @@ public class ClientSecretPostAuthenticationConverterTests { request.addParameter(OAuth2ParameterNames.CLIENT_ID, "client-1"); request.addParameter(OAuth2ParameterNames.CLIENT_ID, "client-2"); assertThatThrownBy(() -> this.converter.convert(request)).isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); } @@ -73,7 +73,7 @@ public class ClientSecretPostAuthenticationConverterTests { request.addParameter(OAuth2ParameterNames.CLIENT_SECRET, "client-secret-1"); request.addParameter(OAuth2ParameterNames.CLIENT_SECRET, "client-secret-2"); assertThatThrownBy(() -> this.converter.convert(request)).isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/JwtClientAssertionAuthenticationConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/JwtClientAssertionAuthenticationConverterTests.java index 1dcf3cf5..7874be2c 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/JwtClientAssertionAuthenticationConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/JwtClientAssertionAuthenticationConverterTests.java @@ -124,7 +124,7 @@ public class JwtClientAssertionAuthenticationConverterTests { private void assertThrown(MockHttpServletRequest request, String errorCode) { assertThatThrownBy(() -> this.converter.convert(request)).isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(errorCode); } diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceAuthorizationConsentAuthenticationConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceAuthorizationConsentAuthenticationConverterTests.java index dec8f509..c7ec48ae 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceAuthorizationConsentAuthenticationConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceAuthorizationConsentAuthenticationConverterTests.java @@ -15,6 +15,8 @@ */ package org.springframework.security.oauth2.server.authorization.web.authentication; +import java.util.Map; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -31,7 +33,6 @@ import org.springframework.security.oauth2.core.OAuth2ErrorCodes; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.security.oauth2.server.authorization.authentication.OAuth2DeviceAuthorizationConsentAuthenticationToken; -import static java.util.Map.entry; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -280,8 +281,8 @@ public class OAuth2DeviceAuthorizationConsentAuthenticationConverterTests { assertThat(authentication.getPrincipal()).isInstanceOf(TestingAuthenticationToken.class); assertThat(authentication.getUserCode()).isEqualTo(USER_CODE); assertThat(authentication.getScopes()).containsExactly("message.read", "message.write"); - assertThat(authentication.getAdditionalParameters()).containsExactly(entry("param-1", "value-1"), - entry("param-2", new String[] { "value-1", "value-2" })); + assertThat(authentication.getAdditionalParameters()).containsExactly(Map.entry("param-1", "value-1"), + Map.entry("param-2", new String[] { "value-1", "value-2" })); } @Test diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceAuthorizationRequestAuthenticationConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceAuthorizationRequestAuthenticationConverterTests.java index ab641ce2..7296e35d 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceAuthorizationRequestAuthenticationConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceAuthorizationRequestAuthenticationConverterTests.java @@ -15,6 +15,8 @@ */ package org.springframework.security.oauth2.server.authorization.web.authentication; +import java.util.Map; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -30,7 +32,6 @@ import org.springframework.security.oauth2.core.OAuth2ErrorCodes; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.security.oauth2.server.authorization.authentication.OAuth2DeviceAuthorizationRequestAuthenticationToken; -import static java.util.Map.entry; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -109,8 +110,8 @@ public class OAuth2DeviceAuthorizationRequestAuthenticationConverterTests { assertThat(authentication.getPrincipal()).isInstanceOf(TestingAuthenticationToken.class); assertThat(authentication.getAuthorizationUri()).endsWith(AUTHORIZATION_URI); assertThat(authentication.getScopes()).containsExactly("message.read", "message.write"); - assertThat(authentication.getAdditionalParameters()).containsExactly(entry("param-1", "value-1"), - entry("param-2", new String[] { "value-1", "value-2" })); + assertThat(authentication.getAdditionalParameters()).containsExactly(Map.entry("param-1", "value-1"), + Map.entry("param-2", new String[] { "value-1", "value-2" })); } private static MockHttpServletRequest createRequest() { diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceCodeAuthenticationConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceCodeAuthenticationConverterTests.java index 4aed04fa..bb84e9f2 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceCodeAuthenticationConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceCodeAuthenticationConverterTests.java @@ -15,6 +15,8 @@ */ package org.springframework.security.oauth2.server.authorization.web.authentication; +import java.util.Map; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -32,7 +34,6 @@ import org.springframework.security.oauth2.core.OAuth2ErrorCodes; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.security.oauth2.server.authorization.authentication.OAuth2DeviceCodeAuthenticationToken; -import static java.util.Map.entry; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -116,8 +117,8 @@ public class OAuth2DeviceCodeAuthenticationConverterTests { assertThat(authentication).isNotNull(); assertThat(authentication.getDeviceCode()).isEqualTo(DEVICE_CODE); assertThat(authentication.getPrincipal()).isInstanceOf(TestingAuthenticationToken.class); - assertThat(authentication.getAdditionalParameters()).containsExactly(entry("param-1", "value-1"), - entry("param-2", new String[] { "value-1", "value-2" })); + assertThat(authentication.getAdditionalParameters()).containsExactly(Map.entry("param-1", "value-1"), + Map.entry("param-2", new String[] { "value-1", "value-2" })); } private static MockHttpServletRequest createRequest() { diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceVerificationAuthenticationConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceVerificationAuthenticationConverterTests.java index a8e2b7ad..5ab5731f 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceVerificationAuthenticationConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2DeviceVerificationAuthenticationConverterTests.java @@ -15,6 +15,8 @@ */ package org.springframework.security.oauth2.server.authorization.web.authentication; +import java.util.Map; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -33,7 +35,6 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.security.oauth2.server.authorization.authentication.OAuth2DeviceVerificationAuthenticationToken; import org.springframework.web.util.UriComponentsBuilder; -import static java.util.Map.entry; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @@ -179,8 +180,8 @@ public class OAuth2DeviceVerificationAuthenticationConverterTests { assertThat(authentication).isNotNull(); assertThat(authentication.getPrincipal()).isInstanceOf(TestingAuthenticationToken.class); assertThat(authentication.getUserCode()).isEqualTo(USER_CODE); - assertThat(authentication.getAdditionalParameters()).containsExactly(entry("param-1", "value-1"), - entry("param-2", new String[] { "value-1", "value-2" })); + assertThat(authentication.getAdditionalParameters()).containsExactly(Map.entry("param-1", "value-1"), + Map.entry("param-2", new String[] { "value-1", "value-2" })); } private static MockHttpServletRequest createRequest() { diff --git a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/PublicClientAuthenticationConverterTests.java b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/PublicClientAuthenticationConverterTests.java index 5106e240..c522b3e6 100644 --- a/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/PublicClientAuthenticationConverterTests.java +++ b/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/PublicClientAuthenticationConverterTests.java @@ -52,7 +52,7 @@ public class PublicClientAuthenticationConverterTests { MockHttpServletRequest request = createPkceTokenRequest(); request.removeParameter(OAuth2ParameterNames.CLIENT_ID); assertThatThrownBy(() -> this.converter.convert(request)).isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); } @@ -62,7 +62,7 @@ public class PublicClientAuthenticationConverterTests { MockHttpServletRequest request = createPkceTokenRequest(); request.addParameter(OAuth2ParameterNames.CLIENT_ID, "client-2"); assertThatThrownBy(() -> this.converter.convert(request)).isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); } @@ -72,7 +72,7 @@ public class PublicClientAuthenticationConverterTests { MockHttpServletRequest request = createPkceTokenRequest(); request.addParameter(PkceParameterNames.CODE_VERIFIER, "code-verifier-2"); assertThatThrownBy(() -> this.converter.convert(request)).isInstanceOf(OAuth2AuthenticationException.class) - .extracting(ex -> ((OAuth2AuthenticationException) ex).getError()) + .extracting((ex) -> ((OAuth2AuthenticationException) ex).getError()) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST); }