From e9130489a6428bdc0f05e75276e02391facfe1b3 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 27 Jul 2020 21:34:26 -0700 Subject: [PATCH] Remove restricted static imports Replace static imports with class referenced methods. With the exception of a few well known static imports, checkstyle restricts the static imports that a class can use. For example, `asList(...)` would be replaced with `Arrays.asList(...)`. Issue gh-8945 --- .../acls/jdbc/JdbcAclServiceTests.java | 4 +- ...onProviderBuilderSecurityBuilderTests.java | 12 +- ...AuthenticationProviderConfigurerTests.java | 13 +- .../config/annotation/rsocket/JwtITests.java | 5 +- .../rsocket/SimpleAuthenticationITests.java | 5 +- ...pUserServiceBeanDefinitionParserTests.java | 20 +- .../SecurityReactorContextConfiguration.java | 4 +- .../OAuth2ResourceServerConfigurer.java | 4 +- .../saml2/Saml2LoginConfigurer.java | 5 +- .../http/AuthenticationConfigBuilder.java | 53 ++--- ...nvocationSecurityMetadataSourceParser.java | 4 +- .../config/http/HttpConfigurationBuilder.java | 52 ++--- .../OAuth2ClientBeanDefinitionParser.java | 18 +- .../http/OAuth2LoginBeanDefinitionParser.java | 18 +- ...balMethodSecurityBeanDefinitionParser.java | 24 +- ...ageBrokerSecurityBeanDefinitionParser.java | 4 +- .../config/SecurityNamespaceHandlerTests.java | 42 ++-- .../NamespaceAuthenticationManagerTests.java | 6 +- ...reBeanFactoryObjectPostProcessorTests.java | 2 +- ...curityConfigurerAdapterPowermockTests.java | 8 +- .../WebSecurityConfigurerAdapterTests.java | 11 +- .../web/builders/HttpConfigurationTests.java | 13 +- .../OAuth2ClientConfigurationTests.java | 32 ++- ...ntextConfigurationResourceServerTests.java | 16 +- ...urityReactorContextConfigurationTests.java | 23 +- .../HeadersConfigurerEagerHeadersTests.java | 9 +- .../web/configurers/Issue55Tests.java | 2 +- .../LogoutConfigurerClearSiteDataTests.java | 17 +- .../NamespaceHttpOpenIDLoginTests.java | 4 +- ...ionManagementConfigurerServlet31Tests.java | 2 +- .../client/OAuth2LoginConfigurerTests.java | 8 +- .../OAuth2ResourceServerConfigurerTests.java | 33 ++- .../openid/OpenIDLoginConfigurerTests.java | 6 +- .../saml2/Saml2LoginConfigurerTests.java | 23 +- .../saml2/TestSaml2Credentials.java | 9 +- .../reactive/EnableWebFluxSecurityTests.java | 7 +- ...SocketMessageBrokerConfigurerDocTests.java | 4 +- ...ceFactoryBeanPropertiesResourceITests.java | 2 +- ...yBeanPropertiesResourceLocationITests.java | 2 +- ...erviceResourceFactoryBeanStringITests.java | 2 +- .../UserDetailsResourceFactoryBeanTests.java | 2 +- ...ityDebugBeanFactoryPostProcessorTests.java | 8 +- .../security/config/http/CsrfConfigTests.java | 17 +- .../FormLoginBeanDefinitionParserTests.java | 4 +- .../config/http/MiscHttpConfigTests.java | 6 +- ...OAuth2ClientBeanDefinitionParserTests.java | 6 +- .../OAuth2LoginBeanDefinitionParserTests.java | 22 +- ...sourceServerBeanDefinitionParserTests.java | 70 +++--- .../config/http/OpenIDConfigTests.java | 4 +- .../config/http/RememberMeConfigTests.java | 42 ++-- ...yContextHolderAwareRequestConfigTests.java | 2 +- ...SessionManagementConfigServlet31Tests.java | 2 +- .../http/SessionManagementConfigTests.java | 8 +- .../CustomHttpSecurityConfigurerTests.java | 5 +- ...thodSecurityBeanDefinitionParserTests.java | 29 +-- ...ceFactoryBeanPropertiesResourceITests.java | 2 +- ...yBeanPropertiesResourceLocationITests.java | 2 +- ...anagerResourceFactoryBeanStringITests.java | 2 +- .../config/test/SpringTestContext.java | 4 +- .../InMemoryXmlWebApplicationContext.java | 11 +- .../config/web/server/CorsSpecTests.java | 2 +- .../config/web/server/HeaderSpecTests.java | 2 +- .../config/web/server/OAuth2LoginTests.java | 4 +- .../server/OAuth2ResourceServerSpecTests.java | 6 +- .../web/server/ServerHttpSecurityTests.java | 24 +- .../RoleHierarchyUtilsTests.java | 12 +- ...yContextScheduledExecutorServiceTests.java | 10 +- ...tDelegatingSecurityContextTestSupport.java | 25 ++- .../core/SpringSecurityCoreVersionTests.java | 51 +++-- ...PasswordAuthenticationTokenMixinTests.java | 9 +- .../crypto/encrypt/AesBytesEncryptor.java | 29 +-- .../BouncyCastleAesCbcBytesEncryptor.java | 10 +- .../BouncyCastleAesGcmBytesEncryptor.java | 10 +- .../password/AbstractPasswordEncoder.java | 8 +- .../password/Pbkdf2PasswordEncoder.java | 12 +- .../password/StandardPasswordEncoder.java | 10 +- .../encrypt/AesBytesEncryptorTests.java | 12 +- etc/checkstyle/checkstyle-suppressions.xml | 1 - .../AbstractMessageMatcherComposite.java | 12 +- ...ageSecurityMetadataSourceFactoryTests.java | 10 +- .../MessageExpressionVoterTests.java | 19 +- ...ultMessageSecurityMetadataSourceTests.java | 6 +- ...ecurityContextChannelInterceptorTests.java | 3 +- .../handler/invocation/ResolvableMethod.java | 15 +- ...activeOAuth2AccessTokenResponseClient.java | 5 +- ...2AuthorizationGrantRequestEntityUtils.java | 4 +- .../ClientRegistrationDeserializer.java | 45 ++-- ...Auth2AuthorizationRequestDeserializer.java | 30 ++- .../oauth2/client/jackson2/StdConverters.java | 10 +- .../OidcIdTokenDecoderFactory.java | 7 +- .../ReactiveOidcIdTokenDecoderFactory.java | 9 +- .../registration/ClientRegistration.java | 4 +- .../OAuth2UserRequestEntityConverter.java | 4 +- .../client/OAuth2AuthorizedClientTests.java | 8 +- ...zationCodeAuthenticationProviderTests.java | 30 +-- ...orizationCodeAuthenticationTokenTests.java | 15 +- ...Auth2LoginAuthenticationProviderTests.java | 22 +- .../OAuth2LoginAuthenticationTokenTests.java | 15 +- ...orizationCodeTokenResponseClientTests.java | 23 +- ...nCodeGrantRequestEntityConverterTests.java | 5 +- ...th2AuthorizationCodeGrantRequestTests.java | 8 +- ...tialsGrantRequestEntityConverterTests.java | 3 +- ...th2ClientCredentialsGrantRequestTests.java | 2 +- ...swordGrantRequestEntityConverterTests.java | 3 +- ...TokenGrantRequestEntityConverterTests.java | 3 +- .../OAuth2AuthenticationTokenMixinTests.java | 4 +- ...zationCodeAuthenticationProviderTests.java | 33 +-- ...odeReactiveAuthenticationManagerTests.java | 17 +- .../OidcReactiveOAuth2UserServiceTests.java | 15 +- .../oidc/userinfo/OidcUserRequestTests.java | 8 +- .../oidc/userinfo/OidcUserServiceTests.java | 24 +- .../registration/ClientRegistrationTests.java | 16 +- ...CustomUserTypesOAuth2UserServiceTests.java | 12 +- .../DefaultOAuth2UserServiceTests.java | 17 +- ...DefaultReactiveOAuth2UserServiceTests.java | 11 +- ...OAuth2UserRequestEntityConverterTests.java | 3 +- ...uth2AuthorizationCodeGrantFilterTests.java | 15 +- .../OAuth2LoginAuthenticationFilterTests.java | 5 +- ...AuthorizedClientArgumentResolverTests.java | 4 +- ...zedClientExchangeFilterFunctionITests.java | 29 ++- ...izedClientExchangeFilterFunctionTests.java | 112 ++++++---- ...zedClientExchangeFilterFunctionITests.java | 25 ++- ...izedClientExchangeFilterFunctionTests.java | 203 ++++++++++------- ...2AuthorizationCodeGrantWebFilterTests.java | 5 +- ...rizationRequestRedirectWebFilterTests.java | 2 +- .../DefaultOAuth2AuthenticatedPrincipal.java | 6 +- .../oauth2/core/oidc/OidcIdToken.java | 41 ++-- .../oauth2/core/oidc/OidcUserInfo.java | 61 ++---- .../OAuth2AuthorizationExchangeTests.java | 10 +- .../core/oidc/OidcIdTokenBuilderTests.java | 14 +- .../core/oidc/OidcUserInfoBuilderTests.java | 8 +- .../oauth2/core/oidc/OidcUserInfoTests.java | 29 +-- .../oauth2/core/oidc/TestOidcIdTokens.java | 6 +- .../security/oauth2/jwt/Jwt.java | 26 +-- .../security/oauth2/jwt/JwtDecoders.java | 4 +- .../oauth2/jwt/JwtIssuerValidator.java | 4 +- .../jwt/NimbusJwtDecoderJwkSupport.java | 5 +- .../oauth2/jwt/ReactiveJwtDecoders.java | 5 +- .../security/oauth2/jwt/JwtBuilderTests.java | 13 +- .../oauth2/jwt/JwtClaimValidatorTests.java | 11 +- .../oauth2/jwt/JwtIssuerValidatorTests.java | 9 +- .../jwt/JwtTimestampValidatorTests.java | 24 +- .../jwt/NimbusJwtDecoderJwkSupportTests.java | 4 +- .../oauth2/jwt/NimbusJwtDecoderTests.java | 82 ++++--- .../jwt/NimbusReactiveJwtDecoderTests.java | 79 ++++--- .../server/resource/BearerTokenErrors.java | 13 +- .../resource/InvalidBearerTokenException.java | 6 +- .../OpaqueTokenAuthenticationProvider.java | 8 +- ...queTokenReactiveAuthenticationManager.java | 8 +- .../NimbusOpaqueTokenIntrospector.java | 25 +-- ...NimbusReactiveOpaqueTokenIntrospector.java | 25 +-- .../web/DefaultBearerTokenResolver.java | 11 +- ...verBearerTokenAuthenticationConverter.java | 9 +- .../resource/BearerTokenErrorsTests.java | 32 ++- ...icationEventPublisherBearerTokenTests.java | 4 +- .../BearerTokenAuthenticationTests.java | 13 +- .../JwtAuthenticationConverterTests.java | 8 +- .../JwtAuthenticationProviderTests.java | 6 +- .../JwtAuthenticationTokenTests.java | 4 +- .../JwtGrantedAuthoritiesConverterTests.java | 36 +-- ...uerAuthenticationManagerResolverTests.java | 4 +- ...iveAuthenticationManagerResolverTests.java | 4 +- ...JwtReactiveAuthenticationManagerTests.java | 4 +- ...paqueTokenAuthenticationProviderTests.java | 32 ++- ...kenReactiveAuthenticationManagerTests.java | 32 ++- ...wtAuthenticationConverterAdapterTests.java | 15 +- ...activeJwtAuthenticationConverterTests.java | 6 +- ...antedAuthoritiesConverterAdapterTests.java | 4 +- .../NimbusOpaqueTokenIntrospectorTests.java | 30 ++- ...sReactiveOpaqueTokenIntrospectorTests.java | 30 ++- ...rverBearerExchangeFilterFunctionTests.java | 10 +- ...vletBearerExchangeFilterFunctionTests.java | 14 +- .../AuthorizationPayloadInterceptorTests.java | 13 +- .../core/OpenSamlInitializationService.java | 20 +- .../saml2/core/Saml2X509Credential.java | 16 +- .../credentials/Saml2X509Credential.java | 16 +- .../OpenSamlAuthenticationProvider.java | 86 ++++---- .../OpenSamlAuthenticationRequestFactory.java | 14 +- .../Saml2AuthenticationRequestFactory.java | 14 +- .../Saml2AuthenticationToken.java | 7 +- .../Saml2PostAuthenticationRequest.java | 4 +- .../Saml2RedirectAuthenticationRequest.java | 4 +- .../service/authentication/Saml2Utils.java | 10 +- .../metadata/OpenSamlMetadataResolver.java | 10 +- ...oryRelyingPartyRegistrationRepository.java | 13 +- ...gistrationBuilderHttpMessageConverter.java | 21 +- .../servlet/filter/Saml2ServletUtils.java | 74 +++++++ .../Saml2WebSsoAuthenticationFilter.java | 10 +- ...aml2WebSsoAuthenticationRequestFilter.java | 6 +- ...faultRelyingPartyRegistrationResolver.java | 14 +- .../Saml2AuthenticationTokenConverter.java | 7 +- .../security/saml2/core/Saml2Utils.java | 10 +- .../saml2/core/Saml2X509CredentialTests.java | 42 ++-- .../saml2/core/TestSaml2X509Credentials.java | 23 +- .../credentials/Saml2X509CredentialTests.java | 42 ++-- .../credentials/TestSaml2X509Credentials.java | 23 +- .../OpenSamlAuthenticationProviderTests.java | 206 +++++++++--------- ...SamlAuthenticationRequestFactoryTests.java | 65 +++--- ...aml2AuthenticationRequestFactoryTests.java | 12 +- .../authentication/TestOpenSamlObjects.java | 5 +- ...estSaml2AuthenticationRequestContexts.java | 4 +- .../OpenSamlMetadataResolverTests.java | 16 +- ...ationBuilderHttpMessageConverterTests.java | 12 +- .../RelyingPartyRegistrationTests.java | 19 +- .../RelyingPartyRegistrationsTests.java | 2 +- .../TestRelyingPartyRegistrations.java | 18 +- ...ebSsoAuthenticationRequestFilterTests.java | 20 +- ...RelyingPartyRegistrationResolverTests.java | 5 +- ...enticationRequestContextResolverTests.java | 4 +- ...aml2AuthenticationTokenConverterTests.java | 10 +- .../service/web/Saml2MetadataFilterTests.java | 10 +- .../server/SecurityMockServerConfigurers.java | 12 +- .../SecurityMockMvcRequestPostProcessors.java | 16 +- .../SecurityMockMvcResultMatchers.java | 30 +-- ...yMockServerConfigurerOpaqueTokenTests.java | 54 +++-- ...tyMockServerConfigurersAnnotatedTests.java | 22 +- ...kServerConfigurersClassAnnotatedTests.java | 10 +- ...SecurityMockServerConfigurersJwtTests.java | 30 ++- ...ockServerConfigurersOAuth2ClientTests.java | 48 ++-- ...MockServerConfigurersOAuth2LoginTests.java | 39 ++-- ...tyMockServerConfigurersOidcLoginTests.java | 53 +++-- .../SecurityMockServerConfigurersTests.java | 38 ++-- ...yMockMvcRequestBuildersFormLoginTests.java | 4 +- ...MockMvcRequestBuildersFormLogoutTests.java | 4 +- ...uestPostProcessorsAuthenticationTests.java | 7 +- ...equestPostProcessorsOAuth2ClientTests.java | 13 +- ...RequestPostProcessorsOAuth2LoginTests.java | 5 +- ...vcRequestPostProcessorsOidcLoginTests.java | 5 +- ...RequestPostProcessorsOpaqueTokenTests.java | 10 +- ...estPostProcessorsSecurityContextTests.java | 7 +- ...ostProcessorsTestSecurityContextTests.java | 7 +- ...RequestPostProcessorsUserDetailsTests.java | 7 +- ...MockMvcRequestPostProcessorsUserTests.java | 7 +- ...oginRequestBuilderAuthenticationTests.java | 4 +- .../test/web/support/WebTestUtilsTests.java | 24 +- .../www/BasicAuthenticationConverter.java | 5 +- .../security/web/csrf/CsrfFilter.java | 6 +- ...tionConverterServerWebExchangeMatcher.java | 7 +- .../web/server/csrf/CsrfWebFilter.java | 6 +- .../transport/HttpsRedirectWebFilter.java | 5 +- .../TokenBasedRememberMeServicesTests.java | 69 +++--- ...efaultLogoutPageGeneratingFilterTests.java | 2 +- ...ecurityWebApplicationInitializerTests.java | 50 ++--- ...SessionSecurityContextRepositoryTests.java | 40 ++-- .../ClearSiteDataHeaderWriterTests.java | 13 +- .../security/web/method/ResolvableMethod.java | 15 +- .../CsrfRequestDataValueProcessorTests.java | 5 +- .../SwitchUserWebFilterTests.java | 34 +-- ...egatingServerAccessDeniedHandlerTests.java | 11 +- .../web/server/csrf/CsrfWebFilterTests.java | 36 +-- .../ServerWebExchangeMatchersTests.java | 14 +- ...yContextHolderAwareRequestFilterTests.java | 30 +-- 252 files changed, 2216 insertions(+), 2222 deletions(-) create mode 100644 saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2ServletUtils.java diff --git a/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcAclServiceTests.java b/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcAclServiceTests.java index 373a270587..6d7e6a8f70 100644 --- a/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcAclServiceTests.java +++ b/acl/src/test/java/org/springframework/security/acls/jdbc/JdbcAclServiceTests.java @@ -43,10 +43,10 @@ import org.springframework.security.acls.model.ObjectIdentity; import org.springframework.security.acls.model.Sid; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.AdditionalMatchers.aryEq; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; /** @@ -105,7 +105,7 @@ public class JdbcAclServiceTests { List result = new ArrayList<>(); result.add(new ObjectIdentityImpl(Object.class, "5577")); Object[] args = { "1", "org.springframework.security.acls.jdbc.JdbcAclServiceTests$MockLongIdDomainObject" }; - given(this.jdbcOperations.query(anyString(), aryEq(args), any(RowMapper.class))).willReturn(result); + given(this.jdbcOperations.query(anyString(), eq(args), any(RowMapper.class))).willReturn(result); ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockLongIdDomainObject.class, 1L); List objectIdentities = this.aclService.findChildren(objectIdentity); diff --git a/config/src/integration-test/java/org/springframework/security/config/annotation/authentication/ldap/LdapAuthenticationProviderBuilderSecurityBuilderTests.java b/config/src/integration-test/java/org/springframework/security/config/annotation/authentication/ldap/LdapAuthenticationProviderBuilderSecurityBuilderTests.java index 64c72962b9..b51a4128b9 100644 --- a/config/src/integration-test/java/org/springframework/security/config/annotation/authentication/ldap/LdapAuthenticationProviderBuilderSecurityBuilderTests.java +++ b/config/src/integration-test/java/org/springframework/security/config/annotation/authentication/ldap/LdapAuthenticationProviderBuilderSecurityBuilderTests.java @@ -18,6 +18,7 @@ package org.springframework.security.config.annotation.authentication.ldap; import java.io.IOException; import java.net.ServerSocket; +import java.util.Collections; import java.util.List; import javax.naming.directory.SearchControls; @@ -46,7 +47,6 @@ import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; -import static java.util.Collections.singleton; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated; @@ -117,8 +117,9 @@ public class LdapAuthenticationProviderBuilderSecurityBuilderTests { public void bindAuthentication() throws Exception { this.spring.register(BindAuthenticationConfig.class).autowire(); - this.mockMvc.perform(formLogin().user("bob").password("bobspassword")).andExpect(authenticated() - .withUsername("bob").withAuthorities(singleton(new SimpleGrantedAuthority("ROLE_DEVELOPERS")))); + this.mockMvc.perform(formLogin().user("bob").password("bobspassword")) + .andExpect(authenticated().withUsername("bob") + .withAuthorities(Collections.singleton(new SimpleGrantedAuthority("ROLE_DEVELOPERS")))); } // SEC-2472 @@ -126,8 +127,9 @@ public class LdapAuthenticationProviderBuilderSecurityBuilderTests { public void canUseCryptoPasswordEncoder() throws Exception { this.spring.register(PasswordEncoderConfig.class).autowire(); - this.mockMvc.perform(formLogin().user("bcrypt").password("password")).andExpect(authenticated() - .withUsername("bcrypt").withAuthorities(singleton(new SimpleGrantedAuthority("ROLE_DEVELOPERS")))); + this.mockMvc.perform(formLogin().user("bcrypt").password("password")) + .andExpect(authenticated().withUsername("bcrypt") + .withAuthorities(Collections.singleton(new SimpleGrantedAuthority("ROLE_DEVELOPERS")))); } private LdapAuthenticationProvider ldapProvider() { diff --git a/config/src/integration-test/java/org/springframework/security/config/annotation/authentication/ldap/LdapAuthenticationProviderConfigurerTests.java b/config/src/integration-test/java/org/springframework/security/config/annotation/authentication/ldap/LdapAuthenticationProviderConfigurerTests.java index cf9f64f7c0..328dbc4a3b 100644 --- a/config/src/integration-test/java/org/springframework/security/config/annotation/authentication/ldap/LdapAuthenticationProviderConfigurerTests.java +++ b/config/src/integration-test/java/org/springframework/security/config/annotation/authentication/ldap/LdapAuthenticationProviderConfigurerTests.java @@ -16,6 +16,8 @@ package org.springframework.security.config.annotation.authentication.ldap; +import java.util.Collections; + import org.junit.Rule; import org.junit.Test; @@ -29,7 +31,6 @@ import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.test.web.servlet.MockMvc; -import static java.util.Collections.singleton; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated; @@ -54,16 +55,18 @@ public class LdapAuthenticationProviderConfigurerTests { public void authenticationManagerSupportMultipleLdapContextWithDefaultRolePrefix() throws Exception { this.spring.register(MultiLdapAuthenticationProvidersConfig.class).autowire(); - this.mockMvc.perform(formLogin().user("bob").password("bobspassword")).andExpect(authenticated() - .withUsername("bob").withAuthorities(singleton(new SimpleGrantedAuthority("ROLE_DEVELOPERS")))); + this.mockMvc.perform(formLogin().user("bob").password("bobspassword")) + .andExpect(authenticated().withUsername("bob") + .withAuthorities(Collections.singleton(new SimpleGrantedAuthority("ROLE_DEVELOPERS")))); } @Test public void authenticationManagerSupportMultipleLdapContextWithCustomRolePrefix() throws Exception { this.spring.register(MultiLdapWithCustomRolePrefixAuthenticationProvidersConfig.class).autowire(); - this.mockMvc.perform(formLogin().user("bob").password("bobspassword")).andExpect(authenticated() - .withUsername("bob").withAuthorities(singleton(new SimpleGrantedAuthority("ROL_DEVELOPERS")))); + this.mockMvc.perform(formLogin().user("bob").password("bobspassword")) + .andExpect(authenticated().withUsername("bob") + .withAuthorities(Collections.singleton(new SimpleGrantedAuthority("ROL_DEVELOPERS")))); } @Test diff --git a/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/JwtITests.java b/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/JwtITests.java index 36008b73b1..7fa45e111f 100644 --- a/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/JwtITests.java +++ b/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/JwtITests.java @@ -21,6 +21,7 @@ import java.util.List; import io.rsocket.RSocketFactory; import io.rsocket.frame.decoder.PayloadDecoder; +import io.rsocket.metadata.WellKnownMimeType; import io.rsocket.transport.netty.server.CloseableChannel; import io.rsocket.transport.netty.server.TcpServerTransport; import org.junit.After; @@ -51,7 +52,6 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.MimeType; import org.springframework.util.MimeTypeUtils; -import static io.rsocket.metadata.WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; @@ -109,7 +109,8 @@ public class JwtITests { @Test public void routeWhenAuthenticationBearerThenAuthorized() { - MimeType authenticationMimeType = MimeTypeUtils.parseMimeType(MESSAGE_RSOCKET_AUTHENTICATION.getString()); + MimeType authenticationMimeType = MimeTypeUtils + .parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString()); BearerTokenMetadata credentials = new BearerTokenMetadata("token"); given(this.decoder.decode(any())).willReturn(Mono.just(jwt())); diff --git a/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/SimpleAuthenticationITests.java b/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/SimpleAuthenticationITests.java index edbc18ca77..6dc34ec2dd 100644 --- a/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/SimpleAuthenticationITests.java +++ b/config/src/integration-test/java/org/springframework/security/config/annotation/rsocket/SimpleAuthenticationITests.java @@ -22,6 +22,7 @@ import java.util.List; import io.rsocket.RSocketFactory; import io.rsocket.exceptions.ApplicationErrorException; import io.rsocket.frame.decoder.PayloadDecoder; +import io.rsocket.metadata.WellKnownMimeType; import io.rsocket.transport.netty.server.CloseableChannel; import io.rsocket.transport.netty.server.TcpServerTransport; import org.junit.After; @@ -50,7 +51,6 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.MimeType; import org.springframework.util.MimeTypeUtils; -import static io.rsocket.metadata.WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; @@ -101,7 +101,8 @@ public class SimpleAuthenticationITests { @Test public void retrieveMonoWhenAuthorizedThenGranted() { - MimeType authenticationMimeType = MimeTypeUtils.parseMimeType(MESSAGE_RSOCKET_AUTHENTICATION.getString()); + MimeType authenticationMimeType = MimeTypeUtils + .parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString()); UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("rob", "password"); this.requester = RSocketRequester.builder().setupMetadata(credentials, authenticationMimeType) diff --git a/config/src/integration-test/java/org/springframework/security/config/ldap/LdapUserServiceBeanDefinitionParserTests.java b/config/src/integration-test/java/org/springframework/security/config/ldap/LdapUserServiceBeanDefinitionParserTests.java index 219c11db0b..42a798290a 100644 --- a/config/src/integration-test/java/org/springframework/security/config/ldap/LdapUserServiceBeanDefinitionParserTests.java +++ b/config/src/integration-test/java/org/springframework/security/config/ldap/LdapUserServiceBeanDefinitionParserTests.java @@ -36,11 +36,6 @@ import org.springframework.security.ldap.userdetails.PersonContextMapper; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; -import static org.springframework.security.config.ldap.LdapUserServiceBeanDefinitionParser.INET_ORG_PERSON_MAPPER_CLASS; -import static org.springframework.security.config.ldap.LdapUserServiceBeanDefinitionParser.LDAP_AUTHORITIES_POPULATOR_CLASS; -import static org.springframework.security.config.ldap.LdapUserServiceBeanDefinitionParser.LDAP_SEARCH_CLASS; -import static org.springframework.security.config.ldap.LdapUserServiceBeanDefinitionParser.LDAP_USER_MAPPER_CLASS; -import static org.springframework.security.config.ldap.LdapUserServiceBeanDefinitionParser.PERSON_MAPPER_CLASS; /** * @author Luke Taylor @@ -61,11 +56,16 @@ public class LdapUserServiceBeanDefinitionParserTests { @Test public void beanClassNamesAreCorrect() { - assertThat(FilterBasedLdapUserSearch.class.getName()).isEqualTo(LDAP_SEARCH_CLASS); - assertThat(PersonContextMapper.class.getName()).isEqualTo(PERSON_MAPPER_CLASS); - assertThat(InetOrgPersonContextMapper.class.getName()).isEqualTo(INET_ORG_PERSON_MAPPER_CLASS); - assertThat(LdapUserDetailsMapper.class.getName()).isEqualTo(LDAP_USER_MAPPER_CLASS); - assertThat(DefaultLdapAuthoritiesPopulator.class.getName()).isEqualTo(LDAP_AUTHORITIES_POPULATOR_CLASS); + assertThat(FilterBasedLdapUserSearch.class.getName()) + .isEqualTo(LdapUserServiceBeanDefinitionParser.LDAP_SEARCH_CLASS); + assertThat(PersonContextMapper.class.getName()) + .isEqualTo(LdapUserServiceBeanDefinitionParser.PERSON_MAPPER_CLASS); + assertThat(InetOrgPersonContextMapper.class.getName()) + .isEqualTo(LdapUserServiceBeanDefinitionParser.INET_ORG_PERSON_MAPPER_CLASS); + assertThat(LdapUserDetailsMapper.class.getName()) + .isEqualTo(LdapUserServiceBeanDefinitionParser.LDAP_USER_MAPPER_CLASS); + assertThat(DefaultLdapAuthoritiesPopulator.class.getName()) + .isEqualTo(LdapUserServiceBeanDefinitionParser.LDAP_AUTHORITIES_POPULATOR_CLASS); assertThat(new LdapUserServiceBeanDefinitionParser().getBeanClassName(mock(Element.class))) .isEqualTo(LdapUserDetailsService.class.getName()); } diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfiguration.java b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfiguration.java index efdb706234..71f00115b3 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfiguration.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfiguration.java @@ -40,8 +40,6 @@ import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; -import static org.springframework.security.config.annotation.web.configuration.SecurityReactorContextConfiguration.SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES; - /** * {@link Configuration} that (potentially) adds a "decorating" {@code Publisher} for the * last operator created in every {@code Mono} or {@code Flux}. @@ -88,7 +86,7 @@ class SecurityReactorContextConfiguration { } CoreSubscriber createSubscriberIfNecessary(CoreSubscriber delegate) { - if (delegate.currentContext().hasKey(SECURITY_CONTEXT_ATTRIBUTES)) { + if (delegate.currentContext().hasKey(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES)) { // Already enriched. No need to create Subscriber so return original return delegate; } diff --git a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurer.java b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurer.java index 9b45741903..e73875032d 100644 --- a/config/src/main/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurer.java +++ b/config/src/main/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurer.java @@ -51,8 +51,6 @@ import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; -import static org.springframework.security.oauth2.jwt.NimbusJwtDecoder.withJwkSetUri; - /** * * An {@link AbstractHttpConfigurer} for OAuth 2.0 Resource Server Support. @@ -367,7 +365,7 @@ public final class OAuth2ResourceServerConfigurer> setAuthenticationFilter(this.saml2WebSsoAuthenticationFilter); super.loginProcessingUrl(this.loginProcessingUrl); - if (hasText(this.loginPage)) { + if (StringUtils.hasText(this.loginPage)) { // Set custom login page super.loginPage(this.loginPage); super.init(http); diff --git a/config/src/main/java/org/springframework/security/config/http/AuthenticationConfigBuilder.java b/config/src/main/java/org/springframework/security/config/http/AuthenticationConfigBuilder.java index 4063f5ac47..67dd4572c4 100644 --- a/config/src/main/java/org/springframework/security/config/http/AuthenticationConfigBuilder.java +++ b/config/src/main/java/org/springframework/security/config/http/AuthenticationConfigBuilder.java @@ -68,22 +68,6 @@ import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; import org.springframework.util.xml.DomUtils; -import static org.springframework.security.config.http.SecurityFilters.ANONYMOUS_FILTER; -import static org.springframework.security.config.http.SecurityFilters.BASIC_AUTH_FILTER; -import static org.springframework.security.config.http.SecurityFilters.BEARER_TOKEN_AUTH_FILTER; -import static org.springframework.security.config.http.SecurityFilters.EXCEPTION_TRANSLATION_FILTER; -import static org.springframework.security.config.http.SecurityFilters.FORM_LOGIN_FILTER; -import static org.springframework.security.config.http.SecurityFilters.LOGIN_PAGE_FILTER; -import static org.springframework.security.config.http.SecurityFilters.LOGOUT_FILTER; -import static org.springframework.security.config.http.SecurityFilters.LOGOUT_PAGE_FILTER; -import static org.springframework.security.config.http.SecurityFilters.OAUTH2_AUTHORIZATION_CODE_GRANT_FILTER; -import static org.springframework.security.config.http.SecurityFilters.OAUTH2_AUTHORIZATION_REQUEST_FILTER; -import static org.springframework.security.config.http.SecurityFilters.OAUTH2_LOGIN_FILTER; -import static org.springframework.security.config.http.SecurityFilters.OPENID_FILTER; -import static org.springframework.security.config.http.SecurityFilters.PRE_AUTH_FILTER; -import static org.springframework.security.config.http.SecurityFilters.REMEMBER_ME_FILTER; -import static org.springframework.security.config.http.SecurityFilters.X509_FILTER; - /** * Handles creation of authentication mechanism filters and related beans for <http> * parsing. @@ -993,59 +977,64 @@ final class AuthenticationConfigBuilder { List filters = new ArrayList<>(); if (this.anonymousFilter != null) { - filters.add(new OrderDecorator(this.anonymousFilter, ANONYMOUS_FILTER)); + filters.add(new OrderDecorator(this.anonymousFilter, SecurityFilters.ANONYMOUS_FILTER)); } if (this.rememberMeFilter != null) { - filters.add(new OrderDecorator(this.rememberMeFilter, REMEMBER_ME_FILTER)); + filters.add(new OrderDecorator(this.rememberMeFilter, SecurityFilters.REMEMBER_ME_FILTER)); } if (this.logoutFilter != null) { - filters.add(new OrderDecorator(this.logoutFilter, LOGOUT_FILTER)); + filters.add(new OrderDecorator(this.logoutFilter, SecurityFilters.LOGOUT_FILTER)); } if (this.x509Filter != null) { - filters.add(new OrderDecorator(this.x509Filter, X509_FILTER)); + filters.add(new OrderDecorator(this.x509Filter, SecurityFilters.X509_FILTER)); } if (this.jeeFilter != null) { - filters.add(new OrderDecorator(this.jeeFilter, PRE_AUTH_FILTER)); + filters.add(new OrderDecorator(this.jeeFilter, SecurityFilters.PRE_AUTH_FILTER)); } if (this.formFilterId != null) { - filters.add(new OrderDecorator(new RuntimeBeanReference(this.formFilterId), FORM_LOGIN_FILTER)); + filters.add( + new OrderDecorator(new RuntimeBeanReference(this.formFilterId), SecurityFilters.FORM_LOGIN_FILTER)); } if (this.oauth2LoginFilterId != null) { - filters.add(new OrderDecorator(new RuntimeBeanReference(this.oauth2LoginFilterId), OAUTH2_LOGIN_FILTER)); + filters.add(new OrderDecorator(new RuntimeBeanReference(this.oauth2LoginFilterId), + SecurityFilters.OAUTH2_LOGIN_FILTER)); filters.add(new OrderDecorator(this.oauth2AuthorizationRequestRedirectFilter, - OAUTH2_AUTHORIZATION_REQUEST_FILTER)); + SecurityFilters.OAUTH2_AUTHORIZATION_REQUEST_FILTER)); } if (this.openIDFilterId != null) { - filters.add(new OrderDecorator(new RuntimeBeanReference(this.openIDFilterId), OPENID_FILTER)); + filters.add( + new OrderDecorator(new RuntimeBeanReference(this.openIDFilterId), SecurityFilters.OPENID_FILTER)); } if (this.loginPageGenerationFilter != null) { - filters.add(new OrderDecorator(this.loginPageGenerationFilter, LOGIN_PAGE_FILTER)); - filters.add(new OrderDecorator(this.logoutPageGenerationFilter, LOGOUT_PAGE_FILTER)); + filters.add(new OrderDecorator(this.loginPageGenerationFilter, SecurityFilters.LOGIN_PAGE_FILTER)); + filters.add(new OrderDecorator(this.logoutPageGenerationFilter, SecurityFilters.LOGOUT_PAGE_FILTER)); } if (this.basicFilter != null) { - filters.add(new OrderDecorator(this.basicFilter, BASIC_AUTH_FILTER)); + filters.add(new OrderDecorator(this.basicFilter, SecurityFilters.BASIC_AUTH_FILTER)); } if (this.bearerTokenAuthenticationFilter != null) { - filters.add(new OrderDecorator(this.bearerTokenAuthenticationFilter, BEARER_TOKEN_AUTH_FILTER)); + filters.add( + new OrderDecorator(this.bearerTokenAuthenticationFilter, SecurityFilters.BEARER_TOKEN_AUTH_FILTER)); } if (this.authorizationCodeGrantFilter != null) { filters.add(new OrderDecorator(this.authorizationRequestRedirectFilter, - OAUTH2_AUTHORIZATION_REQUEST_FILTER.getOrder() + 1)); - filters.add(new OrderDecorator(this.authorizationCodeGrantFilter, OAUTH2_AUTHORIZATION_CODE_GRANT_FILTER)); + SecurityFilters.OAUTH2_AUTHORIZATION_REQUEST_FILTER.getOrder() + 1)); + filters.add(new OrderDecorator(this.authorizationCodeGrantFilter, + SecurityFilters.OAUTH2_AUTHORIZATION_CODE_GRANT_FILTER)); } - filters.add(new OrderDecorator(this.etf, EXCEPTION_TRANSLATION_FILTER)); + filters.add(new OrderDecorator(this.etf, SecurityFilters.EXCEPTION_TRANSLATION_FILTER)); return filters; } diff --git a/config/src/main/java/org/springframework/security/config/http/FilterInvocationSecurityMetadataSourceParser.java b/config/src/main/java/org/springframework/security/config/http/FilterInvocationSecurityMetadataSourceParser.java index 440913add9..78452dc7f3 100644 --- a/config/src/main/java/org/springframework/security/config/http/FilterInvocationSecurityMetadataSourceParser.java +++ b/config/src/main/java/org/springframework/security/config/http/FilterInvocationSecurityMetadataSourceParser.java @@ -40,8 +40,6 @@ import org.springframework.security.web.access.intercept.FilterInvocationSecurit import org.springframework.util.StringUtils; import org.springframework.util.xml.DomUtils; -import static org.springframework.security.config.http.HttpSecurityBeanDefinitionParser.ATT_REQUEST_MATCHER_REF; - /** * Allows for convenient creation of a {@link FilterInvocationSecurityMetadataSource} bean * for use with a FilterSecurityInterceptor. @@ -161,7 +159,7 @@ public class FilterInvocationSecurityMetadataSourceParser implements BeanDefinit } String path = urlElt.getAttribute(ATT_PATTERN); - String matcherRef = urlElt.getAttribute(ATT_REQUEST_MATCHER_REF); + String matcherRef = urlElt.getAttribute(HttpSecurityBeanDefinitionParser.ATT_REQUEST_MATCHER_REF); boolean hasMatcherRef = StringUtils.hasText(matcherRef); if (!hasMatcherRef && !StringUtils.hasText(path)) { diff --git a/config/src/main/java/org/springframework/security/config/http/HttpConfigurationBuilder.java b/config/src/main/java/org/springframework/security/config/http/HttpConfigurationBuilder.java index 78a7e50bc1..9d570fe4c2 100644 --- a/config/src/main/java/org/springframework/security/config/http/HttpConfigurationBuilder.java +++ b/config/src/main/java/org/springframework/security/config/http/HttpConfigurationBuilder.java @@ -74,24 +74,6 @@ import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; import org.springframework.util.xml.DomUtils; -import static org.springframework.security.config.http.HttpSecurityBeanDefinitionParser.ATT_FILTERS; -import static org.springframework.security.config.http.HttpSecurityBeanDefinitionParser.ATT_HTTP_METHOD; -import static org.springframework.security.config.http.HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN; -import static org.springframework.security.config.http.HttpSecurityBeanDefinitionParser.ATT_REQUEST_MATCHER_REF; -import static org.springframework.security.config.http.HttpSecurityBeanDefinitionParser.ATT_REQUIRES_CHANNEL; -import static org.springframework.security.config.http.SecurityFilters.CHANNEL_FILTER; -import static org.springframework.security.config.http.SecurityFilters.CONCURRENT_SESSION_FILTER; -import static org.springframework.security.config.http.SecurityFilters.CORS_FILTER; -import static org.springframework.security.config.http.SecurityFilters.CSRF_FILTER; -import static org.springframework.security.config.http.SecurityFilters.FILTER_SECURITY_INTERCEPTOR; -import static org.springframework.security.config.http.SecurityFilters.HEADERS_FILTER; -import static org.springframework.security.config.http.SecurityFilters.JAAS_API_SUPPORT_FILTER; -import static org.springframework.security.config.http.SecurityFilters.REQUEST_CACHE_FILTER; -import static org.springframework.security.config.http.SecurityFilters.SECURITY_CONTEXT_FILTER; -import static org.springframework.security.config.http.SecurityFilters.SERVLET_API_SUPPORT_FILTER; -import static org.springframework.security.config.http.SecurityFilters.SESSION_MANAGEMENT_FILTER; -import static org.springframework.security.config.http.SecurityFilters.WEB_ASYNC_MANAGER_FILTER; - /** * Stateful class which helps HttpSecurityBDP to create the configuration for the * <http> element. @@ -197,7 +179,7 @@ class HttpConfigurationBuilder { this.interceptUrls = DomUtils.getChildElementsByTagName(element, Elements.INTERCEPT_URL); for (Element urlElt : this.interceptUrls) { - if (StringUtils.hasText(urlElt.getAttribute(ATT_FILTERS))) { + if (StringUtils.hasText(urlElt.getAttribute(HttpSecurityBeanDefinitionParser.ATT_FILTERS))) { pc.getReaderContext() .error("The use of \"filters='none'\" is no longer supported. Please define a" + " separate element for the pattern you want to exclude and use the attribute" @@ -637,16 +619,16 @@ class HttpConfigurationBuilder { ManagedMap channelRequestMap = new ManagedMap<>(); for (Element urlElt : this.interceptUrls) { - String path = urlElt.getAttribute(ATT_PATH_PATTERN); - String method = urlElt.getAttribute(ATT_HTTP_METHOD); - String matcherRef = urlElt.getAttribute(ATT_REQUEST_MATCHER_REF); + String path = urlElt.getAttribute(HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN); + String method = urlElt.getAttribute(HttpSecurityBeanDefinitionParser.ATT_HTTP_METHOD); + String matcherRef = urlElt.getAttribute(HttpSecurityBeanDefinitionParser.ATT_REQUEST_MATCHER_REF); boolean hasMatcherRef = StringUtils.hasText(matcherRef); if (!hasMatcherRef && !StringUtils.hasText(path)) { this.pc.getReaderContext().error("pattern attribute cannot be empty or null", urlElt); } - String requiredChannel = urlElt.getAttribute(ATT_REQUIRES_CHANNEL); + String requiredChannel = urlElt.getAttribute(HttpSecurityBeanDefinitionParser.ATT_REQUIRES_CHANNEL); if (StringUtils.hasText(requiredChannel)) { BeanMetadataElement matcher = hasMatcherRef ? new RuntimeBeanReference(matcherRef) @@ -805,47 +787,47 @@ class HttpConfigurationBuilder { List filters = new ArrayList<>(); if (this.cpf != null) { - filters.add(new OrderDecorator(this.cpf, CHANNEL_FILTER)); + filters.add(new OrderDecorator(this.cpf, SecurityFilters.CHANNEL_FILTER)); } if (this.concurrentSessionFilter != null) { - filters.add(new OrderDecorator(this.concurrentSessionFilter, CONCURRENT_SESSION_FILTER)); + filters.add(new OrderDecorator(this.concurrentSessionFilter, SecurityFilters.CONCURRENT_SESSION_FILTER)); } if (this.webAsyncManagerFilter != null) { - filters.add(new OrderDecorator(this.webAsyncManagerFilter, WEB_ASYNC_MANAGER_FILTER)); + filters.add(new OrderDecorator(this.webAsyncManagerFilter, SecurityFilters.WEB_ASYNC_MANAGER_FILTER)); } - filters.add(new OrderDecorator(this.securityContextPersistenceFilter, SECURITY_CONTEXT_FILTER)); + filters.add(new OrderDecorator(this.securityContextPersistenceFilter, SecurityFilters.SECURITY_CONTEXT_FILTER)); if (this.servApiFilter != null) { - filters.add(new OrderDecorator(this.servApiFilter, SERVLET_API_SUPPORT_FILTER)); + filters.add(new OrderDecorator(this.servApiFilter, SecurityFilters.SERVLET_API_SUPPORT_FILTER)); } if (this.jaasApiFilter != null) { - filters.add(new OrderDecorator(this.jaasApiFilter, JAAS_API_SUPPORT_FILTER)); + filters.add(new OrderDecorator(this.jaasApiFilter, SecurityFilters.JAAS_API_SUPPORT_FILTER)); } if (this.sfpf != null) { - filters.add(new OrderDecorator(this.sfpf, SESSION_MANAGEMENT_FILTER)); + filters.add(new OrderDecorator(this.sfpf, SecurityFilters.SESSION_MANAGEMENT_FILTER)); } - filters.add(new OrderDecorator(this.fsi, FILTER_SECURITY_INTERCEPTOR)); + filters.add(new OrderDecorator(this.fsi, SecurityFilters.FILTER_SECURITY_INTERCEPTOR)); if (this.sessionPolicy != SessionCreationPolicy.STATELESS) { - filters.add(new OrderDecorator(this.requestCacheAwareFilter, REQUEST_CACHE_FILTER)); + filters.add(new OrderDecorator(this.requestCacheAwareFilter, SecurityFilters.REQUEST_CACHE_FILTER)); } if (this.corsFilter != null) { - filters.add(new OrderDecorator(this.corsFilter, CORS_FILTER)); + filters.add(new OrderDecorator(this.corsFilter, SecurityFilters.CORS_FILTER)); } if (this.addHeadersFilter != null) { - filters.add(new OrderDecorator(this.addHeadersFilter, HEADERS_FILTER)); + filters.add(new OrderDecorator(this.addHeadersFilter, SecurityFilters.HEADERS_FILTER)); } if (this.csrfFilter != null) { - filters.add(new OrderDecorator(this.csrfFilter, CSRF_FILTER)); + filters.add(new OrderDecorator(this.csrfFilter, SecurityFilters.CSRF_FILTER)); } return filters; diff --git a/config/src/main/java/org/springframework/security/config/http/OAuth2ClientBeanDefinitionParser.java b/config/src/main/java/org/springframework/security/config/http/OAuth2ClientBeanDefinitionParser.java index 129a09233c..04ca9fc919 100644 --- a/config/src/main/java/org/springframework/security/config/http/OAuth2ClientBeanDefinitionParser.java +++ b/config/src/main/java/org/springframework/security/config/http/OAuth2ClientBeanDefinitionParser.java @@ -31,11 +31,6 @@ import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepo import org.springframework.util.StringUtils; import org.springframework.util.xml.DomUtils; -import static org.springframework.security.config.http.OAuth2ClientBeanDefinitionParserUtils.createDefaultAuthorizedClientRepository; -import static org.springframework.security.config.http.OAuth2ClientBeanDefinitionParserUtils.getAuthorizedClientRepository; -import static org.springframework.security.config.http.OAuth2ClientBeanDefinitionParserUtils.getAuthorizedClientService; -import static org.springframework.security.config.http.OAuth2ClientBeanDefinitionParserUtils.getClientRegistrationRepository; - /** * @author Joe Grandja * @since 5.3 @@ -71,12 +66,15 @@ final class OAuth2ClientBeanDefinitionParser implements BeanDefinitionParser { public BeanDefinition parse(Element element, ParserContext parserContext) { Element authorizationCodeGrantElt = DomUtils.getChildElementByTagName(element, ELT_AUTHORIZATION_CODE_GRANT); - BeanMetadataElement clientRegistrationRepository = getClientRegistrationRepository(element); - BeanMetadataElement authorizedClientRepository = getAuthorizedClientRepository(element); + BeanMetadataElement clientRegistrationRepository = OAuth2ClientBeanDefinitionParserUtils + .getClientRegistrationRepository(element); + BeanMetadataElement authorizedClientRepository = OAuth2ClientBeanDefinitionParserUtils + .getAuthorizedClientRepository(element); if (authorizedClientRepository == null) { - BeanMetadataElement authorizedClientService = getAuthorizedClientService(element); - this.defaultAuthorizedClientRepository = createDefaultAuthorizedClientRepository( - clientRegistrationRepository, authorizedClientService); + BeanMetadataElement authorizedClientService = OAuth2ClientBeanDefinitionParserUtils + .getAuthorizedClientService(element); + this.defaultAuthorizedClientRepository = OAuth2ClientBeanDefinitionParserUtils + .createDefaultAuthorizedClientRepository(clientRegistrationRepository, authorizedClientService); authorizedClientRepository = new RuntimeBeanReference(OAuth2AuthorizedClientRepository.class); } BeanMetadataElement authorizationRequestRepository = getAuthorizationRequestRepository( diff --git a/config/src/main/java/org/springframework/security/config/http/OAuth2LoginBeanDefinitionParser.java b/config/src/main/java/org/springframework/security/config/http/OAuth2LoginBeanDefinitionParser.java index c99d48c0a1..1a6a07305c 100644 --- a/config/src/main/java/org/springframework/security/config/http/OAuth2LoginBeanDefinitionParser.java +++ b/config/src/main/java/org/springframework/security/config/http/OAuth2LoginBeanDefinitionParser.java @@ -68,11 +68,6 @@ import org.springframework.util.xml.DomUtils; import org.springframework.web.accept.ContentNegotiationStrategy; import org.springframework.web.accept.HeaderContentNegotiationStrategy; -import static org.springframework.security.config.http.OAuth2ClientBeanDefinitionParserUtils.createDefaultAuthorizedClientRepository; -import static org.springframework.security.config.http.OAuth2ClientBeanDefinitionParserUtils.getAuthorizedClientRepository; -import static org.springframework.security.config.http.OAuth2ClientBeanDefinitionParserUtils.getAuthorizedClientService; -import static org.springframework.security.config.http.OAuth2ClientBeanDefinitionParserUtils.getClientRegistrationRepository; - /** * @author Ruby Hartono * @since 5.3 @@ -150,12 +145,15 @@ final class OAuth2LoginBeanDefinitionParser implements BeanDefinitionParser { .registerBeanComponent(new BeanComponentDefinition(oauth2LoginBeanConfig, oauth2LoginBeanConfigId)); // configure filter - BeanMetadataElement clientRegistrationRepository = getClientRegistrationRepository(element); - BeanMetadataElement authorizedClientRepository = getAuthorizedClientRepository(element); + BeanMetadataElement clientRegistrationRepository = OAuth2ClientBeanDefinitionParserUtils + .getClientRegistrationRepository(element); + BeanMetadataElement authorizedClientRepository = OAuth2ClientBeanDefinitionParserUtils + .getAuthorizedClientRepository(element); if (authorizedClientRepository == null) { - BeanMetadataElement authorizedClientService = getAuthorizedClientService(element); - this.defaultAuthorizedClientRepository = createDefaultAuthorizedClientRepository( - clientRegistrationRepository, authorizedClientService); + BeanMetadataElement authorizedClientService = OAuth2ClientBeanDefinitionParserUtils + .getAuthorizedClientService(element); + this.defaultAuthorizedClientRepository = OAuth2ClientBeanDefinitionParserUtils + .createDefaultAuthorizedClientRepository(clientRegistrationRepository, authorizedClientService); authorizedClientRepository = new RuntimeBeanReference(OAuth2AuthorizedClientRepository.class); } BeanMetadataElement accessTokenResponseClient = getAccessTokenResponseClient(element); diff --git a/config/src/main/java/org/springframework/security/config/method/GlobalMethodSecurityBeanDefinitionParser.java b/config/src/main/java/org/springframework/security/config/method/GlobalMethodSecurityBeanDefinitionParser.java index b1674518ba..91439f2d35 100644 --- a/config/src/main/java/org/springframework/security/config/method/GlobalMethodSecurityBeanDefinitionParser.java +++ b/config/src/main/java/org/springframework/security/config/method/GlobalMethodSecurityBeanDefinitionParser.java @@ -80,13 +80,6 @@ import org.springframework.util.Assert; import org.springframework.util.StringUtils; import org.springframework.util.xml.DomUtils; -import static org.springframework.security.config.Elements.EXPRESSION_HANDLER; -import static org.springframework.security.config.Elements.INVOCATION_ATTRIBUTE_FACTORY; -import static org.springframework.security.config.Elements.INVOCATION_HANDLING; -import static org.springframework.security.config.Elements.POST_INVOCATION_ADVICE; -import static org.springframework.security.config.Elements.PRE_INVOCATION_ADVICE; -import static org.springframework.security.config.Elements.PROTECT_POINTCUT; - /** * Processes the top-level "global-method-security" element. * @@ -150,12 +143,12 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP } if (prePostAnnotationsEnabled) { - Element prePostElt = DomUtils.getChildElementByTagName(element, INVOCATION_HANDLING); - Element expressionHandlerElt = DomUtils.getChildElementByTagName(element, EXPRESSION_HANDLER); + Element prePostElt = DomUtils.getChildElementByTagName(element, Elements.INVOCATION_HANDLING); + Element expressionHandlerElt = DomUtils.getChildElementByTagName(element, Elements.EXPRESSION_HANDLER); if (prePostElt != null && expressionHandlerElt != null) { - pc.getReaderContext().error( - INVOCATION_HANDLING + " and " + EXPRESSION_HANDLER + " cannot be used together ", source); + pc.getReaderContext().error(Elements.INVOCATION_HANDLING + " and " + Elements.EXPRESSION_HANDLER + + " cannot be used together ", source); } BeanDefinitionBuilder preInvocationVoterBldr = BeanDefinitionBuilder @@ -170,11 +163,12 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP if (prePostElt != null) { // Customized override of expression handling system - String attributeFactoryRef = DomUtils.getChildElementByTagName(prePostElt, INVOCATION_ATTRIBUTE_FACTORY) + String attributeFactoryRef = DomUtils + .getChildElementByTagName(prePostElt, Elements.INVOCATION_ATTRIBUTE_FACTORY) .getAttribute("ref"); - String preAdviceRef = DomUtils.getChildElementByTagName(prePostElt, PRE_INVOCATION_ADVICE) + String preAdviceRef = DomUtils.getChildElementByTagName(prePostElt, Elements.PRE_INVOCATION_ADVICE) .getAttribute("ref"); - String postAdviceRef = DomUtils.getChildElementByTagName(prePostElt, POST_INVOCATION_ADVICE) + String postAdviceRef = DomUtils.getChildElementByTagName(prePostElt, Elements.POST_INVOCATION_ADVICE) .getAttribute("ref"); mds.addConstructorArgReference(attributeFactoryRef); @@ -257,7 +251,7 @@ public class GlobalMethodSecurityBeanDefinitionParser implements BeanDefinitionP // Now create a Map for each // sub-element Map> pointcutMap = parseProtectPointcuts(pc, - DomUtils.getChildElementsByTagName(element, PROTECT_POINTCUT)); + DomUtils.getChildElementsByTagName(element, Elements.PROTECT_POINTCUT)); if (pointcutMap.size() > 0) { if (useAspectJ) { diff --git a/config/src/main/java/org/springframework/security/config/websocket/WebSocketMessageBrokerSecurityBeanDefinitionParser.java b/config/src/main/java/org/springframework/security/config/websocket/WebSocketMessageBrokerSecurityBeanDefinitionParser.java index 234cb459a8..e72a81ebb7 100644 --- a/config/src/main/java/org/springframework/security/config/websocket/WebSocketMessageBrokerSecurityBeanDefinitionParser.java +++ b/config/src/main/java/org/springframework/security/config/websocket/WebSocketMessageBrokerSecurityBeanDefinitionParser.java @@ -54,8 +54,6 @@ import org.springframework.util.PathMatcher; import org.springframework.util.StringUtils; import org.springframework.util.xml.DomUtils; -import static org.springframework.security.config.Elements.EXPRESSION_HANDLER; - /** * Parses Spring Security's websocket namespace support. A simple example is: * @@ -121,7 +119,7 @@ public final class WebSocketMessageBrokerSecurityBeanDefinitionParser implements ManagedMap matcherToExpression = new ManagedMap<>(); String id = element.getAttribute(ID_ATTR); - Element expressionHandlerElt = DomUtils.getChildElementByTagName(element, EXPRESSION_HANDLER); + Element expressionHandlerElt = DomUtils.getChildElementByTagName(element, Elements.EXPRESSION_HANDLER); String expressionHandlerRef = expressionHandlerElt == null ? null : expressionHandlerElt.getAttribute("ref"); boolean expressionHandlerDefined = StringUtils.hasText(expressionHandlerRef); diff --git a/config/src/test/java/org/springframework/security/config/SecurityNamespaceHandlerTests.java b/config/src/test/java/org/springframework/security/config/SecurityNamespaceHandlerTests.java index 3623491195..7d1522b9ac 100644 --- a/config/src/test/java/org/springframework/security/config/SecurityNamespaceHandlerTests.java +++ b/config/src/test/java/org/springframework/security/config/SecurityNamespaceHandlerTests.java @@ -20,6 +20,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @@ -34,11 +35,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; -import static org.powermock.api.mockito.PowerMockito.doThrow; -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.spy; -import static org.powermock.api.mockito.PowerMockito.verifyStatic; -import static org.powermock.api.mockito.PowerMockito.verifyZeroInteractions; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyZeroInteractions; /** * @author Luke Taylor @@ -88,9 +86,9 @@ public class SecurityNamespaceHandlerTests { @Test public void initDoesNotLogErrorWhenFilterChainProxyFailsToLoad() throws Exception { String className = "javax.servlet.Filter"; - spy(ClassUtils.class); - doThrow(new NoClassDefFoundError(className)).when(ClassUtils.class, "forName", eq(FILTER_CHAIN_PROXY_CLASSNAME), - any(ClassLoader.class)); + PowerMockito.spy(ClassUtils.class); + PowerMockito.doThrow(new NoClassDefFoundError(className)).when(ClassUtils.class, "forName", + eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class)); Log logger = mock(Log.class); SecurityNamespaceHandler handler = new SecurityNamespaceHandler(); @@ -98,7 +96,7 @@ public class SecurityNamespaceHandlerTests { handler.init(); - verifyStatic(ClassUtils.class); + PowerMockito.verifyStatic(ClassUtils.class); ClassUtils.forName(eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class)); verifyZeroInteractions(logger); } @@ -108,18 +106,18 @@ public class SecurityNamespaceHandlerTests { String className = "javax.servlet.Filter"; this.thrown.expect(BeanDefinitionParsingException.class); this.thrown.expectMessage("NoClassDefFoundError: " + className); - spy(ClassUtils.class); - doThrow(new NoClassDefFoundError(className)).when(ClassUtils.class, "forName", eq(FILTER_CHAIN_PROXY_CLASSNAME), - any(ClassLoader.class)); + PowerMockito.spy(ClassUtils.class); + PowerMockito.doThrow(new NoClassDefFoundError(className)).when(ClassUtils.class, "forName", + eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class)); new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER + XML_HTTP_BLOCK); } @Test public void filterNoClassDefFoundErrorNoHttpBlock() throws Exception { String className = "javax.servlet.Filter"; - spy(ClassUtils.class); - doThrow(new NoClassDefFoundError(className)).when(ClassUtils.class, "forName", eq(FILTER_CHAIN_PROXY_CLASSNAME), - any(ClassLoader.class)); + PowerMockito.spy(ClassUtils.class); + PowerMockito.doThrow(new NoClassDefFoundError(className)).when(ClassUtils.class, "forName", + eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class)); new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER); // should load just fine since no http block } @@ -129,8 +127,8 @@ public class SecurityNamespaceHandlerTests { String className = FILTER_CHAIN_PROXY_CLASSNAME; this.thrown.expect(BeanDefinitionParsingException.class); this.thrown.expectMessage("ClassNotFoundException: " + className); - spy(ClassUtils.class); - doThrow(new ClassNotFoundException(className)).when(ClassUtils.class, "forName", + PowerMockito.spy(ClassUtils.class); + PowerMockito.doThrow(new ClassNotFoundException(className)).when(ClassUtils.class, "forName", eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class)); new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER + XML_HTTP_BLOCK); } @@ -138,8 +136,8 @@ public class SecurityNamespaceHandlerTests { @Test public void filterChainProxyClassNotFoundExceptionNoHttpBlock() throws Exception { String className = FILTER_CHAIN_PROXY_CLASSNAME; - spy(ClassUtils.class); - doThrow(new ClassNotFoundException(className)).when(ClassUtils.class, "forName", + PowerMockito.spy(ClassUtils.class); + PowerMockito.doThrow(new ClassNotFoundException(className)).when(ClassUtils.class, "forName", eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class)); new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER); // should load just fine since no http block @@ -148,9 +146,9 @@ public class SecurityNamespaceHandlerTests { @Test public void websocketNotFoundExceptionNoMessageBlock() throws Exception { String className = FILTER_CHAIN_PROXY_CLASSNAME; - spy(ClassUtils.class); - doThrow(new ClassNotFoundException(className)).when(ClassUtils.class, "forName", eq(Message.class.getName()), - any(ClassLoader.class)); + PowerMockito.spy(ClassUtils.class); + PowerMockito.doThrow(new ClassNotFoundException(className)).when(ClassUtils.class, "forName", + eq(Message.class.getName()), any(ClassLoader.class)); new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER); // should load just fine since no websocket block } diff --git a/config/src/test/java/org/springframework/security/config/annotation/authentication/NamespaceAuthenticationManagerTests.java b/config/src/test/java/org/springframework/security/config/annotation/authentication/NamespaceAuthenticationManagerTests.java index 4f924e7878..01ae058853 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/authentication/NamespaceAuthenticationManagerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/authentication/NamespaceAuthenticationManagerTests.java @@ -24,6 +24,8 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.test.SpringTestRule; import org.springframework.security.core.userdetails.PasswordEncodedUser; +import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders; +import org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers; import org.springframework.test.web.servlet.MockMvc; import static org.assertj.core.api.Assertions.assertThat; @@ -70,8 +72,8 @@ public class NamespaceAuthenticationManagerTests { public void authenticationManagerWhenGlobalAndEraseCredentialsIsFalseThenCredentialsNotNull() throws Exception { this.spring.register(GlobalEraseCredentialsFalseConfig.class).autowire(); - this.mockMvc.perform(formLogin()) - .andExpect(authenticated().withAuthentication(a -> assertThat(a.getCredentials()).isNotNull())); + this.mockMvc.perform(SecurityMockMvcRequestBuilders.formLogin()).andExpect(SecurityMockMvcResultMatchers + .authenticated().withAuthentication(a -> assertThat(a.getCredentials()).isNotNull())); } @EnableWebSecurity diff --git a/config/src/test/java/org/springframework/security/config/annotation/configuration/AutowireBeanFactoryObjectPostProcessorTests.java b/config/src/test/java/org/springframework/security/config/annotation/configuration/AutowireBeanFactoryObjectPostProcessorTests.java index c24f59a092..bea9e42276 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/configuration/AutowireBeanFactoryObjectPostProcessorTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/configuration/AutowireBeanFactoryObjectPostProcessorTests.java @@ -34,7 +34,7 @@ import org.springframework.security.config.annotation.ObjectPostProcessor; import org.springframework.security.config.test.SpringTestRule; import org.springframework.web.context.ServletContextAware; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.isNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/WebSecurityConfigurerAdapterPowermockTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/WebSecurityConfigurerAdapterPowermockTests.java index 7c68fabcde..72db1d8064 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/WebSecurityConfigurerAdapterPowermockTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/WebSecurityConfigurerAdapterPowermockTests.java @@ -22,6 +22,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; +import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @@ -48,8 +49,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -import static org.powermock.api.mockito.PowerMockito.spy; -import static org.powermock.api.mockito.PowerMockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; /** @@ -79,9 +78,10 @@ public class WebSecurityConfigurerAdapterPowermockTests { @Test public void loadConfigWhenDefaultConfigurerAsSpringFactoryhenDefaultConfigurerApplied() { - spy(SpringFactoriesLoader.class); + PowerMockito.spy(SpringFactoriesLoader.class); DefaultConfigurer configurer = new DefaultConfigurer(); - when(SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, getClass().getClassLoader())) + PowerMockito + .when(SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, getClass().getClassLoader())) .thenReturn(Arrays.asList(configurer)); loadConfig(Config.class); diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/WebSecurityConfigurerAdapterTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/WebSecurityConfigurerAdapterTests.java index dcd06d382d..af3accc65a 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/WebSecurityConfigurerAdapterTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/WebSecurityConfigurerAdapterTests.java @@ -55,7 +55,8 @@ import org.springframework.web.accept.HeaderContentNegotiationStrategy; import org.springframework.web.filter.OncePerRequestFilter; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.ThrowableAssert.catchThrowable; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -153,11 +154,9 @@ public class WebSecurityConfigurerAdapterTests { MyFilter myFilter = this.spring.getContext().getBean(MyFilter.class); - Throwable thrown = catchThrowable(() -> myFilter.userDetailsService.loadUserByUsername("user")); - assertThat(thrown).isNull(); - - thrown = catchThrowable(() -> myFilter.userDetailsService.loadUserByUsername("admin")); - assertThat(thrown).isInstanceOf(UsernameNotFoundException.class); + assertThatCode(() -> myFilter.userDetailsService.loadUserByUsername("user")).doesNotThrowAnyException(); + assertThatExceptionOfType(UsernameNotFoundException.class) + .isThrownBy(() -> myFilter.userDetailsService.loadUserByUsername("admin")); } // SEC-2274: WebSecurityConfigurer adds ApplicationContext as a shared object diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/builders/HttpConfigurationTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/builders/HttpConfigurationTests.java index e84265cfdf..890de93c1f 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/builders/HttpConfigurationTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/builders/HttpConfigurationTests.java @@ -38,8 +38,7 @@ import org.springframework.security.core.userdetails.PasswordEncodedUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.filter.OncePerRequestFilter; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.ThrowableAssert.catchThrowable; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -62,11 +61,11 @@ public class HttpConfigurationTests { @Test public void configureWhenAddFilterUnregisteredThenThrowsBeanCreationException() { - Throwable thrown = catchThrowable(() -> this.spring.register(UnregisteredFilterConfig.class).autowire()); - assertThat(thrown).isInstanceOf(BeanCreationException.class); - assertThat(thrown.getMessage()).contains("The Filter class " + UnregisteredFilter.class.getName() - + " does not have a registered order and cannot be added without a specified order." - + " Consider using addFilterBefore or addFilterAfter instead."); + assertThatExceptionOfType(BeanCreationException.class) + .isThrownBy(() -> this.spring.register(UnregisteredFilterConfig.class).autowire()) + .withMessageContaining("The Filter class " + UnregisteredFilter.class.getName() + + " does not have a registered order and cannot be added without a specified order." + + " Consider using addFilterBefore or addFilterAfter instead."); } // https://github.com/spring-projects/spring-security-javaconfig/issues/104 diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfigurationTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfigurationTests.java index 3824048542..80f6c0666f 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfigurationTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfigurationTests.java @@ -34,10 +34,12 @@ import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResp import org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest; import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; +import org.springframework.security.oauth2.client.registration.TestClientRegistrations; import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; +import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @@ -52,9 +54,6 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyZeroInteractions; -import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientCredentials; -import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -79,7 +78,8 @@ public class OAuth2ClientConfigurationTests { TestingAuthenticationToken authentication = new TestingAuthenticationToken(principalName, "password"); ClientRegistrationRepository clientRegistrationRepository = mock(ClientRegistrationRepository.class); - ClientRegistration clientRegistration = clientRegistration().registrationId(clientRegistrationId).build(); + ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration() + .registrationId(clientRegistrationId).build(); given(clientRegistrationRepository.findByRegistrationId(eq(clientRegistrationId))) .willReturn(clientRegistration); @@ -99,8 +99,10 @@ public class OAuth2ClientConfigurationTests { OAuth2AuthorizedClientArgumentResolverConfig.ACCESS_TOKEN_RESPONSE_CLIENT = accessTokenResponseClient; this.spring.register(OAuth2AuthorizedClientArgumentResolverConfig.class).autowire(); - this.mockMvc.perform(get("/authorized-client").with(authentication(authentication))).andExpect(status().isOk()) - .andExpect(content().string("resolved")); + this.mockMvc + .perform(get("/authorized-client") + .with(SecurityMockMvcRequestPostProcessors.authentication(authentication))) + .andExpect(status().isOk()).andExpect(content().string("resolved")); verifyZeroInteractions(accessTokenResponseClient); } @@ -115,7 +117,8 @@ public class OAuth2ClientConfigurationTests { OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class); OAuth2AccessTokenResponseClient accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class); - ClientRegistration clientRegistration = clientCredentials().registrationId(clientRegistrationId).build(); + ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials() + .registrationId(clientRegistrationId).build(); given(clientRegistrationRepository.findByRegistrationId(clientRegistrationId)).willReturn(clientRegistration); OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234") @@ -128,8 +131,10 @@ public class OAuth2ClientConfigurationTests { OAuth2AuthorizedClientArgumentResolverConfig.ACCESS_TOKEN_RESPONSE_CLIENT = accessTokenResponseClient; this.spring.register(OAuth2AuthorizedClientArgumentResolverConfig.class).autowire(); - this.mockMvc.perform(get("/authorized-client").with(authentication(authentication))).andExpect(status().isOk()) - .andExpect(content().string("resolved")); + this.mockMvc + .perform(get("/authorized-client") + .with(SecurityMockMvcRequestPostProcessors.authentication(authentication))) + .andExpect(status().isOk()).andExpect(content().string("resolved")); verify(accessTokenResponseClient, times(1)).getTokenResponse(any(OAuth2ClientCredentialsGrantRequest.class)); } @@ -176,7 +181,8 @@ public class OAuth2ClientConfigurationTests { OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class); OAuth2AuthorizedClientManager authorizedClientManager = mock(OAuth2AuthorizedClientManager.class); - ClientRegistration clientRegistration = clientRegistration().registrationId(clientRegistrationId).build(); + ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration() + .registrationId(clientRegistrationId).build(); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, principalName, TestOAuth2AccessTokens.noScopes()); @@ -187,8 +193,10 @@ public class OAuth2ClientConfigurationTests { OAuth2AuthorizedClientManagerRegisteredConfig.AUTHORIZED_CLIENT_MANAGER = authorizedClientManager; this.spring.register(OAuth2AuthorizedClientManagerRegisteredConfig.class).autowire(); - this.mockMvc.perform(get("/authorized-client").with(authentication(authentication))).andExpect(status().isOk()) - .andExpect(content().string("resolved")); + this.mockMvc + .perform(get("/authorized-client") + .with(SecurityMockMvcRequestPostProcessors.authentication(authentication))) + .andExpect(status().isOk()).andExpect(content().string("resolved")); verify(authorizedClientManager).authorize(any()); verifyNoInteractions(clientRegistrationRepository); diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfigurationResourceServerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfigurationResourceServerTests.java index 6b4d806e1e..457fa6185d 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfigurationResourceServerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfigurationResourceServerTests.java @@ -31,14 +31,14 @@ import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.test.SpringTestRule; import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication; +import org.springframework.security.oauth2.server.resource.authentication.TestBearerTokenAuthentications; import org.springframework.security.oauth2.server.resource.web.reactive.function.client.ServletBearerExchangeFilterFunction; +import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.reactive.function.client.WebClient; -import static org.springframework.security.oauth2.server.resource.authentication.TestBearerTokenAuthentications.bearer; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -60,21 +60,21 @@ public class SecurityReactorContextConfigurationResourceServerTests { // gh-7418 @Test public void requestWhenUsingFilterThenBearerTokenPropagated() throws Exception { - BearerTokenAuthentication authentication = bearer(); + BearerTokenAuthentication authentication = TestBearerTokenAuthentications.bearer(); this.spring.register(BearerFilterConfig.class, WebServerConfig.class, Controller.class).autowire(); - this.mockMvc.perform(get("/token").with(authentication(authentication))).andExpect(status().isOk()) - .andExpect(content().string("Bearer token")); + this.mockMvc.perform(get("/token").with(SecurityMockMvcRequestPostProcessors.authentication(authentication))) + .andExpect(status().isOk()).andExpect(content().string("Bearer token")); } // gh-7418 @Test public void requestWhenNotUsingFilterThenBearerTokenNotPropagated() throws Exception { - BearerTokenAuthentication authentication = bearer(); + BearerTokenAuthentication authentication = TestBearerTokenAuthentications.bearer(); this.spring.register(BearerFilterlessConfig.class, WebServerConfig.class, Controller.class).autowire(); - this.mockMvc.perform(get("/token").with(authentication(authentication))).andExpect(status().isOk()) - .andExpect(content().string("")); + this.mockMvc.perform(get("/token").with(SecurityMockMvcRequestPostProcessors.authentication(authentication))) + .andExpect(status().isOk()).andExpect(content().string("")); } @EnableWebSecurity diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfigurationTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfigurationTests.java index 0f632bdb27..23c82f730e 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfigurationTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configuration/SecurityReactorContextConfigurationTests.java @@ -33,11 +33,13 @@ import reactor.core.publisher.Operators; import reactor.test.StepVerifier; import reactor.util.context.Context; +import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.SecurityReactorContextConfiguration.SecurityReactorContextSubscriber; import org.springframework.security.config.test.SpringTestRule; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; @@ -51,8 +53,6 @@ import org.springframework.web.reactive.function.client.ExchangeFilterFunction; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; -import static org.springframework.http.HttpMethod.GET; -import static org.springframework.security.config.annotation.web.configuration.SecurityReactorContextConfiguration.SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES; /** * Tests for {@link SecurityReactorContextConfiguration}. @@ -88,7 +88,7 @@ public class SecurityReactorContextConfigurationTests { @Test public void createSubscriberIfNecessaryWhenSubscriberContextContainsSecurityContextAttributesThenReturnOriginalSubscriber() { - Context context = Context.of(SECURITY_CONTEXT_ATTRIBUTES, new HashMap<>()); + Context context = Context.of(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES, new HashMap<>()); BaseSubscriber originalSubscriber = new BaseSubscriber() { @Override public Context currentContext() { @@ -120,7 +120,8 @@ public class SecurityReactorContextConfigurationTests { Context resultContext = subscriber.currentContext(); assertThat(resultContext.getOrEmpty(testKey)).hasValue(testValue); - Map securityContextAttributes = resultContext.getOrDefault(SECURITY_CONTEXT_ATTRIBUTES, null); + Map securityContextAttributes = resultContext + .getOrDefault(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES, null); assertThat(securityContextAttributes).hasSize(3); assertThat(securityContextAttributes).contains(entry(HttpServletRequest.class, this.servletRequest), entry(HttpServletResponse.class, this.servletResponse), @@ -133,7 +134,8 @@ public class SecurityReactorContextConfigurationTests { .setRequestAttributes(new ServletRequestAttributes(this.servletRequest, this.servletResponse)); SecurityContextHolder.getContext().setAuthentication(this.authentication); - Context parentContext = Context.of(SECURITY_CONTEXT_ATTRIBUTES, new HashMap<>()); + Context parentContext = Context.of(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES, + new HashMap<>()); BaseSubscriber parent = new BaseSubscriber() { @Override public Context currentContext() { @@ -206,8 +208,9 @@ public class SecurityReactorContextConfigurationTests { ClientResponse clientResponseOk = ClientResponse.create(HttpStatus.OK).build(); ExchangeFilterFunction filter = (req, next) -> Mono.subscriberContext() - .filter(ctx -> ctx.hasKey(SECURITY_CONTEXT_ATTRIBUTES)).map(ctx -> ctx.get(SECURITY_CONTEXT_ATTRIBUTES)) - .cast(Map.class).map(attributes -> { + .filter(ctx -> ctx.hasKey(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES)) + .map(ctx -> ctx.get(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES)).cast(Map.class) + .map(attributes -> { if (attributes.containsKey(HttpServletRequest.class) && attributes.containsKey(HttpServletResponse.class) && attributes.containsKey(Authentication.class)) { @@ -218,7 +221,7 @@ public class SecurityReactorContextConfigurationTests { } }); - ClientRequest clientRequest = ClientRequest.create(GET, URI.create("https://example.com")).build(); + ClientRequest clientRequest = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build(); MockExchangeFunction exchange = new MockExchangeFunction(); Map expectedContextAttributes = new HashMap<>(); @@ -230,8 +233,8 @@ public class SecurityReactorContextConfigurationTests { .flatMap(response -> filter.filter(clientRequest, exchange)); StepVerifier.create(clientResponseMono).expectAccessibleContext() - .contains(SECURITY_CONTEXT_ATTRIBUTES, expectedContextAttributes).then().expectNext(clientResponseOk) - .verifyComplete(); + .contains(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES, expectedContextAttributes) + .then().expectNext(clientResponseOk).verifyComplete(); } @EnableWebSecurity diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/HeadersConfigurerEagerHeadersTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/HeadersConfigurerEagerHeadersTests.java index 0586a75bac..12d4c472cb 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/HeadersConfigurerEagerHeadersTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/HeadersConfigurerEagerHeadersTests.java @@ -20,6 +20,7 @@ import org.junit.Rule; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; import org.springframework.security.config.annotation.ObjectPostProcessor; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; @@ -28,9 +29,6 @@ import org.springframework.security.config.test.SpringTestRule; import org.springframework.security.web.header.HeaderWriterFilter; import org.springframework.test.web.servlet.MockMvc; -import static org.springframework.http.HttpHeaders.CACHE_CONTROL; -import static org.springframework.http.HttpHeaders.EXPIRES; -import static org.springframework.http.HttpHeaders.PRAGMA; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; @@ -54,8 +52,9 @@ public class HeadersConfigurerEagerHeadersTests { this.mvc.perform(get("/").secure(true)).andExpect(header().string("X-Content-Type-Options", "nosniff")) .andExpect(header().string("X-Frame-Options", "DENY")) .andExpect(header().string("Strict-Transport-Security", "max-age=31536000 ; includeSubDomains")) - .andExpect(header().string(CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate")) - .andExpect(header().string(EXPIRES, "0")).andExpect(header().string(PRAGMA, "no-cache")) + .andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate")) + .andExpect(header().string(HttpHeaders.EXPIRES, "0")) + .andExpect(header().string(HttpHeaders.PRAGMA, "no-cache")) .andExpect(header().string("X-XSS-Protection", "1; mode=block")); } diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/Issue55Tests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/Issue55Tests.java index b071eadbb0..4191869ae3 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/Issue55Tests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/Issue55Tests.java @@ -39,7 +39,7 @@ import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.access.intercept.FilterSecurityInterceptor; import org.springframework.stereotype.Component; -import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/LogoutConfigurerClearSiteDataTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/LogoutConfigurerClearSiteDataTests.java index 8b8a8ac9e8..ac8ed76df9 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/LogoutConfigurerClearSiteDataTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/LogoutConfigurerClearSiteDataTests.java @@ -27,16 +27,13 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur import org.springframework.security.config.test.SpringTestRule; import org.springframework.security.test.context.annotation.SecurityTestExecutionListeners; import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; import org.springframework.security.web.authentication.logout.HeaderWriterLogoutHandler; import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter; +import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; -import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.CACHE; -import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.COOKIES; -import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.EXECUTION_CONTEXTS; -import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.STORAGE; 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.header; @@ -55,7 +52,8 @@ public class LogoutConfigurerClearSiteDataTests { private static final String CLEAR_SITE_DATA_HEADER = "Clear-Site-Data"; - private static final ClearSiteDataHeaderWriter.Directive[] SOURCE = { CACHE, COOKIES, STORAGE, EXECUTION_CONTEXTS }; + private static final Directive[] SOURCE = { Directive.CACHE, Directive.COOKIES, Directive.STORAGE, + Directive.EXECUTION_CONTEXTS }; private static final String HEADER_VALUE = "\"cache\", \"cookies\", \"storage\", \"executionContexts\""; @@ -70,7 +68,7 @@ public class LogoutConfigurerClearSiteDataTests { public void logoutWhenRequestTypeGetThenHeaderNotPresentt() throws Exception { this.spring.register(HttpLogoutConfig.class).autowire(); - this.mvc.perform(get("/logout").secure(true).with(csrf())) + this.mvc.perform(get("/logout").secure(true).with(SecurityMockMvcRequestPostProcessors.csrf())) .andExpect(header().doesNotExist(CLEAR_SITE_DATA_HEADER)); } @@ -79,7 +77,8 @@ public class LogoutConfigurerClearSiteDataTests { public void logoutWhenRequestTypePostAndNotSecureThenHeaderNotPresent() throws Exception { this.spring.register(HttpLogoutConfig.class).autowire(); - this.mvc.perform(post("/logout").with(csrf())).andExpect(header().doesNotExist(CLEAR_SITE_DATA_HEADER)); + this.mvc.perform(post("/logout").with(SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(header().doesNotExist(CLEAR_SITE_DATA_HEADER)); } @Test @@ -87,7 +86,7 @@ public class LogoutConfigurerClearSiteDataTests { public void logoutWhenRequestTypePostAndSecureThenHeaderIsPresent() throws Exception { this.spring.register(HttpLogoutConfig.class).autowire(); - this.mvc.perform(post("/logout").secure(true).with(csrf())) + this.mvc.perform(post("/logout").secure(true).with(SecurityMockMvcRequestPostProcessors.csrf())) .andExpect(header().stringValues(CLEAR_SITE_DATA_HEADER, HEADER_VALUE)); } diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpOpenIDLoginTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpOpenIDLoginTests.java index f06590f03c..780a2eee08 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpOpenIDLoginTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpOpenIDLoginTests.java @@ -26,6 +26,7 @@ import org.junit.Rule; import org.junit.Test; import org.openid4java.consumer.ConsumerManager; import org.openid4java.discovery.DiscoveryInformation; +import org.openid4java.discovery.yadis.YadisResolver; import org.openid4java.message.AuthRequest; import org.springframework.beans.factory.annotation.Autowired; @@ -63,7 +64,6 @@ 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.openid4java.discovery.yadis.YadisResolver.YADIS_XRDS_LOCATION; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @@ -107,7 +107,7 @@ public class NamespaceHttpOpenIDLoginTests { try (MockWebServer server = new MockWebServer()) { String endpoint = server.url("/").toString(); - server.enqueue(new MockResponse().addHeader(YADIS_XRDS_LOCATION, endpoint)); + server.enqueue(new MockResponse().addHeader(YadisResolver.YADIS_XRDS_LOCATION, endpoint)); server.enqueue(new MockResponse() .setBody(String.format("%s", endpoint))); diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurerServlet31Tests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurerServlet31Tests.java index d2e84b594b..1dd734d486 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurerServlet31Tests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurerServlet31Tests.java @@ -44,7 +44,7 @@ import org.springframework.security.web.context.HttpSessionSecurityContextReposi import org.springframework.security.web.csrf.CsrfToken; import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2LoginConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2LoginConfigurerTests.java index 81f12e07cf..1b9aaeb670 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2LoginConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/client/OAuth2LoginConfigurerTests.java @@ -69,6 +69,7 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequ import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames; import org.springframework.security.oauth2.core.oidc.OidcIdToken; +import org.springframework.security.oauth2.core.oidc.TestOidcIdTokens; import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames; import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser; import org.springframework.security.oauth2.core.oidc.user.OidcUser; @@ -80,6 +81,7 @@ import org.springframework.security.oauth2.core.user.OAuth2UserAuthority; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.jwt.JwtDecoderFactory; +import org.springframework.security.oauth2.jwt.TestJwts; import org.springframework.security.web.FilterChainProxy; import org.springframework.security.web.context.HttpRequestResponseHolder; import org.springframework.security.web.context.HttpSessionSecurityContextRepository; @@ -92,8 +94,6 @@ 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.springframework.security.oauth2.core.oidc.TestOidcIdTokens.idToken; -import static org.springframework.security.oauth2.jwt.TestJwts.jwt; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @@ -602,7 +602,7 @@ public class OAuth2LoginConfigurerTests { } private static OAuth2UserService createOidcUserService() { - OidcIdToken idToken = idToken().build(); + OidcIdToken idToken = TestOidcIdTokens.idToken().build(); return request -> new DefaultOidcUser(Collections.singleton(new OidcUserAuthority(idToken)), idToken); } @@ -993,7 +993,7 @@ public class OAuth2LoginConfigurerTests { claims.put(IdTokenClaimNames.ISS, "http://localhost/iss"); claims.put(IdTokenClaimNames.AUD, Arrays.asList("clientId", "a", "u", "d")); claims.put(IdTokenClaimNames.AZP, "clientId"); - Jwt jwt = jwt().claims(c -> c.putAll(claims)).build(); + Jwt jwt = TestJwts.jwt().claims(c -> c.putAll(claims)).build(); JwtDecoder jwtDecoder = mock(JwtDecoder.class); given(jwtDecoder.decode(any())).willReturn(jwt); return jwtDecoder; diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java index d48878e014..8351a52ce5 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java @@ -94,13 +94,16 @@ import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.core.OAuth2Error; import org.springframework.security.oauth2.core.OAuth2TokenValidator; import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult; +import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; import org.springframework.security.oauth2.jose.TestKeys; import org.springframework.security.oauth2.jwt.BadJwtException; import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.jwt.JwtClaimNames; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.jwt.JwtException; import org.springframework.security.oauth2.jwt.JwtTimestampValidator; import org.springframework.security.oauth2.jwt.NimbusJwtDecoder; +import org.springframework.security.oauth2.jwt.TestJwts; import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; @@ -124,6 +127,7 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestOperations; import org.springframework.web.context.support.GenericWebApplicationContext; @@ -131,7 +135,7 @@ import org.springframework.web.context.support.GenericWebApplicationContext; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.core.StringStartsWith.startsWith; +import static org.hamcrest.CoreMatchers.startsWith; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -140,12 +144,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.springframework.security.config.Customizer.withDefaults; -import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.noScopes; -import static org.springframework.security.oauth2.jwt.JwtClaimNames.ISS; -import static org.springframework.security.oauth2.jwt.JwtClaimNames.SUB; -import static org.springframework.security.oauth2.jwt.NimbusJwtDecoder.withJwkSetUri; -import static org.springframework.security.oauth2.jwt.NimbusJwtDecoder.withPublicKey; -import static org.springframework.security.oauth2.jwt.TestJwts.jwt; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -154,8 +152,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.web.bind.annotation.RequestMethod.GET; -import static org.springframework.web.bind.annotation.RequestMethod.POST; /** * Tests for {@link OAuth2ResourceServerConfigurer} @@ -169,9 +165,9 @@ public class OAuth2ResourceServerConfigurerTests { private static final String JWT_SUBJECT = "mock-test-subject"; - private static final Map JWT_CLAIMS = Collections.singletonMap(SUB, JWT_SUBJECT); + private static final Map JWT_CLAIMS = Collections.singletonMap(JwtClaimNames.SUB, JWT_SUBJECT); - private static final Jwt JWT = jwt().build(); + private static final Jwt JWT = TestJwts.jwt().build(); private static final String JWK_SET_URI = "https://mock.org"; @@ -185,8 +181,8 @@ public class OAuth2ResourceServerConfigurerTests { private static final String CLIENT_SECRET = "client-secret"; private static final BearerTokenAuthentication INTROSPECTION_AUTHENTICATION_TOKEN = new BearerTokenAuthentication( - new DefaultOAuth2AuthenticatedPrincipal(JWT_CLAIMS, Collections.emptyList()), noScopes(), - Collections.emptyList()); + new DefaultOAuth2AuthenticatedPrincipal(JWT_CLAIMS, Collections.emptyList()), + TestOAuth2AccessTokens.noScopes(), Collections.emptyList()); @Autowired(required = false) MockMvc mvc; @@ -1361,8 +1357,8 @@ public class OAuth2ResourceServerConfigurerTests { private String jwtFromIssuer(String issuer) throws Exception { Map claims = new HashMap<>(); - claims.put(ISS, issuer); - claims.put(SUB, "test-subject"); + claims.put(JwtClaimNames.ISS, issuer); + claims.put(JwtClaimNames.SUB, "test-subject"); claims.put("scope", "message:read"); JWSObject jws = new JWSObject(new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("1").build(), new Payload(new JSONObject(claims))); @@ -2066,7 +2062,7 @@ public class OAuth2ResourceServerConfigurerTests { JwtDecoder decoder() throws Exception { RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA") .generatePublic(new X509EncodedKeySpec(this.spec)); - return withPublicKey(publicKey).build(); + return NimbusJwtDecoder.withPublicKey(publicKey).build(); } } @@ -2285,7 +2281,7 @@ public class OAuth2ResourceServerConfigurerTests { return "post"; } - @RequestMapping(value = "/authenticated", method = { GET, POST }) + @RequestMapping(value = "/authenticated", method = { RequestMethod.GET, RequestMethod.POST }) public String authenticated(Authentication authentication) { return authentication.getName(); } @@ -2365,7 +2361,8 @@ public class OAuth2ResourceServerConfigurerTests { @Bean NimbusJwtDecoder jwtDecoder() { - return withJwkSetUri("https://example.org/.well-known/jwks.json").restOperations(this.rest).build(); + return NimbusJwtDecoder.withJwkSetUri("https://example.org/.well-known/jwks.json").restOperations(this.rest) + .build(); } @Bean diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/openid/OpenIDLoginConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/openid/OpenIDLoginConfigurerTests.java index f546583a5d..e5cb902773 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/openid/OpenIDLoginConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/openid/OpenIDLoginConfigurerTests.java @@ -24,6 +24,7 @@ import org.junit.Rule; import org.junit.Test; import org.openid4java.consumer.ConsumerManager; import org.openid4java.discovery.DiscoveryInformation; +import org.openid4java.discovery.yadis.YadisResolver; import org.openid4java.message.AuthRequest; import org.springframework.beans.factory.annotation.Autowired; @@ -47,7 +48,6 @@ 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.openid4java.discovery.yadis.YadisResolver.YADIS_XRDS_LOCATION; import static org.springframework.security.config.Customizer.withDefaults; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; @@ -113,7 +113,7 @@ public class OpenIDLoginConfigurerTests { try (MockWebServer server = new MockWebServer()) { String endpoint = server.url("/").toString(); - server.enqueue(new MockResponse().addHeader(YADIS_XRDS_LOCATION, endpoint)); + server.enqueue(new MockResponse().addHeader(YadisResolver.YADIS_XRDS_LOCATION, endpoint)); server.enqueue(new MockResponse() .setBody(String.format("%s", endpoint))); @@ -151,7 +151,7 @@ public class OpenIDLoginConfigurerTests { try (MockWebServer server = new MockWebServer()) { String endpoint = server.url("/").toString(); - server.enqueue(new MockResponse().addHeader(YADIS_XRDS_LOCATION, endpoint)); + server.enqueue(new MockResponse().addHeader(YadisResolver.YADIS_XRDS_LOCATION, endpoint)); server.enqueue(new MockResponse() .setBody(String.format("%s", endpoint))); diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/saml2/Saml2LoginConfigurerTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/saml2/Saml2LoginConfigurerTests.java index b70773de04..4a6223ef00 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/saml2/Saml2LoginConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/saml2/Saml2LoginConfigurerTests.java @@ -19,6 +19,7 @@ package org.springframework.security.config.annotation.web.configurers.saml2; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.Arrays; import java.util.Base64; @@ -60,14 +61,17 @@ import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper; import org.springframework.security.saml2.Saml2Exception; +import org.springframework.security.saml2.core.TestSaml2X509Credentials; import org.springframework.security.saml2.provider.service.authentication.OpenSamlAuthenticationProvider; import org.springframework.security.saml2.provider.service.authentication.OpenSamlAuthenticationRequestFactory; import org.springframework.security.saml2.provider.service.authentication.Saml2Authentication; import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationRequestContext; import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationRequestFactory; import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationToken; +import org.springframework.security.saml2.provider.service.authentication.TestSaml2AuthenticationRequestContexts; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository; +import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import org.springframework.security.saml2.provider.service.servlet.filter.Saml2WebSsoAuthenticationFilter; import org.springframework.security.saml2.provider.service.web.Saml2AuthenticationRequestContextResolver; import org.springframework.security.web.FilterChainProxy; @@ -81,7 +85,6 @@ import org.springframework.test.web.servlet.MvcResult; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; -import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; @@ -89,10 +92,6 @@ import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.springframework.security.config.Customizer.withDefaults; -import static org.springframework.security.saml2.core.TestSaml2X509Credentials.relyingPartyVerifyingCredential; -import static org.springframework.security.saml2.provider.service.authentication.TestSaml2AuthenticationRequestContexts.authenticationRequestContext; -import static org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations.noCredentials; -import static org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations.relyingPartyRegistration; 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.redirectedUrl; @@ -171,7 +170,8 @@ public class Saml2LoginConfigurerTests { public void saml2LoginWhenCustomAuthenticationRequestContextResolverThenUses() throws Exception { this.spring.register(CustomAuthenticationRequestContextResolver.class).autowire(); - Saml2AuthenticationRequestContext context = authenticationRequestContext().build(); + Saml2AuthenticationRequestContext context = TestSaml2AuthenticationRequestContexts + .authenticationRequestContext().build(); Saml2AuthenticationRequestContextResolver resolver = CustomAuthenticationRequestContextResolver.resolver; given(resolver.resolve(any(HttpServletRequest.class))).willReturn(context); this.mvc.perform(get("/saml2/authenticate/registration-id")).andExpect(status().isFound()); @@ -193,9 +193,9 @@ public class Saml2LoginConfigurerTests { @Test public void authenticateWhenCustomAuthenticationConverterThenUses() throws Exception { this.spring.register(CustomAuthenticationConverter.class).autowire(); - RelyingPartyRegistration relyingPartyRegistration = noCredentials() - .assertingPartyDetails( - party -> party.verificationX509Credentials(c -> c.add(relyingPartyVerifyingCredential()))) + RelyingPartyRegistration relyingPartyRegistration = TestRelyingPartyRegistrations.noCredentials() + .assertingPartyDetails(party -> party.verificationX509Credentials( + c -> c.add(TestSaml2X509Credentials.relyingPartyVerifyingCredential()))) .build(); String response = new String(samlDecode(SIGNED_RESPONSE)); given(CustomAuthenticationConverter.authenticationConverter.convert(any(HttpServletRequest.class))) @@ -254,7 +254,7 @@ public class Saml2LoginConfigurerTests { InflaterOutputStream iout = new InflaterOutputStream(out, new Inflater(true)); iout.write(b); iout.finish(); - return new String(out.toByteArray(), UTF_8); + return new String(out.toByteArray(), StandardCharsets.UTF_8); } catch (IOException e) { throw new Saml2Exception("Unable to inflate string", e); @@ -387,7 +387,8 @@ public class Saml2LoginConfigurerTests { @Bean RelyingPartyRegistrationRepository relyingPartyRegistrationRepository() { RelyingPartyRegistrationRepository repository = mock(RelyingPartyRegistrationRepository.class); - given(repository.findByRegistrationId(anyString())).willReturn(relyingPartyRegistration().build()); + given(repository.findByRegistrationId(anyString())) + .willReturn(TestRelyingPartyRegistrations.relyingPartyRegistration().build()); return repository; } diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/saml2/TestSaml2Credentials.java b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/saml2/TestSaml2Credentials.java index 22ff7efd72..ddccf53692 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/configurers/saml2/TestSaml2Credentials.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/configurers/saml2/TestSaml2Credentials.java @@ -24,10 +24,7 @@ import java.security.cert.X509Certificate; import org.springframework.security.converter.RsaKeyConverters; import org.springframework.security.saml2.credentials.Saml2X509Credential; - -import static org.springframework.security.saml2.credentials.Saml2X509Credential.Saml2X509CredentialType.DECRYPTION; -import static org.springframework.security.saml2.credentials.Saml2X509Credential.Saml2X509CredentialType.SIGNING; -import static org.springframework.security.saml2.credentials.Saml2X509Credential.Saml2X509CredentialType.VERIFICATION; +import org.springframework.security.saml2.credentials.Saml2X509Credential.Saml2X509CredentialType; /** * Preconfigured SAML credentials for SAML integration tests. @@ -58,7 +55,7 @@ public class TestSaml2Credentials { + "xbzb7ykxVr7EVFXwltPxzE9TmL9OACNNyF5eJHWMRMllarUvkcXlh4pux4ks9e6z\n" + "V9DQBy2zds9f1I3qxg0eX6JnGrXi/ZiCT+lJgVe3ZFXiejiLAiKB04sXW3ti0LW3\n" + "lx13Y1YlQ4/tlpgTgfIJxKV6nyPiLoK0nywbMd+vpAirDt2Oc+hk\n" + "-----END CERTIFICATE-----"; - return new Saml2X509Credential(x509Certificate(certificate), VERIFICATION); + return new Saml2X509Credential(x509Certificate(certificate), Saml2X509CredentialType.VERIFICATION); } static X509Certificate x509Certificate(String source) { @@ -105,7 +102,7 @@ public class TestSaml2Credentials { + "RZ/nbTJ7VTeZOSyRoVn5XHhpuJ0B\n" + "-----END CERTIFICATE-----"; PrivateKey pk = RsaKeyConverters.pkcs8().convert(new ByteArrayInputStream(key.getBytes())); X509Certificate cert = x509Certificate(certificate); - return new Saml2X509Credential(pk, cert, SIGNING, DECRYPTION); + return new Saml2X509Credential(pk, cert, Saml2X509CredentialType.SIGNING, Saml2X509CredentialType.DECRYPTION); } } diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/reactive/EnableWebFluxSecurityTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/reactive/EnableWebFluxSecurityTests.java index fdd1461eeb..036618be7b 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/reactive/EnableWebFluxSecurityTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/reactive/EnableWebFluxSecurityTests.java @@ -51,6 +51,7 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.test.context.annotation.SecurityTestExecutionListeners; import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers; import org.springframework.security.test.web.reactive.server.WebTestClientBuilder; import org.springframework.security.web.reactive.result.method.annotation.AuthenticationPrincipalArgumentResolver; import org.springframework.security.web.reactive.result.view.CsrfRequestDataValueProcessor; @@ -71,7 +72,6 @@ import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.result.view.AbstractView; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf; /** * @author Rob Winch @@ -202,8 +202,9 @@ public class EnableWebFluxSecurityTests { MultiValueMap data = new LinkedMultiValueMap<>(); data.add("username", "user"); data.add("password", "password"); - client.mutateWith(csrf()).post().uri("/login").body(BodyInserters.fromFormData(data)).exchange().expectStatus() - .is3xxRedirection().expectHeader().valueMatches("Location", "/"); + client.mutateWith(SecurityMockServerConfigurers.csrf()).post().uri("/login") + .body(BodyInserters.fromFormData(data)).exchange().expectStatus().is3xxRedirection().expectHeader() + .valueMatches("Location", "/"); } @Test diff --git a/config/src/test/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurerDocTests.java b/config/src/test/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurerDocTests.java index 83ada36fdd..76333746ad 100644 --- a/config/src/test/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurerDocTests.java +++ b/config/src/test/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurerDocTests.java @@ -46,8 +46,6 @@ import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; -import static org.springframework.messaging.simp.SimpMessageType.MESSAGE; -import static org.springframework.messaging.simp.SimpMessageType.SUBSCRIBE; public class AbstractSecurityWebSocketMessageBrokerConfigurerDocTests { @@ -139,7 +137,7 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerDocTests { .simpDestMatchers("/app/**").hasRole("USER") // <3> .simpSubscribeDestMatchers("/user/**", "/topic/friends/*").hasRole("USER") // <4> - .simpTypeMatchers(MESSAGE, SUBSCRIBE).denyAll() // <5> + .simpTypeMatchers(SimpMessageType.MESSAGE, SimpMessageType.SUBSCRIBE).denyAll() // <5> .anyMessage().denyAll(); // <6> } diff --git a/config/src/test/java/org/springframework/security/config/core/userdetails/ReactiveUserDetailsServiceResourceFactoryBeanPropertiesResourceITests.java b/config/src/test/java/org/springframework/security/config/core/userdetails/ReactiveUserDetailsServiceResourceFactoryBeanPropertiesResourceITests.java index 58c4e09397..1cbe52e40d 100644 --- a/config/src/test/java/org/springframework/security/config/core/userdetails/ReactiveUserDetailsServiceResourceFactoryBeanPropertiesResourceITests.java +++ b/config/src/test/java/org/springframework/security/config/core/userdetails/ReactiveUserDetailsServiceResourceFactoryBeanPropertiesResourceITests.java @@ -26,7 +26,7 @@ import org.springframework.security.core.userdetails.ReactiveUserDetailsService; import org.springframework.security.util.InMemoryResource; import org.springframework.test.context.junit4.SpringRunner; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch diff --git a/config/src/test/java/org/springframework/security/config/core/userdetails/ReactiveUserDetailsServiceResourceFactoryBeanPropertiesResourceLocationITests.java b/config/src/test/java/org/springframework/security/config/core/userdetails/ReactiveUserDetailsServiceResourceFactoryBeanPropertiesResourceLocationITests.java index 28908297f8..effd00c71e 100644 --- a/config/src/test/java/org/springframework/security/config/core/userdetails/ReactiveUserDetailsServiceResourceFactoryBeanPropertiesResourceLocationITests.java +++ b/config/src/test/java/org/springframework/security/config/core/userdetails/ReactiveUserDetailsServiceResourceFactoryBeanPropertiesResourceLocationITests.java @@ -25,7 +25,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.security.core.userdetails.ReactiveUserDetailsService; import org.springframework.test.context.junit4.SpringRunner; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch diff --git a/config/src/test/java/org/springframework/security/config/core/userdetails/ReactiveUserDetailsServiceResourceFactoryBeanStringITests.java b/config/src/test/java/org/springframework/security/config/core/userdetails/ReactiveUserDetailsServiceResourceFactoryBeanStringITests.java index ff4eac53f2..76bccac1ba 100644 --- a/config/src/test/java/org/springframework/security/config/core/userdetails/ReactiveUserDetailsServiceResourceFactoryBeanStringITests.java +++ b/config/src/test/java/org/springframework/security/config/core/userdetails/ReactiveUserDetailsServiceResourceFactoryBeanStringITests.java @@ -25,7 +25,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.security.core.userdetails.ReactiveUserDetailsService; import org.springframework.test.context.junit4.SpringRunner; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch diff --git a/config/src/test/java/org/springframework/security/config/core/userdetails/UserDetailsResourceFactoryBeanTests.java b/config/src/test/java/org/springframework/security/config/core/userdetails/UserDetailsResourceFactoryBeanTests.java index 6a366f7fcc..5e476818cb 100644 --- a/config/src/test/java/org/springframework/security/config/core/userdetails/UserDetailsResourceFactoryBeanTests.java +++ b/config/src/test/java/org/springframework/security/config/core/userdetails/UserDetailsResourceFactoryBeanTests.java @@ -29,7 +29,7 @@ import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.util.InMemoryResource; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * @author Rob Winch diff --git a/config/src/test/java/org/springframework/security/config/debug/SecurityDebugBeanFactoryPostProcessorTests.java b/config/src/test/java/org/springframework/security/config/debug/SecurityDebugBeanFactoryPostProcessorTests.java index d3bd58daaa..6d065fce3a 100644 --- a/config/src/test/java/org/springframework/security/config/debug/SecurityDebugBeanFactoryPostProcessorTests.java +++ b/config/src/test/java/org/springframework/security/config/debug/SecurityDebugBeanFactoryPostProcessorTests.java @@ -18,13 +18,12 @@ package org.springframework.security.config.debug; import org.junit.Rule; import org.junit.Test; +import org.springframework.security.config.BeanIds; import org.springframework.security.config.test.SpringTestRule; import org.springframework.security.web.FilterChainProxy; import org.springframework.security.web.debug.DebugFilter; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.config.BeanIds.FILTER_CHAIN_PROXY; -import static org.springframework.security.config.BeanIds.SPRING_SECURITY_FILTER_CHAIN; /** * @author Rob Winch @@ -42,8 +41,9 @@ public class SecurityDebugBeanFactoryPostProcessorTests { "classpath:org/springframework/security/config/debug/SecurityDebugBeanFactoryPostProcessorTests-context.xml") .autowire(); - assertThat(this.spring.getContext().getBean(SPRING_SECURITY_FILTER_CHAIN)).isInstanceOf(DebugFilter.class); - assertThat(this.spring.getContext().getBean(FILTER_CHAIN_PROXY)).isInstanceOf(FilterChainProxy.class); + assertThat(this.spring.getContext().getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN)) + .isInstanceOf(DebugFilter.class); + assertThat(this.spring.getContext().getBean(BeanIds.FILTER_CHAIN_PROXY)).isInstanceOf(FilterChainProxy.class); } } diff --git a/config/src/test/java/org/springframework/security/config/http/CsrfConfigTests.java b/config/src/test/java/org/springframework/security/config/http/CsrfConfigTests.java index 2801c4e593..ea4938b57b 100644 --- a/config/src/test/java/org/springframework/security/config/http/CsrfConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/CsrfConfigTests.java @@ -50,6 +50,7 @@ import org.springframework.test.web.servlet.ResultMatcher; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.support.RequestDataValueProcessor; @@ -68,14 +69,6 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.request; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.web.bind.annotation.RequestMethod.DELETE; -import static org.springframework.web.bind.annotation.RequestMethod.GET; -import static org.springframework.web.bind.annotation.RequestMethod.HEAD; -import static org.springframework.web.bind.annotation.RequestMethod.OPTIONS; -import static org.springframework.web.bind.annotation.RequestMethod.PATCH; -import static org.springframework.web.bind.annotation.RequestMethod.POST; -import static org.springframework.web.bind.annotation.RequestMethod.PUT; -import static org.springframework.web.bind.annotation.RequestMethod.TRACE; /** * @author Rob Winch @@ -441,20 +434,22 @@ public class CsrfConfigTests { @Controller public static class RootController { - @RequestMapping(value = "/csrf-in-header", method = { HEAD, TRACE, OPTIONS }) + @RequestMapping(value = "/csrf-in-header", + method = { RequestMethod.HEAD, RequestMethod.TRACE, RequestMethod.OPTIONS }) @ResponseBody String csrfInHeaderAndBody(CsrfToken token, HttpServletResponse response) { response.setHeader(token.getHeaderName(), token.getToken()); return csrfInBody(token); } - @RequestMapping(value = "/csrf", method = { POST, PUT, PATCH, DELETE, GET }) + @RequestMapping(value = "/csrf", method = { RequestMethod.POST, RequestMethod.PUT, RequestMethod.PATCH, + RequestMethod.DELETE, RequestMethod.GET }) @ResponseBody String csrfInBody(CsrfToken token) { return token.getToken(); } - @RequestMapping(value = "/ok", method = { POST, GET }) + @RequestMapping(value = "/ok", method = { RequestMethod.POST, RequestMethod.GET }) @ResponseBody String ok() { return "ok"; diff --git a/config/src/test/java/org/springframework/security/config/http/FormLoginBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/http/FormLoginBeanDefinitionParserTests.java index d36570f88e..2bdb457036 100644 --- a/config/src/test/java/org/springframework/security/config/http/FormLoginBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/http/FormLoginBeanDefinitionParserTests.java @@ -24,8 +24,8 @@ import org.springframework.security.web.WebAttributes; import org.springframework.test.web.servlet.MockMvc; import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.core.IsNot.not; -import static org.hamcrest.core.IsNull.nullValue; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.CoreMatchers.nullValue; 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.content; diff --git a/config/src/test/java/org/springframework/security/config/http/MiscHttpConfigTests.java b/config/src/test/java/org/springframework/security/config/http/MiscHttpConfigTests.java index c3b59f29fc..a1f99f4d41 100644 --- a/config/src/test/java/org/springframework/security/config/http/MiscHttpConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/MiscHttpConfigTests.java @@ -102,6 +102,7 @@ import org.springframework.security.web.savedrequest.RequestCache; import org.springframework.security.web.savedrequest.RequestCacheAwareFilter; import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter; import org.springframework.security.web.session.SessionManagementFilter; +import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.web.bind.annotation.GetMapping; @@ -120,7 +121,6 @@ import static org.mockito.Mockito.verify; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.x509; -import static org.springframework.test.util.ReflectionTestUtils.getField; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; @@ -618,8 +618,8 @@ public class MiscHttpConfigTests { this.mvc.perform(get("/details").session(session)).andExpect(content().string(details.getClass().getName())); - assertThat(getField(getFilter(OpenIDAuthenticationFilter.class), "authenticationDetailsSource")) - .isEqualTo(source); + assertThat(ReflectionTestUtils.getField(getFilter(OpenIDAuthenticationFilter.class), + "authenticationDetailsSource")).isEqualTo(source); } @Test diff --git a/config/src/test/java/org/springframework/security/config/http/OAuth2ClientBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/http/OAuth2ClientBeanDefinitionParserTests.java index 7b86dd796a..859e549a86 100644 --- a/config/src/test/java/org/springframework/security/config/http/OAuth2ClientBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/http/OAuth2ClientBeanDefinitionParserTests.java @@ -40,6 +40,7 @@ import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; +import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses; import org.springframework.security.test.context.annotation.SecurityTestExecutionListeners; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -55,7 +56,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses.accessTokenResponse; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; @@ -153,7 +153,7 @@ public class OAuth2ClientBeanDefinitionParserTests { given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any())) .willReturn(authorizationRequest); - OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build(); + OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build(); given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); MultiValueMap params = new LinkedMultiValueMap<>(); @@ -183,7 +183,7 @@ public class OAuth2ClientBeanDefinitionParserTests { given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any())) .willReturn(authorizationRequest); - OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build(); + OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build(); given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); MultiValueMap params = new LinkedMultiValueMap<>(); diff --git a/config/src/test/java/org/springframework/security/config/http/OAuth2LoginBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/http/OAuth2LoginBeanDefinitionParserTests.java index b2162505f5..5b98d0cdc0 100644 --- a/config/src/test/java/org/springframework/security/config/http/OAuth2LoginBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/http/OAuth2LoginBeanDefinitionParserTests.java @@ -52,6 +52,7 @@ import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; +import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses; import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests; import org.springframework.security.oauth2.core.oidc.user.OidcUser; import org.springframework.security.oauth2.core.user.OAuth2User; @@ -78,8 +79,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses.accessTokenResponse; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses.oidcAccessTokenResponse; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; @@ -214,7 +213,7 @@ public class OAuth2LoginBeanDefinitionParserTests { given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any())) .willReturn(authorizationRequest); - OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build(); + OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build(); given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); OAuth2User oauth2User = TestOAuth2Users.create(); @@ -243,7 +242,7 @@ public class OAuth2LoginBeanDefinitionParserTests { given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any())) .willReturn(authorizationRequest); - OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build(); + OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build(); given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); OAuth2User oauth2User = TestOAuth2Users.create(); @@ -269,7 +268,8 @@ public class OAuth2LoginBeanDefinitionParserTests { given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any())) .willReturn(authorizationRequest); - OAuth2AccessTokenResponse accessTokenResponse = oidcAccessTokenResponse().build(); + OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.oidcAccessTokenResponse() + .build(); given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); Jwt jwt = TestJwts.user(); @@ -297,7 +297,7 @@ public class OAuth2LoginBeanDefinitionParserTests { given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any())) .willReturn(authorizationRequest); - OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build(); + OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build(); given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); OAuth2User oauth2User = TestOAuth2Users.create(); @@ -326,7 +326,7 @@ public class OAuth2LoginBeanDefinitionParserTests { given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any())) .willReturn(authorizationRequest); - accessTokenResponse = oidcAccessTokenResponse().build(); + accessTokenResponse = TestOAuth2AccessTokenResponses.oidcAccessTokenResponse().build(); given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); Jwt jwt = TestJwts.user(); @@ -359,7 +359,7 @@ public class OAuth2LoginBeanDefinitionParserTests { given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any())) .willReturn(authorizationRequest); - OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build(); + OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build(); given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); OAuth2User oauth2User = TestOAuth2Users.create(); @@ -428,7 +428,7 @@ public class OAuth2LoginBeanDefinitionParserTests { given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any())) .willReturn(authorizationRequest); - OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build(); + OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build(); given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); OAuth2User oauth2User = TestOAuth2Users.create(); @@ -456,7 +456,7 @@ public class OAuth2LoginBeanDefinitionParserTests { given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any())) .willReturn(authorizationRequest); - OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build(); + OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build(); given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); OAuth2User oauth2User = TestOAuth2Users.create(); @@ -484,7 +484,7 @@ public class OAuth2LoginBeanDefinitionParserTests { given(this.authorizationRequestRepository.removeAuthorizationRequest(any(), any())) .willReturn(authorizationRequest); - OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().build(); + OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build(); given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); OAuth2User oauth2User = TestOAuth2Users.create(); diff --git a/config/src/test/java/org/springframework/security/config/http/OAuth2ResourceServerBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/http/OAuth2ResourceServerBeanDefinitionParserTests.java index c753c8d1a6..53b1dc8715 100644 --- a/config/src/test/java/org/springframework/security/config/http/OAuth2ResourceServerBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/http/OAuth2ResourceServerBeanDefinitionParserTests.java @@ -76,9 +76,11 @@ import org.springframework.security.oauth2.core.OAuth2TokenValidator; import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult; import org.springframework.security.oauth2.jose.TestKeys; import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.jwt.JwtClaimNames; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.jwt.JwtException; import org.springframework.security.oauth2.jwt.NimbusJwtDecoder; +import org.springframework.security.oauth2.jwt.TestJwts; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.security.oauth2.server.resource.introspection.NimbusOpaqueTokenIntrospector; import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector; @@ -96,23 +98,15 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.core.StringStartsWith.startsWith; +import static org.hamcrest.CoreMatchers.startsWith; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; 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.times; import static org.mockito.Mockito.verify; -import static org.powermock.api.mockito.PowerMockito.when; -import static org.springframework.security.config.http.OAuth2ResourceServerBeanDefinitionParser.AUTHENTICATION_MANAGER_RESOLVER_REF; -import static org.springframework.security.config.http.OAuth2ResourceServerBeanDefinitionParser.JwtBeanDefinitionParser.DECODER_REF; -import static org.springframework.security.config.http.OAuth2ResourceServerBeanDefinitionParser.JwtBeanDefinitionParser.JWK_SET_URI; -import static org.springframework.security.config.http.OAuth2ResourceServerBeanDefinitionParser.OpaqueTokenBeanDefinitionParser.INTROSPECTION_URI; -import static org.springframework.security.config.http.OAuth2ResourceServerBeanDefinitionParser.OpaqueTokenBeanDefinitionParser.INTROSPECTOR_REF; -import static org.springframework.security.oauth2.jwt.JwtClaimNames.ISS; -import static org.springframework.security.oauth2.jwt.JwtClaimNames.SUB; -import static org.springframework.security.oauth2.jwt.TestJwts.jwt; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -435,10 +429,10 @@ public class OAuth2ResourceServerBeanDefinitionParserTests { .autowire(); JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class); - when(decoder.decode("token")).thenReturn(jwt().build()); + given(decoder.decode("token")).willReturn(TestJwts.jwt().build()); BearerTokenResolver bearerTokenResolver = this.spring.getContext().getBean(BearerTokenResolver.class); - when(bearerTokenResolver.resolve(any(HttpServletRequest.class))).thenReturn("token"); + given(bearerTokenResolver.resolve(any(HttpServletRequest.class))).willReturn("token"); this.mvc.perform(get("/")).andExpect(status().isNotFound()); @@ -453,7 +447,7 @@ public class OAuth2ResourceServerBeanDefinitionParserTests { this.spring.configLocations(xml("MockJwtDecoder"), xml("AllowBearerTokenInBody")).autowire(); JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class); - when(decoder.decode(anyString())).thenReturn(jwt().build()); + given(decoder.decode(anyString())).willReturn(TestJwts.jwt().build()); this.mvc.perform(get("/authenticated").header("Authorization", "Bearer token")) .andExpect(status().isNotFound()); @@ -468,7 +462,7 @@ public class OAuth2ResourceServerBeanDefinitionParserTests { this.spring.configLocations(xml("MockJwtDecoder"), xml("AllowBearerTokenInQuery")).autowire(); JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class); - Mockito.when(decoder.decode(anyString())).thenReturn(jwt().build()); + given(decoder.decode(anyString())).willReturn(TestJwts.jwt().build()); this.mvc.perform(get("/authenticated").header("Authorization", "Bearer token")) .andExpect(status().isNotFound()); @@ -517,7 +511,7 @@ public class OAuth2ResourceServerBeanDefinitionParserTests { JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class); - when(decoder.decode(anyString())).thenReturn(jwt().build()); + given(decoder.decode(anyString())).willReturn(TestJwts.jwt().build()); this.mvc.perform(get("/authenticated").header("Authorization", "Bearer token")) .andExpect(status().isNotFound()); @@ -552,7 +546,7 @@ public class OAuth2ResourceServerBeanDefinitionParserTests { this.spring.configLocations(xml("MockJwtDecoder"), xml("AccessDeniedHandler")).autowire(); JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class); - Mockito.when(decoder.decode(anyString())).thenReturn(jwt().build()); + given(decoder.decode(anyString())).willReturn(TestJwts.jwt().build()); this.mvc.perform(get("/authenticated").header("Authorization", "Bearer insufficiently_scoped")) .andExpect(status().isForbidden()) @@ -572,7 +566,7 @@ public class OAuth2ResourceServerBeanDefinitionParserTests { OAuth2Error error = new OAuth2Error("custom-error", "custom-description", "custom-uri"); - when(jwtValidator.validate(any(Jwt.class))).thenReturn(OAuth2TokenValidatorResult.failure(error)); + given(jwtValidator.validate(any(Jwt.class))).willReturn(OAuth2TokenValidatorResult.failure(error)); this.mvc.perform(get("/").header("Authorization", "Bearer " + token)).andExpect(status().isUnauthorized()) .andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, containsString("custom-description"))); @@ -609,11 +603,11 @@ public class OAuth2ResourceServerBeanDefinitionParserTests { Converter jwtAuthenticationConverter = (Converter) this.spring .getContext().getBean("jwtAuthenticationConverter"); - when(jwtAuthenticationConverter.convert(any(Jwt.class))) - .thenReturn(new JwtAuthenticationToken(jwt().build(), Collections.emptyList())); + given(jwtAuthenticationConverter.convert(any(Jwt.class))) + .willReturn(new JwtAuthenticationToken(TestJwts.jwt().build(), Collections.emptyList())); JwtDecoder jwtDecoder = this.spring.getContext().getBean(JwtDecoder.class); - Mockito.when(jwtDecoder.decode(anyString())).thenReturn(jwt().build()); + given(jwtDecoder.decode(anyString())).willReturn(TestJwts.jwt().build()); this.mvc.perform(get("/").header("Authorization", "Bearer token")).andExpect(status().isNotFound()); @@ -702,8 +696,8 @@ public class OAuth2ResourceServerBeanDefinitionParserTests { AuthenticationManagerResolver authenticationManagerResolver = this.spring.getContext() .getBean(AuthenticationManagerResolver.class); - when(authenticationManagerResolver.resolve(any(HttpServletRequest.class))) - .thenReturn(authentication -> new JwtAuthenticationToken(jwt().build(), Collections.emptyList())); + given(authenticationManagerResolver.resolve(any(HttpServletRequest.class))).willReturn( + authentication -> new JwtAuthenticationToken(TestJwts.jwt().build(), Collections.emptyList())); this.mvc.perform(get("/").header("Authorization", "Bearer token")).andExpect(status().isNotFound()); @@ -754,7 +748,7 @@ public class OAuth2ResourceServerBeanDefinitionParserTests { this.spring.configLocations(xml("MockJwtDecoder"), xml("BasicAndResourceServer")).autowire(); JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class); - when(decoder.decode(anyString())).thenThrow(JwtException.class); + given(decoder.decode(anyString())).willThrow(JwtException.class); this.mvc.perform(get("/authenticated").with(httpBasic("some", "user"))).andExpect(status().isUnauthorized()) .andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, startsWith("Basic"))); @@ -775,7 +769,7 @@ public class OAuth2ResourceServerBeanDefinitionParserTests { this.spring.configLocations(xml("MockJwtDecoder"), xml("FormAndResourceServer")).autowire(); JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class); - when(decoder.decode(anyString())).thenThrow(JwtException.class); + given(decoder.decode(anyString())).willThrow(JwtException.class); MvcResult result = this.mvc.perform(get("/authenticated")).andExpect(status().isUnauthorized()).andReturn(); @@ -827,7 +821,8 @@ public class OAuth2ResourceServerBeanDefinitionParserTests { OAuth2ResourceServerBeanDefinitionParser parser = new OAuth2ResourceServerBeanDefinitionParser(null, null, null, null, null); Element element = mock(Element.class); - when(element.hasAttribute(AUTHENTICATION_MANAGER_RESOLVER_REF)).thenReturn(true); + given(element.hasAttribute(OAuth2ResourceServerBeanDefinitionParser.AUTHENTICATION_MANAGER_RESOLVER_REF)) + .willReturn(true); Element child = mock(Element.class); ParserContext pc = new ParserContext(mock(XmlReaderContext.class), mock(BeanDefinitionParserDelegate.class)); @@ -844,7 +839,8 @@ public class OAuth2ResourceServerBeanDefinitionParserTests { OAuth2ResourceServerBeanDefinitionParser parser = new OAuth2ResourceServerBeanDefinitionParser(null, null, null, null, null); Element element = mock(Element.class); - when(element.hasAttribute(AUTHENTICATION_MANAGER_RESOLVER_REF)).thenReturn(false); + given(element.hasAttribute(OAuth2ResourceServerBeanDefinitionParser.AUTHENTICATION_MANAGER_RESOLVER_REF)) + .willReturn(false); ParserContext pc = new ParserContext(mock(XmlReaderContext.class), mock(BeanDefinitionParserDelegate.class)); parser.validateConfiguration(element, null, null, pc); verify(pc.getReaderContext()).error(anyString(), eq(element)); @@ -854,8 +850,8 @@ public class OAuth2ResourceServerBeanDefinitionParserTests { public void validateConfigurationWhenBothJwtAttributesThenError() { JwtBeanDefinitionParser parser = new JwtBeanDefinitionParser(); Element element = mock(Element.class); - when(element.hasAttribute(JWK_SET_URI)).thenReturn(true); - when(element.hasAttribute(DECODER_REF)).thenReturn(true); + given(element.hasAttribute(JwtBeanDefinitionParser.JWK_SET_URI)).willReturn(true); + given(element.hasAttribute(JwtBeanDefinitionParser.DECODER_REF)).willReturn(true); ParserContext pc = new ParserContext(mock(XmlReaderContext.class), mock(BeanDefinitionParserDelegate.class)); parser.validateConfiguration(element, pc); verify(pc.getReaderContext()).error(anyString(), eq(element)); @@ -865,8 +861,8 @@ public class OAuth2ResourceServerBeanDefinitionParserTests { public void validateConfigurationWhenNoJwtAttributesThenError() { JwtBeanDefinitionParser parser = new JwtBeanDefinitionParser(); Element element = mock(Element.class); - when(element.hasAttribute(JWK_SET_URI)).thenReturn(false); - when(element.hasAttribute(DECODER_REF)).thenReturn(false); + given(element.hasAttribute(JwtBeanDefinitionParser.JWK_SET_URI)).willReturn(false); + given(element.hasAttribute(JwtBeanDefinitionParser.DECODER_REF)).willReturn(false); ParserContext pc = new ParserContext(mock(XmlReaderContext.class), mock(BeanDefinitionParserDelegate.class)); parser.validateConfiguration(element, pc); verify(pc.getReaderContext()).error(anyString(), eq(element)); @@ -876,8 +872,8 @@ public class OAuth2ResourceServerBeanDefinitionParserTests { public void validateConfigurationWhenBothOpaqueTokenModesThenError() { OpaqueTokenBeanDefinitionParser parser = new OpaqueTokenBeanDefinitionParser(); Element element = mock(Element.class); - when(element.hasAttribute(INTROSPECTION_URI)).thenReturn(true); - when(element.hasAttribute(INTROSPECTOR_REF)).thenReturn(true); + given(element.hasAttribute(OpaqueTokenBeanDefinitionParser.INTROSPECTION_URI)).willReturn(true); + given(element.hasAttribute(OpaqueTokenBeanDefinitionParser.INTROSPECTOR_REF)).willReturn(true); ParserContext pc = new ParserContext(mock(XmlReaderContext.class), mock(BeanDefinitionParserDelegate.class)); parser.validateConfiguration(element, pc); verify(pc.getReaderContext()).error(anyString(), eq(element)); @@ -887,8 +883,8 @@ public class OAuth2ResourceServerBeanDefinitionParserTests { public void validateConfigurationWhenNoOpaqueTokenModeThenError() { OpaqueTokenBeanDefinitionParser parser = new OpaqueTokenBeanDefinitionParser(); Element element = mock(Element.class); - when(element.hasAttribute(INTROSPECTION_URI)).thenReturn(false); - when(element.hasAttribute(INTROSPECTOR_REF)).thenReturn(false); + given(element.hasAttribute(OpaqueTokenBeanDefinitionParser.INTROSPECTION_URI)).willReturn(false); + given(element.hasAttribute(OpaqueTokenBeanDefinitionParser.INTROSPECTOR_REF)).willReturn(false); ParserContext pc = new ParserContext(mock(XmlReaderContext.class), mock(BeanDefinitionParserDelegate.class)); parser.validateConfiguration(element, pc); verify(pc.getReaderContext()).error(anyString(), eq(element)); @@ -920,8 +916,8 @@ public class OAuth2ResourceServerBeanDefinitionParserTests { private String jwtFromIssuer(String issuer) throws Exception { Map claims = new HashMap<>(); - claims.put(ISS, issuer); - claims.put(SUB, "test-subject"); + claims.put(JwtClaimNames.ISS, issuer); + claims.put(JwtClaimNames.SUB, "test-subject"); claims.put("scope", "message:read"); JWSObject jws = new JWSObject(new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("1").build(), new Payload(new JSONObject(claims))); @@ -939,7 +935,7 @@ public class OAuth2ResourceServerBeanDefinitionParserTests { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); ResponseEntity entity = new ResponseEntity<>(response, headers, HttpStatus.OK); - Mockito.when(rest.exchange(any(RequestEntity.class), eq(String.class))).thenReturn(entity); + given(rest.exchange(any(RequestEntity.class), eq(String.class))).willReturn(entity); } private String json(String name) throws IOException { diff --git a/config/src/test/java/org/springframework/security/config/http/OpenIDConfigTests.java b/config/src/test/java/org/springframework/security/config/http/OpenIDConfigTests.java index 04e92bdc43..f260d2efc6 100644 --- a/config/src/test/java/org/springframework/security/config/http/OpenIDConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/OpenIDConfigTests.java @@ -26,6 +26,7 @@ import okhttp3.mockwebserver.MockWebServer; import org.junit.Rule; import org.junit.Test; import org.openid4java.consumer.ConsumerManager; +import org.openid4java.discovery.yadis.YadisResolver; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.parsing.BeanDefinitionParsingException; @@ -48,7 +49,6 @@ 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.openid4java.discovery.yadis.YadisResolver.YADIS_XRDS_LOCATION; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; @@ -147,7 +147,7 @@ public class OpenIDConfigTests { try (MockWebServer server = new MockWebServer()) { String endpoint = server.url("/").toString(); - server.enqueue(new MockResponse().addHeader(YADIS_XRDS_LOCATION, endpoint)); + server.enqueue(new MockResponse().addHeader(YadisResolver.YADIS_XRDS_LOCATION, endpoint)); server.enqueue(new MockResponse() .setBody(String.format("%s", endpoint))); diff --git a/config/src/test/java/org/springframework/security/config/http/RememberMeConfigTests.java b/config/src/test/java/org/springframework/security/config/http/RememberMeConfigTests.java index ea8243372a..97203086dc 100644 --- a/config/src/test/java/org/springframework/security/config/http/RememberMeConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/RememberMeConfigTests.java @@ -30,6 +30,8 @@ import org.springframework.security.TestDataSource; import org.springframework.security.config.test.SpringTestRule; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices; +import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.ResultActions; @@ -43,9 +45,6 @@ import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.verify; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; -import static org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.DEFAULT_PARAMETER; -import static org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY; -import static org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl.CREATE_TABLE_SQL; 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.cookie; @@ -73,7 +72,8 @@ public class RememberMeConfigTests { this.spring.configLocations(this.xml("WithTokenRepository")).autowire(); MvcResult result = this.rememberAuthentication("user", "password") - .andExpect(cookie().secure(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, false)).andReturn(); + .andExpect(cookie().secure(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, false)) + .andReturn(); Cookie cookie = rememberMeCookie(result); @@ -91,10 +91,11 @@ public class RememberMeConfigTests { TestDataSource dataSource = this.spring.getContext().getBean(TestDataSource.class); JdbcTemplate template = new JdbcTemplate(dataSource); - template.execute(CREATE_TABLE_SQL); + template.execute(JdbcTokenRepositoryImpl.CREATE_TABLE_SQL); MvcResult result = this.rememberAuthentication("user", "password") - .andExpect(cookie().secure(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, false)).andReturn(); + .andExpect(cookie().secure(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, false)) + .andReturn(); Cookie cookie = rememberMeCookie(result); @@ -111,10 +112,11 @@ public class RememberMeConfigTests { TestDataSource dataSource = this.spring.getContext().getBean(TestDataSource.class); JdbcTemplate template = new JdbcTemplate(dataSource); - template.execute(CREATE_TABLE_SQL); + template.execute(JdbcTokenRepositoryImpl.CREATE_TABLE_SQL); MvcResult result = this.rememberAuthentication("user", "password") - .andExpect(cookie().secure(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, false)).andReturn(); + .andExpect(cookie().secure(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, false)) + .andReturn(); Cookie cookie = rememberMeCookie(result); @@ -130,8 +132,9 @@ public class RememberMeConfigTests { this.spring.configLocations(this.xml("WithServicesRef")).autowire(); MvcResult result = this.rememberAuthentication("user", "password") - .andExpect(cookie().secure(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, false)) - .andExpect(cookie().maxAge(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, 5000)).andReturn(); + .andExpect(cookie().secure(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, false)) + .andExpect(cookie().maxAge(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, 5000)) + .andReturn(); Cookie cookie = rememberMeCookie(result); @@ -139,7 +142,8 @@ public class RememberMeConfigTests { // SEC-909 this.mvc.perform(post("/logout").cookie(cookie).with(csrf())) - .andExpect(cookie().maxAge(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, 0)).andReturn(); + .andExpect(cookie().maxAge(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, 0)) + .andReturn(); } @Test @@ -152,7 +156,7 @@ public class RememberMeConfigTests { Cookie cookie = rememberMeCookie(result); this.mvc.perform(post("/logout").cookie(cookie).with(csrf())) - .andExpect(cookie().maxAge(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, 0)); + .andExpect(cookie().maxAge(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, 0)); } @Test @@ -162,7 +166,8 @@ public class RememberMeConfigTests { this.spring.configLocations(this.xml("TokenValidity")).autowire(); MvcResult result = this.rememberAuthentication("user", "password") - .andExpect(cookie().maxAge(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, 10000)).andReturn(); + .andExpect(cookie().maxAge(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, 10000)) + .andReturn(); Cookie cookie = rememberMeCookie(result); @@ -175,7 +180,7 @@ public class RememberMeConfigTests { this.spring.configLocations(this.xml("NegativeTokenValidity")).autowire(); this.rememberAuthentication("user", "password") - .andExpect(cookie().maxAge(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, -1)); + .andExpect(cookie().maxAge(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, -1)); } @Test @@ -191,7 +196,7 @@ public class RememberMeConfigTests { this.spring.configLocations(this.xml("Sec2165")).autowire(); this.rememberAuthentication("user", "password") - .andExpect(cookie().maxAge(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, 30)); + .andExpect(cookie().maxAge(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, 30)); } @Test @@ -200,7 +205,7 @@ public class RememberMeConfigTests { this.spring.configLocations(this.xml("SecureCookie")).autowire(); this.rememberAuthentication("user", "password") - .andExpect(cookie().secure(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, true)); + .andExpect(cookie().secure(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, true)); } /** @@ -212,7 +217,7 @@ public class RememberMeConfigTests { this.spring.configLocations(this.xml("Sec1827")).autowire(); this.rememberAuthentication("user", "password") - .andExpect(cookie().secure(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, false)); + .andExpect(cookie().secure(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, false)); } @Test @@ -304,7 +309,8 @@ public class RememberMeConfigTests { private ResultActions rememberAuthentication(String username, String password) throws Exception { - return this.mvc.perform(login(username, password).param(DEFAULT_PARAMETER, "true").with(csrf())) + return this.mvc.perform( + login(username, password).param(AbstractRememberMeServices.DEFAULT_PARAMETER, "true").with(csrf())) .andExpect(redirectedUrl("/")); } diff --git a/config/src/test/java/org/springframework/security/config/http/SecurityContextHolderAwareRequestConfigTests.java b/config/src/test/java/org/springframework/security/config/http/SecurityContextHolderAwareRequestConfigTests.java index d2f89090fc..20df7178b3 100644 --- a/config/src/test/java/org/springframework/security/config/http/SecurityContextHolderAwareRequestConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/SecurityContextHolderAwareRequestConfigTests.java @@ -39,7 +39,7 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.core.StringContains.containsString; +import static org.hamcrest.CoreMatchers.containsString; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.cookie; diff --git a/config/src/test/java/org/springframework/security/config/http/SessionManagementConfigServlet31Tests.java b/config/src/test/java/org/springframework/security/config/http/SessionManagementConfigServlet31Tests.java index 6fe90928bb..f7a43ff8a2 100644 --- a/config/src/test/java/org/springframework/security/config/http/SessionManagementConfigServlet31Tests.java +++ b/config/src/test/java/org/springframework/security/config/http/SessionManagementConfigServlet31Tests.java @@ -39,7 +39,7 @@ import org.springframework.security.web.context.HttpRequestResponseHolder; import org.springframework.security.web.context.HttpSessionSecurityContextRepository; import org.springframework.util.ReflectionUtils; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch diff --git a/config/src/test/java/org/springframework/security/config/http/SessionManagementConfigTests.java b/config/src/test/java/org/springframework/security/config/http/SessionManagementConfigTests.java index 00445262d6..1abb75a816 100644 --- a/config/src/test/java/org/springframework/security/config/http/SessionManagementConfigTests.java +++ b/config/src/test/java/org/springframework/security/config/http/SessionManagementConfigTests.java @@ -48,6 +48,7 @@ import org.springframework.security.web.authentication.logout.LogoutHandler; import org.springframework.security.web.authentication.logout.LogoutSuccessEventPublishingLogoutHandler; import org.springframework.security.web.authentication.session.SessionAuthenticationException; import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy; +import org.springframework.security.web.context.HttpSessionSecurityContextRepository; import org.springframework.security.web.session.ConcurrentSessionFilter; import org.springframework.security.web.session.SessionManagementFilter; import org.springframework.test.web.servlet.MockMvc; @@ -60,7 +61,6 @@ import org.springframework.web.context.WebApplicationContext; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; -import static org.springframework.security.web.context.HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY; 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.content; @@ -139,7 +139,8 @@ public class SessionManagementConfigTests { assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_MOVED_TEMPORARILY); assertThat(request.getSession(false)).isNotNull(); - assertThat(request.getSession(false).getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isNotNull(); + assertThat(request.getSession(false) + .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)).isNotNull(); } @Test @@ -169,7 +170,8 @@ public class SessionManagementConfigTests { .session(new MockHttpSession()).with(csrf())) .andExpect(status().isFound()).andExpect(session()).andReturn(); - assertThat(result.getRequest().getSession(false).getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isNull(); + assertThat(result.getRequest().getSession(false) + .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)).isNull(); } @Test diff --git a/config/src/test/java/org/springframework/security/config/http/customconfigurer/CustomHttpSecurityConfigurerTests.java b/config/src/test/java/org/springframework/security/config/http/customconfigurer/CustomHttpSecurityConfigurerTests.java index 8826baff99..9cf4508d7d 100644 --- a/config/src/test/java/org/springframework/security/config/http/customconfigurer/CustomHttpSecurityConfigurerTests.java +++ b/config/src/test/java/org/springframework/security/config/http/customconfigurer/CustomHttpSecurityConfigurerTests.java @@ -37,7 +37,6 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur import org.springframework.security.web.FilterChainProxy; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.config.http.customconfigurer.CustomConfigurer.customConfigurer; /** * @author Rob Winch @@ -126,7 +125,7 @@ public class CustomHttpSecurityConfigurerTests { protected void configure(HttpSecurity http) throws Exception { // @formatter:off http - .apply(customConfigurer()) + .apply(CustomConfigurer.customConfigurer()) .loginPage("/custom"); // @formatter:on } @@ -151,7 +150,7 @@ public class CustomHttpSecurityConfigurerTests { protected void configure(HttpSecurity http) throws Exception { // @formatter:off http - .apply(customConfigurer()) + .apply(CustomConfigurer.customConfigurer()) .and() .csrf().disable() .formLogin() diff --git a/config/src/test/java/org/springframework/security/config/method/GlobalMethodSecurityBeanDefinitionParserTests.java b/config/src/test/java/org/springframework/security/config/method/GlobalMethodSecurityBeanDefinitionParserTests.java index 880de2e9a7..579d47cb87 100644 --- a/config/src/test/java/org/springframework/security/config/method/GlobalMethodSecurityBeanDefinitionParserTests.java +++ b/config/src/test/java/org/springframework/security/config/method/GlobalMethodSecurityBeanDefinitionParserTests.java @@ -59,7 +59,6 @@ import org.springframework.security.util.FieldUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; -import static org.springframework.security.config.ConfigTestUtils.AUTH_PROVIDER_XML; /** * @author Ben Alex @@ -185,7 +184,8 @@ public class GlobalMethodSecurityBeanDefinitionParserTests { + "" + " " + "" + AUTH_PROVIDER_XML); + + " access='ROLE_USER'/>" + "" + + ConfigTestUtils.AUTH_PROVIDER_XML); this.target = (BusinessService) this.appContext.getBean("target"); // String method should not be protected this.target.someOther("somestring"); @@ -215,7 +215,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests { + "" + " " + " " - + "" + AUTH_PROVIDER_XML); + + "" + ConfigTestUtils.AUTH_PROVIDER_XML); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("Test", "Password", AuthorityUtils.createAuthorityList("ROLE_SOMEOTHERROLE")); @@ -229,7 +229,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests { @SuppressWarnings("unchecked") @Test public void expressionVoterAndAfterInvocationProviderUseSameExpressionHandlerInstance() throws Exception { - setContext("" + AUTH_PROVIDER_XML); + setContext("" + ConfigTestUtils.AUTH_PROVIDER_XML); AffirmativeBased adm = (AffirmativeBased) this.appContext.getBeansOfType(AffirmativeBased.class).values() .toArray()[0]; List voters = (List) FieldUtils.getFieldValue(adm, "decisionVoters"); @@ -247,7 +247,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests { public void accessIsDeniedForHasRoleExpression() { setContext("" + "" - + AUTH_PROVIDER_XML); + + ConfigTestUtils.AUTH_PROVIDER_XML); SecurityContextHolder.getContext().setAuthentication(this.bob); this.target = (BusinessService) this.appContext.getBean("target"); this.target.someAdminMethod(); @@ -259,7 +259,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests { + "" + " " + "" + "" - + AUTH_PROVIDER_XML); + + ConfigTestUtils.AUTH_PROVIDER_XML); SecurityContextHolder.getContext().setAuthentication(this.bob); ExpressionProtectedBusinessServiceImpl target = (ExpressionProtectedBusinessServiceImpl) this.appContext .getBean("target"); @@ -270,7 +270,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests { public void preAndPostFilterAnnotationsWorkWithLists() { setContext("" + "" - + AUTH_PROVIDER_XML); + + ConfigTestUtils.AUTH_PROVIDER_XML); SecurityContextHolder.getContext().setAuthentication(this.bob); this.target = (BusinessService) this.appContext.getBean("target"); List arg = new ArrayList<>(); @@ -289,7 +289,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests { public void prePostFilterAnnotationWorksWithArrays() { setContext("" + "" - + AUTH_PROVIDER_XML); + + ConfigTestUtils.AUTH_PROVIDER_XML); SecurityContextHolder.getContext().setAuthentication(this.bob); this.target = (BusinessService) this.appContext.getBean("target"); Object[] arg = new String[] { "joe", "bob", "sam" }; @@ -306,7 +306,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests { + "" + " " + "" + "" - + AUTH_PROVIDER_XML); + + ConfigTestUtils.AUTH_PROVIDER_XML); } // SEC-1450 @@ -317,7 +317,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests { "" + "" + " " - + "" + AUTH_PROVIDER_XML); + + "" + ConfigTestUtils.AUTH_PROVIDER_XML); Foo foo = (Foo) this.appContext.getBean("target"); foo.foo(new SecurityConfig("A")); } @@ -327,7 +327,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests { @SuppressWarnings("unchecked") public void genericsMethodArgumentNamesAreResolved() { setContext("" - + "" + AUTH_PROVIDER_XML); + + "" + ConfigTestUtils.AUTH_PROVIDER_XML); SecurityContextHolder.getContext().setAuthentication(this.bob); Foo foo = (Foo) this.appContext.getBean("target"); foo.foo(new SecurityConfig("A")); @@ -341,7 +341,8 @@ public class GlobalMethodSecurityBeanDefinitionParserTests { parent.registerSingleton("runAsMgr", RunAsManagerImpl.class, props); parent.refresh(); - setContext("" + AUTH_PROVIDER_XML, parent); + setContext("" + ConfigTestUtils.AUTH_PROVIDER_XML, + parent); RunAsManagerImpl ram = (RunAsManagerImpl) this.appContext.getBean("runAsMgr"); MethodSecurityMetadataSourceAdvisor msi = (MethodSecurityMetadataSourceAdvisor) this.appContext .getBeansOfType(MethodSecurityMetadataSourceAdvisor.class).values().toArray()[0]; @@ -355,7 +356,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests { + "" + " " + "" + "" - + AUTH_PROVIDER_XML); + + ConfigTestUtils.AUTH_PROVIDER_XML); // External MDS should take precedence over PreAuthorize SecurityContextHolder.getContext().setAuthentication(this.bob); Foo foo = (Foo) this.appContext.getBean("target"); @@ -377,7 +378,7 @@ public class GlobalMethodSecurityBeanDefinitionParserTests { + ".foo' access='ROLE_ADMIN'/>" + "" + "" + "" - + " " + "" + AUTH_PROVIDER_XML); + + " " + "" + ConfigTestUtils.AUTH_PROVIDER_XML); SecurityContextHolder.getContext().setAuthentication(this.bob); Foo foo = (Foo) this.appContext.getBean("target"); try { diff --git a/config/src/test/java/org/springframework/security/config/provisioning/UserDetailsManagerResourceFactoryBeanPropertiesResourceITests.java b/config/src/test/java/org/springframework/security/config/provisioning/UserDetailsManagerResourceFactoryBeanPropertiesResourceITests.java index b873becd89..4baab7a972 100644 --- a/config/src/test/java/org/springframework/security/config/provisioning/UserDetailsManagerResourceFactoryBeanPropertiesResourceITests.java +++ b/config/src/test/java/org/springframework/security/config/provisioning/UserDetailsManagerResourceFactoryBeanPropertiesResourceITests.java @@ -26,7 +26,7 @@ import org.springframework.security.provisioning.UserDetailsManager; import org.springframework.security.util.InMemoryResource; import org.springframework.test.context.junit4.SpringRunner; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch diff --git a/config/src/test/java/org/springframework/security/config/provisioning/UserDetailsManagerResourceFactoryBeanPropertiesResourceLocationITests.java b/config/src/test/java/org/springframework/security/config/provisioning/UserDetailsManagerResourceFactoryBeanPropertiesResourceLocationITests.java index 086a067fdf..d02a00723c 100644 --- a/config/src/test/java/org/springframework/security/config/provisioning/UserDetailsManagerResourceFactoryBeanPropertiesResourceLocationITests.java +++ b/config/src/test/java/org/springframework/security/config/provisioning/UserDetailsManagerResourceFactoryBeanPropertiesResourceLocationITests.java @@ -25,7 +25,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.security.provisioning.UserDetailsManager; import org.springframework.test.context.junit4.SpringRunner; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch diff --git a/config/src/test/java/org/springframework/security/config/provisioning/UserDetailsManagerResourceFactoryBeanStringITests.java b/config/src/test/java/org/springframework/security/config/provisioning/UserDetailsManagerResourceFactoryBeanStringITests.java index f42c35ff9e..cf85689257 100644 --- a/config/src/test/java/org/springframework/security/config/provisioning/UserDetailsManagerResourceFactoryBeanStringITests.java +++ b/config/src/test/java/org/springframework/security/config/provisioning/UserDetailsManagerResourceFactoryBeanStringITests.java @@ -25,7 +25,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.security.provisioning.UserDetailsManager; import org.springframework.test.context.junit4.SpringRunner; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch diff --git a/config/src/test/java/org/springframework/security/config/test/SpringTestContext.java b/config/src/test/java/org/springframework/security/config/test/SpringTestContext.java index e604008f56..d4f477eb25 100644 --- a/config/src/test/java/org/springframework/security/config/test/SpringTestContext.java +++ b/config/src/test/java/org/springframework/security/config/test/SpringTestContext.java @@ -28,6 +28,7 @@ import javax.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.security.config.util.InMemoryXmlWebApplicationContext; import org.springframework.test.context.web.GenericXmlWebContextLoader; import org.springframework.test.web.servlet.MockMvc; @@ -41,7 +42,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; /** @@ -129,7 +129,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()).build(); this.context.getBeanFactory().registerResolvableDependency(MockMvc.class, mockMvc); diff --git a/config/src/test/java/org/springframework/security/config/util/InMemoryXmlWebApplicationContext.java b/config/src/test/java/org/springframework/security/config/util/InMemoryXmlWebApplicationContext.java index 5ffae5ac04..8bcb27565a 100644 --- a/config/src/test/java/org/springframework/security/config/util/InMemoryXmlWebApplicationContext.java +++ b/config/src/test/java/org/springframework/security/config/util/InMemoryXmlWebApplicationContext.java @@ -23,10 +23,6 @@ import org.springframework.core.io.Resource; import org.springframework.security.util.InMemoryResource; import org.springframework.web.context.support.AbstractRefreshableWebApplicationContext; -import static org.springframework.security.config.util.InMemoryXmlApplicationContext.BEANS_CLOSE; -import static org.springframework.security.config.util.InMemoryXmlApplicationContext.BEANS_OPENING; -import static org.springframework.security.config.util.InMemoryXmlApplicationContext.SPRING_SECURITY_VERSION; - /** * @author Joe Grandja */ @@ -35,15 +31,16 @@ public class InMemoryXmlWebApplicationContext extends AbstractRefreshableWebAppl private Resource inMemoryXml; public InMemoryXmlWebApplicationContext(String xml) { - this(xml, SPRING_SECURITY_VERSION, null); + this(xml, InMemoryXmlApplicationContext.SPRING_SECURITY_VERSION, null); } public InMemoryXmlWebApplicationContext(String xml, ApplicationContext parent) { - this(xml, SPRING_SECURITY_VERSION, parent); + this(xml, InMemoryXmlApplicationContext.SPRING_SECURITY_VERSION, parent); } public InMemoryXmlWebApplicationContext(String xml, String secVersion, ApplicationContext parent) { - String fullXml = BEANS_OPENING + secVersion + ".xsd'>\n" + xml + BEANS_CLOSE; + String fullXml = InMemoryXmlApplicationContext.BEANS_OPENING + secVersion + ".xsd'>\n" + xml + + InMemoryXmlApplicationContext.BEANS_CLOSE; this.inMemoryXml = new InMemoryResource(fullXml); setAllowBeanDefinitionOverriding(true); setParent(parent); diff --git a/config/src/test/java/org/springframework/security/config/web/server/CorsSpecTests.java b/config/src/test/java/org/springframework/security/config/web/server/CorsSpecTests.java index 6407d13d9a..9bec73e8bd 100644 --- a/config/src/test/java/org/springframework/security/config/web/server/CorsSpecTests.java +++ b/config/src/test/java/org/springframework/security/config/web/server/CorsSpecTests.java @@ -37,7 +37,7 @@ import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.reactive.CorsConfigurationSource; -import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; diff --git a/config/src/test/java/org/springframework/security/config/web/server/HeaderSpecTests.java b/config/src/test/java/org/springframework/security/config/web/server/HeaderSpecTests.java index 20091cc7d8..5608941875 100644 --- a/config/src/test/java/org/springframework/security/config/web/server/HeaderSpecTests.java +++ b/config/src/test/java/org/springframework/security/config/web/server/HeaderSpecTests.java @@ -39,7 +39,7 @@ import org.springframework.security.web.server.header.XXssProtectionServerHttpHe import org.springframework.test.web.reactive.server.FluxExchangeResult; import org.springframework.test.web.reactive.server.WebTestClient; -import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.security.config.Customizer.withDefaults; /** diff --git a/config/src/test/java/org/springframework/security/config/web/server/OAuth2LoginTests.java b/config/src/test/java/org/springframework/security/config/web/server/OAuth2LoginTests.java index 71703fa63d..428739a1af 100644 --- a/config/src/test/java/org/springframework/security/config/web/server/OAuth2LoginTests.java +++ b/config/src/test/java/org/springframework/security/config/web/server/OAuth2LoginTests.java @@ -80,6 +80,7 @@ import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.JwtValidationException; import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder; import org.springframework.security.oauth2.jwt.ReactiveJwtDecoderFactory; +import org.springframework.security.oauth2.jwt.TestJwts; import org.springframework.security.test.web.reactive.server.WebTestClientBuilder; import org.springframework.security.web.server.SecurityWebFilterChain; import org.springframework.security.web.server.WebFilterChainProxy; @@ -108,7 +109,6 @@ 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.springframework.security.oauth2.jwt.TestJwts.jwt; /** * @author Rob Winch @@ -680,7 +680,7 @@ public class OAuth2LoginTests { claims.put(IdTokenClaimNames.ISS, "http://localhost/issuer"); claims.put(IdTokenClaimNames.AUD, Collections.singletonList("client")); claims.put(IdTokenClaimNames.AZP, "client"); - Jwt jwt = jwt().claims(c -> c.putAll(claims)).build(); + Jwt jwt = TestJwts.jwt().claims(c -> c.putAll(claims)).build(); return Mono.just(jwt); }; } diff --git a/config/src/test/java/org/springframework/security/config/web/server/OAuth2ResourceServerSpecTests.java b/config/src/test/java/org/springframework/security/config/web/server/OAuth2ResourceServerSpecTests.java index 2367e23eb8..eb4940ca2d 100644 --- a/config/src/test/java/org/springframework/security/config/web/server/OAuth2ResourceServerSpecTests.java +++ b/config/src/test/java/org/springframework/security/config/web/server/OAuth2ResourceServerSpecTests.java @@ -61,6 +61,7 @@ import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.core.OAuth2Error; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder; +import org.springframework.security.oauth2.jwt.TestJwts; import org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; import org.springframework.security.oauth2.server.resource.authentication.ReactiveJwtAuthenticationConverterAdapter; @@ -80,13 +81,12 @@ import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; -import static org.hamcrest.core.StringStartsWith.startsWith; +import static org.hamcrest.CoreMatchers.startsWith; 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.springframework.security.oauth2.jwt.TestJwts.jwt; /** * Tests for @@ -108,7 +108,7 @@ public class OAuth2ResourceServerSpecTests { + " \"n\":\"0IUjrPZDz-3z0UE4ppcKU36v7hnh8FJjhu3lbJYj0qj9eZiwEJxi9HHUfSK1DhUQG7mJBbYTK1tPYCgre5EkfKh-64VhYUa-vz17zYCmuB8fFj4XHE3MLkWIG-AUn8hNbPzYYmiBTjfGnMKxLHjsbdTiF4mtn-85w366916R6midnAuiPD4HjZaZ1PAsuY60gr8bhMEDtJ8unz81hoQrozpBZJ6r8aR1PrsWb1OqPMloK9kAIutJNvWYKacp8WYAp2WWy72PxQ7Fb0eIA1br3A5dnp-Cln6JROJcZUIRJ-QvS6QONWeS2407uQmS-i-lybsqaH0ldYC7NBEBA5inPQ\"\n" + " }\n" + " ]\n" + "}\n"; - private Jwt jwt = jwt().build(); + private Jwt jwt = TestJwts.jwt().build(); private String clientId = "client"; diff --git a/config/src/test/java/org/springframework/security/config/web/server/ServerHttpSecurityTests.java b/config/src/test/java/org/springframework/security/config/web/server/ServerHttpSecurityTests.java index 425c8b7c84..44fe067da9 100644 --- a/config/src/test/java/org/springframework/security/config/web/server/ServerHttpSecurityTests.java +++ b/config/src/test/java/org/springframework/security/config/web/server/ServerHttpSecurityTests.java @@ -61,6 +61,7 @@ import org.springframework.security.web.server.csrf.CsrfWebFilter; import org.springframework.security.web.server.csrf.ServerCsrfTokenRepository; import org.springframework.security.web.server.savedrequest.ServerRequestCache; import org.springframework.security.web.server.savedrequest.WebSessionServerRequestCache; +import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.reactive.server.EntityExchangeResult; import org.springframework.test.web.reactive.server.FluxExchangeResult; import org.springframework.test.web.reactive.server.WebTestClient; @@ -78,7 +79,6 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.springframework.security.config.Customizer.withDefaults; -import static org.springframework.test.util.ReflectionTestUtils.getField; /** * @author Rob Winch @@ -187,8 +187,8 @@ public class ServerHttpSecurityTests { assertThat(getWebFilter(securityWebFilterChain, CsrfWebFilter.class)).isNotPresent(); Optional logoutHandler = getWebFilter(securityWebFilterChain, LogoutWebFilter.class) - .map(logoutWebFilter -> (ServerLogoutHandler) getField(logoutWebFilter, LogoutWebFilter.class, - "logoutHandler")); + .map(logoutWebFilter -> (ServerLogoutHandler) ReflectionTestUtils.getField(logoutWebFilter, + LogoutWebFilter.class, "logoutHandler")); assertThat(logoutHandler).get().isExactlyInstanceOf(SecurityContextServerLogoutHandler.class); } @@ -199,17 +199,17 @@ public class ServerHttpSecurityTests { .and().build(); assertThat(getWebFilter(securityWebFilterChain, CsrfWebFilter.class)).get() - .extracting(csrfWebFilter -> getField(csrfWebFilter, "csrfTokenRepository")) + .extracting(csrfWebFilter -> ReflectionTestUtils.getField(csrfWebFilter, "csrfTokenRepository")) .isEqualTo(this.csrfTokenRepository); Optional logoutHandler = getWebFilter(securityWebFilterChain, LogoutWebFilter.class) - .map(logoutWebFilter -> (ServerLogoutHandler) getField(logoutWebFilter, LogoutWebFilter.class, - "logoutHandler")); + .map(logoutWebFilter -> (ServerLogoutHandler) ReflectionTestUtils.getField(logoutWebFilter, + LogoutWebFilter.class, "logoutHandler")); assertThat(logoutHandler).get().isExactlyInstanceOf(DelegatingServerLogoutHandler.class) - .extracting(delegatingLogoutHandler -> ((List) getField(delegatingLogoutHandler, - DelegatingServerLogoutHandler.class, "delegates")).stream().map(ServerLogoutHandler::getClass) - .collect(Collectors.toList())) + .extracting(delegatingLogoutHandler -> ((List) ReflectionTestUtils + .getField(delegatingLogoutHandler, DelegatingServerLogoutHandler.class, "delegates")).stream() + .map(ServerLogoutHandler::getClass).collect(Collectors.toList())) .isEqualTo(Arrays.asList(SecurityContextServerLogoutHandler.class, CsrfServerLogoutHandler.class)); } @@ -439,8 +439,8 @@ public class ServerHttpSecurityTests { OAuth2LoginAuthenticationWebFilter authenticationWebFilter = getWebFilter(securityFilterChain, OAuth2LoginAuthenticationWebFilter.class).get(); - Object handler = getField(authenticationWebFilter, "authenticationSuccessHandler"); - assertThat(getField(handler, "requestCache")).isSameAs(requestCache); + Object handler = ReflectionTestUtils.getField(authenticationWebFilter, "authenticationSuccessHandler"); + assertThat(ReflectionTestUtils.getField(handler, "requestCache")).isSameAs(requestCache); } @Test @@ -467,7 +467,7 @@ public class ServerHttpSecurityTests { private boolean isX509Filter(WebFilter filter) { try { - Object converter = getField(filter, "authenticationConverter"); + Object converter = ReflectionTestUtils.getField(filter, "authenticationConverter"); return converter.getClass().isAssignableFrom(ServerX509AuthenticationConverter.class); } catch (IllegalArgumentException e) { diff --git a/core/src/test/java/org/springframework/security/access/hierarchicalroles/RoleHierarchyUtilsTests.java b/core/src/test/java/org/springframework/security/access/hierarchicalroles/RoleHierarchyUtilsTests.java index 64543a3242..d9d7a9e6b3 100644 --- a/core/src/test/java/org/springframework/security/access/hierarchicalroles/RoleHierarchyUtilsTests.java +++ b/core/src/test/java/org/springframework/security/access/hierarchicalroles/RoleHierarchyUtilsTests.java @@ -15,6 +15,7 @@ */ package org.springframework.security.access.hierarchicalroles; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -23,7 +24,6 @@ import java.util.TreeMap; import org.junit.Test; -import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; /** @@ -45,9 +45,9 @@ public class RoleHierarchyUtilsTests { // @formatter:on Map> roleHierarchyMap = new TreeMap<>(); - roleHierarchyMap.put("ROLE_A", asList("ROLE_B", "ROLE_C")); - roleHierarchyMap.put("ROLE_B", asList("ROLE_D")); - roleHierarchyMap.put("ROLE_C", asList("ROLE_D")); + roleHierarchyMap.put("ROLE_A", Arrays.asList("ROLE_B", "ROLE_C")); + roleHierarchyMap.put("ROLE_B", Arrays.asList("ROLE_D")); + roleHierarchyMap.put("ROLE_C", Arrays.asList("ROLE_D")); String roleHierarchy = RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap); @@ -67,7 +67,7 @@ public class RoleHierarchyUtilsTests { @Test(expected = IllegalArgumentException.class) public void roleHierarchyFromMapWhenRoleNullThenThrowsIllegalArgumentException() { Map> roleHierarchyMap = new HashMap<>(); - roleHierarchyMap.put(null, asList("ROLE_B", "ROLE_C")); + roleHierarchyMap.put(null, Arrays.asList("ROLE_B", "ROLE_C")); RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap); } @@ -75,7 +75,7 @@ public class RoleHierarchyUtilsTests { @Test(expected = IllegalArgumentException.class) public void roleHierarchyFromMapWhenRoleEmptyThenThrowsIllegalArgumentException() { Map> roleHierarchyMap = new HashMap<>(); - roleHierarchyMap.put("", asList("ROLE_B", "ROLE_C")); + roleHierarchyMap.put("", Arrays.asList("ROLE_B", "ROLE_C")); RoleHierarchyUtils.roleHierarchyFromMap(roleHierarchyMap); } diff --git a/core/src/test/java/org/springframework/security/concurrent/AbstractDelegatingSecurityContextScheduledExecutorServiceTests.java b/core/src/test/java/org/springframework/security/concurrent/AbstractDelegatingSecurityContextScheduledExecutorServiceTests.java index 62de21e806..166a021508 100644 --- a/core/src/test/java/org/springframework/security/concurrent/AbstractDelegatingSecurityContextScheduledExecutorServiceTests.java +++ b/core/src/test/java/org/springframework/security/concurrent/AbstractDelegatingSecurityContextScheduledExecutorServiceTests.java @@ -22,7 +22,7 @@ import org.junit.Before; import org.junit.Test; import org.mockito.Mock; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; @@ -55,7 +55,7 @@ public abstract class AbstractDelegatingSecurityContextScheduledExecutorServiceT given((ScheduledFuture) this.delegate.schedule(this.wrappedRunnable, 1, TimeUnit.SECONDS)) .willReturn(this.expectedResult); ScheduledFuture result = this.executor.schedule(this.runnable, 1, TimeUnit.SECONDS); - assertThat(result).isEqualTo(this.expectedResult); + assertThat((Object) result).isEqualTo(this.expectedResult); verify(this.delegate).schedule(this.wrappedRunnable, 1, TimeUnit.SECONDS); } @@ -63,7 +63,7 @@ public abstract class AbstractDelegatingSecurityContextScheduledExecutorServiceT public void scheduleCallable() { given(this.delegate.schedule(this.wrappedCallable, 1, TimeUnit.SECONDS)).willReturn(this.expectedResult); ScheduledFuture result = this.executor.schedule(this.callable, 1, TimeUnit.SECONDS); - assertThat(result).isEqualTo(this.expectedResult); + assertThat((Object) result).isEqualTo(this.expectedResult); verify(this.delegate).schedule(this.wrappedCallable, 1, TimeUnit.SECONDS); } @@ -73,7 +73,7 @@ public abstract class AbstractDelegatingSecurityContextScheduledExecutorServiceT given((ScheduledFuture) this.delegate.scheduleAtFixedRate(this.wrappedRunnable, 1, 2, TimeUnit.SECONDS)) .willReturn(this.expectedResult); ScheduledFuture result = this.executor.scheduleAtFixedRate(this.runnable, 1, 2, TimeUnit.SECONDS); - assertThat(result).isEqualTo(this.expectedResult); + assertThat((Object) result).isEqualTo(this.expectedResult); verify(this.delegate).scheduleAtFixedRate(this.wrappedRunnable, 1, 2, TimeUnit.SECONDS); } @@ -83,7 +83,7 @@ public abstract class AbstractDelegatingSecurityContextScheduledExecutorServiceT given((ScheduledFuture) this.delegate.scheduleWithFixedDelay(this.wrappedRunnable, 1, 2, TimeUnit.SECONDS)).willReturn(this.expectedResult); ScheduledFuture result = this.executor.scheduleWithFixedDelay(this.runnable, 1, 2, TimeUnit.SECONDS); - assertThat(result).isEqualTo(this.expectedResult); + assertThat((Object) result).isEqualTo(this.expectedResult); verify(this.delegate).scheduleWithFixedDelay(this.wrappedRunnable, 1, 2, TimeUnit.SECONDS); } diff --git a/core/src/test/java/org/springframework/security/concurrent/AbstractDelegatingSecurityContextTestSupport.java b/core/src/test/java/org/springframework/security/concurrent/AbstractDelegatingSecurityContextTestSupport.java index c5bf4e56cc..1ab51e3220 100644 --- a/core/src/test/java/org/springframework/security/concurrent/AbstractDelegatingSecurityContextTestSupport.java +++ b/core/src/test/java/org/springframework/security/concurrent/AbstractDelegatingSecurityContextTestSupport.java @@ -23,6 +23,7 @@ import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; +import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @@ -30,8 +31,6 @@ import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import static org.mockito.ArgumentMatchers.eq; -import static org.powermock.api.mockito.PowerMockito.doReturn; -import static org.powermock.api.mockito.PowerMockito.spy; /** * Abstract base class for testing classes that extend @@ -67,19 +66,21 @@ public abstract class AbstractDelegatingSecurityContextTestSupport { protected Runnable wrappedRunnable; public final void explicitSecurityContextPowermockSetup() throws Exception { - spy(DelegatingSecurityContextCallable.class); - doReturn(this.wrappedCallable).when(DelegatingSecurityContextCallable.class, "create", eq(this.callable), - this.securityContextCaptor.capture()); - spy(DelegatingSecurityContextRunnable.class); - doReturn(this.wrappedRunnable).when(DelegatingSecurityContextRunnable.class, "create", eq(this.runnable), - this.securityContextCaptor.capture()); + PowerMockito.spy(DelegatingSecurityContextCallable.class); + PowerMockito.doReturn(this.wrappedCallable).when(DelegatingSecurityContextCallable.class, "create", + eq(this.callable), this.securityContextCaptor.capture()); + PowerMockito.spy(DelegatingSecurityContextRunnable.class); + PowerMockito.doReturn(this.wrappedRunnable).when(DelegatingSecurityContextRunnable.class, "create", + eq(this.runnable), this.securityContextCaptor.capture()); } public final void currentSecurityContextPowermockSetup() throws Exception { - spy(DelegatingSecurityContextCallable.class); - doReturn(this.wrappedCallable).when(DelegatingSecurityContextCallable.class, "create", this.callable, null); - spy(DelegatingSecurityContextRunnable.class); - doReturn(this.wrappedRunnable).when(DelegatingSecurityContextRunnable.class, "create", this.runnable, null); + PowerMockito.spy(DelegatingSecurityContextCallable.class); + PowerMockito.doReturn(this.wrappedCallable).when(DelegatingSecurityContextCallable.class, "create", + this.callable, null); + PowerMockito.spy(DelegatingSecurityContextRunnable.class); + PowerMockito.doReturn(this.wrappedRunnable).when(DelegatingSecurityContextRunnable.class, "create", + this.runnable, null); } @Before diff --git a/core/src/test/java/org/springframework/security/core/SpringSecurityCoreVersionTests.java b/core/src/test/java/org/springframework/security/core/SpringSecurityCoreVersionTests.java index e743fb1212..7b77032d7f 100644 --- a/core/src/test/java/org/springframework/security/core/SpringSecurityCoreVersionTests.java +++ b/core/src/test/java/org/springframework/security/core/SpringSecurityCoreVersionTests.java @@ -21,6 +21,7 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; +import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; @@ -33,8 +34,6 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; -import static org.powermock.api.mockito.PowerMockito.doReturn; -import static org.powermock.api.mockito.PowerMockito.spy; /** * Checks that the embedded version information is up to date. @@ -83,10 +82,10 @@ public class SpringSecurityCoreVersionTests { @Test public void noLoggingIfVersionsAreEqual() throws Exception { String version = "1"; - spy(SpringSecurityCoreVersion.class); - spy(SpringVersion.class); - doReturn(version).when(SpringSecurityCoreVersion.class, "getVersion"); - doReturn(version).when(SpringVersion.class, "getVersion"); + PowerMockito.spy(SpringSecurityCoreVersion.class); + PowerMockito.spy(SpringVersion.class); + PowerMockito.doReturn(version).when(SpringSecurityCoreVersion.class, "getVersion"); + PowerMockito.doReturn(version).when(SpringVersion.class, "getVersion"); performChecks(); @@ -95,10 +94,10 @@ public class SpringSecurityCoreVersionTests { @Test public void noLoggingIfSpringVersionNull() throws Exception { - spy(SpringSecurityCoreVersion.class); - spy(SpringVersion.class); - doReturn("1").when(SpringSecurityCoreVersion.class, "getVersion"); - doReturn(null).when(SpringVersion.class, "getVersion"); + PowerMockito.spy(SpringSecurityCoreVersion.class); + PowerMockito.spy(SpringVersion.class); + PowerMockito.doReturn("1").when(SpringSecurityCoreVersion.class, "getVersion"); + PowerMockito.doReturn(null).when(SpringVersion.class, "getVersion"); performChecks(); @@ -107,10 +106,10 @@ public class SpringSecurityCoreVersionTests { @Test public void warnIfSpringVersionTooSmall() throws Exception { - spy(SpringSecurityCoreVersion.class); - spy(SpringVersion.class); - doReturn("3").when(SpringSecurityCoreVersion.class, "getVersion"); - doReturn("2").when(SpringVersion.class, "getVersion"); + PowerMockito.spy(SpringSecurityCoreVersion.class); + PowerMockito.spy(SpringVersion.class); + PowerMockito.doReturn("3").when(SpringSecurityCoreVersion.class, "getVersion"); + PowerMockito.doReturn("2").when(SpringVersion.class, "getVersion"); performChecks(); @@ -119,10 +118,10 @@ public class SpringSecurityCoreVersionTests { @Test public void noWarnIfSpringVersionLarger() throws Exception { - spy(SpringSecurityCoreVersion.class); - spy(SpringVersion.class); - doReturn("4.0.0.RELEASE").when(SpringSecurityCoreVersion.class, "getVersion"); - doReturn("4.0.0.RELEASE").when(SpringVersion.class, "getVersion"); + PowerMockito.spy(SpringSecurityCoreVersion.class); + PowerMockito.spy(SpringVersion.class); + PowerMockito.doReturn("4.0.0.RELEASE").when(SpringSecurityCoreVersion.class, "getVersion"); + PowerMockito.doReturn("4.0.0.RELEASE").when(SpringVersion.class, "getVersion"); performChecks(); @@ -133,10 +132,10 @@ public class SpringSecurityCoreVersionTests { @Test public void noWarnIfSpringPatchVersionDoubleDigits() throws Exception { String minSpringVersion = "3.2.8.RELEASE"; - spy(SpringSecurityCoreVersion.class); - spy(SpringVersion.class); - doReturn("3.2.0.RELEASE").when(SpringSecurityCoreVersion.class, "getVersion"); - doReturn("3.2.10.RELEASE").when(SpringVersion.class, "getVersion"); + PowerMockito.spy(SpringSecurityCoreVersion.class); + PowerMockito.spy(SpringVersion.class); + PowerMockito.doReturn("3.2.0.RELEASE").when(SpringSecurityCoreVersion.class, "getVersion"); + PowerMockito.doReturn("3.2.10.RELEASE").when(SpringVersion.class, "getVersion"); performChecks(minSpringVersion); @@ -145,10 +144,10 @@ public class SpringSecurityCoreVersionTests { @Test public void noLoggingIfPropertySet() throws Exception { - spy(SpringSecurityCoreVersion.class); - spy(SpringVersion.class); - doReturn("3").when(SpringSecurityCoreVersion.class, "getVersion"); - doReturn("2").when(SpringVersion.class, "getVersion"); + PowerMockito.spy(SpringSecurityCoreVersion.class); + PowerMockito.spy(SpringVersion.class); + PowerMockito.doReturn("3").when(SpringSecurityCoreVersion.class, "getVersion"); + PowerMockito.doReturn("2").when(SpringVersion.class, "getVersion"); System.setProperty(getDisableChecksProperty(), Boolean.TRUE.toString()); performChecks(); diff --git a/core/src/test/java/org/springframework/security/jackson2/UsernamePasswordAuthenticationTokenMixinTests.java b/core/src/test/java/org/springframework/security/jackson2/UsernamePasswordAuthenticationTokenMixinTests.java index 0741c926be..130c9ea0ab 100644 --- a/core/src/test/java/org/springframework/security/jackson2/UsernamePasswordAuthenticationTokenMixinTests.java +++ b/core/src/test/java/org/springframework/security/jackson2/UsernamePasswordAuthenticationTokenMixinTests.java @@ -20,6 +20,8 @@ import java.io.IOException; import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonClassDescription; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonInclude.Value; import com.fasterxml.jackson.core.JsonProcessingException; import org.json.JSONException; import org.junit.Test; @@ -29,10 +31,6 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; -import static com.fasterxml.jackson.annotation.JsonInclude.Include.ALWAYS; -import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_ABSENT; -import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; -import static com.fasterxml.jackson.annotation.JsonInclude.Value.construct; import static org.assertj.core.api.Assertions.assertThat; /** @@ -181,7 +179,8 @@ public class UsernamePasswordAuthenticationTokenMixinTests extends AbstractMixin @Test public void serializingThenDeserializingWithConfiguredObjectMapperShouldWork() throws IOException { - this.mapper.setDefaultPropertyInclusion(construct(ALWAYS, NON_NULL)).setSerializationInclusion(NON_ABSENT); + this.mapper.setDefaultPropertyInclusion(Value.construct(Include.ALWAYS, Include.NON_NULL)) + .setSerializationInclusion(Include.NON_ABSENT); UsernamePasswordAuthenticationToken original = new UsernamePasswordAuthenticationToken("Frodo", null); String serialized = this.mapper.writeValueAsString(original); UsernamePasswordAuthenticationToken deserialized = this.mapper.readValue(serialized, diff --git a/crypto/src/main/java/org/springframework/security/crypto/encrypt/AesBytesEncryptor.java b/crypto/src/main/java/org/springframework/security/crypto/encrypt/AesBytesEncryptor.java index 9a8f517371..85e5478814 100644 --- a/crypto/src/main/java/org/springframework/security/crypto/encrypt/AesBytesEncryptor.java +++ b/crypto/src/main/java/org/springframework/security/crypto/encrypt/AesBytesEncryptor.java @@ -27,13 +27,7 @@ import javax.crypto.spec.SecretKeySpec; import org.springframework.security.crypto.codec.Hex; import org.springframework.security.crypto.keygen.BytesKeyGenerator; import org.springframework.security.crypto.keygen.KeyGenerators; - -import static org.springframework.security.crypto.encrypt.CipherUtils.doFinal; -import static org.springframework.security.crypto.encrypt.CipherUtils.initCipher; -import static org.springframework.security.crypto.encrypt.CipherUtils.newCipher; -import static org.springframework.security.crypto.encrypt.CipherUtils.newSecretKey; -import static org.springframework.security.crypto.util.EncodingUtils.concatenate; -import static org.springframework.security.crypto.util.EncodingUtils.subArray; +import org.springframework.security.crypto.util.EncodingUtils; /** * Encryptor that uses AES encryption. @@ -80,7 +74,7 @@ public final class AesBytesEncryptor implements BytesEncryptor { } public Cipher createCipher() { - return newCipher(this.toString()); + return CipherUtils.newCipher(this.toString()); } public BytesKeyGenerator defaultIvGenerator() { @@ -98,8 +92,8 @@ public final class AesBytesEncryptor implements BytesEncryptor { } public AesBytesEncryptor(String password, CharSequence salt, BytesKeyGenerator ivGenerator, CipherAlgorithm alg) { - this(newSecretKey("PBKDF2WithHmacSHA1", new PBEKeySpec(password.toCharArray(), Hex.decode(salt), 1024, 256)), - ivGenerator, alg); + this(CipherUtils.newSecretKey("PBKDF2WithHmacSHA1", + new PBEKeySpec(password.toCharArray(), Hex.decode(salt), 1024, 256)), ivGenerator, alg); } /** @@ -122,9 +116,9 @@ public final class AesBytesEncryptor implements BytesEncryptor { public byte[] encrypt(byte[] bytes) { synchronized (this.encryptor) { byte[] iv = this.ivGenerator.generateKey(); - initCipher(this.encryptor, Cipher.ENCRYPT_MODE, this.secretKey, this.alg.getParameterSpec(iv)); - byte[] encrypted = doFinal(this.encryptor, bytes); - return this.ivGenerator != NULL_IV_GENERATOR ? concatenate(iv, encrypted) : encrypted; + CipherUtils.initCipher(this.encryptor, Cipher.ENCRYPT_MODE, this.secretKey, this.alg.getParameterSpec(iv)); + byte[] encrypted = CipherUtils.doFinal(this.encryptor, bytes); + return this.ivGenerator != NULL_IV_GENERATOR ? EncodingUtils.concatenate(iv, encrypted) : encrypted; } } @@ -132,8 +126,8 @@ public final class AesBytesEncryptor implements BytesEncryptor { public byte[] decrypt(byte[] encryptedBytes) { synchronized (this.decryptor) { byte[] iv = iv(encryptedBytes); - initCipher(this.decryptor, Cipher.DECRYPT_MODE, this.secretKey, this.alg.getParameterSpec(iv)); - return doFinal(this.decryptor, + CipherUtils.initCipher(this.decryptor, Cipher.DECRYPT_MODE, this.secretKey, this.alg.getParameterSpec(iv)); + return CipherUtils.doFinal(this.decryptor, this.ivGenerator != NULL_IV_GENERATOR ? encrypted(encryptedBytes, iv.length) : encryptedBytes); } } @@ -141,12 +135,13 @@ public final class AesBytesEncryptor implements BytesEncryptor { // internal helpers private byte[] iv(byte[] encrypted) { - return this.ivGenerator != NULL_IV_GENERATOR ? subArray(encrypted, 0, this.ivGenerator.getKeyLength()) + return this.ivGenerator != NULL_IV_GENERATOR + ? EncodingUtils.subArray(encrypted, 0, this.ivGenerator.getKeyLength()) : NULL_IV_GENERATOR.generateKey(); } private byte[] encrypted(byte[] encryptedBytes, int ivLength) { - return subArray(encryptedBytes, ivLength, encryptedBytes.length); + return EncodingUtils.subArray(encryptedBytes, ivLength, encryptedBytes.length); } private static final BytesKeyGenerator NULL_IV_GENERATOR = new BytesKeyGenerator() { diff --git a/crypto/src/main/java/org/springframework/security/crypto/encrypt/BouncyCastleAesCbcBytesEncryptor.java b/crypto/src/main/java/org/springframework/security/crypto/encrypt/BouncyCastleAesCbcBytesEncryptor.java index 4ddcd5684a..62b51b2afe 100644 --- a/crypto/src/main/java/org/springframework/security/crypto/encrypt/BouncyCastleAesCbcBytesEncryptor.java +++ b/crypto/src/main/java/org/springframework/security/crypto/encrypt/BouncyCastleAesCbcBytesEncryptor.java @@ -24,9 +24,7 @@ import org.bouncycastle.crypto.params.ParametersWithIV; import org.springframework.security.crypto.encrypt.AesBytesEncryptor.CipherAlgorithm; import org.springframework.security.crypto.keygen.BytesKeyGenerator; - -import static org.springframework.security.crypto.util.EncodingUtils.concatenate; -import static org.springframework.security.crypto.util.EncodingUtils.subArray; +import org.springframework.security.crypto.util.EncodingUtils; /** * An Encryptor equivalent to {@link AesBytesEncryptor} using {@link CipherAlgorithm#CBC} @@ -55,13 +53,13 @@ public class BouncyCastleAesCbcBytesEncryptor extends BouncyCastleAesBytesEncryp new CBCBlockCipher(new org.bouncycastle.crypto.engines.AESFastEngine()), new PKCS7Padding()); blockCipher.init(true, new ParametersWithIV(this.secretKey, iv)); byte[] encrypted = process(blockCipher, bytes); - return iv != null ? concatenate(iv, encrypted) : encrypted; + return iv != null ? EncodingUtils.concatenate(iv, encrypted) : encrypted; } @Override public byte[] decrypt(byte[] encryptedBytes) { - byte[] iv = subArray(encryptedBytes, 0, this.ivGenerator.getKeyLength()); - encryptedBytes = subArray(encryptedBytes, this.ivGenerator.getKeyLength(), encryptedBytes.length); + byte[] iv = EncodingUtils.subArray(encryptedBytes, 0, this.ivGenerator.getKeyLength()); + encryptedBytes = EncodingUtils.subArray(encryptedBytes, this.ivGenerator.getKeyLength(), encryptedBytes.length); @SuppressWarnings("deprecation") PaddedBufferedBlockCipher blockCipher = new PaddedBufferedBlockCipher( diff --git a/crypto/src/main/java/org/springframework/security/crypto/encrypt/BouncyCastleAesGcmBytesEncryptor.java b/crypto/src/main/java/org/springframework/security/crypto/encrypt/BouncyCastleAesGcmBytesEncryptor.java index d017530c0a..46fcc569a1 100644 --- a/crypto/src/main/java/org/springframework/security/crypto/encrypt/BouncyCastleAesGcmBytesEncryptor.java +++ b/crypto/src/main/java/org/springframework/security/crypto/encrypt/BouncyCastleAesGcmBytesEncryptor.java @@ -22,9 +22,7 @@ import org.bouncycastle.crypto.params.AEADParameters; import org.springframework.security.crypto.encrypt.AesBytesEncryptor.CipherAlgorithm; import org.springframework.security.crypto.keygen.BytesKeyGenerator; - -import static org.springframework.security.crypto.util.EncodingUtils.concatenate; -import static org.springframework.security.crypto.util.EncodingUtils.subArray; +import org.springframework.security.crypto.util.EncodingUtils; /** * An Encryptor equivalent to {@link AesBytesEncryptor} using {@link CipherAlgorithm#GCM} @@ -53,13 +51,13 @@ public class BouncyCastleAesGcmBytesEncryptor extends BouncyCastleAesBytesEncryp blockCipher.init(true, new AEADParameters(this.secretKey, 128, iv, null)); byte[] encrypted = process(blockCipher, bytes); - return iv != null ? concatenate(iv, encrypted) : encrypted; + return iv != null ? EncodingUtils.concatenate(iv, encrypted) : encrypted; } @Override public byte[] decrypt(byte[] encryptedBytes) { - byte[] iv = subArray(encryptedBytes, 0, this.ivGenerator.getKeyLength()); - encryptedBytes = subArray(encryptedBytes, this.ivGenerator.getKeyLength(), encryptedBytes.length); + byte[] iv = EncodingUtils.subArray(encryptedBytes, 0, this.ivGenerator.getKeyLength()); + encryptedBytes = EncodingUtils.subArray(encryptedBytes, this.ivGenerator.getKeyLength(), encryptedBytes.length); @SuppressWarnings("deprecation") GCMBlockCipher blockCipher = new GCMBlockCipher(new org.bouncycastle.crypto.engines.AESFastEngine()); diff --git a/crypto/src/main/java/org/springframework/security/crypto/password/AbstractPasswordEncoder.java b/crypto/src/main/java/org/springframework/security/crypto/password/AbstractPasswordEncoder.java index db43f51292..7f5e22ed60 100644 --- a/crypto/src/main/java/org/springframework/security/crypto/password/AbstractPasswordEncoder.java +++ b/crypto/src/main/java/org/springframework/security/crypto/password/AbstractPasswordEncoder.java @@ -20,9 +20,7 @@ import java.security.MessageDigest; import org.springframework.security.crypto.codec.Hex; import org.springframework.security.crypto.keygen.BytesKeyGenerator; import org.springframework.security.crypto.keygen.KeyGenerators; - -import static org.springframework.security.crypto.util.EncodingUtils.concatenate; -import static org.springframework.security.crypto.util.EncodingUtils.subArray; +import org.springframework.security.crypto.util.EncodingUtils; /** * Abstract base class for password encoders @@ -47,14 +45,14 @@ public abstract class AbstractPasswordEncoder implements PasswordEncoder { @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { byte[] digested = Hex.decode(encodedPassword); - byte[] salt = subArray(digested, 0, this.saltGenerator.getKeyLength()); + byte[] salt = EncodingUtils.subArray(digested, 0, this.saltGenerator.getKeyLength()); return matches(digested, encodeAndConcatenate(rawPassword, salt)); } protected abstract byte[] encode(CharSequence rawPassword, byte[] salt); protected byte[] encodeAndConcatenate(CharSequence rawPassword, byte[] salt) { - return concatenate(salt, encode(rawPassword, salt)); + return EncodingUtils.concatenate(salt, encode(rawPassword, salt)); } /** diff --git a/crypto/src/main/java/org/springframework/security/crypto/password/Pbkdf2PasswordEncoder.java b/crypto/src/main/java/org/springframework/security/crypto/password/Pbkdf2PasswordEncoder.java index 53e56a1de8..2b4f5465fe 100644 --- a/crypto/src/main/java/org/springframework/security/crypto/password/Pbkdf2PasswordEncoder.java +++ b/crypto/src/main/java/org/springframework/security/crypto/password/Pbkdf2PasswordEncoder.java @@ -27,9 +27,7 @@ import org.springframework.security.crypto.codec.Hex; import org.springframework.security.crypto.codec.Utf8; import org.springframework.security.crypto.keygen.BytesKeyGenerator; import org.springframework.security.crypto.keygen.KeyGenerators; - -import static org.springframework.security.crypto.util.EncodingUtils.concatenate; -import static org.springframework.security.crypto.util.EncodingUtils.subArray; +import org.springframework.security.crypto.util.EncodingUtils; /** * A {@code PasswordEncoder} implementation that uses PBKDF2 with a configurable number of @@ -147,7 +145,7 @@ public class Pbkdf2PasswordEncoder implements PasswordEncoder { @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { byte[] digested = decode(encodedPassword); - byte[] salt = subArray(digested, 0, this.saltGenerator.getKeyLength()); + byte[] salt = EncodingUtils.subArray(digested, 0, this.saltGenerator.getKeyLength()); return MessageDigest.isEqual(digested, encode(rawPassword, salt)); } @@ -160,10 +158,10 @@ public class Pbkdf2PasswordEncoder implements PasswordEncoder { private byte[] encode(CharSequence rawPassword, byte[] salt) { try { - PBEKeySpec spec = new PBEKeySpec(rawPassword.toString().toCharArray(), concatenate(salt, this.secret), - this.iterations, this.hashWidth); + PBEKeySpec spec = new PBEKeySpec(rawPassword.toString().toCharArray(), + EncodingUtils.concatenate(salt, this.secret), this.iterations, this.hashWidth); SecretKeyFactory skf = SecretKeyFactory.getInstance(this.algorithm); - return concatenate(salt, skf.generateSecret(spec).getEncoded()); + return EncodingUtils.concatenate(salt, skf.generateSecret(spec).getEncoded()); } catch (GeneralSecurityException e) { throw new IllegalStateException("Could not create hash", e); diff --git a/crypto/src/main/java/org/springframework/security/crypto/password/StandardPasswordEncoder.java b/crypto/src/main/java/org/springframework/security/crypto/password/StandardPasswordEncoder.java index 016783c24c..bca1380bfd 100644 --- a/crypto/src/main/java/org/springframework/security/crypto/password/StandardPasswordEncoder.java +++ b/crypto/src/main/java/org/springframework/security/crypto/password/StandardPasswordEncoder.java @@ -21,9 +21,7 @@ import org.springframework.security.crypto.codec.Hex; import org.springframework.security.crypto.codec.Utf8; import org.springframework.security.crypto.keygen.BytesKeyGenerator; import org.springframework.security.crypto.keygen.KeyGenerators; - -import static org.springframework.security.crypto.util.EncodingUtils.concatenate; -import static org.springframework.security.crypto.util.EncodingUtils.subArray; +import org.springframework.security.crypto.util.EncodingUtils; /** * This {@link PasswordEncoder} is provided for legacy purposes only and is not considered @@ -81,7 +79,7 @@ public final class StandardPasswordEncoder implements PasswordEncoder { @Override public boolean matches(CharSequence rawPassword, String encodedPassword) { byte[] digested = decode(encodedPassword); - byte[] salt = subArray(digested, 0, this.saltGenerator.getKeyLength()); + byte[] salt = EncodingUtils.subArray(digested, 0, this.saltGenerator.getKeyLength()); return MessageDigest.isEqual(digested, digest(rawPassword, salt)); } @@ -99,8 +97,8 @@ public final class StandardPasswordEncoder implements PasswordEncoder { } private byte[] digest(CharSequence rawPassword, byte[] salt) { - byte[] digest = this.digester.digest(concatenate(salt, this.secret, Utf8.encode(rawPassword))); - return concatenate(salt, digest); + byte[] digest = this.digester.digest(EncodingUtils.concatenate(salt, this.secret, Utf8.encode(rawPassword))); + return EncodingUtils.concatenate(salt, digest); } private byte[] decode(CharSequence encodedPassword) { diff --git a/crypto/src/test/java/org/springframework/security/crypto/encrypt/AesBytesEncryptorTests.java b/crypto/src/test/java/org/springframework/security/crypto/encrypt/AesBytesEncryptorTests.java index 124889e337..0d1a9b678b 100644 --- a/crypto/src/test/java/org/springframework/security/crypto/encrypt/AesBytesEncryptorTests.java +++ b/crypto/src/test/java/org/springframework/security/crypto/encrypt/AesBytesEncryptorTests.java @@ -23,14 +23,13 @@ import org.junit.Before; import org.junit.Test; import org.springframework.security.crypto.codec.Hex; +import org.springframework.security.crypto.encrypt.AesBytesEncryptor.CipherAlgorithm; import org.springframework.security.crypto.keygen.BytesKeyGenerator; +import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder.SecretKeyFactoryAlgorithm; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.springframework.security.crypto.encrypt.AesBytesEncryptor.CipherAlgorithm.GCM; -import static org.springframework.security.crypto.encrypt.CipherUtils.newSecretKey; -import static org.springframework.security.crypto.password.Pbkdf2PasswordEncoder.SecretKeyFactoryAlgorithm.PBKDF2WithHmacSHA1; /** * Tests for {@link AesBytesEncryptor} @@ -76,7 +75,8 @@ public class AesBytesEncryptorTests { @Test public void roundtripWhenUsingGcmThenEncryptsAndDecrypts() { CryptoAssumptions.assumeGCMJCE(); - AesBytesEncryptor encryptor = new AesBytesEncryptor(this.password, this.hexSalt, this.generator, GCM); + AesBytesEncryptor encryptor = new AesBytesEncryptor(this.password, this.hexSalt, this.generator, + CipherAlgorithm.GCM); byte[] encryption = encryptor.encrypt(this.secret.getBytes()); assertThat(new String(Hex.encode(encryption))) @@ -90,8 +90,8 @@ public class AesBytesEncryptorTests { public void roundtripWhenUsingSecretKeyThenEncryptsAndDecrypts() { CryptoAssumptions.assumeGCMJCE(); PBEKeySpec keySpec = new PBEKeySpec(this.password.toCharArray(), Hex.decode(this.hexSalt), 1024, 256); - SecretKey secretKey = newSecretKey(PBKDF2WithHmacSHA1.name(), keySpec); - AesBytesEncryptor encryptor = new AesBytesEncryptor(secretKey, this.generator, GCM); + SecretKey secretKey = CipherUtils.newSecretKey(SecretKeyFactoryAlgorithm.PBKDF2WithHmacSHA1.name(), keySpec); + AesBytesEncryptor encryptor = new AesBytesEncryptor(secretKey, this.generator, CipherAlgorithm.GCM); byte[] encryption = encryptor.encrypt(this.secret.getBytes()); assertThat(new String(Hex.encode(encryption))) diff --git a/etc/checkstyle/checkstyle-suppressions.xml b/etc/checkstyle/checkstyle-suppressions.xml index a0d4fa92c7..8a54814b09 100644 --- a/etc/checkstyle/checkstyle-suppressions.xml +++ b/etc/checkstyle/checkstyle-suppressions.xml @@ -3,7 +3,6 @@ "-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN" "https://checkstyle.org/dtds/suppressions_1_2.dtd"> - diff --git a/messaging/src/main/java/org/springframework/security/messaging/util/matcher/AbstractMessageMatcherComposite.java b/messaging/src/main/java/org/springframework/security/messaging/util/matcher/AbstractMessageMatcherComposite.java index 6bb2b627e8..e5a4ef2c3a 100644 --- a/messaging/src/main/java/org/springframework/security/messaging/util/matcher/AbstractMessageMatcherComposite.java +++ b/messaging/src/main/java/org/springframework/security/messaging/util/matcher/AbstractMessageMatcherComposite.java @@ -15,13 +15,13 @@ */ package org.springframework.security.messaging.util.matcher; +import java.util.Arrays; import java.util.List; import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; -import static java.util.Arrays.asList; -import static org.apache.commons.logging.LogFactory.getLog; -import static org.springframework.util.Assert.notEmpty; +import org.springframework.util.Assert; /** * Abstract {@link MessageMatcher} containing multiple {@link MessageMatcher} @@ -30,7 +30,7 @@ import static org.springframework.util.Assert.notEmpty; */ abstract class AbstractMessageMatcherComposite implements MessageMatcher { - protected final Log LOGGER = getLog(getClass()); + protected final Log LOGGER = LogFactory.getLog(getClass()); private final List> messageMatchers; @@ -39,7 +39,7 @@ abstract class AbstractMessageMatcherComposite implements MessageMatcher { * @param messageMatchers the {@link MessageMatcher} instances to try */ AbstractMessageMatcherComposite(List> messageMatchers) { - notEmpty(messageMatchers, "messageMatchers must contain a value"); + Assert.notEmpty(messageMatchers, "messageMatchers must contain a value"); if (messageMatchers.contains(null)) { throw new IllegalArgumentException("messageMatchers cannot contain null values"); } @@ -53,7 +53,7 @@ abstract class AbstractMessageMatcherComposite implements MessageMatcher { */ @SafeVarargs AbstractMessageMatcherComposite(MessageMatcher... messageMatchers) { - this(asList(messageMatchers)); + this(Arrays.asList(messageMatchers)); } public List> getMessageMatchers() { diff --git a/messaging/src/test/java/org/springframework/security/messaging/access/expression/ExpressionBasedMessageSecurityMetadataSourceFactoryTests.java b/messaging/src/test/java/org/springframework/security/messaging/access/expression/ExpressionBasedMessageSecurityMetadataSourceFactoryTests.java index 12b93ce5e3..e905aff96c 100644 --- a/messaging/src/test/java/org/springframework/security/messaging/access/expression/ExpressionBasedMessageSecurityMetadataSourceFactoryTests.java +++ b/messaging/src/test/java/org/springframework/security/messaging/access/expression/ExpressionBasedMessageSecurityMetadataSourceFactoryTests.java @@ -31,8 +31,7 @@ import org.springframework.security.messaging.access.intercept.MessageSecurityMe import org.springframework.security.messaging.util.matcher.MessageMatcher; import static org.assertj.core.api.Assertions.assertThat; -import static org.powermock.api.mockito.PowerMockito.when; -import static org.springframework.security.messaging.access.expression.ExpressionBasedMessageSecurityMetadataSourceFactory.createExpressionMessageMetadataSource; +import static org.mockito.BDDMockito.given; @RunWith(MockitoJUnitRunner.class) public class ExpressionBasedMessageSecurityMetadataSourceFactoryTests { @@ -67,7 +66,8 @@ public class ExpressionBasedMessageSecurityMetadataSourceFactoryTests { this.matcherToExpression.put(this.matcher1, this.expression1); this.matcherToExpression.put(this.matcher2, this.expression2); - this.source = createExpressionMessageMetadataSource(this.matcherToExpression); + this.source = ExpressionBasedMessageSecurityMetadataSourceFactory + .createExpressionMessageMetadataSource(this.matcherToExpression); this.rootObject = new MessageSecurityExpressionRoot(this.authentication, this.message); } @@ -81,7 +81,7 @@ public class ExpressionBasedMessageSecurityMetadataSourceFactoryTests { @Test public void createExpressionMessageMetadataSourceMatchFirst() { - when(this.matcher1.matches(this.message)).thenReturn(true); + given(this.matcher1.matches(this.message)).willReturn(true); Collection attrs = this.source.getAttributes(this.message); @@ -94,7 +94,7 @@ public class ExpressionBasedMessageSecurityMetadataSourceFactoryTests { @Test public void createExpressionMessageMetadataSourceMatchSecond() { - when(this.matcher2.matches(this.message)).thenReturn(true); + given(this.matcher2.matches(this.message)).willReturn(true); Collection attrs = this.source.getAttributes(this.message); diff --git a/messaging/src/test/java/org/springframework/security/messaging/access/expression/MessageExpressionVoterTests.java b/messaging/src/test/java/org/springframework/security/messaging/access/expression/MessageExpressionVoterTests.java index 1462d8fecd..0af2476af3 100644 --- a/messaging/src/test/java/org/springframework/security/messaging/access/expression/MessageExpressionVoterTests.java +++ b/messaging/src/test/java/org/springframework/security/messaging/access/expression/MessageExpressionVoterTests.java @@ -27,6 +27,7 @@ import org.mockito.junit.MockitoJUnitRunner; import org.springframework.expression.EvaluationContext; import org.springframework.expression.Expression; import org.springframework.messaging.Message; +import org.springframework.security.access.AccessDecisionVoter; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; import org.springframework.security.access.expression.SecurityExpressionHandler; @@ -39,9 +40,6 @@ 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.springframework.security.access.AccessDecisionVoter.ACCESS_ABSTAIN; -import static org.springframework.security.access.AccessDecisionVoter.ACCESS_DENIED; -import static org.springframework.security.access.AccessDecisionVoter.ACCESS_GRANTED; @RunWith(MockitoJUnitRunner.class) public class MessageExpressionVoterTests { @@ -79,19 +77,22 @@ public class MessageExpressionVoterTests { @Test public void voteGranted() { given(this.expression.getValue(any(EvaluationContext.class), eq(Boolean.class))).willReturn(true); - assertThat(this.voter.vote(this.authentication, this.message, this.attributes)).isEqualTo(ACCESS_GRANTED); + assertThat(this.voter.vote(this.authentication, this.message, this.attributes)) + .isEqualTo(AccessDecisionVoter.ACCESS_GRANTED); } @Test public void voteDenied() { given(this.expression.getValue(any(EvaluationContext.class), eq(Boolean.class))).willReturn(false); - assertThat(this.voter.vote(this.authentication, this.message, this.attributes)).isEqualTo(ACCESS_DENIED); + assertThat(this.voter.vote(this.authentication, this.message, this.attributes)) + .isEqualTo(AccessDecisionVoter.ACCESS_DENIED); } @Test public void voteAbstain() { this.attributes = Arrays.asList(new SecurityConfig("ROLE_USER")); - assertThat(this.voter.vote(this.authentication, this.message, this.attributes)).isEqualTo(ACCESS_ABSTAIN); + assertThat(this.voter.vote(this.authentication, this.message, this.attributes)) + .isEqualTo(AccessDecisionVoter.ACCESS_ABSTAIN); } @Test @@ -126,7 +127,8 @@ public class MessageExpressionVoterTests { .willReturn(this.evaluationContext); given(this.expression.getValue(this.evaluationContext, Boolean.class)).willReturn(true); - assertThat(this.voter.vote(this.authentication, this.message, this.attributes)).isEqualTo(ACCESS_GRANTED); + assertThat(this.voter.vote(this.authentication, this.message, this.attributes)) + .isEqualTo(AccessDecisionVoter.ACCESS_GRANTED); verify(this.expressionHandler).createEvaluationContext(this.authentication, this.message); } @@ -142,7 +144,8 @@ public class MessageExpressionVoterTests { given(configAttribute.postProcess(this.evaluationContext, this.message)).willReturn(this.evaluationContext); given(this.expression.getValue(any(EvaluationContext.class), eq(Boolean.class))).willReturn(true); - assertThat(this.voter.vote(this.authentication, this.message, this.attributes)).isEqualTo(ACCESS_GRANTED); + assertThat(this.voter.vote(this.authentication, this.message, this.attributes)) + .isEqualTo(AccessDecisionVoter.ACCESS_GRANTED); verify(configAttribute).postProcess(this.evaluationContext, this.message); } diff --git a/messaging/src/test/java/org/springframework/security/messaging/access/intercept/DefaultMessageSecurityMetadataSourceTests.java b/messaging/src/test/java/org/springframework/security/messaging/access/intercept/DefaultMessageSecurityMetadataSourceTests.java index 3feaa06ec9..83e53d9057 100644 --- a/messaging/src/test/java/org/springframework/security/messaging/access/intercept/DefaultMessageSecurityMetadataSourceTests.java +++ b/messaging/src/test/java/org/springframework/security/messaging/access/intercept/DefaultMessageSecurityMetadataSourceTests.java @@ -32,7 +32,7 @@ import org.springframework.security.core.Authentication; import org.springframework.security.messaging.util.matcher.MessageMatcher; import static org.assertj.core.api.Assertions.assertThat; -import static org.powermock.api.mockito.PowerMockito.when; +import static org.mockito.BDDMockito.given; @RunWith(MockitoJUnitRunner.class) public class DefaultMessageSecurityMetadataSourceTests { @@ -73,14 +73,14 @@ public class DefaultMessageSecurityMetadataSourceTests { @Test public void getAttributesFirst() { - when(this.matcher1.matches(this.message)).thenReturn(true); + given(this.matcher1.matches(this.message)).willReturn(true); assertThat(this.source.getAttributes(this.message)).containsOnly(this.config1); } @Test public void getAttributesSecond() { - when(this.matcher1.matches(this.message)).thenReturn(true); + given(this.matcher1.matches(this.message)).willReturn(true); assertThat(this.source.getAttributes(this.message)).containsOnly(this.config2); } diff --git a/messaging/src/test/java/org/springframework/security/messaging/context/SecurityContextChannelInterceptorTests.java b/messaging/src/test/java/org/springframework/security/messaging/context/SecurityContextChannelInterceptorTests.java index 8b19f08fa5..7295ef0b2a 100644 --- a/messaging/src/test/java/org/springframework/security/messaging/context/SecurityContextChannelInterceptorTests.java +++ b/messaging/src/test/java/org/springframework/security/messaging/context/SecurityContextChannelInterceptorTests.java @@ -35,7 +35,6 @@ import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContextHolder; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.core.context.SecurityContextHolder.clearContext; @RunWith(MockitoJUnitRunner.class) public class SecurityContextChannelInterceptorTests { @@ -69,7 +68,7 @@ public class SecurityContextChannelInterceptorTests { @After public void cleanup() { - clearContext(); + SecurityContextHolder.clearContext(); } @Test(expected = IllegalArgumentException.class) diff --git a/messaging/src/test/java/org/springframework/security/messaging/handler/invocation/ResolvableMethod.java b/messaging/src/test/java/org/springframework/security/messaging/handler/invocation/ResolvableMethod.java index 25e1e6af82..653b3a2c66 100644 --- a/messaging/src/test/java/org/springframework/security/messaging/handler/invocation/ResolvableMethod.java +++ b/messaging/src/test/java/org/springframework/security/messaging/handler/invocation/ResolvableMethod.java @@ -27,6 +27,7 @@ import java.util.Set; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.Supplier; +import java.util.stream.Collectors; import org.aopalliance.intercept.MethodInterceptor; import org.apache.commons.logging.Log; @@ -54,8 +55,6 @@ import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; import org.springframework.util.ReflectionUtils; -import static java.util.stream.Collectors.joining; - /** * NOTE: This class is a replica of the same class in spring-web so it can be used for * tests in spring-messaging. @@ -216,13 +215,14 @@ public final class ResolvableMethod { private String formatMethod() { return (method().getName() + Arrays.stream(this.method.getParameters()).map(this::formatParameter) - .collect(joining(",\n\t", "(\n\t", "\n)"))); + .collect(Collectors.joining(",\n\t", "(\n\t", "\n)"))); } private String formatParameter(Parameter param) { Annotation[] anns = param.getAnnotations(); return (anns.length > 0 - ? Arrays.stream(anns).map(this::formatAnnotation).collect(joining(",", "[", "]")) + " " + param + ? Arrays.stream(anns).map(this::formatAnnotation).collect(Collectors.joining(",", "[", "]")) + " " + + param : param.toString()); } @@ -427,8 +427,8 @@ public final class ResolvableMethod { } private String formatMethods(Set methods) { - return "\nMatched:\n" - + methods.stream().map(Method::toGenericString).collect(joining(",\n\t", "[\n\t", "\n]")); + return "\nMatched:\n" + methods.stream().map(Method::toGenericString) + .collect(Collectors.joining(",\n\t", "[\n\t", "\n]")); } public ResolvableMethod mockCall(Consumer invoker) { @@ -504,7 +504,8 @@ public final class ResolvableMethod { } private String formatFilters() { - return this.filters.stream().map(Object::toString).collect(joining(",\n\t\t", "[\n\t\t", "\n\t]")); + return this.filters.stream().map(Object::toString) + .collect(Collectors.joining(",\n\t\t", "[\n\t\t", "\n\t]")); } } diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/AbstractWebClientReactiveOAuth2AccessTokenResponseClient.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/AbstractWebClientReactiveOAuth2AccessTokenResponseClient.java index 67a489046e..81329fb5ad 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/AbstractWebClientReactiveOAuth2AccessTokenResponseClient.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/AbstractWebClientReactiveOAuth2AccessTokenResponseClient.java @@ -26,6 +26,7 @@ import org.springframework.security.oauth2.client.registration.ClientRegistratio import org.springframework.security.oauth2.core.ClientAuthenticationMethod; import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; +import org.springframework.security.oauth2.core.web.reactive.function.OAuth2BodyExtractors; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; @@ -33,8 +34,6 @@ import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.client.ClientResponse; import org.springframework.web.reactive.function.client.WebClient; -import static org.springframework.security.oauth2.core.web.reactive.function.OAuth2BodyExtractors.oauth2AccessTokenResponse; - /** * Abstract base class for all of the {@code WebClientReactive*TokenResponseClient}s that * communicate to the Authorization Server's Token Endpoint. @@ -169,7 +168,7 @@ abstract class AbstractWebClientReactiveOAuth2AccessTokenResponseClient readTokenResponse(T grantRequest, ClientResponse response) { - return response.body(oauth2AccessTokenResponse()) + return response.body(OAuth2BodyExtractors.oauth2AccessTokenResponse()) .map(tokenResponse -> populateTokenResponse(grantRequest, tokenResponse)); } diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/OAuth2AuthorizationGrantRequestEntityUtils.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/OAuth2AuthorizationGrantRequestEntityUtils.java index af7b288ac2..20079b80c0 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/OAuth2AuthorizationGrantRequestEntityUtils.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/OAuth2AuthorizationGrantRequestEntityUtils.java @@ -24,8 +24,6 @@ import org.springframework.http.RequestEntity; import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.core.ClientAuthenticationMethod; -import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED_VALUE; - /** * Utility methods used by the {@link Converter}'s that convert from an implementation of * an {@link AbstractOAuth2AuthorizationGrantRequest} to a {@link RequestEntity} @@ -53,7 +51,7 @@ final class OAuth2AuthorizationGrantRequestEntityUtils { private static HttpHeaders getDefaultTokenRequestHeaders() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8)); - final MediaType contentType = MediaType.valueOf(APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8"); + final MediaType contentType = MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8"); headers.setContentType(contentType); return headers; } diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson2/ClientRegistrationDeserializer.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson2/ClientRegistrationDeserializer.java index 58482899c1..f299bdc242 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson2/ClientRegistrationDeserializer.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson2/ClientRegistrationDeserializer.java @@ -29,12 +29,6 @@ import org.springframework.security.oauth2.core.AuthenticationMethod; import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.ClientAuthenticationMethod; -import static org.springframework.security.oauth2.client.jackson2.JsonNodeUtils.MAP_TYPE_REFERENCE; -import static org.springframework.security.oauth2.client.jackson2.JsonNodeUtils.SET_TYPE_REFERENCE; -import static org.springframework.security.oauth2.client.jackson2.JsonNodeUtils.findObjectNode; -import static org.springframework.security.oauth2.client.jackson2.JsonNodeUtils.findStringValue; -import static org.springframework.security.oauth2.client.jackson2.JsonNodeUtils.findValue; - /** * A {@code JsonDeserializer} for {@link ClientRegistration}. * @@ -55,28 +49,31 @@ final class ClientRegistrationDeserializer extends JsonDeserializer configurationMetadata = clientRegistration.providerDetails.configurationMetadata; - if (configurationMetadata != EMPTY_MAP) { + if (configurationMetadata != Collections.EMPTY_MAP) { this.configurationMetadata = new HashMap<>(configurationMetadata); } this.clientName = clientRegistration.clientName; diff --git a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/userinfo/OAuth2UserRequestEntityConverter.java b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/userinfo/OAuth2UserRequestEntityConverter.java index e0213ca9b4..7267d1862c 100644 --- a/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/userinfo/OAuth2UserRequestEntityConverter.java +++ b/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/userinfo/OAuth2UserRequestEntityConverter.java @@ -30,8 +30,6 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.util.UriComponentsBuilder; -import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED_VALUE; - /** * A {@link Converter} that converts the provided {@link OAuth2UserRequest} to a * {@link RequestEntity} representation of a request for the UserInfo Endpoint. @@ -45,7 +43,7 @@ import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED_VAL public class OAuth2UserRequestEntityConverter implements Converter> { private static final MediaType DEFAULT_CONTENT_TYPE = MediaType - .valueOf(APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8"); + .valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8"); /** * Returns the {@link RequestEntity} used for the UserInfo Request. diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientTests.java index 942c460ea2..4aa7b77f76 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientTests.java @@ -19,11 +19,11 @@ import org.junit.Before; import org.junit.Test; import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.TestClientRegistrations; import org.springframework.security.oauth2.core.OAuth2AccessToken; +import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration; -import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.noScopes; /** * Tests for {@link OAuth2AuthorizedClient}. @@ -40,9 +40,9 @@ public class OAuth2AuthorizedClientTests { @Before public void setUp() { - this.clientRegistration = clientRegistration().build(); + this.clientRegistration = TestClientRegistrations.clientRegistration().build(); this.principalName = "principal"; - this.accessToken = noScopes(); + this.accessToken = TestOAuth2AccessTokens.noScopes(); } @Test(expected = IllegalArgumentException.class) diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationProviderTests.java index c745de44fd..2b724c2e20 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationProviderTests.java @@ -25,23 +25,22 @@ import org.junit.Test; import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient; import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest; import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.TestClientRegistrations; import org.springframework.security.oauth2.core.OAuth2AuthorizationException; import org.springframework.security.oauth2.core.OAuth2ErrorCodes; import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse; +import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses; +import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests; +import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses.accessTokenResponse; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests.request; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses.error; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses.success; /** * Tests for {@link OAuth2AuthorizationCodeAuthenticationProvider}. @@ -61,8 +60,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @Before @SuppressWarnings("unchecked") public void setUp() { - this.clientRegistration = clientRegistration().build(); - this.authorizationRequest = request().build(); + this.clientRegistration = TestClientRegistrations.clientRegistration().build(); + this.authorizationRequest = TestOAuth2AuthorizationRequests.request().build(); this.accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class); this.authenticationProvider = new OAuth2AuthorizationCodeAuthenticationProvider(this.accessTokenResponseClient); } @@ -80,7 +79,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @Test public void authenticateWhenAuthorizationErrorResponseThenThrowOAuth2AuthorizationException() { - OAuth2AuthorizationResponse authorizationResponse = error().errorCode(OAuth2ErrorCodes.INVALID_REQUEST).build(); + OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.error() + .errorCode(OAuth2ErrorCodes.INVALID_REQUEST).build(); OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest, authorizationResponse); @@ -92,7 +92,8 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @Test public void authenticateWhenAuthorizationResponseStateNotEqualAuthorizationRequestStateThenThrowOAuth2AuthorizationException() { - OAuth2AuthorizationResponse authorizationResponse = success().state("67890").build(); + OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.success().state("67890") + .build(); OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest, authorizationResponse); @@ -104,11 +105,12 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { @Test public void authenticateWhenAuthorizationSuccessResponseThenExchangedForAccessToken() { - OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().refreshToken("refresh").build(); + OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse() + .refreshToken("refresh").build(); given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest, - success().build()); + TestOAuth2AuthorizationResponses.success().build()); OAuth2AuthorizationCodeAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeAuthenticationToken) this.authenticationProvider .authenticate( new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, authorizationExchange)); @@ -131,12 +133,12 @@ public class OAuth2AuthorizationCodeAuthenticationProviderTests { additionalParameters.put("param1", "value1"); additionalParameters.put("param2", "value2"); - OAuth2AccessTokenResponse accessTokenResponse = accessTokenResponse().additionalParameters(additionalParameters) - .build(); + OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse() + .additionalParameters(additionalParameters).build(); given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse); OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest, - success().build()); + TestOAuth2AuthorizationResponses.success().build()); OAuth2AuthorizationCodeAuthenticationToken authentication = (OAuth2AuthorizationCodeAuthenticationToken) this.authenticationProvider .authenticate( diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationTokenTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationTokenTests.java index 33d2e8a7e8..0498058917 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationTokenTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationTokenTests.java @@ -21,15 +21,15 @@ import org.junit.Before; import org.junit.Test; import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.TestClientRegistrations; import org.springframework.security.oauth2.core.OAuth2AccessToken; +import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange; +import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests; +import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration; -import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.noScopes; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests.request; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses.success; /** * Tests for {@link OAuth2AuthorizationCodeAuthenticationToken}. @@ -46,9 +46,10 @@ public class OAuth2AuthorizationCodeAuthenticationTokenTests { @Before public void setUp() { - this.clientRegistration = clientRegistration().build(); - this.authorizationExchange = new OAuth2AuthorizationExchange(request().build(), success().code("code").build()); - this.accessToken = noScopes(); + this.clientRegistration = TestClientRegistrations.clientRegistration().build(); + this.authorizationExchange = new OAuth2AuthorizationExchange(TestOAuth2AuthorizationRequests.request().build(), + TestOAuth2AuthorizationResponses.success().code("code").build()); + this.accessToken = TestOAuth2AccessTokens.noScopes(); } @Test diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginAuthenticationProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginAuthenticationProviderTests.java index e62a2724f4..1be451737a 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginAuthenticationProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginAuthenticationProviderTests.java @@ -36,6 +36,7 @@ import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMap import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient; import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest; import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.TestClientRegistrations; import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; import org.springframework.security.oauth2.client.userinfo.OAuth2UserService; import org.springframework.security.oauth2.core.OAuth2AccessToken; @@ -45,6 +46,8 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenRespon import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse; +import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests; +import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses; import org.springframework.security.oauth2.core.user.OAuth2User; import static org.assertj.core.api.Assertions.assertThat; @@ -53,10 +56,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests.request; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses.error; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses.success; /** * Tests for {@link OAuth2LoginAuthenticationProvider}. @@ -85,9 +84,9 @@ public class OAuth2LoginAuthenticationProviderTests { @Before @SuppressWarnings("unchecked") public void setUp() { - this.clientRegistration = clientRegistration().build(); - this.authorizationRequest = request().scope("scope1", "scope2").build(); - this.authorizationResponse = success().build(); + this.clientRegistration = TestClientRegistrations.clientRegistration().build(); + this.authorizationRequest = TestOAuth2AuthorizationRequests.request().scope("scope1", "scope2").build(); + this.authorizationResponse = TestOAuth2AuthorizationResponses.success().build(); this.authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest, this.authorizationResponse); this.accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class); @@ -121,7 +120,8 @@ public class OAuth2LoginAuthenticationProviderTests { @Test public void authenticateWhenAuthorizationRequestContainsOpenidScopeThenReturnNull() { - OAuth2AuthorizationRequest authorizationRequest = request().scope("openid").build(); + OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request().scope("openid") + .build(); OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest, this.authorizationResponse); @@ -136,7 +136,8 @@ public class OAuth2LoginAuthenticationProviderTests { this.exception.expect(OAuth2AuthenticationException.class); this.exception.expectMessage(containsString(OAuth2ErrorCodes.INVALID_REQUEST)); - OAuth2AuthorizationResponse authorizationResponse = error().errorCode(OAuth2ErrorCodes.INVALID_REQUEST).build(); + OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.error() + .errorCode(OAuth2ErrorCodes.INVALID_REQUEST).build(); OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest, authorizationResponse); @@ -149,7 +150,8 @@ public class OAuth2LoginAuthenticationProviderTests { this.exception.expect(OAuth2AuthenticationException.class); this.exception.expectMessage(containsString("invalid_state_parameter")); - OAuth2AuthorizationResponse authorizationResponse = success().state("67890").build(); + OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.success().state("67890") + .build(); OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest, authorizationResponse); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginAuthenticationTokenTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginAuthenticationTokenTests.java index c2c3c312e0..0fd7bc89b3 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginAuthenticationTokenTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginAuthenticationTokenTests.java @@ -23,16 +23,16 @@ import org.junit.Test; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.TestClientRegistrations; import org.springframework.security.oauth2.core.OAuth2AccessToken; +import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange; +import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests; +import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses; import org.springframework.security.oauth2.core.user.OAuth2User; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; -import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration; -import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.noScopes; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests.request; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses.success; /** * Tests for {@link OAuth2LoginAuthenticationToken}. @@ -55,9 +55,10 @@ public class OAuth2LoginAuthenticationTokenTests { public void setUp() { this.principal = mock(OAuth2User.class); this.authorities = Collections.emptyList(); - this.clientRegistration = clientRegistration().build(); - this.authorizationExchange = new OAuth2AuthorizationExchange(request().build(), success().code("code").build()); - this.accessToken = noScopes(); + this.clientRegistration = TestClientRegistrations.clientRegistration().build(); + this.authorizationExchange = new OAuth2AuthorizationExchange(TestOAuth2AuthorizationRequests.request().build(), + TestOAuth2AuthorizationResponses.success().code("code").build()); + this.accessToken = TestOAuth2AccessTokens.noScopes(); } @Test(expected = IllegalArgumentException.class) diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/NimbusAuthorizationCodeTokenResponseClientTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/NimbusAuthorizationCodeTokenResponseClientTests.java index 27f5322891..6928ec433a 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/NimbusAuthorizationCodeTokenResponseClientTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/NimbusAuthorizationCodeTokenResponseClientTests.java @@ -27,6 +27,7 @@ import org.junit.rules.ExpectedException; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.TestClientRegistrations; import org.springframework.security.oauth2.core.ClientAuthenticationMethod; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.OAuth2AuthorizationException; @@ -34,12 +35,11 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenRespon import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse; +import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests; +import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.containsString; -import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests.request; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses.success; /** * Tests for {@link NimbusAuthorizationCodeTokenResponseClient}. @@ -63,10 +63,10 @@ public class NimbusAuthorizationCodeTokenResponseClientTests { @Before public void setUp() { - this.clientRegistrationBuilder = clientRegistration() + this.clientRegistrationBuilder = TestClientRegistrations.clientRegistration() .clientAuthenticationMethod(ClientAuthenticationMethod.BASIC); - this.authorizationRequest = request().build(); - this.authorizationResponse = success().build(); + this.authorizationRequest = TestOAuth2AuthorizationRequests.request().build(); + this.authorizationResponse = TestOAuth2AuthorizationResponses.success().build(); this.authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest, this.authorizationResponse); } @@ -112,7 +112,8 @@ public class NimbusAuthorizationCodeTokenResponseClientTests { this.exception.expect(IllegalArgumentException.class); String redirectUri = "http:\\example.com"; - OAuth2AuthorizationRequest authorizationRequest = request().redirectUri(redirectUri).build(); + OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request() + .redirectUri(redirectUri).build(); OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest, this.authorizationResponse); @@ -260,8 +261,8 @@ public class NimbusAuthorizationCodeTokenResponseClientTests { String tokenUri = server.url("/oauth2/token").toString(); this.clientRegistrationBuilder.tokenUri(tokenUri); - OAuth2AuthorizationRequest authorizationRequest = request().scope("openid", "profile", "email", "address") - .build(); + OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request() + .scope("openid", "profile", "email", "address").build(); OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest, this.authorizationResponse); @@ -287,8 +288,8 @@ public class NimbusAuthorizationCodeTokenResponseClientTests { String tokenUri = server.url("/oauth2/token").toString(); this.clientRegistrationBuilder.tokenUri(tokenUri); - OAuth2AuthorizationRequest authorizationRequest = request().scope("openid", "profile", "email", "address") - .build(); + OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request() + .scope("openid", "profile", "email", "address").build(); OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest, this.authorizationResponse); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2AuthorizationCodeGrantRequestEntityConverterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2AuthorizationCodeGrantRequestEntityConverterTests.java index 6060fc316e..c366481e19 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2AuthorizationCodeGrantRequestEntityConverterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2AuthorizationCodeGrantRequestEntityConverterTests.java @@ -37,7 +37,6 @@ import org.springframework.security.oauth2.core.endpoint.PkceParameterNames; import org.springframework.util.MultiValueMap; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED_VALUE; /** * Tests for {@link OAuth2AuthorizationCodeGrantRequestEntityConverter}. @@ -84,7 +83,7 @@ public class OAuth2AuthorizationCodeGrantRequestEntityConverterTests { HttpHeaders headers = requestEntity.getHeaders(); assertThat(headers.getAccept()).contains(MediaType.APPLICATION_JSON_UTF8); assertThat(headers.getContentType()) - .isEqualTo(MediaType.valueOf(APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8")); + .isEqualTo(MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8")); assertThat(headers.getFirst(HttpHeaders.AUTHORIZATION)).startsWith("Basic "); MultiValueMap formParameters = (MultiValueMap) requestEntity.getBody(); @@ -127,7 +126,7 @@ public class OAuth2AuthorizationCodeGrantRequestEntityConverterTests { HttpHeaders headers = requestEntity.getHeaders(); assertThat(headers.getAccept()).contains(MediaType.APPLICATION_JSON_UTF8); assertThat(headers.getContentType()) - .isEqualTo(MediaType.valueOf(APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8")); + .isEqualTo(MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8")); assertThat(headers.getFirst(HttpHeaders.AUTHORIZATION)).isNull(); MultiValueMap formParameters = (MultiValueMap) requestEntity.getBody(); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2AuthorizationCodeGrantRequestTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2AuthorizationCodeGrantRequestTests.java index 2a70175ca1..53b1c25372 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2AuthorizationCodeGrantRequestTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2AuthorizationCodeGrantRequestTests.java @@ -19,12 +19,12 @@ import org.junit.Before; import org.junit.Test; import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.TestClientRegistrations; import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange; +import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationExchanges; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationExchanges.success; /** * Tests for {@link OAuth2AuthorizationCodeGrantRequest}. @@ -39,8 +39,8 @@ public class OAuth2AuthorizationCodeGrantRequestTests { @Before public void setUp() { - this.clientRegistration = clientRegistration().build(); - this.authorizationExchange = success(); + this.clientRegistration = TestClientRegistrations.clientRegistration().build(); + this.authorizationExchange = TestOAuth2AuthorizationExchanges.success(); } @Test(expected = IllegalArgumentException.class) diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2ClientCredentialsGrantRequestEntityConverterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2ClientCredentialsGrantRequestEntityConverterTests.java index dcc6e6cc64..2e4a53c849 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2ClientCredentialsGrantRequestEntityConverterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2ClientCredentialsGrantRequestEntityConverterTests.java @@ -29,7 +29,6 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.util.MultiValueMap; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED_VALUE; /** * Tests for {@link OAuth2ClientCredentialsGrantRequestEntityConverter}. @@ -66,7 +65,7 @@ public class OAuth2ClientCredentialsGrantRequestEntityConverterTests { HttpHeaders headers = requestEntity.getHeaders(); assertThat(headers.getAccept()).contains(MediaType.APPLICATION_JSON_UTF8); assertThat(headers.getContentType()) - .isEqualTo(MediaType.valueOf(APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8")); + .isEqualTo(MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8")); assertThat(headers.getFirst(HttpHeaders.AUTHORIZATION)).startsWith("Basic "); MultiValueMap formParameters = (MultiValueMap) requestEntity.getBody(); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2ClientCredentialsGrantRequestTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2ClientCredentialsGrantRequestTests.java index 35bb1b74dd..60a8f12d0d 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2ClientCredentialsGrantRequestTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2ClientCredentialsGrantRequestTests.java @@ -23,7 +23,7 @@ import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.ClientAuthenticationMethod; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Java6Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * Tests for {@link OAuth2ClientCredentialsGrantRequest}. diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2PasswordGrantRequestEntityConverterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2PasswordGrantRequestEntityConverterTests.java index 127adf35fd..add7b3eba4 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2PasswordGrantRequestEntityConverterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2PasswordGrantRequestEntityConverterTests.java @@ -29,7 +29,6 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.util.MultiValueMap; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED_VALUE; /** * Tests for {@link OAuth2PasswordGrantRequestEntityConverter}. @@ -63,7 +62,7 @@ public class OAuth2PasswordGrantRequestEntityConverterTests { HttpHeaders headers = requestEntity.getHeaders(); assertThat(headers.getAccept()).contains(MediaType.APPLICATION_JSON_UTF8); assertThat(headers.getContentType()) - .isEqualTo(MediaType.valueOf(APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8")); + .isEqualTo(MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8")); assertThat(headers.getFirst(HttpHeaders.AUTHORIZATION)).startsWith("Basic "); MultiValueMap formParameters = (MultiValueMap) requestEntity.getBody(); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2RefreshTokenGrantRequestEntityConverterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2RefreshTokenGrantRequestEntityConverterTests.java index 02b7bf6ff3..c696b34592 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2RefreshTokenGrantRequestEntityConverterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/OAuth2RefreshTokenGrantRequestEntityConverterTests.java @@ -34,7 +34,6 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.util.MultiValueMap; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED_VALUE; /** * Tests for {@link OAuth2RefreshTokenGrantRequestEntityConverter}. @@ -69,7 +68,7 @@ public class OAuth2RefreshTokenGrantRequestEntityConverterTests { HttpHeaders headers = requestEntity.getHeaders(); assertThat(headers.getAccept()).contains(MediaType.APPLICATION_JSON_UTF8); assertThat(headers.getContentType()) - .isEqualTo(MediaType.valueOf(APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8")); + .isEqualTo(MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8")); assertThat(headers.getFirst(HttpHeaders.AUTHORIZATION)).startsWith("Basic "); MultiValueMap formParameters = (MultiValueMap) requestEntity.getBody(); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationTokenMixinTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationTokenMixinTests.java index db8b48d968..eeca9168d6 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationTokenMixinTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationTokenMixinTests.java @@ -37,6 +37,7 @@ import org.springframework.security.oauth2.client.authentication.TestOAuth2Authe import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames; import org.springframework.security.oauth2.core.oidc.OidcIdToken; import org.springframework.security.oauth2.core.oidc.OidcUserInfo; +import org.springframework.security.oauth2.core.oidc.StandardClaimNames; import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser; import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority; import org.springframework.security.oauth2.core.oidc.user.TestOidcUsers; @@ -47,7 +48,6 @@ import org.springframework.util.StringUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.springframework.security.oauth2.core.oidc.StandardClaimNames.NAME; /** * Tests for {@link OAuth2AuthenticationTokenMixin}. @@ -317,7 +317,7 @@ public class OAuth2AuthenticationTokenMixinTests { " \"claims\": {\n" + " \"@class\": \"java.util.Collections$UnmodifiableMap\",\n" + " \"sub\": \"" + userInfo.getSubject() + "\",\n" + - " \"name\": \"" + userInfo.getClaim(NAME) + "\"\n" + + " \"name\": \"" + userInfo.getClaim(StandardClaimNames.NAME) + "\"\n" + " }\n" + " }"; // @formatter:on diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeAuthenticationProviderTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeAuthenticationProviderTests.java index 6cad3746f6..2be0abc377 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeAuthenticationProviderTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeAuthenticationProviderTests.java @@ -43,6 +43,7 @@ import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResp import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest; import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest; import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.TestClientRegistrations; import org.springframework.security.oauth2.client.userinfo.OAuth2UserService; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; @@ -51,12 +52,15 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenRespon import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse; +import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests; +import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses; import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames; import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames; import org.springframework.security.oauth2.core.oidc.user.OidcUser; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.jwt.JwtException; +import org.springframework.security.oauth2.jwt.TestJwts; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.containsString; @@ -65,12 +69,6 @@ import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.springframework.security.oauth2.client.oidc.authentication.OidcAuthorizationCodeAuthenticationProvider.createHash; -import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests.request; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses.error; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses.success; -import static org.springframework.security.oauth2.jwt.TestJwts.jwt; /** * Tests for {@link OidcAuthorizationCodeAuthenticationProvider}. @@ -107,20 +105,20 @@ public class OidcAuthorizationCodeAuthenticationProviderTests { @Before @SuppressWarnings("unchecked") public void setUp() { - this.clientRegistration = clientRegistration().clientId("client1").build(); + this.clientRegistration = TestClientRegistrations.clientRegistration().clientId("client1").build(); Map attributes = new HashMap<>(); Map additionalParameters = new HashMap<>(); try { String nonce = this.secureKeyGenerator.generateKey(); - this.nonceHash = createHash(nonce); + this.nonceHash = OidcAuthorizationCodeAuthenticationProvider.createHash(nonce); attributes.put(OidcParameterNames.NONCE, nonce); additionalParameters.put(OidcParameterNames.NONCE, this.nonceHash); } catch (NoSuchAlgorithmException e) { } - this.authorizationRequest = request().scope("openid", "profile", "email").attributes(attributes) - .additionalParameters(additionalParameters).build(); - this.authorizationResponse = success().build(); + this.authorizationRequest = TestOAuth2AuthorizationRequests.request().scope("openid", "profile", "email") + .attributes(attributes).additionalParameters(additionalParameters).build(); + this.authorizationResponse = TestOAuth2AuthorizationResponses.success().build(); this.authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest, this.authorizationResponse); this.accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class); @@ -163,7 +161,8 @@ public class OidcAuthorizationCodeAuthenticationProviderTests { @Test public void authenticateWhenAuthorizationRequestDoesNotContainOpenidScopeThenReturnNull() { - OAuth2AuthorizationRequest authorizationRequest = request().scope("scope1").build(); + OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request().scope("scope1") + .build(); OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest, this.authorizationResponse); @@ -178,7 +177,8 @@ public class OidcAuthorizationCodeAuthenticationProviderTests { this.exception.expect(OAuth2AuthenticationException.class); this.exception.expectMessage(containsString(OAuth2ErrorCodes.INVALID_SCOPE)); - OAuth2AuthorizationResponse authorizationResponse = error().errorCode(OAuth2ErrorCodes.INVALID_SCOPE).build(); + OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.error() + .errorCode(OAuth2ErrorCodes.INVALID_SCOPE).build(); OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest, authorizationResponse); @@ -191,7 +191,8 @@ public class OidcAuthorizationCodeAuthenticationProviderTests { this.exception.expect(OAuth2AuthenticationException.class); this.exception.expectMessage(containsString("invalid_state_parameter")); - OAuth2AuthorizationResponse authorizationResponse = success().state("89012").build(); + OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.success().state("89012") + .build(); OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest, authorizationResponse); @@ -217,7 +218,7 @@ public class OidcAuthorizationCodeAuthenticationProviderTests { this.exception.expect(OAuth2AuthenticationException.class); this.exception.expectMessage(containsString("missing_signature_verifier")); - ClientRegistration clientRegistration = clientRegistration().jwkSetUri(null).build(); + ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().jwkSetUri(null).build(); this.authenticationProvider .authenticate(new OAuth2LoginAuthenticationToken(clientRegistration, this.authorizationExchange)); @@ -333,7 +334,7 @@ public class OidcAuthorizationCodeAuthenticationProviderTests { } private void setUpIdToken(Map claims) { - Jwt idToken = jwt().claims(c -> c.putAll(claims)).build(); + Jwt idToken = TestJwts.jwt().claims(c -> c.putAll(claims)).build(); JwtDecoder jwtDecoder = mock(JwtDecoder.class); given(jwtDecoder.decode(anyString())).willReturn(idToken); this.authenticationProvider.setJwtDecoderFactory(registration -> jwtDecoder); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeReactiveAuthenticationManagerTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeReactiveAuthenticationManagerTests.java index 74bbe392bd..86935d9027 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeReactiveAuthenticationManagerTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeReactiveAuthenticationManagerTests.java @@ -63,6 +63,7 @@ import org.springframework.security.oauth2.core.oidc.user.OidcUser; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.JwtException; import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder; +import org.springframework.security.oauth2.jwt.TestJwts; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; @@ -71,8 +72,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.springframework.security.oauth2.client.oidc.authentication.OidcAuthorizationCodeReactiveAuthenticationManager.createHash; -import static org.springframework.security.oauth2.jwt.TestJwts.jwt; /** * @author Rob Winch @@ -196,7 +195,7 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests { claims.put(IdTokenClaimNames.SUB, "sub"); claims.put(IdTokenClaimNames.AUD, Arrays.asList("client-id")); claims.put(IdTokenClaimNames.NONCE, "invalid-nonce-hash"); - Jwt idToken = jwt().claims(c -> c.putAll(claims)).build(); + Jwt idToken = TestJwts.jwt().claims(c -> c.putAll(claims)).build(); given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken)); @@ -221,7 +220,7 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests { claims.put(IdTokenClaimNames.SUB, "rob"); claims.put(IdTokenClaimNames.AUD, Arrays.asList("client-id")); claims.put(IdTokenClaimNames.NONCE, this.nonceHash); - Jwt idToken = jwt().claims(c -> c.putAll(claims)).build(); + Jwt idToken = TestJwts.jwt().claims(c -> c.putAll(claims)).build(); given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); given(this.userService.loadUser(any())).willReturn(Mono.empty()); @@ -244,7 +243,7 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests { claims.put(IdTokenClaimNames.SUB, "rob"); claims.put(IdTokenClaimNames.AUD, Arrays.asList("client-id")); claims.put(IdTokenClaimNames.NONCE, this.nonceHash); - Jwt idToken = jwt().claims(c -> c.putAll(claims)).build(); + Jwt idToken = TestJwts.jwt().claims(c -> c.putAll(claims)).build(); given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); DefaultOidcUser user = new DefaultOidcUser(AuthorityUtils.createAuthorityList("ROLE_USER"), this.idToken); @@ -275,7 +274,7 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests { claims.put(IdTokenClaimNames.SUB, "rob"); claims.put(IdTokenClaimNames.AUD, Arrays.asList("client-id")); claims.put(IdTokenClaimNames.NONCE, this.nonceHash); - Jwt idToken = jwt().claims(c -> c.putAll(claims)).build(); + Jwt idToken = TestJwts.jwt().claims(c -> c.putAll(claims)).build(); given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); DefaultOidcUser user = new DefaultOidcUser(AuthorityUtils.createAuthorityList("ROLE_USER"), this.idToken); @@ -310,7 +309,7 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests { claims.put(IdTokenClaimNames.SUB, "rob"); claims.put(IdTokenClaimNames.AUD, Arrays.asList(clientRegistration.getClientId())); claims.put(IdTokenClaimNames.NONCE, this.nonceHash); - Jwt idToken = jwt().claims(c -> c.putAll(claims)).build(); + Jwt idToken = TestJwts.jwt().claims(c -> c.putAll(claims)).build(); given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); DefaultOidcUser user = new DefaultOidcUser(AuthorityUtils.createAuthorityList("ROLE_USER"), this.idToken); @@ -340,7 +339,7 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests { claims.put(IdTokenClaimNames.SUB, "rob"); claims.put(IdTokenClaimNames.AUD, Collections.singletonList(clientRegistration.getClientId())); claims.put(IdTokenClaimNames.NONCE, this.nonceHash); - Jwt idToken = jwt().claims(c -> c.putAll(claims)).build(); + Jwt idToken = TestJwts.jwt().claims(c -> c.putAll(claims)).build(); given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse)); DefaultOidcUser user = new DefaultOidcUser(AuthorityUtils.createAuthorityList("ROLE_USER"), this.idToken); @@ -366,7 +365,7 @@ public class OidcAuthorizationCodeReactiveAuthenticationManagerTests { Map additionalParameters = new HashMap<>(); try { String nonce = this.secureKeyGenerator.generateKey(); - this.nonceHash = createHash(nonce); + this.nonceHash = OidcAuthorizationCodeReactiveAuthenticationManager.createHash(nonce); attributes.put(OidcParameterNames.NONCE, nonce); additionalParameters.put(OidcParameterNames.NONCE, this.nonceHash); } diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcReactiveOAuth2UserServiceTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcReactiveOAuth2UserServiceTests.java index 04a51b5d20..1d9af0f825 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcReactiveOAuth2UserServiceTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcReactiveOAuth2UserServiceTests.java @@ -41,10 +41,12 @@ import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; import org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserService; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; +import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; import org.springframework.security.oauth2.core.converter.ClaimTypeConverter; import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames; import org.springframework.security.oauth2.core.oidc.OidcIdToken; import org.springframework.security.oauth2.core.oidc.StandardClaimNames; +import org.springframework.security.oauth2.core.oidc.TestOidcIdTokens; import org.springframework.security.oauth2.core.oidc.user.OidcUser; import org.springframework.security.oauth2.core.user.DefaultOAuth2User; import org.springframework.security.oauth2.core.user.OAuth2User; @@ -58,10 +60,6 @@ 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.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration; -import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.noScopes; -import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.scopes; -import static org.springframework.security.oauth2.core.oidc.TestOidcIdTokens.idToken; /** * @author Rob Winch @@ -76,7 +74,7 @@ public class OidcReactiveOAuth2UserServiceTests { private ClientRegistration.Builder registration = TestClientRegistrations.clientRegistration() .userNameAttributeName(IdTokenClaimNames.SUB); - private OidcIdToken idToken = idToken().build(); + private OidcIdToken idToken = TestOidcIdTokens.idToken().build(); private OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", Instant.now(), Instant.now().plus(Duration.ofDays(1)), Collections.singleton("read:user")); @@ -195,8 +193,8 @@ public class OidcReactiveOAuth2UserServiceTests { @Test public void loadUserWhenTokenContainsScopesThenIndividualScopeAuthorities() { OidcReactiveOAuth2UserService userService = new OidcReactiveOAuth2UserService(); - OidcUserRequest request = new OidcUserRequest(clientRegistration().build(), - scopes("message:read", "message:write"), idToken().build()); + OidcUserRequest request = new OidcUserRequest(TestClientRegistrations.clientRegistration().build(), + TestOAuth2AccessTokens.scopes("message:read", "message:write"), TestOidcIdTokens.idToken().build()); OidcUser user = userService.loadUser(request).block(); assertThat(user.getAuthorities()).hasSize(3); @@ -209,7 +207,8 @@ public class OidcReactiveOAuth2UserServiceTests { @Test public void loadUserWhenTokenDoesNotContainScopesThenNoScopeAuthorities() { OidcReactiveOAuth2UserService userService = new OidcReactiveOAuth2UserService(); - OidcUserRequest request = new OidcUserRequest(clientRegistration().build(), noScopes(), idToken().build()); + OidcUserRequest request = new OidcUserRequest(TestClientRegistrations.clientRegistration().build(), + TestOAuth2AccessTokens.noScopes(), TestOidcIdTokens.idToken().build()); OidcUser user = userService.loadUser(request).block(); assertThat(user.getAuthorities()).hasSize(1); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserRequestTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserRequestTests.java index 88f668af69..a5ac5ebdc3 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserRequestTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserRequestTests.java @@ -25,13 +25,13 @@ import org.junit.Before; import org.junit.Test; import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.TestClientRegistrations; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.oidc.OidcIdToken; +import org.springframework.security.oauth2.core.oidc.TestOidcIdTokens; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration; -import static org.springframework.security.oauth2.core.oidc.TestOidcIdTokens.idToken; /** * Tests for {@link OidcUserRequest}. @@ -50,10 +50,10 @@ public class OidcUserRequestTests { @Before public void setUp() { - this.clientRegistration = clientRegistration().build(); + this.clientRegistration = TestClientRegistrations.clientRegistration().build(); this.accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token-1234", Instant.now(), Instant.now().plusSeconds(60), new LinkedHashSet<>(Arrays.asList("scope1", "scope2"))); - this.idToken = idToken().authorizedParty(this.clientRegistration.getClientId()).build(); + this.idToken = TestOidcIdTokens.idToken().authorizedParty(this.clientRegistration.getClientId()).build(); this.additionalParameters = new HashMap<>(); this.additionalParameters.put("param1", "value1"); this.additionalParameters.put("param2", "value2"); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserServiceTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserServiceTests.java index 229e38c64f..017b77408a 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserServiceTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserServiceTests.java @@ -39,15 +39,18 @@ import org.springframework.http.MediaType; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.TestClientRegistrations; import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; import org.springframework.security.oauth2.core.AuthenticationMethod; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; +import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; import org.springframework.security.oauth2.core.converter.ClaimTypeConverter; import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames; import org.springframework.security.oauth2.core.oidc.OidcIdToken; import org.springframework.security.oauth2.core.oidc.OidcScopes; import org.springframework.security.oauth2.core.oidc.StandardClaimNames; +import org.springframework.security.oauth2.core.oidc.TestOidcIdTokens; import org.springframework.security.oauth2.core.oidc.user.OidcUser; import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority; @@ -58,10 +61,6 @@ 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.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration; -import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.noScopes; -import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.scopes; -import static org.springframework.security.oauth2.core.oidc.TestOidcIdTokens.idToken; /** * Tests for {@link OidcUserService}. @@ -87,11 +86,11 @@ public class OidcUserServiceTests { public void setup() throws Exception { this.server = new MockWebServer(); this.server.start(); - this.clientRegistrationBuilder = clientRegistration().userInfoUri(null) + this.clientRegistrationBuilder = TestClientRegistrations.clientRegistration().userInfoUri(null) .userInfoAuthenticationMethod(AuthenticationMethod.HEADER) .userNameAttributeName(StandardClaimNames.SUB); - this.accessToken = scopes(OidcScopes.OPENID, OidcScopes.PROFILE); + this.accessToken = TestOAuth2AccessTokens.scopes(OidcScopes.OPENID, OidcScopes.PROFILE); Map idTokenClaims = new HashMap<>(); idTokenClaims.put(IdTokenClaimNames.ISS, "https://provider.com"); @@ -154,7 +153,7 @@ public class OidcUserServiceTests { public void loadUserWhenNonStandardScopesAuthorizedThenUserInfoEndpointNotRequested() { ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri("https://provider.com/user") .build(); - this.accessToken = scopes("scope1", "scope2"); + this.accessToken = TestOAuth2AccessTokens.scopes("scope1", "scope2"); OidcUser user = this.userService .loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken)); @@ -173,7 +172,7 @@ public class OidcUserServiceTests { ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri).build(); - this.accessToken = scopes("scope1", "scope2"); + this.accessToken = TestOAuth2AccessTokens.scopes("scope1", "scope2"); this.userService.setAccessibleScopes(Collections.singleton("scope2")); OidcUser user = this.userService @@ -193,7 +192,7 @@ public class OidcUserServiceTests { ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri).build(); - this.accessToken = scopes("scope1", "scope2"); + this.accessToken = TestOAuth2AccessTokens.scopes("scope1", "scope2"); this.userService.setAccessibleScopes(Collections.emptySet()); OidcUser user = this.userService @@ -434,8 +433,8 @@ public class OidcUserServiceTests { @Test public void loadUserWhenTokenContainsScopesThenIndividualScopeAuthorities() { OidcUserService userService = new OidcUserService(); - OidcUserRequest request = new OidcUserRequest(clientRegistration().build(), - scopes("message:read", "message:write"), idToken().build()); + OidcUserRequest request = new OidcUserRequest(TestClientRegistrations.clientRegistration().build(), + TestOAuth2AccessTokens.scopes("message:read", "message:write"), TestOidcIdTokens.idToken().build()); OidcUser user = userService.loadUser(request); assertThat(user.getAuthorities()).hasSize(3); @@ -448,7 +447,8 @@ public class OidcUserServiceTests { @Test public void loadUserWhenTokenDoesNotContainScopesThenNoScopeAuthorities() { OidcUserService userService = new OidcUserService(); - OidcUserRequest request = new OidcUserRequest(clientRegistration().build(), noScopes(), idToken().build()); + OidcUserRequest request = new OidcUserRequest(TestClientRegistrations.clientRegistration().build(), + TestOAuth2AccessTokens.noScopes(), TestOidcIdTokens.idToken().build()); OidcUser user = userService.loadUser(request); assertThat(user.getAuthorities()).hasSize(1); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/ClientRegistrationTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/ClientRegistrationTests.java index b841824ae5..33bea2962b 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/ClientRegistrationTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/ClientRegistrationTests.java @@ -30,8 +30,6 @@ import org.springframework.security.oauth2.core.ClientAuthenticationMethod; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.springframework.security.oauth2.client.registration.ClientRegistration.withClientRegistration; -import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration; /** * Tests for {@link ClientRegistration}. @@ -497,8 +495,8 @@ public class ClientRegistrationTests { @Test public void buildWhenClientRegistrationProvidedThenMakesACopy() { - ClientRegistration clientRegistration = clientRegistration().build(); - ClientRegistration updated = withClientRegistration(clientRegistration).build(); + ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build(); + ClientRegistration updated = ClientRegistration.withClientRegistration(clientRegistration).build(); assertThat(clientRegistration.getScopes()).isEqualTo(updated.getScopes()); assertThat(clientRegistration.getScopes()).isNotSameAs(updated.getScopes()); assertThat(clientRegistration.getProviderDetails().getConfigurationMetadata()) @@ -509,8 +507,8 @@ public class ClientRegistrationTests { @Test public void buildWhenClientRegistrationProvidedThenEachPropertyMatches() { - ClientRegistration clientRegistration = clientRegistration().build(); - ClientRegistration updated = withClientRegistration(clientRegistration).build(); + ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build(); + ClientRegistration updated = ClientRegistration.withClientRegistration(clientRegistration).build(); assertThat(clientRegistration.getRegistrationId()).isEqualTo(updated.getRegistrationId()); assertThat(clientRegistration.getClientId()).isEqualTo(updated.getClientId()); assertThat(clientRegistration.getClientSecret()).isEqualTo(updated.getClientSecret()); @@ -544,9 +542,9 @@ public class ClientRegistrationTests { @Test public void buildWhenClientRegistrationValuesOverriddenThenPropagated() { - ClientRegistration clientRegistration = clientRegistration().build(); - ClientRegistration updated = withClientRegistration(clientRegistration).clientSecret("a-new-secret") - .scope("a-new-scope") + ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build(); + ClientRegistration updated = ClientRegistration.withClientRegistration(clientRegistration) + .clientSecret("a-new-secret").scope("a-new-scope") .providerConfigurationMetadata(Collections.singletonMap("a-new-config", "a-new-value")).build(); assertThat(clientRegistration.getClientSecret()).isNotEqualTo(updated.getClientSecret()); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/CustomUserTypesOAuth2UserServiceTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/CustomUserTypesOAuth2UserServiceTests.java index 1fde0671fd..5fa6eab627 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/CustomUserTypesOAuth2UserServiceTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/CustomUserTypesOAuth2UserServiceTests.java @@ -34,15 +34,15 @@ import org.springframework.http.MediaType; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.TestClientRegistrations; import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; +import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; import org.springframework.security.oauth2.core.user.OAuth2User; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.containsString; -import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration; -import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.noScopes; /** * Tests for {@link CustomUserTypesOAuth2UserService}. @@ -68,8 +68,8 @@ public class CustomUserTypesOAuth2UserServiceTests { this.server = new MockWebServer(); this.server.start(); String registrationId = "client-registration-id-1"; - this.clientRegistrationBuilder = clientRegistration().registrationId(registrationId); - this.accessToken = noScopes(); + this.clientRegistrationBuilder = TestClientRegistrations.clientRegistration().registrationId(registrationId); + this.accessToken = TestOAuth2AccessTokens.noScopes(); Map> customUserTypes = new HashMap<>(); customUserTypes.put(registrationId, CustomOAuth2User.class); @@ -113,8 +113,8 @@ public class CustomUserTypesOAuth2UserServiceTests { @Test public void loadUserWhenCustomUserTypeNotFoundThenReturnNull() { - ClientRegistration clientRegistration = clientRegistration().registrationId("other-client-registration-id-1") - .build(); + ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration() + .registrationId("other-client-registration-id-1").build(); OAuth2User user = this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)); assertThat(user).isNull(); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DefaultOAuth2UserServiceTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DefaultOAuth2UserServiceTests.java index b4256a3b0b..97db1f4eeb 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DefaultOAuth2UserServiceTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DefaultOAuth2UserServiceTests.java @@ -40,9 +40,11 @@ import org.springframework.http.ResponseEntity; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.client.registration.ClientRegistration; +import org.springframework.security.oauth2.client.registration.TestClientRegistrations; import org.springframework.security.oauth2.core.AuthenticationMethod; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; +import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.security.oauth2.core.user.OAuth2UserAuthority; import org.springframework.web.client.RestOperations; @@ -53,9 +55,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration; -import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.noScopes; -import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.scopes; /** * Tests for {@link DefaultOAuth2UserService}. @@ -80,8 +79,9 @@ public class DefaultOAuth2UserServiceTests { public void setup() throws Exception { this.server = new MockWebServer(); this.server.start(); - this.clientRegistrationBuilder = clientRegistration().userInfoUri(null).userNameAttributeName(null); - this.accessToken = noScopes(); + this.clientRegistrationBuilder = TestClientRegistrations.clientRegistration().userInfoUri(null) + .userNameAttributeName(null); + this.accessToken = TestOAuth2AccessTokens.noScopes(); } @After @@ -312,8 +312,8 @@ public class DefaultOAuth2UserServiceTests { Map body = new HashMap<>(); body.put("id", "id"); DefaultOAuth2UserService userService = withMockResponse(body); - OAuth2UserRequest request = new OAuth2UserRequest(clientRegistration().build(), - scopes("message:read", "message:write")); + OAuth2UserRequest request = new OAuth2UserRequest(TestClientRegistrations.clientRegistration().build(), + TestOAuth2AccessTokens.scopes("message:read", "message:write")); OAuth2User user = userService.loadUser(request); assertThat(user.getAuthorities()).hasSize(3); @@ -328,7 +328,8 @@ public class DefaultOAuth2UserServiceTests { Map body = new HashMap<>(); body.put("id", "id"); DefaultOAuth2UserService userService = withMockResponse(body); - OAuth2UserRequest request = new OAuth2UserRequest(clientRegistration().build(), noScopes()); + OAuth2UserRequest request = new OAuth2UserRequest(TestClientRegistrations.clientRegistration().build(), + TestOAuth2AccessTokens.noScopes()); OAuth2User user = userService.loadUser(request); assertThat(user.getAuthorities()).hasSize(1); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DefaultReactiveOAuth2UserServiceTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DefaultReactiveOAuth2UserServiceTests.java index 2e98a22fe2..2ac7888a57 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DefaultReactiveOAuth2UserServiceTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DefaultReactiveOAuth2UserServiceTests.java @@ -45,6 +45,7 @@ import org.springframework.security.oauth2.client.registration.TestClientRegistr import org.springframework.security.oauth2.core.AuthenticationMethod; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; +import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.security.oauth2.core.user.OAuth2UserAuthority; import org.springframework.web.reactive.function.client.WebClient; @@ -55,9 +56,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; -import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration; -import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.noScopes; -import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.scopes; /** * @author Rob Winch @@ -208,8 +206,8 @@ public class DefaultReactiveOAuth2UserServiceTests { Map body = new HashMap<>(); body.put("id", "id"); DefaultReactiveOAuth2UserService userService = withMockResponse(body); - OAuth2UserRequest request = new OAuth2UserRequest(clientRegistration().build(), - scopes("message:read", "message:write")); + OAuth2UserRequest request = new OAuth2UserRequest(TestClientRegistrations.clientRegistration().build(), + TestOAuth2AccessTokens.scopes("message:read", "message:write")); OAuth2User user = userService.loadUser(request).block(); assertThat(user.getAuthorities()).hasSize(3); @@ -224,7 +222,8 @@ public class DefaultReactiveOAuth2UserServiceTests { Map body = new HashMap<>(); body.put("id", "id"); DefaultReactiveOAuth2UserService userService = withMockResponse(body); - OAuth2UserRequest request = new OAuth2UserRequest(clientRegistration().build(), noScopes()); + OAuth2UserRequest request = new OAuth2UserRequest(TestClientRegistrations.clientRegistration().build(), + TestOAuth2AccessTokens.noScopes()); OAuth2User user = userService.loadUser(request).block(); assertThat(user.getAuthorities()).hasSize(1); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/OAuth2UserRequestEntityConverterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/OAuth2UserRequestEntityConverterTests.java index 7516095a72..a48c7531dd 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/OAuth2UserRequestEntityConverterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/OAuth2UserRequestEntityConverterTests.java @@ -33,7 +33,6 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.util.MultiValueMap; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED_VALUE; /** * Tests for {@link OAuth2UserRequestEntityConverter}. @@ -78,7 +77,7 @@ public class OAuth2UserRequestEntityConverterTests { HttpHeaders headers = requestEntity.getHeaders(); assertThat(headers.getAccept()).contains(MediaType.APPLICATION_JSON); assertThat(headers.getContentType()) - .isEqualTo(MediaType.valueOf(APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8")); + .isEqualTo(MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8")); MultiValueMap formParameters = (MultiValueMap) requestEntity.getBody(); assertThat(formParameters.getFirst(OAuth2ParameterNames.ACCESS_TOKEN)) diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilterTests.java index 13eb23d8f5..99c8f21033 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilterTests.java @@ -49,8 +49,12 @@ import org.springframework.security.oauth2.client.registration.TestClientRegistr import org.springframework.security.oauth2.core.OAuth2AuthorizationException; import org.springframework.security.oauth2.core.OAuth2Error; import org.springframework.security.oauth2.core.OAuth2ErrorCodes; +import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; +import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; +import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationExchanges; +import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests; import org.springframework.security.web.savedrequest.HttpSessionRequestCache; import org.springframework.security.web.savedrequest.RequestCache; import org.springframework.security.web.util.UrlUtils; @@ -65,10 +69,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.springframework.security.oauth2.core.TestOAuth2AccessTokens.noScopes; -import static org.springframework.security.oauth2.core.TestOAuth2RefreshTokens.refreshToken; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationExchanges.success; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests.request; /** * Tests for {@link OAuth2AuthorizationCodeGrantFilter}. @@ -473,14 +473,15 @@ public class OAuth2AuthorizationCodeGrantFilterTests { ClientRegistration registration) { Map attributes = new HashMap<>(); attributes.put(OAuth2ParameterNames.REGISTRATION_ID, registration.getRegistrationId()); - OAuth2AuthorizationRequest authorizationRequest = request().attributes(attributes) - .redirectUri(UrlUtils.buildFullRequestUrl(request)).build(); + OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request() + .attributes(attributes).redirectUri(UrlUtils.buildFullRequestUrl(request)).build(); this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, request, response); } private void setUpAuthenticationResult(ClientRegistration registration) { OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken( - registration, success(), noScopes(), refreshToken()); + registration, TestOAuth2AuthorizationExchanges.success(), TestOAuth2AccessTokens.noScopes(), + TestOAuth2RefreshTokens.refreshToken()); given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authentication); } diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2LoginAuthenticationFilterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2LoginAuthenticationFilterTests.java index c632f1b81e..73b5cd3b0b 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2LoginAuthenticationFilterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2LoginAuthenticationFilterTests.java @@ -50,6 +50,7 @@ import org.springframework.security.oauth2.core.OAuth2RefreshToken; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; +import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationExchanges; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.WebAuthenticationDetails; @@ -65,7 +66,6 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationExchanges.success; /** * Tests for {@link OAuth2LoginAuthenticationFilter}. @@ -490,7 +490,8 @@ public class OAuth2LoginAuthenticationFilterTests { given(this.loginAuthentication.getName()).willReturn(this.principalName1); given(this.loginAuthentication.getAuthorities()).willReturn(AuthorityUtils.createAuthorityList("ROLE_USER")); given(this.loginAuthentication.getClientRegistration()).willReturn(registration); - given(this.loginAuthentication.getAuthorizationExchange()).willReturn(success()); + given(this.loginAuthentication.getAuthorizationExchange()) + .willReturn(TestOAuth2AuthorizationExchanges.success()); given(this.loginAuthentication.getAccessToken()).willReturn(mock(OAuth2AccessToken.class)); given(this.loginAuthentication.getRefreshToken()).willReturn(mock(OAuth2RefreshToken.class)); given(this.loginAuthentication.isAuthenticated()).willReturn(true); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java index e3564117d4..fcef072043 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java @@ -61,8 +61,8 @@ import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; import org.springframework.web.context.request.ServletWebRequest; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; +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.anyString; import static org.mockito.ArgumentMatchers.eq; diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionITests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionITests.java index 8007fad1bc..faefc4d01c 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionITests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionITests.java @@ -63,7 +63,6 @@ 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.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId; /** * @author Phil Clay @@ -142,8 +141,10 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionITests { .willReturn(Mono.just(clientRegistration)); this.webClient.get().uri(this.serverUrl) - .attributes(clientRegistrationId(clientRegistration.getRegistrationId())).retrieve() - .bodyToMono(String.class).subscriberContext(Context.of(ServerWebExchange.class, this.exchange)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .clientRegistrationId(clientRegistration.getRegistrationId())) + .retrieve().bodyToMono(String.class) + .subscriberContext(Context.of(ServerWebExchange.class, this.exchange)) .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication)).block(); assertThat(this.server.getRequestCount()).isEqualTo(2); @@ -180,8 +181,10 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionITests { eq(clientRegistration.getRegistrationId()), eq(this.authentication), eq(this.exchange)); this.webClient.get().uri(this.serverUrl) - .attributes(clientRegistrationId(clientRegistration.getRegistrationId())).retrieve() - .bodyToMono(String.class).subscriberContext(Context.of(ServerWebExchange.class, this.exchange)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .clientRegistrationId(clientRegistration.getRegistrationId())) + .retrieve().bodyToMono(String.class) + .subscriberContext(Context.of(ServerWebExchange.class, this.exchange)) .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication)).block(); assertThat(this.server.getRequestCount()).isEqualTo(2); @@ -221,11 +224,13 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionITests { .willReturn(Mono.just(clientRegistration2)); this.webClient.get().uri(this.serverUrl) - .attributes(clientRegistrationId(clientRegistration1.getRegistrationId())).retrieve() - .bodyToMono(String.class) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .clientRegistrationId(clientRegistration1.getRegistrationId())) + .retrieve().bodyToMono(String.class) .flatMap(response -> this.webClient.get().uri(this.serverUrl) - .attributes(clientRegistrationId(clientRegistration2.getRegistrationId())).retrieve() - .bodyToMono(String.class)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .clientRegistrationId(clientRegistration2.getRegistrationId())) + .retrieve().bodyToMono(String.class)) .subscriberContext(Context.of(ServerWebExchange.class, this.exchange)) .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication)).block(); @@ -267,8 +272,10 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionITests { eq(this.exchange)); Mono requestMono = this.webClient.get().uri(this.serverUrl) - .attributes(clientRegistrationId(clientRegistration.getRegistrationId())).retrieve() - .bodyToMono(String.class).subscriberContext(Context.of(ServerWebExchange.class, this.exchange)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .clientRegistrationId(clientRegistration.getRegistrationId())) + .retrieve().bodyToMono(String.class) + .subscriberContext(Context.of(ServerWebExchange.class, this.exchange)) .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication)); // first try should fail, and remove the cached authorized client diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionTests.java index 950f145c4e..7c0d9b8dd7 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionTests.java @@ -96,8 +96,8 @@ import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -106,9 +106,6 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; -import static org.springframework.http.HttpMethod.GET; -import static org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId; -import static org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient; /** * @author Rob Winch @@ -208,7 +205,7 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { @Test public void filterWhenAuthorizedClientNullThenAuthorizationHeaderNull() { - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build(); this.function.filter(request, this.exchange).block(); @@ -219,8 +216,9 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { public void filterWhenAuthorizedClientThenAuthorizationHeader() { OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .build(); this.function.filter(request, this.exchange).subscriberContext(serverWebExchange()).block(); @@ -232,8 +230,9 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { public void filterWhenExistingAuthorizationThenSingleAuthorizationHeader() { OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .header(HttpHeaders.AUTHORIZATION, "Existing").attributes(oauth2AuthorizedClient(authorizedClient)) + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .header(HttpHeaders.AUTHORIZATION, "Existing") + .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) .build(); this.function.filter(request, this.exchange).subscriberContext(serverWebExchange()).block(); @@ -259,8 +258,9 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { TestingAuthenticationToken authentication = new TestingAuthenticationToken("test", "this"); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .build(); this.function.filter(request, this.exchange) .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication)) @@ -285,8 +285,9 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(registration, "principalName", this.accessToken, null); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .build(); this.function.filter(request, this.exchange) .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication)) @@ -317,8 +318,9 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .build(); TestingAuthenticationToken authentication = new TestingAuthenticationToken("test", "this"); this.function.filter(request, this.exchange) @@ -357,8 +359,9 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", issuedAt); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .build(); this.function.filter(request, this.exchange).subscriberContext(serverWebExchange()).block(); @@ -379,8 +382,9 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { public void filterWhenRefreshTokenNullThenShouldRefreshFalse() { OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .build(); this.function.filter(request, this.exchange).subscriberContext(serverWebExchange()).block(); @@ -399,8 +403,9 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt()); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .build(); this.function.filter(request, this.exchange).subscriberContext(serverWebExchange()).block(); @@ -425,8 +430,9 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt()); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .build(); given(this.exchange.getResponse().rawStatusCode()).willReturn(HttpStatus.UNAUTHORIZED.value()); @@ -460,8 +466,9 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt()); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .build(); WebClientResponseException exception = WebClientResponseException.create(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase(), HttpHeaders.EMPTY, new byte[0], StandardCharsets.UTF_8); @@ -499,8 +506,9 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt()); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .build(); given(this.exchange.getResponse().rawStatusCode()).willReturn(HttpStatus.FORBIDDEN.value()); @@ -534,8 +542,9 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt()); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .build(); WebClientResponseException exception = WebClientResponseException.create(HttpStatus.FORBIDDEN.value(), HttpStatus.FORBIDDEN.getReasonPhrase(), HttpHeaders.EMPTY, new byte[0], StandardCharsets.UTF_8); @@ -573,8 +582,9 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt()); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .build(); String wwwAuthenticateHeader = "Bearer error=\"insufficient_scope\", " + "error_description=\"The request requires higher privileges than provided by the access token.\", " @@ -617,8 +627,9 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt()); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .build(); OAuth2AuthorizationException exception = new OAuth2AuthorizationException( new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, null, null)); @@ -646,8 +657,9 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt()); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .build(); given(this.exchange.getResponse().rawStatusCode()).willReturn(HttpStatus.BAD_REQUEST.value()); @@ -689,8 +701,10 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { .contentType(MediaType.APPLICATION_FORM_URLENCODED).body("username=username&password=password")) .build(); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(clientRegistrationId(registration.getRegistrationId())).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction + .clientRegistrationId(registration.getRegistrationId())) + .build(); this.function.filter(request, this.exchange) .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication)) @@ -715,8 +729,10 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { this.accessToken, refreshToken); given(this.authorizedClientRepository.loadAuthorizedClient(any(), any(), any())) .willReturn(Mono.just(authorizedClient)); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(clientRegistrationId(this.registration.getRegistrationId())).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction + .clientRegistrationId(this.registration.getRegistrationId())) + .build(); this.function.filter(request, this.exchange).subscriberContext(serverWebExchange()).block(); @@ -738,7 +754,7 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { this.accessToken, refreshToken); given(this.authorizedClientRepository.loadAuthorizedClient(any(), any(), any())) .willReturn(Mono.just(authorizedClient)); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build(); this.function.filter(request, this.exchange).subscriberContext(serverWebExchange()).block(); @@ -761,7 +777,7 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { this.accessToken, refreshToken); given(this.authorizedClientRepository.loadAuthorizedClient(any(), any(), any())) .willReturn(Mono.just(authorizedClient)); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build(); OAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), Collections.singletonMap("user", "rob"), "user"); @@ -783,7 +799,7 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { @Test public void filterWhenDefaultOAuth2AuthorizedClientFalseThenEmpty() { - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build(); OAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), Collections.singletonMap("user", "rob"), "user"); @@ -806,8 +822,10 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { this.accessToken, refreshToken); given(this.authorizedClientRepository.loadAuthorizedClient(any(), any(), any())) .willReturn(Mono.just(authorizedClient)); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(clientRegistrationId(this.registration.getRegistrationId())).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction + .clientRegistrationId(this.registration.getRegistrationId())) + .build(); this.function.filter(request, this.exchange).subscriberContext(serverWebExchange()).block(); @@ -835,8 +853,10 @@ public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests { given(this.clientRegistrationRepository.findByRegistrationId(eq(registration.getRegistrationId()))) .willReturn(Mono.just(registration)); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(clientRegistrationId(registration.getRegistrationId())).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction + .clientRegistrationId(registration.getRegistrationId())) + .build(); this.function.filter(request, this.exchange).block(); diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionITests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionITests.java index 7e8ca01a23..deccb25a89 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionITests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionITests.java @@ -64,8 +64,6 @@ 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.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY; -import static org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId; /** * @author Joe Grandja @@ -163,8 +161,9 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionITests { .willReturn(clientRegistration); this.webClient.get().uri(this.serverUrl) - .attributes(clientRegistrationId(clientRegistration.getRegistrationId())).retrieve() - .bodyToMono(String.class).block(); + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .clientRegistrationId(clientRegistration.getRegistrationId())) + .retrieve().bodyToMono(String.class).block(); assertThat(this.server.getRequestCount()).isEqualTo(2); @@ -200,8 +199,9 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionITests { eq(clientRegistration.getRegistrationId()), eq(this.authentication), eq(this.request)); this.webClient.get().uri(this.serverUrl) - .attributes(clientRegistrationId(clientRegistration.getRegistrationId())).retrieve() - .bodyToMono(String.class).block(); + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .clientRegistrationId(clientRegistration.getRegistrationId())) + .retrieve().bodyToMono(String.class).block(); assertThat(this.server.getRequestCount()).isEqualTo(2); @@ -240,11 +240,13 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionITests { .willReturn(clientRegistration2); this.webClient.get().uri(this.serverUrl) - .attributes(clientRegistrationId(clientRegistration1.getRegistrationId())).retrieve() - .bodyToMono(String.class) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .clientRegistrationId(clientRegistration1.getRegistrationId())) + .retrieve().bodyToMono(String.class) .flatMap(response -> this.webClient.get().uri(this.serverUrl) - .attributes(clientRegistrationId(clientRegistration2.getRegistrationId())).retrieve() - .bodyToMono(String.class)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .clientRegistrationId(clientRegistration2.getRegistrationId())) + .retrieve().bodyToMono(String.class)) .subscriberContext(context()).block(); assertThat(this.server.getRequestCount()).isEqualTo(4); @@ -262,7 +264,8 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionITests { contextAttributes.put(HttpServletRequest.class, this.request); contextAttributes.put(HttpServletResponse.class, this.response); contextAttributes.put(Authentication.class, this.authentication); - return Context.of(SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY, contextAttributes); + return Context.of(ServletOAuth2AuthorizedClientExchangeFilterFunction.SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY, + contextAttributes); } private MockResponse jsonResponse(String json) { diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionTests.java index edc3d712b8..d50ba79be8 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionTests.java @@ -105,8 +105,8 @@ import org.springframework.web.reactive.function.client.WebClientResponseExcepti import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -114,16 +114,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; -import static org.springframework.http.HttpMethod.GET; -import static org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId; -import static org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY; -import static org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.authentication; -import static org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.getAuthentication; -import static org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.getRequest; -import static org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.getResponse; -import static org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletRequest; -import static org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletResponse; -import static org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient; /** * @author Rob Winch @@ -240,8 +230,8 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { @Test public void defaultRequestRequestResponseWhenNullRequestContextThenRequestAndResponseNull() { Map attrs = getDefaultRequestAttributes(); - assertThat(getRequest(attrs)).isNull(); - assertThat(getResponse(attrs)).isNull(); + assertThat(ServletOAuth2AuthorizedClientExchangeFilterFunction.getRequest(attrs)).isNull(); + assertThat(ServletOAuth2AuthorizedClientExchangeFilterFunction.getResponse(attrs)).isNull(); } @Test @@ -250,21 +240,22 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { MockHttpServletResponse response = new MockHttpServletResponse(); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request, response)); Map attrs = getDefaultRequestAttributes(); - assertThat(getRequest(attrs)).isEqualTo(request); - assertThat(getResponse(attrs)).isEqualTo(response); + assertThat(ServletOAuth2AuthorizedClientExchangeFilterFunction.getRequest(attrs)).isEqualTo(request); + assertThat(ServletOAuth2AuthorizedClientExchangeFilterFunction.getResponse(attrs)).isEqualTo(response); } @Test public void defaultRequestAuthenticationWhenSecurityContextEmptyThenAuthenticationNull() { Map attrs = getDefaultRequestAttributes(); - assertThat(getAuthentication(attrs)).isNull(); + assertThat(ServletOAuth2AuthorizedClientExchangeFilterFunction.getAuthentication(attrs)).isNull(); } @Test public void defaultRequestAuthenticationWhenAuthenticationSetThenAuthenticationSet() { SecurityContextHolder.getContext().setAuthentication(this.authentication); Map attrs = getDefaultRequestAttributes(); - assertThat(getAuthentication(attrs)).isEqualTo(this.authentication); + assertThat(ServletOAuth2AuthorizedClientExchangeFilterFunction.getAuthentication(attrs)) + .isEqualTo(this.authentication); verifyNoInteractions(this.authorizedClientRepository); } @@ -279,7 +270,7 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { @Test public void filterWhenAuthorizedClientNullThenAuthorizationHeaderNull() { - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build(); this.function.filter(request, this.exchange).block(); @@ -291,10 +282,14 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)) - .attributes(httpServletRequest(new MockHttpServletRequest())) - .attributes(httpServletResponse(new MockHttpServletResponse())).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes( + ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .httpServletRequest(new MockHttpServletRequest())) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .httpServletResponse(new MockHttpServletResponse())) + .build(); this.function.filter(request, this.exchange).block(); @@ -307,10 +302,15 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .header(HttpHeaders.AUTHORIZATION, "Existing").attributes(oauth2AuthorizedClient(authorizedClient)) - .attributes(httpServletRequest(new MockHttpServletRequest())) - .attributes(httpServletResponse(new MockHttpServletResponse())).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .header(HttpHeaders.AUTHORIZATION, "Existing") + .attributes( + ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .httpServletRequest(new MockHttpServletRequest())) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .httpServletResponse(new MockHttpServletResponse())) + .build(); this.function.filter(request, this.exchange).block(); @@ -332,10 +332,15 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)).attributes(authentication(this.authentication)) - .attributes(httpServletRequest(new MockHttpServletRequest())) - .attributes(httpServletResponse(new MockHttpServletResponse())).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes( + ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.authentication(this.authentication)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .httpServletRequest(new MockHttpServletRequest())) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .httpServletResponse(new MockHttpServletResponse())) + .build(); this.function.filter(request, this.exchange).block(); @@ -385,10 +390,15 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)).attributes(authentication(this.authentication)) - .attributes(httpServletRequest(new MockHttpServletRequest())) - .attributes(httpServletResponse(new MockHttpServletResponse())).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes( + ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.authentication(this.authentication)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .httpServletRequest(new MockHttpServletRequest())) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .httpServletResponse(new MockHttpServletResponse())) + .build(); this.function.filter(request, this.exchange).block(); @@ -416,10 +426,15 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, null); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)).attributes(authentication(this.authentication)) - .attributes(httpServletRequest(new MockHttpServletRequest())) - .attributes(httpServletResponse(new MockHttpServletResponse())).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes( + ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.authentication(this.authentication)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .httpServletRequest(new MockHttpServletRequest())) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .httpServletResponse(new MockHttpServletResponse())) + .build(); this.function.filter(request, this.exchange).block(); @@ -453,10 +468,15 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, null); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)).attributes(authentication(this.authentication)) - .attributes(httpServletRequest(new MockHttpServletRequest())) - .attributes(httpServletResponse(new MockHttpServletResponse())).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes( + ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.authentication(this.authentication)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .httpServletRequest(new MockHttpServletRequest())) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .httpServletResponse(new MockHttpServletResponse())) + .build(); this.function.filter(request, this.exchange).block(); @@ -502,10 +522,13 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { servletRequest.setParameter(OAuth2ParameterNames.PASSWORD, "password"); MockHttpServletResponse servletResponse = new MockHttpServletResponse(); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(clientRegistrationId(registration.getRegistrationId())) - .attributes(authentication(this.authentication)).attributes(httpServletRequest(servletRequest)) - .attributes(httpServletResponse(servletResponse)).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction + .clientRegistrationId(registration.getRegistrationId())) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.authentication(this.authentication)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletRequest(servletRequest)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletResponse(servletResponse)) + .build(); this.function.filter(request, this.exchange).block(); @@ -535,10 +558,14 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)) - .attributes(httpServletRequest(new MockHttpServletRequest())) - .attributes(httpServletResponse(new MockHttpServletResponse())).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes( + ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .httpServletRequest(new MockHttpServletRequest())) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .httpServletResponse(new MockHttpServletResponse())) + .build(); this.function.filter(request, this.exchange).block(); @@ -560,10 +587,14 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)) - .attributes(httpServletRequest(new MockHttpServletRequest())) - .attributes(httpServletResponse(new MockHttpServletResponse())).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes( + ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .httpServletRequest(new MockHttpServletRequest())) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .httpServletResponse(new MockHttpServletResponse())) + .build(); this.function.filter(request, this.exchange).block(); @@ -583,10 +614,14 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)) - .attributes(httpServletRequest(new MockHttpServletRequest())) - .attributes(httpServletResponse(new MockHttpServletResponse())).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes( + ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .httpServletRequest(new MockHttpServletRequest())) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction + .httpServletResponse(new MockHttpServletResponse())) + .build(); this.function.filter(request, this.exchange).block(); @@ -621,11 +656,11 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { .willReturn(authorizedClient); // Default request attributes set - final ClientRequest request1 = ClientRequest.create(GET, URI.create("https://example1.com")) + final ClientRequest request1 = ClientRequest.create(HttpMethod.GET, URI.create("https://example1.com")) .attributes(attrs -> attrs.putAll(getDefaultRequestAttributes())).build(); // Default request attributes NOT set - final ClientRequest request2 = ClientRequest.create(GET, URI.create("https://example2.com")).build(); + final ClientRequest request2 = ClientRequest.create(HttpMethod.GET, URI.create("https://example2.com")).build(); Context context = context(servletRequest, servletResponse, authentication); @@ -663,9 +698,12 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { this.accessToken); MockHttpServletRequest servletRequest = new MockHttpServletRequest(); MockHttpServletResponse servletResponse = new MockHttpServletResponse(); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)).attributes(httpServletRequest(servletRequest)) - .attributes(httpServletResponse(servletResponse)).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes( + ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletRequest(servletRequest)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletResponse(servletResponse)) + .build(); given(this.exchange.getResponse().rawStatusCode()).willReturn(httpStatus.value()); given(this.exchange.getResponse().headers()).willReturn(mock(ClientResponse.Headers.class)); @@ -695,9 +733,12 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { this.accessToken); MockHttpServletRequest servletRequest = new MockHttpServletRequest(); MockHttpServletResponse servletResponse = new MockHttpServletResponse(); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)).attributes(httpServletRequest(servletRequest)) - .attributes(httpServletResponse(servletResponse)).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes( + ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletRequest(servletRequest)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletResponse(servletResponse)) + .build(); String wwwAuthenticateHeader = "Bearer error=\"insufficient_scope\", " + "error_description=\"The request requires higher privileges than provided by the access token.\", " @@ -748,9 +789,12 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { this.accessToken); MockHttpServletRequest servletRequest = new MockHttpServletRequest(); MockHttpServletResponse servletResponse = new MockHttpServletResponse(); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)).attributes(httpServletRequest(servletRequest)) - .attributes(httpServletResponse(servletResponse)).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes( + ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletRequest(servletRequest)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletResponse(servletResponse)) + .build(); WebClientResponseException exception = WebClientResponseException.create(httpStatus.value(), httpStatus.getReasonPhrase(), HttpHeaders.EMPTY, new byte[0], StandardCharsets.UTF_8); @@ -781,9 +825,12 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { this.accessToken); MockHttpServletRequest servletRequest = new MockHttpServletRequest(); MockHttpServletResponse servletResponse = new MockHttpServletResponse(); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)).attributes(httpServletRequest(servletRequest)) - .attributes(httpServletResponse(servletResponse)).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes( + ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletRequest(servletRequest)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletResponse(servletResponse)) + .build(); OAuth2AuthorizationException authorizationException = new OAuth2AuthorizationException( new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN)); @@ -814,9 +861,12 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { this.accessToken); MockHttpServletRequest servletRequest = new MockHttpServletRequest(); MockHttpServletResponse servletResponse = new MockHttpServletResponse(); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) - .attributes(oauth2AuthorizedClient(authorizedClient)).attributes(httpServletRequest(servletRequest)) - .attributes(httpServletResponse(servletResponse)).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) + .attributes( + ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletRequest(servletRequest)) + .attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletResponse(servletResponse)) + .build(); given(this.exchange.getResponse().rawStatusCode()).willReturn(HttpStatus.BAD_REQUEST.value()); given(this.exchange.getResponse().headers()).willReturn(mock(ClientResponse.Headers.class)); @@ -833,7 +883,8 @@ public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests { contextAttributes.put(HttpServletRequest.class, servletRequest); contextAttributes.put(HttpServletResponse.class, servletResponse); contextAttributes.put(Authentication.class, authentication); - return Context.of(SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY, contextAttributes); + return Context.of(ServletOAuth2AuthorizedClientExchangeFilterFunction.SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY, + contextAttributes); } private static String getBody(ClientRequest request) { diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationCodeGrantWebFilterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationCodeGrantWebFilterTests.java index 1757e3778c..41d9d22b97 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationCodeGrantWebFilterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationCodeGrantWebFilterTests.java @@ -42,6 +42,7 @@ import org.springframework.security.oauth2.core.OAuth2AuthorizationException; import org.springframework.security.oauth2.core.OAuth2Error; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; +import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests; import org.springframework.security.web.server.savedrequest.ServerRequestCache; import org.springframework.util.CollectionUtils; import org.springframework.web.server.ServerWebExchange; @@ -56,7 +57,6 @@ 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.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests.request; /** * @author Rob Winch @@ -333,7 +333,8 @@ public class OAuth2AuthorizationCodeGrantWebFilterTests { MockServerHttpRequest authorizationRequest, ClientRegistration registration) { Map attributes = new HashMap<>(); attributes.put(OAuth2ParameterNames.REGISTRATION_ID, registration.getRegistrationId()); - return request().attributes(attributes).redirectUri(authorizationRequest.getURI().toString()).build(); + return TestOAuth2AuthorizationRequests.request().attributes(attributes) + .redirectUri(authorizationRequest.getURI().toString()).build(); } private static MockServerHttpRequest createAuthorizationRequest(String requestUri) { diff --git a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationRequestRedirectWebFilterTests.java b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationRequestRedirectWebFilterTests.java index 1675240178..41852e6ff3 100644 --- a/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationRequestRedirectWebFilterTests.java +++ b/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationRequestRedirectWebFilterTests.java @@ -37,7 +37,7 @@ import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.server.handler.FilteringWebHandler; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; +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.verify; diff --git a/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/DefaultOAuth2AuthenticatedPrincipal.java b/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/DefaultOAuth2AuthenticatedPrincipal.java index 66aaf058a5..7107109323 100644 --- a/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/DefaultOAuth2AuthenticatedPrincipal.java +++ b/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/DefaultOAuth2AuthenticatedPrincipal.java @@ -22,10 +22,9 @@ import java.util.Collections; import java.util.Map; import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.util.Assert; -import static org.springframework.security.core.authority.AuthorityUtils.NO_AUTHORITIES; - /** * A domain object that wraps the attributes of an OAuth 2.0 token. * @@ -65,7 +64,8 @@ public final class DefaultOAuth2AuthenticatedPrincipal implements OAuth2Authenti Assert.notEmpty(attributes, "attributes cannot be empty"); this.attributes = Collections.unmodifiableMap(attributes); - this.authorities = authorities == null ? NO_AUTHORITIES : Collections.unmodifiableCollection(authorities); + this.authorities = authorities == null ? AuthorityUtils.NO_AUTHORITIES + : Collections.unmodifiableCollection(authorities); this.name = name == null ? (String) this.attributes.get("sub") : name; } diff --git a/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/OidcIdToken.java b/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/OidcIdToken.java index 4738c784b5..1e7d1d3d6a 100644 --- a/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/OidcIdToken.java +++ b/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/OidcIdToken.java @@ -26,19 +26,6 @@ import java.util.function.Consumer; import org.springframework.security.oauth2.core.AbstractOAuth2Token; import org.springframework.util.Assert; -import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.ACR; -import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.AMR; -import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.AT_HASH; -import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.AUD; -import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.AUTH_TIME; -import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.AZP; -import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.C_HASH; -import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.EXP; -import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.IAT; -import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.ISS; -import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.NONCE; -import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.SUB; - /** * An implementation of an {@link AbstractOAuth2Token} representing an OpenID Connect Core * 1.0 ID Token. @@ -145,7 +132,7 @@ public class OidcIdToken extends AbstractOAuth2Token implements IdTokenClaimAcce * @return the {@link Builder} for further configurations */ public Builder accessTokenHash(String accessTokenHash) { - return claim(AT_HASH, accessTokenHash); + return claim(IdTokenClaimNames.AT_HASH, accessTokenHash); } /** @@ -154,7 +141,7 @@ public class OidcIdToken extends AbstractOAuth2Token implements IdTokenClaimAcce * @return the {@link Builder} for further configurations */ public Builder audience(Collection audience) { - return claim(AUD, audience); + return claim(IdTokenClaimNames.AUD, audience); } /** @@ -163,7 +150,7 @@ public class OidcIdToken extends AbstractOAuth2Token implements IdTokenClaimAcce * @return the {@link Builder} for further configurations */ public Builder authTime(Instant authenticatedAt) { - return claim(AUTH_TIME, authenticatedAt); + return claim(IdTokenClaimNames.AUTH_TIME, authenticatedAt); } /** @@ -174,7 +161,7 @@ public class OidcIdToken extends AbstractOAuth2Token implements IdTokenClaimAcce * @return the {@link Builder} for further configurations */ public Builder authenticationContextClass(String authenticationContextClass) { - return claim(ACR, authenticationContextClass); + return claim(IdTokenClaimNames.ACR, authenticationContextClass); } /** @@ -183,7 +170,7 @@ public class OidcIdToken extends AbstractOAuth2Token implements IdTokenClaimAcce * @return the {@link Builder} for further configurations */ public Builder authenticationMethods(List authenticationMethods) { - return claim(AMR, authenticationMethods); + return claim(IdTokenClaimNames.AMR, authenticationMethods); } /** @@ -192,7 +179,7 @@ public class OidcIdToken extends AbstractOAuth2Token implements IdTokenClaimAcce * @return the {@link Builder} for further configurations */ public Builder authorizationCodeHash(String authorizationCodeHash) { - return claim(C_HASH, authorizationCodeHash); + return claim(IdTokenClaimNames.C_HASH, authorizationCodeHash); } /** @@ -201,7 +188,7 @@ public class OidcIdToken extends AbstractOAuth2Token implements IdTokenClaimAcce * @return the {@link Builder} for further configurations */ public Builder authorizedParty(String authorizedParty) { - return claim(AZP, authorizedParty); + return claim(IdTokenClaimNames.AZP, authorizedParty); } /** @@ -210,7 +197,7 @@ public class OidcIdToken extends AbstractOAuth2Token implements IdTokenClaimAcce * @return the {@link Builder} for further configurations */ public Builder expiresAt(Instant expiresAt) { - return this.claim(EXP, expiresAt); + return this.claim(IdTokenClaimNames.EXP, expiresAt); } /** @@ -219,7 +206,7 @@ public class OidcIdToken extends AbstractOAuth2Token implements IdTokenClaimAcce * @return the {@link Builder} for further configurations */ public Builder issuedAt(Instant issuedAt) { - return this.claim(IAT, issuedAt); + return this.claim(IdTokenClaimNames.IAT, issuedAt); } /** @@ -228,7 +215,7 @@ public class OidcIdToken extends AbstractOAuth2Token implements IdTokenClaimAcce * @return the {@link Builder} for further configurations */ public Builder issuer(String issuer) { - return this.claim(ISS, issuer); + return this.claim(IdTokenClaimNames.ISS, issuer); } /** @@ -237,7 +224,7 @@ public class OidcIdToken extends AbstractOAuth2Token implements IdTokenClaimAcce * @return the {@link Builder} for further configurations */ public Builder nonce(String nonce) { - return this.claim(NONCE, nonce); + return this.claim(IdTokenClaimNames.NONCE, nonce); } /** @@ -246,7 +233,7 @@ public class OidcIdToken extends AbstractOAuth2Token implements IdTokenClaimAcce * @return the {@link Builder} for further configurations */ public Builder subject(String subject) { - return this.claim(SUB, subject); + return this.claim(IdTokenClaimNames.SUB, subject); } /** @@ -254,8 +241,8 @@ public class OidcIdToken extends AbstractOAuth2Token implements IdTokenClaimAcce * @return The constructed {@link OidcIdToken} */ public OidcIdToken build() { - Instant iat = toInstant(this.claims.get(IAT)); - Instant exp = toInstant(this.claims.get(EXP)); + Instant iat = toInstant(this.claims.get(IdTokenClaimNames.IAT)); + Instant exp = toInstant(this.claims.get(IdTokenClaimNames.EXP)); return new OidcIdToken(this.tokenValue, iat, exp, this.claims); } diff --git a/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/OidcUserInfo.java b/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/OidcUserInfo.java index 1269de2164..70d6290fae 100644 --- a/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/OidcUserInfo.java +++ b/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/OidcUserInfo.java @@ -25,27 +25,6 @@ import java.util.function.Consumer; import org.springframework.security.core.SpringSecurityCoreVersion; import org.springframework.util.Assert; -import static org.springframework.security.oauth2.core.oidc.StandardClaimNames.ADDRESS; -import static org.springframework.security.oauth2.core.oidc.StandardClaimNames.BIRTHDATE; -import static org.springframework.security.oauth2.core.oidc.StandardClaimNames.EMAIL; -import static org.springframework.security.oauth2.core.oidc.StandardClaimNames.EMAIL_VERIFIED; -import static org.springframework.security.oauth2.core.oidc.StandardClaimNames.FAMILY_NAME; -import static org.springframework.security.oauth2.core.oidc.StandardClaimNames.GENDER; -import static org.springframework.security.oauth2.core.oidc.StandardClaimNames.GIVEN_NAME; -import static org.springframework.security.oauth2.core.oidc.StandardClaimNames.LOCALE; -import static org.springframework.security.oauth2.core.oidc.StandardClaimNames.MIDDLE_NAME; -import static org.springframework.security.oauth2.core.oidc.StandardClaimNames.NAME; -import static org.springframework.security.oauth2.core.oidc.StandardClaimNames.NICKNAME; -import static org.springframework.security.oauth2.core.oidc.StandardClaimNames.PHONE_NUMBER; -import static org.springframework.security.oauth2.core.oidc.StandardClaimNames.PHONE_NUMBER_VERIFIED; -import static org.springframework.security.oauth2.core.oidc.StandardClaimNames.PICTURE; -import static org.springframework.security.oauth2.core.oidc.StandardClaimNames.PREFERRED_USERNAME; -import static org.springframework.security.oauth2.core.oidc.StandardClaimNames.PROFILE; -import static org.springframework.security.oauth2.core.oidc.StandardClaimNames.SUB; -import static org.springframework.security.oauth2.core.oidc.StandardClaimNames.UPDATED_AT; -import static org.springframework.security.oauth2.core.oidc.StandardClaimNames.WEBSITE; -import static org.springframework.security.oauth2.core.oidc.StandardClaimNames.ZONEINFO; - /** * A representation of a UserInfo Response that is returned from the OAuth 2.0 Protected * Resource UserInfo Endpoint. @@ -155,7 +134,7 @@ public class OidcUserInfo implements StandardClaimAccessor, Serializable { * @return the {@link Builder} for further configurations */ public Builder address(String address) { - return this.claim(ADDRESS, address); + return this.claim(StandardClaimNames.ADDRESS, address); } /** @@ -164,7 +143,7 @@ public class OidcUserInfo implements StandardClaimAccessor, Serializable { * @return the {@link Builder} for further configurations */ public Builder birthdate(String birthdate) { - return this.claim(BIRTHDATE, birthdate); + return this.claim(StandardClaimNames.BIRTHDATE, birthdate); } /** @@ -173,7 +152,7 @@ public class OidcUserInfo implements StandardClaimAccessor, Serializable { * @return the {@link Builder} for further configurations */ public Builder email(String email) { - return this.claim(EMAIL, email); + return this.claim(StandardClaimNames.EMAIL, email); } /** @@ -182,7 +161,7 @@ public class OidcUserInfo implements StandardClaimAccessor, Serializable { * @return the {@link Builder} for further configurations */ public Builder emailVerified(Boolean emailVerified) { - return this.claim(EMAIL_VERIFIED, emailVerified); + return this.claim(StandardClaimNames.EMAIL_VERIFIED, emailVerified); } /** @@ -191,7 +170,7 @@ public class OidcUserInfo implements StandardClaimAccessor, Serializable { * @return the {@link Builder} for further configurations */ public Builder familyName(String familyName) { - return claim(FAMILY_NAME, familyName); + return claim(StandardClaimNames.FAMILY_NAME, familyName); } /** @@ -200,7 +179,7 @@ public class OidcUserInfo implements StandardClaimAccessor, Serializable { * @return the {@link Builder} for further configurations */ public Builder gender(String gender) { - return this.claim(GENDER, gender); + return this.claim(StandardClaimNames.GENDER, gender); } /** @@ -209,7 +188,7 @@ public class OidcUserInfo implements StandardClaimAccessor, Serializable { * @return the {@link Builder} for further configurations */ public Builder givenName(String givenName) { - return claim(GIVEN_NAME, givenName); + return claim(StandardClaimNames.GIVEN_NAME, givenName); } /** @@ -218,7 +197,7 @@ public class OidcUserInfo implements StandardClaimAccessor, Serializable { * @return the {@link Builder} for further configurations */ public Builder locale(String locale) { - return this.claim(LOCALE, locale); + return this.claim(StandardClaimNames.LOCALE, locale); } /** @@ -227,7 +206,7 @@ public class OidcUserInfo implements StandardClaimAccessor, Serializable { * @return the {@link Builder} for further configurations */ public Builder middleName(String middleName) { - return claim(MIDDLE_NAME, middleName); + return claim(StandardClaimNames.MIDDLE_NAME, middleName); } /** @@ -236,7 +215,7 @@ public class OidcUserInfo implements StandardClaimAccessor, Serializable { * @return the {@link Builder} for further configurations */ public Builder name(String name) { - return claim(NAME, name); + return claim(StandardClaimNames.NAME, name); } /** @@ -245,7 +224,7 @@ public class OidcUserInfo implements StandardClaimAccessor, Serializable { * @return the {@link Builder} for further configurations */ public Builder nickname(String nickname) { - return claim(NICKNAME, nickname); + return claim(StandardClaimNames.NICKNAME, nickname); } /** @@ -254,7 +233,7 @@ public class OidcUserInfo implements StandardClaimAccessor, Serializable { * @return the {@link Builder} for further configurations */ public Builder picture(String picture) { - return this.claim(PICTURE, picture); + return this.claim(StandardClaimNames.PICTURE, picture); } /** @@ -263,7 +242,7 @@ public class OidcUserInfo implements StandardClaimAccessor, Serializable { * @return the {@link Builder} for further configurations */ public Builder phoneNumber(String phoneNumber) { - return this.claim(PHONE_NUMBER, phoneNumber); + return this.claim(StandardClaimNames.PHONE_NUMBER, phoneNumber); } /** @@ -272,7 +251,7 @@ public class OidcUserInfo implements StandardClaimAccessor, Serializable { * @return the {@link Builder} for further configurations */ public Builder phoneNumberVerified(String phoneNumberVerified) { - return this.claim(PHONE_NUMBER_VERIFIED, phoneNumberVerified); + return this.claim(StandardClaimNames.PHONE_NUMBER_VERIFIED, phoneNumberVerified); } /** @@ -281,7 +260,7 @@ public class OidcUserInfo implements StandardClaimAccessor, Serializable { * @return the {@link Builder} for further configurations */ public Builder preferredUsername(String preferredUsername) { - return claim(PREFERRED_USERNAME, preferredUsername); + return claim(StandardClaimNames.PREFERRED_USERNAME, preferredUsername); } /** @@ -290,7 +269,7 @@ public class OidcUserInfo implements StandardClaimAccessor, Serializable { * @return the {@link Builder} for further configurations */ public Builder profile(String profile) { - return claim(PROFILE, profile); + return claim(StandardClaimNames.PROFILE, profile); } /** @@ -299,7 +278,7 @@ public class OidcUserInfo implements StandardClaimAccessor, Serializable { * @return the {@link Builder} for further configurations */ public Builder subject(String subject) { - return this.claim(SUB, subject); + return this.claim(StandardClaimNames.SUB, subject); } /** @@ -308,7 +287,7 @@ public class OidcUserInfo implements StandardClaimAccessor, Serializable { * @return the {@link Builder} for further configurations */ public Builder updatedAt(String updatedAt) { - return this.claim(UPDATED_AT, updatedAt); + return this.claim(StandardClaimNames.UPDATED_AT, updatedAt); } /** @@ -317,7 +296,7 @@ public class OidcUserInfo implements StandardClaimAccessor, Serializable { * @return the {@link Builder} for further configurations */ public Builder website(String website) { - return this.claim(WEBSITE, website); + return this.claim(StandardClaimNames.WEBSITE, website); } /** @@ -326,7 +305,7 @@ public class OidcUserInfo implements StandardClaimAccessor, Serializable { * @return the {@link Builder} for further configurations */ public Builder zoneinfo(String zoneinfo) { - return this.claim(ZONEINFO, zoneinfo); + return this.claim(StandardClaimNames.ZONEINFO, zoneinfo); } /** diff --git a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/OAuth2AuthorizationExchangeTests.java b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/OAuth2AuthorizationExchangeTests.java index 7c8cb0bc0e..3f765768b9 100644 --- a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/OAuth2AuthorizationExchangeTests.java +++ b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/endpoint/OAuth2AuthorizationExchangeTests.java @@ -18,8 +18,6 @@ package org.springframework.security.oauth2.core.endpoint; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests.request; -import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses.success; /** * Tests for {@link OAuth2AuthorizationExchange}. @@ -30,18 +28,18 @@ public class OAuth2AuthorizationExchangeTests { @Test(expected = IllegalArgumentException.class) public void constructorWhenAuthorizationRequestIsNullThenThrowIllegalArgumentException() { - new OAuth2AuthorizationExchange(null, success().build()); + new OAuth2AuthorizationExchange(null, TestOAuth2AuthorizationResponses.success().build()); } @Test(expected = IllegalArgumentException.class) public void constructorWhenAuthorizationResponseIsNullThenThrowIllegalArgumentException() { - new OAuth2AuthorizationExchange(request().build(), null); + new OAuth2AuthorizationExchange(TestOAuth2AuthorizationRequests.request().build(), null); } @Test public void constructorWhenRequiredArgsProvidedThenCreated() { - OAuth2AuthorizationRequest authorizationRequest = request().build(); - OAuth2AuthorizationResponse authorizationResponse = success().build(); + OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request().build(); + OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.success().build(); OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse); assertThat(authorizationExchange.getAuthorizationRequest()).isEqualTo(authorizationRequest); diff --git a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/OidcIdTokenBuilderTests.java b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/OidcIdTokenBuilderTests.java index 50d4bb5223..07ba4d5834 100644 --- a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/OidcIdTokenBuilderTests.java +++ b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/OidcIdTokenBuilderTests.java @@ -22,9 +22,6 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; -import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.EXP; -import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.IAT; -import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.SUB; /** * Tests for {@link OidcUserInfo} @@ -62,7 +59,7 @@ public class OidcIdTokenBuilderTests { idToken = idTokenBuilder.expiresAt(now).build(); assertThat(idToken.getExpiresAt()).isSameAs(now); - assertThatCode(() -> idTokenBuilder.claim(EXP, "not an instant").build()) + assertThatCode(() -> idTokenBuilder.claim(IdTokenClaimNames.EXP, "not an instant").build()) .isInstanceOf(IllegalArgumentException.class); } @@ -78,7 +75,7 @@ public class OidcIdTokenBuilderTests { idToken = idTokenBuilder.issuedAt(now).build(); assertThat(idToken.getIssuedAt()).isSameAs(now); - assertThatCode(() -> idTokenBuilder.claim(IAT, "not an instant").build()) + assertThatCode(() -> idTokenBuilder.claim(IdTokenClaimNames.IAT, "not an instant").build()) .isInstanceOf(IllegalArgumentException.class); } @@ -89,10 +86,10 @@ public class OidcIdTokenBuilderTests { String generic = new String("sub"); String named = new String("sub"); - OidcIdToken idToken = idTokenBuilder.subject(named).claim(SUB, generic).build(); + OidcIdToken idToken = idTokenBuilder.subject(named).claim(IdTokenClaimNames.SUB, generic).build(); assertThat(idToken.getSubject()).isSameAs(generic); - idToken = idTokenBuilder.claim(SUB, generic).subject(named).build(); + idToken = idTokenBuilder.claim(IdTokenClaimNames.SUB, generic).subject(named).build(); assertThat(idToken.getSubject()).isSameAs(named); } @@ -100,7 +97,8 @@ public class OidcIdTokenBuilderTests { public void claimsWhenRemovingAClaimThenIsNotPresent() { OidcIdToken.Builder idTokenBuilder = OidcIdToken.withTokenValue("token").claim("needs", "a claim"); - OidcIdToken idToken = idTokenBuilder.subject("sub").claims(claims -> claims.remove(SUB)).build(); + OidcIdToken idToken = idTokenBuilder.subject("sub").claims(claims -> claims.remove(IdTokenClaimNames.SUB)) + .build(); assertThat(idToken.getSubject()).isNull(); } diff --git a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/OidcUserInfoBuilderTests.java b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/OidcUserInfoBuilderTests.java index ce6fddf320..84bdf7f5e9 100644 --- a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/OidcUserInfoBuilderTests.java +++ b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/OidcUserInfoBuilderTests.java @@ -19,7 +19,6 @@ package org.springframework.security.oauth2.core.oidc; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.oauth2.core.oidc.IdTokenClaimNames.SUB; /** * Tests for {@link OidcUserInfo} @@ -49,10 +48,10 @@ public class OidcUserInfoBuilderTests { String generic = new String("sub"); String named = new String("sub"); - OidcUserInfo userInfo = userInfoBuilder.subject(named).claim(SUB, generic).build(); + OidcUserInfo userInfo = userInfoBuilder.subject(named).claim(IdTokenClaimNames.SUB, generic).build(); assertThat(userInfo.getSubject()).isSameAs(generic); - userInfo = userInfoBuilder.claim(SUB, generic).subject(named).build(); + userInfo = userInfoBuilder.claim(IdTokenClaimNames.SUB, generic).subject(named).build(); assertThat(userInfo.getSubject()).isSameAs(named); } @@ -60,7 +59,8 @@ public class OidcUserInfoBuilderTests { public void claimsWhenRemovingAClaimThenIsNotPresent() { OidcUserInfo.Builder userInfoBuilder = OidcUserInfo.builder().claim("needs", "a claim"); - OidcUserInfo userInfo = userInfoBuilder.subject("sub").claims(claims -> claims.remove(SUB)).build(); + OidcUserInfo userInfo = userInfoBuilder.subject("sub").claims(claims -> claims.remove(IdTokenClaimNames.SUB)) + .build(); assertThat(userInfo.getSubject()).isNull(); } diff --git a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/OidcUserInfoTests.java b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/OidcUserInfoTests.java index da3cd4a489..247e4f8b45 100644 --- a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/OidcUserInfoTests.java +++ b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/OidcUserInfoTests.java @@ -23,18 +23,6 @@ import java.util.Map; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.oauth2.core.oidc.DefaultAddressStandardClaimTests.COUNTRY; -import static org.springframework.security.oauth2.core.oidc.DefaultAddressStandardClaimTests.COUNTRY_FIELD_NAME; -import static org.springframework.security.oauth2.core.oidc.DefaultAddressStandardClaimTests.FORMATTED; -import static org.springframework.security.oauth2.core.oidc.DefaultAddressStandardClaimTests.FORMATTED_FIELD_NAME; -import static org.springframework.security.oauth2.core.oidc.DefaultAddressStandardClaimTests.LOCALITY; -import static org.springframework.security.oauth2.core.oidc.DefaultAddressStandardClaimTests.LOCALITY_FIELD_NAME; -import static org.springframework.security.oauth2.core.oidc.DefaultAddressStandardClaimTests.POSTAL_CODE; -import static org.springframework.security.oauth2.core.oidc.DefaultAddressStandardClaimTests.POSTAL_CODE_FIELD_NAME; -import static org.springframework.security.oauth2.core.oidc.DefaultAddressStandardClaimTests.REGION; -import static org.springframework.security.oauth2.core.oidc.DefaultAddressStandardClaimTests.REGION_FIELD_NAME; -import static org.springframework.security.oauth2.core.oidc.DefaultAddressStandardClaimTests.STREET_ADDRESS; -import static org.springframework.security.oauth2.core.oidc.DefaultAddressStandardClaimTests.STREET_ADDRESS_FIELD_NAME; /** * Tests for {@link OidcUserInfo}. @@ -147,12 +135,17 @@ public class OidcUserInfoTests { CLAIMS.put(PHONE_NUMBER_VERIFIED_CLAIM, PHONE_NUMBER_VERIFIED_VALUE); ADDRESS_VALUE = new HashMap<>(); - ADDRESS_VALUE.put(FORMATTED_FIELD_NAME, FORMATTED); - ADDRESS_VALUE.put(STREET_ADDRESS_FIELD_NAME, STREET_ADDRESS); - ADDRESS_VALUE.put(LOCALITY_FIELD_NAME, LOCALITY); - ADDRESS_VALUE.put(REGION_FIELD_NAME, REGION); - ADDRESS_VALUE.put(POSTAL_CODE_FIELD_NAME, POSTAL_CODE); - ADDRESS_VALUE.put(COUNTRY_FIELD_NAME, COUNTRY); + ADDRESS_VALUE.put(DefaultAddressStandardClaimTests.FORMATTED_FIELD_NAME, + DefaultAddressStandardClaimTests.FORMATTED); + ADDRESS_VALUE.put(DefaultAddressStandardClaimTests.STREET_ADDRESS_FIELD_NAME, + DefaultAddressStandardClaimTests.STREET_ADDRESS); + ADDRESS_VALUE.put(DefaultAddressStandardClaimTests.LOCALITY_FIELD_NAME, + DefaultAddressStandardClaimTests.LOCALITY); + ADDRESS_VALUE.put(DefaultAddressStandardClaimTests.REGION_FIELD_NAME, DefaultAddressStandardClaimTests.REGION); + ADDRESS_VALUE.put(DefaultAddressStandardClaimTests.POSTAL_CODE_FIELD_NAME, + DefaultAddressStandardClaimTests.POSTAL_CODE); + ADDRESS_VALUE.put(DefaultAddressStandardClaimTests.COUNTRY_FIELD_NAME, + DefaultAddressStandardClaimTests.COUNTRY); CLAIMS.put(ADDRESS_CLAIM, ADDRESS_VALUE); CLAIMS.put(UPDATED_AT_CLAIM, UPDATED_AT_VALUE); diff --git a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/TestOidcIdTokens.java b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/TestOidcIdTokens.java index a97d9c94b6..1f5935bb80 100644 --- a/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/TestOidcIdTokens.java +++ b/oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/oidc/TestOidcIdTokens.java @@ -18,8 +18,6 @@ package org.springframework.security.oauth2.core.oidc; import java.time.Instant; -import static org.springframework.security.oauth2.core.oidc.OidcIdToken.withTokenValue; - /** * Test {@link OidcIdToken}s * @@ -28,8 +26,8 @@ import static org.springframework.security.oauth2.core.oidc.OidcIdToken.withToke public class TestOidcIdTokens { public static OidcIdToken.Builder idToken() { - return withTokenValue("id-token").issuer("https://example.com").subject("subject").issuedAt(Instant.now()) - .expiresAt(Instant.now().plusSeconds(86400)).claim("id", "id"); + return OidcIdToken.withTokenValue("id-token").issuer("https://example.com").subject("subject") + .issuedAt(Instant.now()).expiresAt(Instant.now().plusSeconds(86400)).claim("id", "id"); } } diff --git a/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/Jwt.java b/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/Jwt.java index 89db2fee89..a01c905704 100644 --- a/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/Jwt.java +++ b/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/Jwt.java @@ -25,14 +25,6 @@ import java.util.function.Consumer; import org.springframework.security.oauth2.core.AbstractOAuth2Token; import org.springframework.util.Assert; -import static org.springframework.security.oauth2.jwt.JwtClaimNames.AUD; -import static org.springframework.security.oauth2.jwt.JwtClaimNames.EXP; -import static org.springframework.security.oauth2.jwt.JwtClaimNames.IAT; -import static org.springframework.security.oauth2.jwt.JwtClaimNames.ISS; -import static org.springframework.security.oauth2.jwt.JwtClaimNames.JTI; -import static org.springframework.security.oauth2.jwt.JwtClaimNames.NBF; -import static org.springframework.security.oauth2.jwt.JwtClaimNames.SUB; - /** * An implementation of an {@link AbstractOAuth2Token} representing a JSON Web Token * (JWT). @@ -182,7 +174,7 @@ public class Jwt extends AbstractOAuth2Token implements JwtClaimAccessor { * @return the {@link Builder} for further configurations */ public Builder audience(Collection audience) { - return claim(AUD, audience); + return claim(JwtClaimNames.AUD, audience); } /** @@ -191,7 +183,7 @@ public class Jwt extends AbstractOAuth2Token implements JwtClaimAccessor { * @return the {@link Builder} for further configurations */ public Builder expiresAt(Instant expiresAt) { - this.claim(EXP, expiresAt); + this.claim(JwtClaimNames.EXP, expiresAt); return this; } @@ -201,7 +193,7 @@ public class Jwt extends AbstractOAuth2Token implements JwtClaimAccessor { * @return the {@link Builder} for further configurations */ public Builder jti(String jti) { - this.claim(JTI, jti); + this.claim(JwtClaimNames.JTI, jti); return this; } @@ -211,7 +203,7 @@ public class Jwt extends AbstractOAuth2Token implements JwtClaimAccessor { * @return the {@link Builder} for further configurations */ public Builder issuedAt(Instant issuedAt) { - this.claim(IAT, issuedAt); + this.claim(JwtClaimNames.IAT, issuedAt); return this; } @@ -221,7 +213,7 @@ public class Jwt extends AbstractOAuth2Token implements JwtClaimAccessor { * @return the {@link Builder} for further configurations */ public Builder issuer(String issuer) { - this.claim(ISS, issuer); + this.claim(JwtClaimNames.ISS, issuer); return this; } @@ -231,7 +223,7 @@ public class Jwt extends AbstractOAuth2Token implements JwtClaimAccessor { * @return the {@link Builder} for further configurations */ public Builder notBefore(Instant notBefore) { - this.claim(NBF, notBefore); + this.claim(JwtClaimNames.NBF, notBefore); return this; } @@ -241,7 +233,7 @@ public class Jwt extends AbstractOAuth2Token implements JwtClaimAccessor { * @return the {@link Builder} for further configurations */ public Builder subject(String subject) { - this.claim(SUB, subject); + this.claim(JwtClaimNames.SUB, subject); return this; } @@ -250,8 +242,8 @@ public class Jwt extends AbstractOAuth2Token implements JwtClaimAccessor { * @return The constructed {@link Jwt} */ public Jwt build() { - Instant iat = toInstant(this.claims.get(IAT)); - Instant exp = toInstant(this.claims.get(EXP)); + Instant iat = toInstant(this.claims.get(JwtClaimNames.IAT)); + Instant exp = toInstant(this.claims.get(JwtClaimNames.EXP)); return new Jwt(this.tokenValue, iat, exp, this.headers, this.claims); } diff --git a/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtDecoders.java b/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtDecoders.java index b4acb42b9b..ca8b4d2955 100644 --- a/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtDecoders.java +++ b/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtDecoders.java @@ -20,8 +20,6 @@ import java.util.Map; import org.springframework.security.oauth2.core.OAuth2TokenValidator; import org.springframework.util.Assert; -import static org.springframework.security.oauth2.jwt.NimbusJwtDecoder.withJwkSetUri; - /** * Allows creating a {@link JwtDecoder} from an OpenID @@ -104,7 +102,7 @@ public final class JwtDecoders { private static JwtDecoder withProviderConfiguration(Map configuration, String issuer) { JwtDecoderProviderConfigurationUtils.validateIssuer(configuration, issuer); OAuth2TokenValidator jwtValidator = JwtValidators.createDefaultWithIssuer(issuer); - NimbusJwtDecoder jwtDecoder = withJwkSetUri(configuration.get("jwks_uri").toString()).build(); + NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(configuration.get("jwks_uri").toString()).build(); jwtDecoder.setJwtValidator(jwtValidator); return jwtDecoder; diff --git a/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtIssuerValidator.java b/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtIssuerValidator.java index 6f0c085621..87917a3b95 100644 --- a/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtIssuerValidator.java +++ b/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtIssuerValidator.java @@ -19,8 +19,6 @@ import org.springframework.security.oauth2.core.OAuth2TokenValidator; import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult; import org.springframework.util.Assert; -import static org.springframework.security.oauth2.jwt.JwtClaimNames.ISS; - /** * Validates the "iss" claim in a {@link Jwt}, that is matches a configured value * @@ -37,7 +35,7 @@ public final class JwtIssuerValidator implements OAuth2TokenValidator { */ public JwtIssuerValidator(String issuer) { Assert.notNull(issuer, "issuer cannot be null"); - this.validator = new JwtClaimValidator(ISS, issuer::equals); + this.validator = new JwtClaimValidator(JwtClaimNames.ISS, issuer::equals); } /** diff --git a/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderJwkSupport.java b/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderJwkSupport.java index 2e381ab758..7997154f66 100644 --- a/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderJwkSupport.java +++ b/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderJwkSupport.java @@ -25,8 +25,6 @@ import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm; import org.springframework.util.Assert; import org.springframework.web.client.RestOperations; -import static org.springframework.security.oauth2.jwt.NimbusJwtDecoder.withJwkSetUri; - /** * An implementation of a {@link JwtDecoder} that "decodes" a JSON Web Token (JWT) and * additionally verifies it's digital signature if the JWT is a JSON Web Signature (JWS). @@ -81,7 +79,8 @@ public final class NimbusJwtDecoderJwkSupport implements JwtDecoder { Assert.hasText(jwkSetUrl, "jwkSetUrl cannot be empty"); Assert.hasText(jwsAlgorithm, "jwsAlgorithm cannot be empty"); - this.jwtDecoderBuilder = withJwkSetUri(jwkSetUrl).jwsAlgorithm(SignatureAlgorithm.from(jwsAlgorithm)); + this.jwtDecoderBuilder = NimbusJwtDecoder.withJwkSetUri(jwkSetUrl) + .jwsAlgorithm(SignatureAlgorithm.from(jwsAlgorithm)); this.delegate = makeDelegate(); } diff --git a/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/ReactiveJwtDecoders.java b/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/ReactiveJwtDecoders.java index 702ca0eaef..3f5da085ac 100644 --- a/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/ReactiveJwtDecoders.java +++ b/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/ReactiveJwtDecoders.java @@ -20,8 +20,6 @@ import java.util.Map; import org.springframework.security.oauth2.core.OAuth2TokenValidator; import org.springframework.util.Assert; -import static org.springframework.security.oauth2.jwt.NimbusReactiveJwtDecoder.withJwkSetUri; - /** * Allows creating a {@link ReactiveJwtDecoder} from an OpenID @@ -104,7 +102,8 @@ public final class ReactiveJwtDecoders { private static ReactiveJwtDecoder withProviderConfiguration(Map configuration, String issuer) { JwtDecoderProviderConfigurationUtils.validateIssuer(configuration, issuer); OAuth2TokenValidator jwtValidator = JwtValidators.createDefaultWithIssuer(issuer); - NimbusReactiveJwtDecoder jwtDecoder = withJwkSetUri(configuration.get("jwks_uri").toString()).build(); + NimbusReactiveJwtDecoder jwtDecoder = NimbusReactiveJwtDecoder + .withJwkSetUri(configuration.get("jwks_uri").toString()).build(); jwtDecoder.setJwtValidator(jwtValidator); return jwtDecoder; diff --git a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtBuilderTests.java b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtBuilderTests.java index c0941bb83e..d21ab8723e 100644 --- a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtBuilderTests.java +++ b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtBuilderTests.java @@ -21,9 +21,6 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; -import static org.springframework.security.oauth2.jwt.JwtClaimNames.EXP; -import static org.springframework.security.oauth2.jwt.JwtClaimNames.IAT; -import static org.springframework.security.oauth2.jwt.JwtClaimNames.SUB; /** * Tests for {@link Jwt.Builder}. @@ -69,7 +66,7 @@ public class JwtBuilderTests { jwt = jwtBuilder.expiresAt(now).build(); assertThat(jwt.getExpiresAt()).isSameAs(now); - assertThatCode(() -> jwtBuilder.claim(EXP, "not an instant").build()) + assertThatCode(() -> jwtBuilder.claim(JwtClaimNames.EXP, "not an instant").build()) .isInstanceOf(IllegalArgumentException.class); } @@ -85,7 +82,7 @@ public class JwtBuilderTests { jwt = jwtBuilder.issuedAt(now).build(); assertThat(jwt.getIssuedAt()).isSameAs(now); - assertThatCode(() -> jwtBuilder.claim(IAT, "not an instant").build()) + assertThatCode(() -> jwtBuilder.claim(JwtClaimNames.IAT, "not an instant").build()) .isInstanceOf(IllegalArgumentException.class); } @@ -96,10 +93,10 @@ public class JwtBuilderTests { String generic = new String("sub"); String named = new String("sub"); - Jwt jwt = jwtBuilder.subject(named).claim(SUB, generic).build(); + Jwt jwt = jwtBuilder.subject(named).claim(JwtClaimNames.SUB, generic).build(); assertThat(jwt.getSubject()).isSameAs(generic); - jwt = jwtBuilder.claim(SUB, generic).subject(named).build(); + jwt = jwtBuilder.claim(JwtClaimNames.SUB, generic).subject(named).build(); assertThat(jwt.getSubject()).isSameAs(named); } @@ -107,7 +104,7 @@ public class JwtBuilderTests { public void claimsWhenRemovingAClaimThenIsNotPresent() { Jwt.Builder jwtBuilder = Jwt.withTokenValue("token").claim("needs", "a claim").header("needs", "a header"); - Jwt jwt = jwtBuilder.subject("sub").claims(claims -> claims.remove(SUB)).build(); + Jwt jwt = jwtBuilder.subject("sub").claims(claims -> claims.remove(JwtClaimNames.SUB)).build(); assertThat(jwt.getSubject()).isNull(); } diff --git a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtClaimValidatorTests.java b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtClaimValidatorTests.java index 609383ff46..a2db9b38a2 100644 --- a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtClaimValidatorTests.java +++ b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtClaimValidatorTests.java @@ -23,8 +23,6 @@ import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.springframework.security.oauth2.jwt.JwtClaimNames.ISS; -import static org.springframework.security.oauth2.jwt.TestJwts.jwt; /** * Tests for {@link JwtClaimValidator}. @@ -35,17 +33,17 @@ public class JwtClaimValidatorTests { private static final Predicate test = claim -> claim.equals("http://test"); - private final JwtClaimValidator validator = new JwtClaimValidator<>(ISS, test); + private final JwtClaimValidator validator = new JwtClaimValidator<>(JwtClaimNames.ISS, test); @Test public void validateWhenClaimPassesTheTestThenReturnsSuccess() { - Jwt jwt = jwt().claim(ISS, "http://test").build(); + Jwt jwt = TestJwts.jwt().claim(JwtClaimNames.ISS, "http://test").build(); assertThat(this.validator.validate(jwt)).isEqualTo(OAuth2TokenValidatorResult.success()); } @Test public void validateWhenClaimFailsTheTestThenReturnsFailure() { - Jwt jwt = jwt().claim(ISS, "http://abc").build(); + Jwt jwt = TestJwts.jwt().claim(JwtClaimNames.ISS, "http://abc").build(); assertThat(this.validator.validate(jwt).getErrors().isEmpty()).isFalse(); } @@ -56,7 +54,8 @@ public class JwtClaimValidatorTests { @Test public void validateWhenTestIsNullThenThrowsIllegalArgumentException() { - assertThatThrownBy(() -> new JwtClaimValidator<>(ISS, null)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new JwtClaimValidator<>(JwtClaimNames.ISS, null)) + .isInstanceOf(IllegalArgumentException.class); } @Test diff --git a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtIssuerValidatorTests.java b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtIssuerValidatorTests.java index 688ef5ef65..62c50ef705 100644 --- a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtIssuerValidatorTests.java +++ b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtIssuerValidatorTests.java @@ -21,7 +21,6 @@ import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; -import static org.springframework.security.oauth2.jwt.TestJwts.jwt; /** * @author Josh Cummings @@ -35,14 +34,14 @@ public class JwtIssuerValidatorTests { @Test public void validateWhenIssuerMatchesThenReturnsSuccess() { - Jwt jwt = jwt().claim("iss", ISSUER).build(); + Jwt jwt = TestJwts.jwt().claim("iss", ISSUER).build(); assertThat(this.validator.validate(jwt)).isEqualTo(OAuth2TokenValidatorResult.success()); } @Test public void validateWhenIssuerMismatchesThenReturnsError() { - Jwt jwt = jwt().claim(JwtClaimNames.ISS, "https://other").build(); + Jwt jwt = TestJwts.jwt().claim(JwtClaimNames.ISS, "https://other").build(); OAuth2TokenValidatorResult result = this.validator.validate(jwt); @@ -51,7 +50,7 @@ public class JwtIssuerValidatorTests { @Test public void validateWhenJwtHasNoIssuerThenReturnsError() { - Jwt jwt = jwt().claim(JwtClaimNames.AUD, "https://aud").build(); + Jwt jwt = TestJwts.jwt().claim(JwtClaimNames.AUD, "https://aud").build(); OAuth2TokenValidatorResult result = this.validator.validate(jwt); assertThat(result.getErrors()).isNotEmpty(); @@ -60,7 +59,7 @@ public class JwtIssuerValidatorTests { // gh-6073 @Test public void validateWhenIssuerMatchesAndIsNotAUriThenReturnsSuccess() { - Jwt jwt = jwt().claim(JwtClaimNames.ISS, "issuer").build(); + Jwt jwt = TestJwts.jwt().claim(JwtClaimNames.ISS, "issuer").build(); JwtIssuerValidator validator = new JwtIssuerValidator("issuer"); assertThat(validator.validate(jwt)).isEqualTo(OAuth2TokenValidatorResult.success()); diff --git a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtTimestampValidatorTests.java b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtTimestampValidatorTests.java index 34b7bf0915..04f10f3074 100644 --- a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtTimestampValidatorTests.java +++ b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtTimestampValidatorTests.java @@ -32,8 +32,6 @@ import org.springframework.security.oauth2.jose.jws.JwsAlgorithms; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; -import static org.springframework.security.oauth2.jwt.JwtClaimNames.EXP; -import static org.springframework.security.oauth2.jwt.TestJwts.jwt; /** * Tests verifying {@link JwtTimestampValidator} @@ -56,7 +54,7 @@ public class JwtTimestampValidatorTests { public void validateWhenJwtIsExpiredThenErrorMessageIndicatesExpirationTime() { Instant oneHourAgo = Instant.now().minusSeconds(3600); - Jwt jwt = jwt().expiresAt(oneHourAgo).build(); + Jwt jwt = TestJwts.jwt().expiresAt(oneHourAgo).build(); JwtTimestampValidator jwtValidator = new JwtTimestampValidator(); @@ -70,7 +68,7 @@ public class JwtTimestampValidatorTests { public void validateWhenJwtIsTooEarlyThenErrorMessageIndicatesNotBeforeTime() { Instant oneHourFromNow = Instant.now().plusSeconds(3600); - Jwt jwt = jwt().notBefore(oneHourFromNow).build(); + Jwt jwt = TestJwts.jwt().notBefore(oneHourFromNow).build(); JwtTimestampValidator jwtValidator = new JwtTimestampValidator(); @@ -91,11 +89,11 @@ public class JwtTimestampValidatorTests { Instant justOverOneDayAgo = now.minus(oneDayOff).minusSeconds(10); Instant justOverOneDayFromNow = now.plus(oneDayOff).plusSeconds(10); - Jwt jwt = jwt().expiresAt(almostOneDayAgo).notBefore(almostOneDayFromNow).build(); + Jwt jwt = TestJwts.jwt().expiresAt(almostOneDayAgo).notBefore(almostOneDayFromNow).build(); assertThat(jwtValidator.validate(jwt).hasErrors()).isFalse(); - jwt = jwt().expiresAt(justOverOneDayAgo).build(); + jwt = TestJwts.jwt().expiresAt(justOverOneDayAgo).build(); OAuth2TokenValidatorResult result = jwtValidator.validate(jwt); Collection messages = result.getErrors().stream().map(OAuth2Error::getDescription) @@ -104,7 +102,7 @@ public class JwtTimestampValidatorTests { assertThat(result.hasErrors()).isTrue(); assertThat(messages).contains("Jwt expired at " + justOverOneDayAgo); - jwt = jwt().notBefore(justOverOneDayFromNow).build(); + jwt = TestJwts.jwt().notBefore(justOverOneDayFromNow).build(); result = jwtValidator.validate(jwt); messages = result.getErrors().stream().map(OAuth2Error::getDescription).collect(Collectors.toList()); @@ -116,21 +114,21 @@ public class JwtTimestampValidatorTests { @Test public void validateWhenConfiguredWithFixedClockThenValidatesUsingFixedTime() { - Jwt jwt = jwt().expiresAt(Instant.now(MOCK_NOW)).build(); + Jwt jwt = TestJwts.jwt().expiresAt(Instant.now(MOCK_NOW)).build(); JwtTimestampValidator jwtValidator = new JwtTimestampValidator(Duration.ofNanos(0)); jwtValidator.setClock(MOCK_NOW); assertThat(jwtValidator.validate(jwt).hasErrors()).isFalse(); - jwt = jwt().notBefore(Instant.now(MOCK_NOW)).build(); + jwt = TestJwts.jwt().notBefore(Instant.now(MOCK_NOW)).build(); assertThat(jwtValidator.validate(jwt).hasErrors()).isFalse(); } @Test public void validateWhenNeitherExpiryNorNotBeforeIsSpecifiedThenReturnsSuccessfulResult() { - Jwt jwt = jwt().claims(c -> c.remove(EXP)).build(); + Jwt jwt = TestJwts.jwt().claims(c -> c.remove(JwtClaimNames.EXP)).build(); JwtTimestampValidator jwtValidator = new JwtTimestampValidator(); assertThat(jwtValidator.validate(jwt).hasErrors()).isFalse(); @@ -138,7 +136,7 @@ public class JwtTimestampValidatorTests { @Test public void validateWhenNotBeforeIsValidAndExpiryIsNotSpecifiedThenReturnsSuccessfulResult() { - Jwt jwt = jwt().claims(c -> c.remove(EXP)).notBefore(Instant.MIN).build(); + Jwt jwt = TestJwts.jwt().claims(c -> c.remove(JwtClaimNames.EXP)).notBefore(Instant.MIN).build(); JwtTimestampValidator jwtValidator = new JwtTimestampValidator(); assertThat(jwtValidator.validate(jwt).hasErrors()).isFalse(); @@ -146,7 +144,7 @@ public class JwtTimestampValidatorTests { @Test public void validateWhenExpiryIsValidAndNotBeforeIsNotSpecifiedThenReturnsSuccessfulResult() { - Jwt jwt = jwt().build(); + Jwt jwt = TestJwts.jwt().build(); JwtTimestampValidator jwtValidator = new JwtTimestampValidator(); assertThat(jwtValidator.validate(jwt).hasErrors()).isFalse(); @@ -154,7 +152,7 @@ public class JwtTimestampValidatorTests { @Test public void validateWhenBothExpiryAndNotBeforeAreValidThenReturnsSuccessfulResult() { - Jwt jwt = jwt().expiresAt(Instant.now(MOCK_NOW)).notBefore(Instant.now(MOCK_NOW)).build(); + Jwt jwt = TestJwts.jwt().expiresAt(Instant.now(MOCK_NOW)).notBefore(Instant.now(MOCK_NOW)).build(); JwtTimestampValidator jwtValidator = new JwtTimestampValidator(Duration.ofNanos(0)); jwtValidator.setClock(MOCK_NOW); diff --git a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderJwkSupportTests.java b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderJwkSupportTests.java index 358f8bc99d..215d4ecd34 100644 --- a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderJwkSupportTests.java +++ b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderJwkSupportTests.java @@ -37,8 +37,8 @@ import org.springframework.web.client.RestOperations; import org.springframework.web.client.RestTemplate; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatCode; +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; diff --git a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderTests.java b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderTests.java index 25a07fc930..eeecac5df6 100644 --- a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderTests.java +++ b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderTests.java @@ -76,8 +76,8 @@ import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestOperations; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -85,9 +85,6 @@ 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.springframework.security.oauth2.jwt.NimbusJwtDecoder.withJwkSetUri; -import static org.springframework.security.oauth2.jwt.NimbusJwtDecoder.withPublicKey; -import static org.springframework.security.oauth2.jwt.NimbusJwtDecoder.withSecretKey; /** * Tests for {@link NimbusJwtDecoder} @@ -257,7 +254,7 @@ public class NimbusJwtDecoderTests { public void decodeWhenJwkEndpointIsUnresponsiveThenReturnsJwtException() throws Exception { try (MockWebServer server = new MockWebServer()) { String jwkSetUri = server.url("/.well-known/jwks.json").toString(); - NimbusJwtDecoder jwtDecoder = withJwkSetUri(jwkSetUri).build(); + NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build(); server.shutdown(); assertThatCode(() -> jwtDecoder.decode(SIGNED_JWT)).isInstanceOf(JwtException.class) @@ -271,58 +268,62 @@ public class NimbusJwtDecoderTests { try (MockWebServer server = new MockWebServer()) { Cache cache = new ConcurrentMapCache("test-jwk-set-cache"); String jwkSetUri = server.url("/.well-known/jwks.json").toString(); - NimbusJwtDecoder jwtDecoder = withJwkSetUri(jwkSetUri).cache(cache).build(); + NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).cache(cache).build(); server.shutdown(); assertThatCode(() -> jwtDecoder.decode(SIGNED_JWT)).isInstanceOf(JwtException.class) .isNotInstanceOf(BadJwtException.class) .hasMessageContaining("An error occurred while attempting to decode the Jwt"); + } } @Test public void withJwkSetUriWhenNullOrEmptyThenThrowsException() { - Assertions.assertThatCode(() -> withJwkSetUri(null)).isInstanceOf(IllegalArgumentException.class); + Assertions.assertThatCode(() -> NimbusJwtDecoder.withJwkSetUri(null)) + .isInstanceOf(IllegalArgumentException.class); } @Test public void jwsAlgorithmWhenNullThenThrowsException() { - NimbusJwtDecoder.JwkSetUriJwtDecoderBuilder builder = withJwkSetUri(JWK_SET_URI); + NimbusJwtDecoder.JwkSetUriJwtDecoderBuilder builder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI); Assertions.assertThatCode(() -> builder.jwsAlgorithm(null)).isInstanceOf(IllegalArgumentException.class); } @Test public void restOperationsWhenNullThenThrowsException() { - NimbusJwtDecoder.JwkSetUriJwtDecoderBuilder builder = withJwkSetUri(JWK_SET_URI); + NimbusJwtDecoder.JwkSetUriJwtDecoderBuilder builder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI); Assertions.assertThatCode(() -> builder.restOperations(null)).isInstanceOf(IllegalArgumentException.class); } @Test public void cacheWhenNullThenThrowsException() { - NimbusJwtDecoder.JwkSetUriJwtDecoderBuilder builder = withJwkSetUri(JWK_SET_URI); + NimbusJwtDecoder.JwkSetUriJwtDecoderBuilder builder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI); Assertions.assertThatCode(() -> builder.cache(null)).isInstanceOf(IllegalArgumentException.class); } @Test public void withPublicKeyWhenNullThenThrowsException() { - assertThatThrownBy(() -> withPublicKey(null)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> NimbusJwtDecoder.withPublicKey(null)).isInstanceOf(IllegalArgumentException.class); } @Test public void buildWhenSignatureAlgorithmMismatchesKeyTypeThenThrowsException() { - Assertions.assertThatCode(() -> withPublicKey(key()).signatureAlgorithm(SignatureAlgorithm.ES256).build()) + Assertions.assertThatCode( + () -> NimbusJwtDecoder.withPublicKey(key()).signatureAlgorithm(SignatureAlgorithm.ES256).build()) .isInstanceOf(IllegalStateException.class); } @Test public void decodeWhenUsingPublicKeyThenSuccessfullyDecodes() throws Exception { - NimbusJwtDecoder decoder = withPublicKey(key()).build(); + NimbusJwtDecoder decoder = NimbusJwtDecoder.withPublicKey(key()).build(); assertThat(decoder.decode(RS256_SIGNED_JWT)).extracting(Jwt::getSubject).isEqualTo("test-subject"); } @Test public void decodeWhenUsingPublicKeyWithRs512ThenSuccessfullyDecodes() throws Exception { - NimbusJwtDecoder decoder = withPublicKey(key()).signatureAlgorithm(SignatureAlgorithm.RS512).build(); + NimbusJwtDecoder decoder = NimbusJwtDecoder.withPublicKey(key()).signatureAlgorithm(SignatureAlgorithm.RS512) + .build(); assertThat(decoder.decode(RS512_SIGNED_JWT)).extracting(Jwt::getSubject).isEqualTo("test-subject"); } @@ -335,13 +336,15 @@ public class NimbusJwtDecoderTests { JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().subject("test-subject") .expirationTime(Date.from(Instant.now().plusSeconds(60))).build(); SignedJWT signedJwt = signedJwt(privateKey, header, claimsSet); - NimbusJwtDecoder decoder = withPublicKey(publicKey).signatureAlgorithm(SignatureAlgorithm.RS256).build(); + NimbusJwtDecoder decoder = NimbusJwtDecoder.withPublicKey(publicKey) + .signatureAlgorithm(SignatureAlgorithm.RS256).build(); assertThat(decoder.decode(signedJwt.serialize())).extracting(Jwt::getSubject).isEqualTo("test-subject"); } @Test public void decodeWhenSignatureMismatchesAlgorithmThenThrowsException() throws Exception { - NimbusJwtDecoder decoder = withPublicKey(key()).signatureAlgorithm(SignatureAlgorithm.RS512).build(); + NimbusJwtDecoder decoder = NimbusJwtDecoder.withPublicKey(key()).signatureAlgorithm(SignatureAlgorithm.RS512) + .build(); Assertions.assertThatCode(() -> decoder.decode(RS256_SIGNED_JWT)).isInstanceOf(BadJwtException.class); } @@ -354,7 +357,8 @@ public class NimbusJwtDecoderTests { JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().expirationTime(Date.from(Instant.now().plusSeconds(60))) .build(); SignedJWT signedJwt = signedJwt(privateKey, header, claimsSet); - NimbusJwtDecoder decoder = withPublicKey(publicKey).signatureAlgorithm(SignatureAlgorithm.RS256) + NimbusJwtDecoder decoder = NimbusJwtDecoder.withPublicKey(publicKey) + .signatureAlgorithm(SignatureAlgorithm.RS256) .jwtProcessorCustomizer( p -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))) .build(); @@ -363,20 +367,20 @@ public class NimbusJwtDecoderTests { @Test public void withPublicKeyWhenJwtProcessorCustomizerNullThenThrowsIllegalArgumentException() { - assertThatThrownBy(() -> withPublicKey(key()).jwtProcessorCustomizer(null)) + assertThatThrownBy(() -> NimbusJwtDecoder.withPublicKey(key()).jwtProcessorCustomizer(null)) .isInstanceOf(IllegalArgumentException.class).hasMessage("jwtProcessorCustomizer cannot be null"); } @Test public void withSecretKeyWhenNullThenThrowsIllegalArgumentException() { - assertThatThrownBy(() -> withSecretKey(null)).isInstanceOf(IllegalArgumentException.class) + assertThatThrownBy(() -> NimbusJwtDecoder.withSecretKey(null)).isInstanceOf(IllegalArgumentException.class) .hasMessage("secretKey cannot be null"); } @Test public void withSecretKeyWhenMacAlgorithmNullThenThrowsIllegalArgumentException() { SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY; - assertThatThrownBy(() -> withSecretKey(secretKey).macAlgorithm(null)) + assertThatThrownBy(() -> NimbusJwtDecoder.withSecretKey(secretKey).macAlgorithm(null)) .isInstanceOf(IllegalArgumentException.class).hasMessage("macAlgorithm cannot be null"); } @@ -387,7 +391,7 @@ public class NimbusJwtDecoderTests { JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().subject("test-subject") .expirationTime(Date.from(Instant.now().plusSeconds(60))).build(); SignedJWT signedJWT = signedJwt(secretKey, macAlgorithm, claimsSet); - NimbusJwtDecoder decoder = withSecretKey(secretKey).macAlgorithm(macAlgorithm).build(); + NimbusJwtDecoder decoder = NimbusJwtDecoder.withSecretKey(secretKey).macAlgorithm(macAlgorithm).build(); assertThat(decoder.decode(signedJWT.serialize())).extracting(Jwt::getSubject).isEqualTo("test-subject"); } @@ -398,7 +402,7 @@ public class NimbusJwtDecoderTests { JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().subject("test-subject") .expirationTime(Date.from(Instant.now().plusSeconds(60))).build(); SignedJWT signedJWT = signedJwt(secretKey, macAlgorithm, claimsSet); - NimbusJwtDecoder decoder = withSecretKey(secretKey).macAlgorithm(MacAlgorithm.HS512).build(); + NimbusJwtDecoder decoder = NimbusJwtDecoder.withSecretKey(secretKey).macAlgorithm(MacAlgorithm.HS512).build(); assertThatThrownBy(() -> decoder.decode(signedJWT.serialize())).isInstanceOf(BadJwtException.class) .hasMessageContaining("Unsupported algorithm of HS256"); } @@ -411,7 +415,7 @@ public class NimbusJwtDecoderTests { JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().subject("test-subject") .expirationTime(Date.from(Instant.now().plusSeconds(60))).build(); SignedJWT signedJwt = signedJwt(secretKey, header, claimsSet); - NimbusJwtDecoder decoder = withSecretKey(secretKey).macAlgorithm(MacAlgorithm.HS256).build(); + NimbusJwtDecoder decoder = NimbusJwtDecoder.withSecretKey(secretKey).macAlgorithm(MacAlgorithm.HS256).build(); assertThat(decoder.decode(signedJwt.serialize())).extracting(Jwt::getSubject).isEqualTo("test-subject"); } @@ -423,7 +427,7 @@ public class NimbusJwtDecoderTests { JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().expirationTime(Date.from(Instant.now().plusSeconds(60))) .build(); SignedJWT signedJwt = signedJwt(secretKey, header, claimsSet); - NimbusJwtDecoder decoder = withSecretKey(secretKey).macAlgorithm(MacAlgorithm.HS256) + NimbusJwtDecoder decoder = NimbusJwtDecoder.withSecretKey(secretKey).macAlgorithm(MacAlgorithm.HS256) .jwtProcessorCustomizer( p -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))) .build(); @@ -433,14 +437,15 @@ public class NimbusJwtDecoderTests { @Test public void withSecretKeyWhenJwtProcessorCustomizerNullThenThrowsIllegalArgumentException() { SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY; - assertThatThrownBy(() -> withSecretKey(secretKey).jwtProcessorCustomizer(null)) + assertThatThrownBy(() -> NimbusJwtDecoder.withSecretKey(secretKey).jwtProcessorCustomizer(null)) .isInstanceOf(IllegalArgumentException.class).hasMessage("jwtProcessorCustomizer cannot be null"); } @Test public void jwsKeySelectorWhenNoAlgorithmThenReturnsRS256Selector() { JWKSource jwkSource = mock(JWKSource.class); - JWSKeySelector jwsKeySelector = withJwkSetUri(JWK_SET_URI).jwsKeySelector(jwkSource); + JWSKeySelector jwsKeySelector = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI) + .jwsKeySelector(jwkSource); assertThat(jwsKeySelector instanceof JWSVerificationKeySelector); JWSVerificationKeySelector jwsVerificationKeySelector = (JWSVerificationKeySelector) jwsKeySelector; assertThat(jwsVerificationKeySelector.isAllowed(JWSAlgorithm.RS256)).isTrue(); @@ -449,7 +454,7 @@ public class NimbusJwtDecoderTests { @Test public void jwsKeySelectorWhenOneAlgorithmThenReturnsSingleSelector() { JWKSource jwkSource = mock(JWKSource.class); - JWSKeySelector jwsKeySelector = withJwkSetUri(JWK_SET_URI) + JWSKeySelector jwsKeySelector = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI) .jwsAlgorithm(SignatureAlgorithm.RS512).jwsKeySelector(jwkSource); assertThat(jwsKeySelector instanceof JWSVerificationKeySelector); JWSVerificationKeySelector jwsVerificationKeySelector = (JWSVerificationKeySelector) jwsKeySelector; @@ -459,7 +464,7 @@ public class NimbusJwtDecoderTests { @Test public void jwsKeySelectorWhenMultipleAlgorithmThenReturnsCompositeSelector() { JWKSource jwkSource = mock(JWKSource.class); - JWSKeySelector jwsKeySelector = withJwkSetUri(JWK_SET_URI) + JWSKeySelector jwsKeySelector = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI) .jwsAlgorithm(SignatureAlgorithm.RS256).jwsAlgorithm(SignatureAlgorithm.RS512) .jwsKeySelector(jwkSource); assertThat(jwsKeySelector instanceof JWSVerificationKeySelector); @@ -474,7 +479,8 @@ public class NimbusJwtDecoderTests { RestOperations restOperations = mock(RestOperations.class); given(restOperations.exchange(any(RequestEntity.class), eq(String.class))) .willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK)); - JWTProcessor processor = withJwkSetUri(JWK_SET_URI).restOperations(restOperations).processor(); + JWTProcessor processor = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI) + .restOperations(restOperations).processor(); NimbusJwtDecoder jwtDecoder = new NimbusJwtDecoder(processor); jwtDecoder.decode(SIGNED_JWT); ArgumentCaptor requestEntityCaptor = ArgumentCaptor.forClass(RequestEntity.class); @@ -490,7 +496,8 @@ public class NimbusJwtDecoderTests { RestOperations restOperations = mock(RestOperations.class); given(restOperations.exchange(any(RequestEntity.class), eq(String.class))) .willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK)); - NimbusJwtDecoder jwtDecoder = withJwkSetUri(JWK_SET_URI).restOperations(restOperations).cache(cache).build(); + NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).restOperations(restOperations) + .cache(cache).build(); // when jwtDecoder.decode(SIGNED_JWT); // then @@ -508,7 +515,8 @@ public class NimbusJwtDecoderTests { RestOperations restOperations = mock(RestOperations.class); Cache cache = mock(Cache.class); given(cache.get(eq(JWK_SET_URI), any(Callable.class))).willReturn(JWK_SET); - NimbusJwtDecoder jwtDecoder = withJwkSetUri(JWK_SET_URI).cache(cache).restOperations(restOperations).build(); + NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).cache(cache) + .restOperations(restOperations).build(); // when jwtDecoder.decode(SIGNED_JWT); // then @@ -524,11 +532,13 @@ public class NimbusJwtDecoderTests { RestOperations restOperations = mock(RestOperations.class); given(restOperations.exchange(any(RequestEntity.class), eq(String.class))) .willThrow(new RestClientException("Cannot retrieve JWK Set")); - NimbusJwtDecoder jwtDecoder = withJwkSetUri(JWK_SET_URI).restOperations(restOperations).cache(cache).build(); + NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).restOperations(restOperations) + .cache(cache).build(); // then assertThatCode(() -> jwtDecoder.decode(SIGNED_JWT)).isInstanceOf(JwtException.class) .isNotInstanceOf(BadJwtException.class) .hasMessageContaining("An error occurred while attempting to decode the Jwt"); + } // gh-8730 @@ -537,7 +547,7 @@ public class NimbusJwtDecoderTests { RestOperations restOperations = mock(RestOperations.class); given(restOperations.exchange(any(RequestEntity.class), eq(String.class))) .willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK)); - NimbusJwtDecoder jwtDecoder = withJwkSetUri(JWK_SET_URI).restOperations(restOperations) + NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).restOperations(restOperations) .jwtProcessorCustomizer( p -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))) .build(); @@ -547,7 +557,7 @@ public class NimbusJwtDecoderTests { @Test public void withJwkSetUriWhenJwtProcessorCustomizerNullThenThrowsIllegalArgumentException() { - assertThatThrownBy(() -> withJwkSetUri(JWK_SET_URI).jwtProcessorCustomizer(null)) + assertThatThrownBy(() -> NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).jwtProcessorCustomizer(null)) .isInstanceOf(IllegalArgumentException.class).hasMessage("jwtProcessorCustomizer cannot be null"); } @@ -582,7 +592,7 @@ public class NimbusJwtDecoderTests { RestOperations restOperations = mock(RestOperations.class); given(restOperations.exchange(any(RequestEntity.class), eq(String.class))) .willReturn(new ResponseEntity<>(jwkResponse, HttpStatus.OK)); - return withJwkSetUri(JWK_SET_URI).restOperations(restOperations).processor(); + return NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).restOperations(restOperations).processor(); } private static JWTProcessor withoutSigning() { diff --git a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusReactiveJwtDecoderTests.java b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusReactiveJwtDecoderTests.java index 99c4d04829..e6ab652181 100644 --- a/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusReactiveJwtDecoderTests.java +++ b/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusReactiveJwtDecoderTests.java @@ -66,16 +66,12 @@ import org.springframework.web.reactive.function.client.WebClient; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; +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.spy; import static org.mockito.Mockito.verify; -import static org.springframework.security.oauth2.jwt.NimbusReactiveJwtDecoder.withJwkSetUri; -import static org.springframework.security.oauth2.jwt.NimbusReactiveJwtDecoder.withJwkSource; -import static org.springframework.security.oauth2.jwt.NimbusReactiveJwtDecoder.withPublicKey; -import static org.springframework.security.oauth2.jwt.NimbusReactiveJwtDecoder.withSecretKey; /** * @author Rob Winch @@ -271,24 +267,28 @@ public class NimbusReactiveJwtDecoderTests { @Test public void withJwkSetUriWhenNullOrEmptyThenThrowsException() { - assertThatCode(() -> withJwkSetUri(null)).isInstanceOf(IllegalArgumentException.class); + assertThatCode(() -> NimbusReactiveJwtDecoder.withJwkSetUri(null)).isInstanceOf(IllegalArgumentException.class); } @Test public void jwsAlgorithmWhenNullThenThrowsException() { - NimbusReactiveJwtDecoder.JwkSetUriReactiveJwtDecoderBuilder builder = withJwkSetUri(this.jwkSetUri); + NimbusReactiveJwtDecoder.JwkSetUriReactiveJwtDecoderBuilder builder = NimbusReactiveJwtDecoder + .withJwkSetUri(this.jwkSetUri); assertThatCode(() -> builder.jwsAlgorithm(null)).isInstanceOf(IllegalArgumentException.class); } @Test public void withJwkSetUriWhenJwtProcessorCustomizerNullThenThrowsIllegalArgumentException() { - assertThatCode(() -> withJwkSetUri(this.jwkSetUri).jwtProcessorCustomizer(null).build()) - .isInstanceOf(IllegalArgumentException.class).hasMessage("jwtProcessorCustomizer cannot be null"); + assertThatCode( + () -> NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri).jwtProcessorCustomizer(null).build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("jwtProcessorCustomizer cannot be null"); } @Test public void restOperationsWhenNullThenThrowsException() { - NimbusReactiveJwtDecoder.JwkSetUriReactiveJwtDecoderBuilder builder = withJwkSetUri(this.jwkSetUri); + NimbusReactiveJwtDecoder.JwkSetUriReactiveJwtDecoderBuilder builder = NimbusReactiveJwtDecoder + .withJwkSetUri(this.jwkSetUri); assertThatCode(() -> builder.webClient(null)).isInstanceOf(IllegalArgumentException.class); } @@ -296,7 +296,8 @@ public class NimbusReactiveJwtDecoderTests { @Test public void decodeWhenSignedThenOk() { WebClient webClient = mockJwkSetResponse(this.jwkSet); - NimbusReactiveJwtDecoder decoder = withJwkSetUri(this.jwkSetUri).webClient(webClient).build(); + NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri).webClient(webClient) + .build(); assertThat(decoder.decode(this.messageReadToken).block()).extracting(Jwt::getExpiresAt).isNotNull(); verify(webClient).get(); } @@ -305,7 +306,7 @@ public class NimbusReactiveJwtDecoderTests { @Test public void withJwkSetUriWhenUsingCustomTypeHeaderThenRefuseOmittedType() { WebClient webClient = mockJwkSetResponse(this.jwkSet); - NimbusReactiveJwtDecoder decoder = withJwkSetUri(this.jwkSetUri).webClient(webClient) + NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri).webClient(webClient) .jwtProcessorCustomizer( p -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))) .build(); @@ -315,43 +316,46 @@ public class NimbusReactiveJwtDecoderTests { @Test public void withPublicKeyWhenNullThenThrowsException() { - assertThatThrownBy(() -> withPublicKey(null)).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> NimbusReactiveJwtDecoder.withPublicKey(null)) + .isInstanceOf(IllegalArgumentException.class); } @Test public void buildWhenSignatureAlgorithmMismatchesKeyTypeThenThrowsException() { - assertThatCode(() -> withPublicKey(key()).signatureAlgorithm(SignatureAlgorithm.ES256).build()) - .isInstanceOf(IllegalStateException.class); + assertThatCode(() -> NimbusReactiveJwtDecoder.withPublicKey(key()).signatureAlgorithm(SignatureAlgorithm.ES256) + .build()).isInstanceOf(IllegalStateException.class); } @Test public void buildWhenJwtProcessorCustomizerNullThenThrowsIllegalArgumentException() { - assertThatCode(() -> withPublicKey(key()).jwtProcessorCustomizer(null).build()) + assertThatCode(() -> NimbusReactiveJwtDecoder.withPublicKey(key()).jwtProcessorCustomizer(null).build()) .isInstanceOf(IllegalArgumentException.class).hasMessage("jwtProcessorCustomizer cannot be null"); } @Test public void decodeWhenUsingPublicKeyThenSuccessfullyDecodes() throws Exception { - NimbusReactiveJwtDecoder decoder = withPublicKey(key()).build(); + NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withPublicKey(key()).build(); assertThat(decoder.decode(this.rsa256).block()).extracting(Jwt::getSubject).isEqualTo("test-subject"); } @Test public void decodeWhenUsingPublicKeyWithRs512ThenSuccessfullyDecodes() throws Exception { - NimbusReactiveJwtDecoder decoder = withPublicKey(key()).signatureAlgorithm(SignatureAlgorithm.RS512).build(); + NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withPublicKey(key()) + .signatureAlgorithm(SignatureAlgorithm.RS512).build(); assertThat(decoder.decode(this.rsa512).block()).extracting(Jwt::getSubject).isEqualTo("test-subject"); } @Test public void decodeWhenSignatureMismatchesAlgorithmThenThrowsException() throws Exception { - NimbusReactiveJwtDecoder decoder = withPublicKey(key()).signatureAlgorithm(SignatureAlgorithm.RS512).build(); + NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withPublicKey(key()) + .signatureAlgorithm(SignatureAlgorithm.RS512).build(); assertThatCode(() -> decoder.decode(this.rsa256).block()).isInstanceOf(BadJwtException.class); } // gh-8730 @Test public void withPublicKeyWhenUsingCustomTypeHeaderThenRefuseOmittedType() throws Exception { - NimbusReactiveJwtDecoder decoder = withPublicKey(key()) + NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withPublicKey(key()) .jwtProcessorCustomizer( p -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))) .build(); @@ -363,19 +367,21 @@ public class NimbusReactiveJwtDecoderTests { @Test public void withJwkSourceWhenNullThenThrowsException() { - assertThatCode(() -> withJwkSource(null)).isInstanceOf(IllegalArgumentException.class); + assertThatCode(() -> NimbusReactiveJwtDecoder.withJwkSource(null)).isInstanceOf(IllegalArgumentException.class); } @Test public void withJwkSourceWhenJwtProcessorCustomizerNullThenThrowsIllegalArgumentException() { - assertThatCode(() -> withJwkSource(jwt -> Flux.empty()).jwtProcessorCustomizer(null).build()) - .isInstanceOf(IllegalArgumentException.class).hasMessage("jwtProcessorCustomizer cannot be null"); + assertThatCode( + () -> NimbusReactiveJwtDecoder.withJwkSource(jwt -> Flux.empty()).jwtProcessorCustomizer(null).build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("jwtProcessorCustomizer cannot be null"); } @Test public void decodeWhenCustomJwkSourceResolutionThenDecodes() { - NimbusReactiveJwtDecoder decoder = withJwkSource(jwt -> Flux.fromIterable(parseJWKSet(this.jwkSet).getKeys())) - .build(); + NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder + .withJwkSource(jwt -> Flux.fromIterable(parseJWKSet(this.jwkSet).getKeys())).build(); assertThat(decoder.decode(this.messageReadToken).block()).extracting(Jwt::getExpiresAt).isNotNull(); } @@ -383,7 +389,7 @@ public class NimbusReactiveJwtDecoderTests { // gh-8730 @Test public void withJwkSourceWhenUsingCustomTypeHeaderThenRefuseOmittedType() { - NimbusReactiveJwtDecoder decoder = withJwkSource(jwt -> Flux.empty()) + NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withJwkSource(jwt -> Flux.empty()) .jwtProcessorCustomizer( p -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))) .build(); @@ -394,21 +400,21 @@ public class NimbusReactiveJwtDecoderTests { @Test public void withSecretKeyWhenSecretKeyNullThenThrowsIllegalArgumentException() { - assertThatThrownBy(() -> withSecretKey(null)).isInstanceOf(IllegalArgumentException.class) - .hasMessage("secretKey cannot be null"); + assertThatThrownBy(() -> NimbusReactiveJwtDecoder.withSecretKey(null)) + .isInstanceOf(IllegalArgumentException.class).hasMessage("secretKey cannot be null"); } @Test public void withSecretKeyWhenJwtProcessorCustomizerNullThenThrowsIllegalArgumentException() { SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY; - assertThatThrownBy(() -> withSecretKey(secretKey).jwtProcessorCustomizer(null).build()) + assertThatThrownBy(() -> NimbusReactiveJwtDecoder.withSecretKey(secretKey).jwtProcessorCustomizer(null).build()) .isInstanceOf(IllegalArgumentException.class).hasMessage("jwtProcessorCustomizer cannot be null"); } @Test public void withSecretKeyWhenMacAlgorithmNullThenThrowsIllegalArgumentException() { SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY; - assertThatThrownBy(() -> withSecretKey(secretKey).macAlgorithm(null)) + assertThatThrownBy(() -> NimbusReactiveJwtDecoder.withSecretKey(secretKey).macAlgorithm(null)) .isInstanceOf(IllegalArgumentException.class).hasMessage("macAlgorithm cannot be null"); } @@ -420,7 +426,7 @@ public class NimbusReactiveJwtDecoderTests { .expirationTime(Date.from(Instant.now().plusSeconds(60))).build(); SignedJWT signedJWT = signedJwt(secretKey, macAlgorithm, claimsSet); - this.decoder = withSecretKey(secretKey).macAlgorithm(macAlgorithm).build(); + this.decoder = NimbusReactiveJwtDecoder.withSecretKey(secretKey).macAlgorithm(macAlgorithm).build(); Jwt jwt = this.decoder.decode(signedJWT.serialize()).block(); assertThat(jwt.getSubject()).isEqualTo("test-subject"); } @@ -429,7 +435,7 @@ public class NimbusReactiveJwtDecoderTests { @Test public void withSecretKeyWhenUsingCustomTypeHeaderThenRefuseOmittedType() { SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY; - NimbusReactiveJwtDecoder decoder = withSecretKey(secretKey) + NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withSecretKey(secretKey) .jwtProcessorCustomizer( p -> p.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))) .build(); @@ -445,7 +451,7 @@ public class NimbusReactiveJwtDecoderTests { .expirationTime(Date.from(Instant.now().plusSeconds(60))).build(); SignedJWT signedJWT = signedJwt(secretKey, macAlgorithm, claimsSet); - this.decoder = withSecretKey(secretKey).macAlgorithm(MacAlgorithm.HS512).build(); + this.decoder = NimbusReactiveJwtDecoder.withSecretKey(secretKey).macAlgorithm(MacAlgorithm.HS512).build(); assertThatThrownBy(() -> this.decoder.decode(signedJWT.serialize()).block()) .isInstanceOf(BadJwtException.class); } @@ -453,7 +459,8 @@ public class NimbusReactiveJwtDecoderTests { @Test public void jwsKeySelectorWhenNoAlgorithmThenReturnsRS256Selector() { JWKSource jwkSource = mock(JWKSource.class); - JWSKeySelector jwsKeySelector = withJwkSetUri(this.jwkSetUri).jwsKeySelector(jwkSource); + JWSKeySelector jwsKeySelector = NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri) + .jwsKeySelector(jwkSource); assertThat(jwsKeySelector instanceof JWSVerificationKeySelector); JWSVerificationKeySelector jwsVerificationKeySelector = (JWSVerificationKeySelector) jwsKeySelector; assertThat(jwsVerificationKeySelector.isAllowed(JWSAlgorithm.RS256)).isTrue(); @@ -462,7 +469,7 @@ public class NimbusReactiveJwtDecoderTests { @Test public void jwsKeySelectorWhenOneAlgorithmThenReturnsSingleSelector() { JWKSource jwkSource = mock(JWKSource.class); - JWSKeySelector jwsKeySelector = withJwkSetUri(this.jwkSetUri) + JWSKeySelector jwsKeySelector = NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri) .jwsAlgorithm(SignatureAlgorithm.RS512).jwsKeySelector(jwkSource); assertThat(jwsKeySelector instanceof JWSVerificationKeySelector); JWSVerificationKeySelector jwsVerificationKeySelector = (JWSVerificationKeySelector) jwsKeySelector; @@ -472,7 +479,7 @@ public class NimbusReactiveJwtDecoderTests { @Test public void jwsKeySelectorWhenMultipleAlgorithmThenReturnsCompositeSelector() { JWKSource jwkSource = mock(JWKSource.class); - JWSKeySelector jwsKeySelector = withJwkSetUri(this.jwkSetUri) + JWSKeySelector jwsKeySelector = NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri) .jwsAlgorithm(SignatureAlgorithm.RS256).jwsAlgorithm(SignatureAlgorithm.RS512) .jwsKeySelector(jwkSource); assertThat(jwsKeySelector instanceof JWSVerificationKeySelector); diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/BearerTokenErrors.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/BearerTokenErrors.java index 5a2b50cfbb..357cefe7dd 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/BearerTokenErrors.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/BearerTokenErrors.java @@ -18,10 +18,6 @@ package org.springframework.security.oauth2.server.resource; import org.springframework.http.HttpStatus; -import static org.springframework.security.oauth2.server.resource.BearerTokenErrorCodes.INSUFFICIENT_SCOPE; -import static org.springframework.security.oauth2.server.resource.BearerTokenErrorCodes.INVALID_REQUEST; -import static org.springframework.security.oauth2.server.resource.BearerTokenErrorCodes.INVALID_TOKEN; - /** * A factory for creating {@link BearerTokenError} instances that correspond to the * registered Bearer Token Error @@ -47,7 +43,8 @@ public final class BearerTokenErrors { */ public static BearerTokenError invalidRequest(String message) { try { - return new BearerTokenError(INVALID_REQUEST, HttpStatus.BAD_REQUEST, message, DEFAULT_URI); + return new BearerTokenError(BearerTokenErrorCodes.INVALID_REQUEST, HttpStatus.BAD_REQUEST, message, + DEFAULT_URI); } catch (IllegalArgumentException malformed) { // some third-party library error messages are not suitable for RFC 6750's @@ -63,7 +60,8 @@ public final class BearerTokenErrors { */ public static BearerTokenError invalidToken(String message) { try { - return new BearerTokenError(INVALID_TOKEN, HttpStatus.UNAUTHORIZED, message, DEFAULT_URI); + return new BearerTokenError(BearerTokenErrorCodes.INVALID_TOKEN, HttpStatus.UNAUTHORIZED, message, + DEFAULT_URI); } catch (IllegalArgumentException malformed) { // some third-party library error messages are not suitable for RFC 6750's @@ -79,7 +77,8 @@ public final class BearerTokenErrors { */ public static BearerTokenError insufficientScope(String message, String scope) { try { - return new BearerTokenError(INSUFFICIENT_SCOPE, HttpStatus.FORBIDDEN, message, DEFAULT_URI, scope); + return new BearerTokenError(BearerTokenErrorCodes.INSUFFICIENT_SCOPE, HttpStatus.FORBIDDEN, message, + DEFAULT_URI, scope); } catch (IllegalArgumentException malformed) { // some third-party library error messages are not suitable for RFC 6750's diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/InvalidBearerTokenException.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/InvalidBearerTokenException.java index e3ba596dab..0ba62813da 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/InvalidBearerTokenException.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/InvalidBearerTokenException.java @@ -18,8 +18,6 @@ package org.springframework.security.oauth2.server.resource; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; -import static org.springframework.security.oauth2.server.resource.BearerTokenErrors.invalidToken; - /** * An {@link OAuth2AuthenticationException} that indicates an invalid bearer token. * @@ -38,7 +36,7 @@ public class InvalidBearerTokenException extends OAuth2AuthenticationException { * @param description the description */ public InvalidBearerTokenException(String description) { - super(invalidToken(description)); + super(BearerTokenErrors.invalidToken(description)); } /** @@ -52,7 +50,7 @@ public class InvalidBearerTokenException extends OAuth2AuthenticationException { * @param cause the causing exception */ public InvalidBearerTokenException(String description, Throwable cause) { - super(invalidToken(description), cause); + super(BearerTokenErrors.invalidToken(description), cause); } } diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenAuthenticationProvider.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenAuthenticationProvider.java index 698062b743..23513a9d1f 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenAuthenticationProvider.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenAuthenticationProvider.java @@ -29,13 +29,11 @@ import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; import org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken; import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException; import org.springframework.security.oauth2.server.resource.introspection.BadOpaqueTokenException; +import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames; import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionException; import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector; import org.springframework.util.Assert; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.EXPIRES_AT; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.ISSUED_AT; - /** * An {@link AuthenticationProvider} implementation for opaque * Bearer @@ -113,8 +111,8 @@ public final class OpaqueTokenAuthenticationProvider implements AuthenticationPr } private AbstractAuthenticationToken convert(OAuth2AuthenticatedPrincipal principal, String token) { - Instant iat = principal.getAttribute(ISSUED_AT); - Instant exp = principal.getAttribute(EXPIRES_AT); + Instant iat = principal.getAttribute(OAuth2IntrospectionClaimNames.ISSUED_AT); + Instant exp = principal.getAttribute(OAuth2IntrospectionClaimNames.EXPIRES_AT); OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, token, iat, exp); return new BearerTokenAuthentication(principal, accessToken, principal.getAuthorities()); } diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenReactiveAuthenticationManager.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenReactiveAuthenticationManager.java index 95e763bd9a..8745906907 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenReactiveAuthenticationManager.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenReactiveAuthenticationManager.java @@ -30,13 +30,11 @@ import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken; import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException; import org.springframework.security.oauth2.server.resource.introspection.BadOpaqueTokenException; +import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames; import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionException; import org.springframework.security.oauth2.server.resource.introspection.ReactiveOpaqueTokenIntrospector; import org.springframework.util.Assert; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.EXPIRES_AT; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.ISSUED_AT; - /** * An {@link ReactiveAuthenticationManager} implementation for opaque * Bearer @@ -84,8 +82,8 @@ public class OpaqueTokenReactiveAuthenticationManager implements ReactiveAuthent private Mono authenticate(String token) { return this.introspector.introspect(token).map(principal -> { - Instant iat = principal.getAttribute(ISSUED_AT); - Instant exp = principal.getAttribute(EXPIRES_AT); + Instant iat = principal.getAttribute(OAuth2IntrospectionClaimNames.ISSUED_AT); + Instant exp = principal.getAttribute(OAuth2IntrospectionClaimNames.EXPIRES_AT); // construct token OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, token, iat, exp); diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/NimbusOpaqueTokenIntrospector.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/NimbusOpaqueTokenIntrospector.java index a6b1ff2521..992a58ad58 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/NimbusOpaqueTokenIntrospector.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/NimbusOpaqueTokenIntrospector.java @@ -46,14 +46,6 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestOperations; import org.springframework.web.client.RestTemplate; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.AUDIENCE; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.CLIENT_ID; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.EXPIRES_AT; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.ISSUED_AT; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.ISSUER; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.NOT_BEFORE; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.SCOPE; - /** * A Nimbus implementation of {@link OpaqueTokenIntrospector} that verifies and * introspects a token using the configured @@ -205,28 +197,28 @@ public class NimbusOpaqueTokenIntrospector implements OpaqueTokenIntrospector { for (Audience audience : response.getAudience()) { audiences.add(audience.getValue()); } - claims.put(AUDIENCE, Collections.unmodifiableList(audiences)); + claims.put(OAuth2IntrospectionClaimNames.AUDIENCE, Collections.unmodifiableList(audiences)); } if (response.getClientID() != null) { - claims.put(CLIENT_ID, response.getClientID().getValue()); + claims.put(OAuth2IntrospectionClaimNames.CLIENT_ID, response.getClientID().getValue()); } if (response.getExpirationTime() != null) { Instant exp = response.getExpirationTime().toInstant(); - claims.put(EXPIRES_AT, exp); + claims.put(OAuth2IntrospectionClaimNames.EXPIRES_AT, exp); } if (response.getIssueTime() != null) { Instant iat = response.getIssueTime().toInstant(); - claims.put(ISSUED_AT, iat); + claims.put(OAuth2IntrospectionClaimNames.ISSUED_AT, iat); } if (response.getIssuer() != null) { - claims.put(ISSUER, issuer(response.getIssuer().getValue())); + claims.put(OAuth2IntrospectionClaimNames.ISSUER, issuer(response.getIssuer().getValue())); } if (response.getNotBeforeTime() != null) { - claims.put(NOT_BEFORE, response.getNotBeforeTime().toInstant()); + claims.put(OAuth2IntrospectionClaimNames.NOT_BEFORE, response.getNotBeforeTime().toInstant()); } if (response.getScope() != null) { List scopes = Collections.unmodifiableList(response.getScope().toStringList()); - claims.put(SCOPE, scopes); + claims.put(OAuth2IntrospectionClaimNames.SCOPE, scopes); for (String scope : scopes) { authorities.add(new SimpleGrantedAuthority(this.authorityPrefix + scope)); @@ -241,7 +233,8 @@ public class NimbusOpaqueTokenIntrospector implements OpaqueTokenIntrospector { return new URL(uri); } catch (Exception ex) { - throw new OAuth2IntrospectionException("Invalid " + ISSUER + " value: " + uri); + throw new OAuth2IntrospectionException( + "Invalid " + OAuth2IntrospectionClaimNames.ISSUER + " value: " + uri); } } diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/NimbusReactiveOpaqueTokenIntrospector.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/NimbusReactiveOpaqueTokenIntrospector.java index 81b27931ca..5c7ccf0b04 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/NimbusReactiveOpaqueTokenIntrospector.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/NimbusReactiveOpaqueTokenIntrospector.java @@ -43,14 +43,6 @@ import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.client.ClientResponse; import org.springframework.web.reactive.function.client.WebClient; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.AUDIENCE; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.CLIENT_ID; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.EXPIRES_AT; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.ISSUED_AT; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.ISSUER; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.NOT_BEFORE; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.SCOPE; - /** * A Nimbus implementation of {@link ReactiveOpaqueTokenIntrospector} that verifies and * introspects a token using the configured @@ -158,28 +150,28 @@ public class NimbusReactiveOpaqueTokenIntrospector implements ReactiveOpaqueToke for (Audience audience : response.getAudience()) { audiences.add(audience.getValue()); } - claims.put(AUDIENCE, Collections.unmodifiableList(audiences)); + claims.put(OAuth2IntrospectionClaimNames.AUDIENCE, Collections.unmodifiableList(audiences)); } if (response.getClientID() != null) { - claims.put(CLIENT_ID, response.getClientID().getValue()); + claims.put(OAuth2IntrospectionClaimNames.CLIENT_ID, response.getClientID().getValue()); } if (response.getExpirationTime() != null) { Instant exp = response.getExpirationTime().toInstant(); - claims.put(EXPIRES_AT, exp); + claims.put(OAuth2IntrospectionClaimNames.EXPIRES_AT, exp); } if (response.getIssueTime() != null) { Instant iat = response.getIssueTime().toInstant(); - claims.put(ISSUED_AT, iat); + claims.put(OAuth2IntrospectionClaimNames.ISSUED_AT, iat); } if (response.getIssuer() != null) { - claims.put(ISSUER, issuer(response.getIssuer().getValue())); + claims.put(OAuth2IntrospectionClaimNames.ISSUER, issuer(response.getIssuer().getValue())); } if (response.getNotBeforeTime() != null) { - claims.put(NOT_BEFORE, response.getNotBeforeTime().toInstant()); + claims.put(OAuth2IntrospectionClaimNames.NOT_BEFORE, response.getNotBeforeTime().toInstant()); } if (response.getScope() != null) { List scopes = Collections.unmodifiableList(response.getScope().toStringList()); - claims.put(SCOPE, scopes); + claims.put(OAuth2IntrospectionClaimNames.SCOPE, scopes); for (String scope : scopes) { authorities.add(new SimpleGrantedAuthority(this.authorityPrefix + scope)); @@ -194,7 +186,8 @@ public class NimbusReactiveOpaqueTokenIntrospector implements ReactiveOpaqueToke return new URL(uri); } catch (Exception ex) { - throw new OAuth2IntrospectionException("Invalid " + ISSUER + " value: " + uri); + throw new OAuth2IntrospectionException( + "Invalid " + OAuth2IntrospectionClaimNames.ISSUER + " value: " + uri); } } diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/DefaultBearerTokenResolver.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/DefaultBearerTokenResolver.java index f83cbbd90e..aea2208569 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/DefaultBearerTokenResolver.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/DefaultBearerTokenResolver.java @@ -24,11 +24,9 @@ import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpHeaders; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.server.resource.BearerTokenError; +import org.springframework.security.oauth2.server.resource.BearerTokenErrors; import org.springframework.util.StringUtils; -import static org.springframework.security.oauth2.server.resource.BearerTokenErrors.invalidRequest; -import static org.springframework.security.oauth2.server.resource.BearerTokenErrors.invalidToken; - /** * The default {@link BearerTokenResolver} implementation based on RFC 6750. * @@ -57,7 +55,8 @@ public final class DefaultBearerTokenResolver implements BearerTokenResolver { String parameterToken = resolveFromRequestParameters(request); if (authorizationHeaderToken != null) { if (parameterToken != null) { - BearerTokenError error = invalidRequest("Found multiple bearer tokens in the request"); + BearerTokenError error = BearerTokenErrors + .invalidRequest("Found multiple bearer tokens in the request"); throw new OAuth2AuthenticationException(error); } return authorizationHeaderToken; @@ -109,7 +108,7 @@ public final class DefaultBearerTokenResolver implements BearerTokenResolver { Matcher matcher = authorizationPattern.matcher(authorization); if (!matcher.matches()) { - BearerTokenError error = invalidToken("Bearer token is malformed"); + BearerTokenError error = BearerTokenErrors.invalidToken("Bearer token is malformed"); throw new OAuth2AuthenticationException(error); } @@ -128,7 +127,7 @@ public final class DefaultBearerTokenResolver implements BearerTokenResolver { return values[0]; } - BearerTokenError error = invalidRequest("Found multiple bearer tokens in the request"); + BearerTokenError error = BearerTokenErrors.invalidRequest("Found multiple bearer tokens in the request"); throw new OAuth2AuthenticationException(error); } diff --git a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/server/ServerBearerTokenAuthenticationConverter.java b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/server/ServerBearerTokenAuthenticationConverter.java index 37edea4e99..be467f65a4 100644 --- a/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/server/ServerBearerTokenAuthenticationConverter.java +++ b/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/server/ServerBearerTokenAuthenticationConverter.java @@ -28,13 +28,11 @@ import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken; import org.springframework.security.oauth2.server.resource.BearerTokenError; +import org.springframework.security.oauth2.server.resource.BearerTokenErrors; import org.springframework.security.web.server.authentication.ServerAuthenticationConverter; import org.springframework.util.StringUtils; import org.springframework.web.server.ServerWebExchange; -import static org.springframework.security.oauth2.server.resource.BearerTokenErrors.invalidRequest; -import static org.springframework.security.oauth2.server.resource.BearerTokenErrors.invalidToken; - /** * A strategy for resolving * Bearer @@ -70,7 +68,8 @@ public class ServerBearerTokenAuthenticationConverter implements ServerAuthentic String parameterToken = request.getQueryParams().getFirst("access_token"); if (authorizationHeaderToken != null) { if (parameterToken != null) { - BearerTokenError error = invalidRequest("Found multiple bearer tokens in the request"); + BearerTokenError error = BearerTokenErrors + .invalidRequest("Found multiple bearer tokens in the request"); throw new OAuth2AuthenticationException(error); } return authorizationHeaderToken; @@ -122,7 +121,7 @@ public class ServerBearerTokenAuthenticationConverter implements ServerAuthentic } private static BearerTokenError invalidTokenError() { - return invalidToken("Bearer token is malformed"); + return BearerTokenErrors.invalidToken("Bearer token is malformed"); } private boolean isParameterTokenSupportedForRequest(ServerHttpRequest request) { diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/BearerTokenErrorsTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/BearerTokenErrorsTests.java index f84778f545..e8baca0464 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/BearerTokenErrorsTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/BearerTokenErrorsTests.java @@ -18,13 +18,9 @@ package org.springframework.security.oauth2.server.resource; import org.junit.Test; +import org.springframework.http.HttpStatus; + import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.http.HttpStatus.BAD_REQUEST; -import static org.springframework.http.HttpStatus.FORBIDDEN; -import static org.springframework.http.HttpStatus.UNAUTHORIZED; -import static org.springframework.security.oauth2.server.resource.BearerTokenErrorCodes.INSUFFICIENT_SCOPE; -import static org.springframework.security.oauth2.server.resource.BearerTokenErrorCodes.INVALID_REQUEST; -import static org.springframework.security.oauth2.server.resource.BearerTokenErrorCodes.INVALID_TOKEN; public class BearerTokenErrorsTests { @@ -32,9 +28,9 @@ public class BearerTokenErrorsTests { public void invalidRequestWhenMessageGivenThenBearerTokenErrorReturned() { String message = "message"; BearerTokenError error = BearerTokenErrors.invalidRequest(message); - assertThat(error.getErrorCode()).isSameAs(INVALID_REQUEST); + assertThat(error.getErrorCode()).isSameAs(BearerTokenErrorCodes.INVALID_REQUEST); assertThat(error.getDescription()).isSameAs(message); - assertThat(error.getHttpStatus()).isSameAs(BAD_REQUEST); + assertThat(error.getHttpStatus()).isSameAs(HttpStatus.BAD_REQUEST); assertThat(error.getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1"); } @@ -42,9 +38,9 @@ public class BearerTokenErrorsTests { public void invalidRequestWhenInvalidMessageGivenThenDefaultBearerTokenErrorReturned() { String message = "has \"invalid\" chars"; BearerTokenError error = BearerTokenErrors.invalidRequest(message); - assertThat(error.getErrorCode()).isSameAs(INVALID_REQUEST); + assertThat(error.getErrorCode()).isSameAs(BearerTokenErrorCodes.INVALID_REQUEST); assertThat(error.getDescription()).isEqualTo("Invalid request"); - assertThat(error.getHttpStatus()).isSameAs(BAD_REQUEST); + assertThat(error.getHttpStatus()).isSameAs(HttpStatus.BAD_REQUEST); assertThat(error.getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1"); } @@ -52,9 +48,9 @@ public class BearerTokenErrorsTests { public void invalidTokenWhenMessageGivenThenBearerTokenErrorReturned() { String message = "message"; BearerTokenError error = BearerTokenErrors.invalidToken(message); - assertThat(error.getErrorCode()).isSameAs(INVALID_TOKEN); + assertThat(error.getErrorCode()).isSameAs(BearerTokenErrorCodes.INVALID_TOKEN); assertThat(error.getDescription()).isSameAs(message); - assertThat(error.getHttpStatus()).isSameAs(UNAUTHORIZED); + assertThat(error.getHttpStatus()).isSameAs(HttpStatus.UNAUTHORIZED); assertThat(error.getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1"); } @@ -62,9 +58,9 @@ public class BearerTokenErrorsTests { public void invalidTokenWhenInvalidMessageGivenThenDefaultBearerTokenErrorReturned() { String message = "has \"invalid\" chars"; BearerTokenError error = BearerTokenErrors.invalidToken(message); - assertThat(error.getErrorCode()).isSameAs(INVALID_TOKEN); + assertThat(error.getErrorCode()).isSameAs(BearerTokenErrorCodes.INVALID_TOKEN); assertThat(error.getDescription()).isEqualTo("Invalid token"); - assertThat(error.getHttpStatus()).isSameAs(UNAUTHORIZED); + assertThat(error.getHttpStatus()).isSameAs(HttpStatus.UNAUTHORIZED); assertThat(error.getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1"); } @@ -73,9 +69,9 @@ public class BearerTokenErrorsTests { String message = "message"; String scope = "scope"; BearerTokenError error = BearerTokenErrors.insufficientScope(message, scope); - assertThat(error.getErrorCode()).isSameAs(INSUFFICIENT_SCOPE); + assertThat(error.getErrorCode()).isSameAs(BearerTokenErrorCodes.INSUFFICIENT_SCOPE); assertThat(error.getDescription()).isSameAs(message); - assertThat(error.getHttpStatus()).isSameAs(FORBIDDEN); + assertThat(error.getHttpStatus()).isSameAs(HttpStatus.FORBIDDEN); assertThat(error.getScope()).isSameAs(scope); assertThat(error.getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1"); } @@ -84,9 +80,9 @@ public class BearerTokenErrorsTests { public void insufficientScopeWhenInvalidMessageGivenThenDefaultBearerTokenErrorReturned() { String message = "has \"invalid\" chars"; BearerTokenError error = BearerTokenErrors.insufficientScope(message, "scope"); - assertThat(error.getErrorCode()).isSameAs(INSUFFICIENT_SCOPE); + assertThat(error.getErrorCode()).isSameAs(BearerTokenErrorCodes.INSUFFICIENT_SCOPE); assertThat(error.getDescription()).isSameAs("Insufficient scope"); - assertThat(error.getHttpStatus()).isSameAs(FORBIDDEN); + assertThat(error.getHttpStatus()).isSameAs(HttpStatus.FORBIDDEN); assertThat(error.getScope()).isNull(); assertThat(error.getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1"); } diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/DefaultAuthenticationEventPublisherBearerTokenTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/DefaultAuthenticationEventPublisherBearerTokenTests.java index 84456f738b..10fdb5fe57 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/DefaultAuthenticationEventPublisherBearerTokenTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/DefaultAuthenticationEventPublisherBearerTokenTests.java @@ -22,13 +22,13 @@ import org.springframework.context.ApplicationEventPublisher; import org.springframework.security.authentication.DefaultAuthenticationEventPublisher; import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent; import org.springframework.security.core.Authentication; +import org.springframework.security.oauth2.jwt.TestJwts; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.springframework.security.oauth2.jwt.TestJwts.jwt; /** * Tests for {@link DefaultAuthenticationEventPublisher}'s bearer token use cases @@ -42,7 +42,7 @@ public class DefaultAuthenticationEventPublisherBearerTokenTests { @Test public void publishAuthenticationFailureWhenInvalidBearerTokenExceptionThenMaps() { ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class); - Authentication authentication = new JwtAuthenticationToken(jwt().build()); + Authentication authentication = new JwtAuthenticationToken(TestJwts.jwt().build()); Exception cause = new Exception(); this.publisher = new DefaultAuthenticationEventPublisher(appPublisher); this.publisher.publishAuthenticationFailure(new InvalidBearerTokenException("invalid"), authentication); diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/BearerTokenAuthenticationTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/BearerTokenAuthenticationTests.java index e8c7b3eb44..3a77bbb899 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/BearerTokenAuthenticationTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/BearerTokenAuthenticationTests.java @@ -33,12 +33,10 @@ import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.oauth2.core.DefaultOAuth2AuthenticatedPrincipal; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; +import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.CLIENT_ID; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.SUBJECT; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.USERNAME; /** * Tests for {@link BearerTokenAuthentication} @@ -60,9 +58,9 @@ public class BearerTokenAuthenticationTests { @Before public void setUp() { - this.attributesMap.put(SUBJECT, this.name); - this.attributesMap.put(CLIENT_ID, "client_id"); - this.attributesMap.put(USERNAME, "username"); + this.attributesMap.put(OAuth2IntrospectionClaimNames.SUBJECT, this.name); + this.attributesMap.put(OAuth2IntrospectionClaimNames.CLIENT_ID, "client_id"); + this.attributesMap.put(OAuth2IntrospectionClaimNames.USERNAME, "username"); this.principal = new DefaultOAuth2AuthenticatedPrincipal(this.attributesMap, null); } @@ -86,7 +84,8 @@ public class BearerTokenAuthenticationTests { @Test public void getNameWhenTokenHasUsernameThenReturnsUsernameAttribute() { BearerTokenAuthentication authenticated = new BearerTokenAuthentication(this.principal, this.token, null); - assertThat(authenticated.getName()).isEqualTo(this.principal.getAttribute(SUBJECT)); + assertThat(authenticated.getName()) + .isEqualTo(this.principal.getAttribute(OAuth2IntrospectionClaimNames.SUBJECT)); } @Test diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationConverterTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationConverterTests.java index ad14ba287a..e51eeba4c5 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationConverterTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationConverterTests.java @@ -26,10 +26,10 @@ import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.jwt.TestJwts; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.springframework.security.oauth2.jwt.TestJwts.jwt; /** * Tests for {@link JwtAuthenticationConverter} @@ -43,7 +43,7 @@ public class JwtAuthenticationConverterTests { @Test public void convertWhenDefaultGrantedAuthoritiesConverterSet() { - Jwt jwt = jwt().claim("scope", "message:read message:write").build(); + Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build(); AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt); Collection authorities = authentication.getAuthorities(); @@ -61,7 +61,7 @@ public class JwtAuthenticationConverterTests { @Test public void convertWithOverriddenGrantedAuthoritiesConverter() { - Jwt jwt = jwt().claim("scope", "message:read message:write").build(); + Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build(); Converter> grantedAuthoritiesConverter = token -> Arrays .asList(new SimpleGrantedAuthority("blah")); @@ -98,7 +98,7 @@ public class JwtAuthenticationConverterTests { public void convertWhenPrincipalClaimNameSet() { this.jwtAuthenticationConverter.setPrincipalClaimName("user_id"); - Jwt jwt = jwt().claim("user_id", "100").build(); + Jwt jwt = TestJwts.jwt().claim("user_id", "100").build(); AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt); assertThat(authentication.getName()).isEqualTo("100"); diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationProviderTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationProviderTests.java index ca33f35c69..b74050f296 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationProviderTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationProviderTests.java @@ -30,6 +30,7 @@ import org.springframework.security.oauth2.jwt.BadJwtException; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.jwt.JwtException; +import org.springframework.security.oauth2.jwt.TestJwts; import org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken; import org.springframework.security.oauth2.server.resource.BearerTokenErrorCodes; @@ -37,7 +38,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.springframework.security.oauth2.jwt.TestJwts.jwt; /** * Tests for {@link JwtAuthenticationProvider} @@ -65,7 +65,7 @@ public class JwtAuthenticationProviderTests { public void authenticateWhenJwtDecodesThenAuthenticationHasAttributesContainedInJwt() { BearerTokenAuthenticationToken token = this.authentication(); - Jwt jwt = jwt().claim("name", "value").build(); + Jwt jwt = TestJwts.jwt().claim("name", "value").build(); given(this.jwtDecoder.decode("token")).willReturn(jwt); given(this.jwtAuthenticationConverter.convert(jwt)).willReturn(new JwtAuthenticationToken(jwt)); @@ -113,7 +113,7 @@ public class JwtAuthenticationProviderTests { Object details = mock(Object.class); token.setDetails(details); - Jwt jwt = jwt().build(); + Jwt jwt = TestJwts.jwt().build(); JwtAuthenticationToken authentication = new JwtAuthenticationToken(jwt); given(this.jwtDecoder.decode(token.getToken())).willReturn(jwt); diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationTokenTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationTokenTests.java index 5fc65eb8bf..b47ae58732 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationTokenTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationTokenTests.java @@ -24,11 +24,11 @@ import org.mockito.junit.MockitoJUnitRunner; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.security.oauth2.jose.jws.JwsAlgorithms; import org.springframework.security.oauth2.jwt.Jwt; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; -import static org.springframework.security.oauth2.jose.jws.JwsAlgorithms.RS256; /** * Tests for {@link JwtAuthenticationToken} @@ -124,7 +124,7 @@ public class JwtAuthenticationTokenTests { } private Jwt.Builder builder() { - return Jwt.withTokenValue("token").header("alg", RS256); + return Jwt.withTokenValue("token").header("alg", JwsAlgorithms.RS256); } } diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtGrantedAuthoritiesConverterTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtGrantedAuthoritiesConverterTests.java index 32d1ef773a..f304c0dc67 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtGrantedAuthoritiesConverterTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtGrantedAuthoritiesConverterTests.java @@ -25,9 +25,9 @@ import org.junit.Test; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.jwt.TestJwts; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.oauth2.jwt.TestJwts.jwt; /** * Tests for {@link JwtGrantedAuthoritiesConverter} @@ -45,7 +45,7 @@ public class JwtGrantedAuthoritiesConverterTests { @Test public void convertWhenTokenHasScopeAttributeThenTranslatedToAuthorities() { - Jwt jwt = jwt().claim("scope", "message:read message:write").build(); + Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build(); JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); Collection authorities = jwtGrantedAuthoritiesConverter.convert(jwt); @@ -56,7 +56,7 @@ public class JwtGrantedAuthoritiesConverterTests { @Test public void convertWithCustomAuthorityPrefixWhenTokenHasScopeAttributeThenTranslatedToAuthorities() { - Jwt jwt = jwt().claim("scope", "message:read message:write").build(); + Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build(); JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); jwtGrantedAuthoritiesConverter.setAuthorityPrefix("ROLE_"); @@ -68,7 +68,7 @@ public class JwtGrantedAuthoritiesConverterTests { @Test public void convertWithBlankAsCustomAuthorityPrefixWhenTokenHasScopeAttributeThenTranslatedToAuthorities() { - Jwt jwt = jwt().claim("scope", "message:read message:write").build(); + Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build(); JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); jwtGrantedAuthoritiesConverter.setAuthorityPrefix(""); @@ -80,7 +80,7 @@ public class JwtGrantedAuthoritiesConverterTests { @Test public void convertWhenTokenHasEmptyScopeAttributeThenTranslatedToNoAuthorities() { - Jwt jwt = jwt().claim("scope", "").build(); + Jwt jwt = TestJwts.jwt().claim("scope", "").build(); JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); Collection authorities = jwtGrantedAuthoritiesConverter.convert(jwt); @@ -90,7 +90,7 @@ public class JwtGrantedAuthoritiesConverterTests { @Test public void convertWhenTokenHasScpAttributeThenTranslatedToAuthorities() { - Jwt jwt = jwt().claim("scp", Arrays.asList("message:read", "message:write")).build(); + Jwt jwt = TestJwts.jwt().claim("scp", Arrays.asList("message:read", "message:write")).build(); JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); Collection authorities = jwtGrantedAuthoritiesConverter.convert(jwt); @@ -101,7 +101,7 @@ public class JwtGrantedAuthoritiesConverterTests { @Test public void convertWithCustomAuthorityPrefixWhenTokenHasScpAttributeThenTranslatedToAuthorities() { - Jwt jwt = jwt().claim("scp", Arrays.asList("message:read", "message:write")).build(); + Jwt jwt = TestJwts.jwt().claim("scp", Arrays.asList("message:read", "message:write")).build(); JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); jwtGrantedAuthoritiesConverter.setAuthorityPrefix("ROLE_"); @@ -113,7 +113,7 @@ public class JwtGrantedAuthoritiesConverterTests { @Test public void convertWithBlankAsCustomAuthorityPrefixWhenTokenHasScpAttributeThenTranslatedToAuthorities() { - Jwt jwt = jwt().claim("scp", "message:read message:write").build(); + Jwt jwt = TestJwts.jwt().claim("scp", "message:read message:write").build(); JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); jwtGrantedAuthoritiesConverter.setAuthorityPrefix(""); @@ -125,7 +125,7 @@ public class JwtGrantedAuthoritiesConverterTests { @Test public void convertWhenTokenHasEmptyScpAttributeThenTranslatedToNoAuthorities() { - Jwt jwt = jwt().claim("scp", Collections.emptyList()).build(); + Jwt jwt = TestJwts.jwt().claim("scp", Collections.emptyList()).build(); JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); Collection authorities = jwtGrantedAuthoritiesConverter.convert(jwt); @@ -135,7 +135,7 @@ public class JwtGrantedAuthoritiesConverterTests { @Test public void convertWhenTokenHasBothScopeAndScpThenScopeAttributeIsTranslatedToAuthorities() { - Jwt jwt = jwt().claim("scp", Arrays.asList("message:read", "message:write")) + Jwt jwt = TestJwts.jwt().claim("scp", Arrays.asList("message:read", "message:write")) .claim("scope", "missive:read missive:write").build(); JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); @@ -147,7 +147,8 @@ public class JwtGrantedAuthoritiesConverterTests { @Test public void convertWhenTokenHasEmptyScopeAndNonEmptyScpThenScopeAttributeIsTranslatedToNoAuthorities() { - Jwt jwt = jwt().claim("scp", Arrays.asList("message:read", "message:write")).claim("scope", "").build(); + Jwt jwt = TestJwts.jwt().claim("scp", Arrays.asList("message:read", "message:write")).claim("scope", "") + .build(); JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); Collection authorities = jwtGrantedAuthoritiesConverter.convert(jwt); @@ -157,7 +158,7 @@ public class JwtGrantedAuthoritiesConverterTests { @Test public void convertWhenTokenHasEmptyScopeAndEmptyScpAttributeThenTranslatesToNoAuthorities() { - Jwt jwt = jwt().claim("scp", Collections.emptyList()).claim("scope", Collections.emptyList()).build(); + Jwt jwt = TestJwts.jwt().claim("scp", Collections.emptyList()).claim("scope", Collections.emptyList()).build(); JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); Collection authorities = jwtGrantedAuthoritiesConverter.convert(jwt); @@ -167,7 +168,7 @@ public class JwtGrantedAuthoritiesConverterTests { @Test public void convertWhenTokenHasNoScopeAndNoScpAttributeThenTranslatesToNoAuthorities() { - Jwt jwt = jwt().claim("roles", Arrays.asList("message:read", "message:write")).build(); + Jwt jwt = TestJwts.jwt().claim("roles", Arrays.asList("message:read", "message:write")).build(); JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); Collection authorities = jwtGrantedAuthoritiesConverter.convert(jwt); @@ -177,7 +178,7 @@ public class JwtGrantedAuthoritiesConverterTests { @Test public void convertWhenTokenHasUnsupportedTypeForScopeThenTranslatesToNoAuthorities() { - Jwt jwt = jwt().claim("scope", new String[] { "message:read", "message:write" }).build(); + Jwt jwt = TestJwts.jwt().claim("scope", new String[] { "message:read", "message:write" }).build(); JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); Collection authorities = jwtGrantedAuthoritiesConverter.convert(jwt); @@ -187,7 +188,7 @@ public class JwtGrantedAuthoritiesConverterTests { @Test public void convertWhenTokenHasCustomClaimNameThenCustomClaimNameAttributeIsTranslatedToAuthorities() { - Jwt jwt = jwt().claim("roles", Arrays.asList("message:read", "message:write")) + Jwt jwt = TestJwts.jwt().claim("roles", Arrays.asList("message:read", "message:write")) .claim("scope", "missive:read missive:write").build(); JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); @@ -200,7 +201,8 @@ public class JwtGrantedAuthoritiesConverterTests { @Test public void convertWhenTokenHasEmptyCustomClaimNameThenCustomClaimNameAttributeIsTranslatedToNoAuthorities() { - Jwt jwt = jwt().claim("roles", Collections.emptyList()).claim("scope", "missive:read missive:write").build(); + Jwt jwt = TestJwts.jwt().claim("roles", Collections.emptyList()).claim("scope", "missive:read missive:write") + .build(); JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("roles"); @@ -211,7 +213,7 @@ public class JwtGrantedAuthoritiesConverterTests { @Test public void convertWhenTokenHasNoCustomClaimNameThenCustomClaimNameAttributeIsTranslatedToNoAuthorities() { - Jwt jwt = jwt().claim("scope", "missive:read missive:write").build(); + Jwt jwt = TestJwts.jwt().claim("scope", "missive:read missive:write").build(); JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("roles"); diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerAuthenticationManagerResolverTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerAuthenticationManagerResolverTests.java index 1cab4a21c5..041c0a4f5a 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerAuthenticationManagerResolverTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerAuthenticationManagerResolverTests.java @@ -38,11 +38,11 @@ import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManagerResolver; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.jose.TestKeys; +import org.springframework.security.oauth2.jwt.JwtClaimNames; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.mockito.Mockito.mock; -import static org.springframework.security.oauth2.jwt.JwtClaimNames.ISS; /** * Tests for {@link JwtIssuerAuthenticationManagerResolver} @@ -66,7 +66,7 @@ public class JwtIssuerAuthenticationManagerResolverTests { server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json") .setBody(String.format(DEFAULT_RESPONSE_TEMPLATE, issuer, issuer))); JWSObject jws = new JWSObject(new JWSHeader(JWSAlgorithm.RS256), - new Payload(new JSONObject(Collections.singletonMap(ISS, issuer)))); + new Payload(new JSONObject(Collections.singletonMap(JwtClaimNames.ISS, issuer)))); jws.sign(new RSASSASigner(TestKeys.DEFAULT_PRIVATE_KEY)); JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerAuthenticationManagerResolver( diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerReactiveAuthenticationManagerResolverTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerReactiveAuthenticationManagerResolverTests.java index 58e545ff03..1c3ffd4c09 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerReactiveAuthenticationManagerResolverTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerReactiveAuthenticationManagerResolverTests.java @@ -40,11 +40,11 @@ import org.springframework.security.authentication.ReactiveAuthenticationManager import org.springframework.security.authentication.ReactiveAuthenticationManagerResolver; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.jose.TestKeys; +import org.springframework.security.oauth2.jwt.JwtClaimNames; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.mockito.Mockito.mock; -import static org.springframework.security.oauth2.jwt.JwtClaimNames.ISS; /** * Tests for {@link JwtIssuerReactiveAuthenticationManagerResolver} @@ -67,7 +67,7 @@ public class JwtIssuerReactiveAuthenticationManagerResolverTests { server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json") .setBody(String.format(DEFAULT_RESPONSE_TEMPLATE, issuer, issuer))); JWSObject jws = new JWSObject(new JWSHeader(JWSAlgorithm.RS256), - new Payload(new JSONObject(Collections.singletonMap(ISS, issuer)))); + new Payload(new JSONObject(Collections.singletonMap(JwtClaimNames.ISS, issuer)))); jws.sign(new RSASSASigner(TestKeys.DEFAULT_PRIVATE_KEY)); JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver( diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtReactiveAuthenticationManagerTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtReactiveAuthenticationManagerTests.java index 1289ad57b8..e0e34f1cc3 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtReactiveAuthenticationManagerTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtReactiveAuthenticationManagerTests.java @@ -32,13 +32,13 @@ import org.springframework.security.oauth2.jwt.BadJwtException; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.JwtException; import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder; +import org.springframework.security.oauth2.jwt.TestJwts; import org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; -import static org.springframework.security.oauth2.jwt.TestJwts.jwt; /** * @author Rob Winch @@ -57,7 +57,7 @@ public class JwtReactiveAuthenticationManagerTests { @Before public void setup() { this.manager = new JwtReactiveAuthenticationManager(this.jwtDecoder); - this.jwt = jwt().claim("scope", "message:read message:write").build(); + this.jwt = TestJwts.jwt().claim("scope", "message:read message:write").build(); } @Test diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenAuthenticationProviderTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenAuthenticationProviderTests.java index 1f27b57b5e..3d69c5c690 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenAuthenticationProviderTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenAuthenticationProviderTests.java @@ -26,6 +26,7 @@ import org.junit.Test; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; +import org.springframework.security.oauth2.core.TestOAuth2AuthenticatedPrincipals; import org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken; import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionAuthenticatedPrincipal; import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames; @@ -37,15 +38,6 @@ import static org.assertj.core.api.Assertions.assertThatCode; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.springframework.security.oauth2.core.TestOAuth2AuthenticatedPrincipals.active; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.ACTIVE; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.AUDIENCE; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.EXPIRES_AT; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.ISSUER; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.NOT_BEFORE; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.SCOPE; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.SUBJECT; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.USERNAME; /** * Tests for {@link OpaqueTokenAuthenticationProvider} @@ -56,8 +48,8 @@ public class OpaqueTokenAuthenticationProviderTests { @Test public void authenticateWhenActiveTokenThenOk() throws Exception { - OAuth2AuthenticatedPrincipal principal = active( - attributes -> attributes.put("extension_field", "twenty-seven")); + OAuth2AuthenticatedPrincipal principal = TestOAuth2AuthenticatedPrincipals + .active(attributes -> attributes.put("extension_field", "twenty-seven")); OpaqueTokenIntrospector introspector = mock(OpaqueTokenIntrospector.class); given(introspector.introspect(any())).willReturn(principal); OpaqueTokenAuthenticationProvider provider = new OpaqueTokenAuthenticationProvider(introspector); @@ -67,14 +59,16 @@ public class OpaqueTokenAuthenticationProviderTests { assertThat(result.getPrincipal()).isInstanceOf(OAuth2IntrospectionAuthenticatedPrincipal.class); Map attributes = ((OAuth2AuthenticatedPrincipal) result.getPrincipal()).getAttributes(); - assertThat(attributes).isNotNull().containsEntry(ACTIVE, true) - .containsEntry(AUDIENCE, Arrays.asList("https://protected.example.net/resource")) + assertThat(attributes).isNotNull().containsEntry(OAuth2IntrospectionClaimNames.ACTIVE, true) + .containsEntry(OAuth2IntrospectionClaimNames.AUDIENCE, + Arrays.asList("https://protected.example.net/resource")) .containsEntry(OAuth2IntrospectionClaimNames.CLIENT_ID, "l238j323ds-23ij4") - .containsEntry(EXPIRES_AT, Instant.ofEpochSecond(1419356238)) - .containsEntry(ISSUER, new URL("https://server.example.com/")) - .containsEntry(NOT_BEFORE, Instant.ofEpochSecond(29348723984L)) - .containsEntry(SCOPE, Arrays.asList("read", "write", "dolphin")) - .containsEntry(SUBJECT, "Z5O3upPC88QrAjx00dis").containsEntry(USERNAME, "jdoe") + .containsEntry(OAuth2IntrospectionClaimNames.EXPIRES_AT, Instant.ofEpochSecond(1419356238)) + .containsEntry(OAuth2IntrospectionClaimNames.ISSUER, new URL("https://server.example.com/")) + .containsEntry(OAuth2IntrospectionClaimNames.NOT_BEFORE, Instant.ofEpochSecond(29348723984L)) + .containsEntry(OAuth2IntrospectionClaimNames.SCOPE, Arrays.asList("read", "write", "dolphin")) + .containsEntry(OAuth2IntrospectionClaimNames.SUBJECT, "Z5O3upPC88QrAjx00dis") + .containsEntry(OAuth2IntrospectionClaimNames.USERNAME, "jdoe") .containsEntry("extension_field", "twenty-seven"); assertThat(result.getAuthorities()).extracting("authority").containsExactly("SCOPE_read", "SCOPE_write", @@ -93,7 +87,7 @@ public class OpaqueTokenAuthenticationProviderTests { assertThat(result.getPrincipal()).isInstanceOf(OAuth2AuthenticatedPrincipal.class); Map attributes = ((OAuth2AuthenticatedPrincipal) result.getPrincipal()).getAttributes(); - assertThat(attributes).isNotNull().doesNotContainKey(SCOPE); + assertThat(attributes).isNotNull().doesNotContainKey(OAuth2IntrospectionClaimNames.SCOPE); assertThat(result.getAuthorities()).isEmpty(); } diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenReactiveAuthenticationManagerTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenReactiveAuthenticationManagerTests.java index 8a498b3ec9..d71c354e38 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenReactiveAuthenticationManagerTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenReactiveAuthenticationManagerTests.java @@ -28,6 +28,7 @@ import reactor.core.publisher.Mono; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; +import org.springframework.security.oauth2.core.TestOAuth2AuthenticatedPrincipals; import org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken; import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionAuthenticatedPrincipal; import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames; @@ -39,15 +40,6 @@ import static org.assertj.core.api.Assertions.assertThatCode; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.springframework.security.oauth2.core.TestOAuth2AuthenticatedPrincipals.active; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.ACTIVE; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.AUDIENCE; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.EXPIRES_AT; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.ISSUER; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.NOT_BEFORE; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.SCOPE; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.SUBJECT; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.USERNAME; /** * Tests for {@link OpaqueTokenReactiveAuthenticationManager} @@ -58,8 +50,8 @@ public class OpaqueTokenReactiveAuthenticationManagerTests { @Test public void authenticateWhenActiveTokenThenOk() throws Exception { - OAuth2AuthenticatedPrincipal authority = active( - attributes -> attributes.put("extension_field", "twenty-seven")); + OAuth2AuthenticatedPrincipal authority = TestOAuth2AuthenticatedPrincipals + .active(attributes -> attributes.put("extension_field", "twenty-seven")); ReactiveOpaqueTokenIntrospector introspector = mock(ReactiveOpaqueTokenIntrospector.class); given(introspector.introspect(any())).willReturn(Mono.just(authority)); OpaqueTokenReactiveAuthenticationManager provider = new OpaqueTokenReactiveAuthenticationManager(introspector); @@ -69,14 +61,16 @@ public class OpaqueTokenReactiveAuthenticationManagerTests { assertThat(result.getPrincipal()).isInstanceOf(OAuth2IntrospectionAuthenticatedPrincipal.class); Map attributes = ((OAuth2AuthenticatedPrincipal) result.getPrincipal()).getAttributes(); - assertThat(attributes).isNotNull().containsEntry(ACTIVE, true) - .containsEntry(AUDIENCE, Arrays.asList("https://protected.example.net/resource")) + assertThat(attributes).isNotNull().containsEntry(OAuth2IntrospectionClaimNames.ACTIVE, true) + .containsEntry(OAuth2IntrospectionClaimNames.AUDIENCE, + Arrays.asList("https://protected.example.net/resource")) .containsEntry(OAuth2IntrospectionClaimNames.CLIENT_ID, "l238j323ds-23ij4") - .containsEntry(EXPIRES_AT, Instant.ofEpochSecond(1419356238)) - .containsEntry(ISSUER, new URL("https://server.example.com/")) - .containsEntry(NOT_BEFORE, Instant.ofEpochSecond(29348723984L)) - .containsEntry(SCOPE, Arrays.asList("read", "write", "dolphin")) - .containsEntry(SUBJECT, "Z5O3upPC88QrAjx00dis").containsEntry(USERNAME, "jdoe") + .containsEntry(OAuth2IntrospectionClaimNames.EXPIRES_AT, Instant.ofEpochSecond(1419356238)) + .containsEntry(OAuth2IntrospectionClaimNames.ISSUER, new URL("https://server.example.com/")) + .containsEntry(OAuth2IntrospectionClaimNames.NOT_BEFORE, Instant.ofEpochSecond(29348723984L)) + .containsEntry(OAuth2IntrospectionClaimNames.SCOPE, Arrays.asList("read", "write", "dolphin")) + .containsEntry(OAuth2IntrospectionClaimNames.SUBJECT, "Z5O3upPC88QrAjx00dis") + .containsEntry(OAuth2IntrospectionClaimNames.USERNAME, "jdoe") .containsEntry("extension_field", "twenty-seven"); assertThat(result.getAuthorities()).extracting("authority").containsExactly("SCOPE_read", "SCOPE_write", @@ -95,7 +89,7 @@ public class OpaqueTokenReactiveAuthenticationManagerTests { assertThat(result.getPrincipal()).isInstanceOf(OAuth2IntrospectionAuthenticatedPrincipal.class); Map attributes = ((OAuth2AuthenticatedPrincipal) result.getPrincipal()).getAttributes(); - assertThat(attributes).isNotNull().doesNotContainKey(SCOPE); + assertThat(attributes).isNotNull().doesNotContainKey(OAuth2IntrospectionClaimNames.SCOPE); assertThat(result.getAuthorities()).isEmpty(); } diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/ReactiveJwtAuthenticationConverterAdapterTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/ReactiveJwtAuthenticationConverterAdapterTests.java index d15161fd07..fdb39984ca 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/ReactiveJwtAuthenticationConverterAdapterTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/ReactiveJwtAuthenticationConverterAdapterTests.java @@ -26,9 +26,9 @@ import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.jwt.TestJwts; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.oauth2.jwt.TestJwts.jwt; /** * Tests for {@link ReactiveJwtAuthenticationConverterAdapter} @@ -44,7 +44,7 @@ public class ReactiveJwtAuthenticationConverterAdapterTests { @Test public void convertWhenTokenHasScopeAttributeThenTranslatedToAuthorities() { - Jwt jwt = jwt().claim("scope", "message:read message:write").build(); + Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build(); AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block(); Collection authorities = authentication.getAuthorities(); @@ -55,7 +55,7 @@ public class ReactiveJwtAuthenticationConverterAdapterTests { @Test public void convertWhenTokenHasEmptyScopeAttributeThenTranslatedToNoAuthorities() { - Jwt jwt = jwt().claim("scope", "").build(); + Jwt jwt = TestJwts.jwt().claim("scope", "").build(); AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block(); @@ -66,7 +66,7 @@ public class ReactiveJwtAuthenticationConverterAdapterTests { @Test public void convertWhenTokenHasScpAttributeThenTranslatedToAuthorities() { - Jwt jwt = jwt().claim("scp", Arrays.asList("message:read", "message:write")).build(); + Jwt jwt = TestJwts.jwt().claim("scp", Arrays.asList("message:read", "message:write")).build(); AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block(); @@ -78,7 +78,7 @@ public class ReactiveJwtAuthenticationConverterAdapterTests { @Test public void convertWhenTokenHasEmptyScpAttributeThenTranslatedToNoAuthorities() { - Jwt jwt = jwt().claim("scp", Arrays.asList()).build(); + Jwt jwt = TestJwts.jwt().claim("scp", Arrays.asList()).build(); AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block(); @@ -89,7 +89,7 @@ public class ReactiveJwtAuthenticationConverterAdapterTests { @Test public void convertWhenTokenHasBothScopeAndScpThenScopeAttributeIsTranslatedToAuthorities() { - Jwt jwt = jwt().claim("scp", Arrays.asList("message:read", "message:write")) + Jwt jwt = TestJwts.jwt().claim("scp", Arrays.asList("message:read", "message:write")) .claim("scope", "missive:read missive:write").build(); AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block(); @@ -102,7 +102,8 @@ public class ReactiveJwtAuthenticationConverterAdapterTests { @Test public void convertWhenTokenHasEmptyScopeAndNonEmptyScpThenScopeAttributeIsTranslatedToNoAuthorities() { - Jwt jwt = jwt().claim("scp", Arrays.asList("message:read", "message:write")).claim("scope", "").build(); + Jwt jwt = TestJwts.jwt().claim("scp", Arrays.asList("message:read", "message:write")).claim("scope", "") + .build(); AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block(); diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/ReactiveJwtAuthenticationConverterTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/ReactiveJwtAuthenticationConverterTests.java index 2eb01d4dfd..d80b9f7800 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/ReactiveJwtAuthenticationConverterTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/ReactiveJwtAuthenticationConverterTests.java @@ -26,10 +26,10 @@ import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.jwt.TestJwts; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.springframework.security.oauth2.jwt.TestJwts.jwt; /** * Tests for {@link ReactiveJwtAuthenticationConverter} @@ -43,7 +43,7 @@ public class ReactiveJwtAuthenticationConverterTests { @Test public void convertWhenDefaultGrantedAuthoritiesConverterSet() { - Jwt jwt = jwt().claim("scope", "message:read message:write").build(); + Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build(); AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block(); Collection authorities = authentication.getAuthorities(); @@ -61,7 +61,7 @@ public class ReactiveJwtAuthenticationConverterTests { @Test public void convertWithOverriddenGrantedAuthoritiesConverter() { - Jwt jwt = jwt().claim("scope", "message:read message:write").build(); + Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build(); Converter> grantedAuthoritiesConverter = token -> Flux .just(new SimpleGrantedAuthority("blah")); diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/ReactiveJwtGrantedAuthoritiesConverterAdapterTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/ReactiveJwtGrantedAuthoritiesConverterAdapterTests.java index 3966b0b4f0..66c550fcfd 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/ReactiveJwtGrantedAuthoritiesConverterAdapterTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/ReactiveJwtGrantedAuthoritiesConverterAdapterTests.java @@ -26,10 +26,10 @@ import org.springframework.core.convert.converter.Converter; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.jwt.TestJwts; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.springframework.security.oauth2.jwt.TestJwts.jwt; /** * Tests for {@link ReactiveJwtGrantedAuthoritiesConverterAdapter} @@ -41,7 +41,7 @@ public class ReactiveJwtGrantedAuthoritiesConverterAdapterTests { @Test public void convertWithGrantedAuthoritiesConverter() { - Jwt jwt = jwt().claim("scope", "message:read message:write").build(); + Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build(); Converter> grantedAuthoritiesConverter = token -> Arrays .asList(new SimpleGrantedAuthority("blah")); diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusOpaqueTokenIntrospectorTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusOpaqueTokenIntrospectorTests.java index 7539acf13d..8eaa70a584 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusOpaqueTokenIntrospectorTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusOpaqueTokenIntrospectorTests.java @@ -50,13 +50,6 @@ 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.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.AUDIENCE; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.EXPIRES_AT; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.ISSUER; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.NOT_BEFORE; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.SCOPE; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.SUBJECT; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.USERNAME; /** * Tests for {@link NimbusOpaqueTokenIntrospector} @@ -116,12 +109,14 @@ public class NimbusOpaqueTokenIntrospectorTests { OAuth2AuthenticatedPrincipal authority = introspectionClient.introspect("token"); assertThat(authority.getAttributes()).isNotNull().containsEntry(OAuth2IntrospectionClaimNames.ACTIVE, true) - .containsEntry(AUDIENCE, Arrays.asList("https://protected.example.net/resource")) + .containsEntry(OAuth2IntrospectionClaimNames.AUDIENCE, + Arrays.asList("https://protected.example.net/resource")) .containsEntry(OAuth2IntrospectionClaimNames.CLIENT_ID, "l238j323ds-23ij4") - .containsEntry(EXPIRES_AT, Instant.ofEpochSecond(1419356238)) - .containsEntry(ISSUER, new URL("https://server.example.com/")) - .containsEntry(SCOPE, Arrays.asList("read", "write", "dolphin")) - .containsEntry(SUBJECT, "Z5O3upPC88QrAjx00dis").containsEntry(USERNAME, "jdoe") + .containsEntry(OAuth2IntrospectionClaimNames.EXPIRES_AT, Instant.ofEpochSecond(1419356238)) + .containsEntry(OAuth2IntrospectionClaimNames.ISSUER, new URL("https://server.example.com/")) + .containsEntry(OAuth2IntrospectionClaimNames.SCOPE, Arrays.asList("read", "write", "dolphin")) + .containsEntry(OAuth2IntrospectionClaimNames.SUBJECT, "Z5O3upPC88QrAjx00dis") + .containsEntry(OAuth2IntrospectionClaimNames.USERNAME, "jdoe") .containsEntry("extension_field", "twenty-seven"); } } @@ -155,8 +150,8 @@ public class NimbusOpaqueTokenIntrospectorTests { public void introspectWhenActiveTokenThenParsesValuesInResponse() { Map introspectedValues = new HashMap<>(); introspectedValues.put(OAuth2IntrospectionClaimNames.ACTIVE, true); - introspectedValues.put(AUDIENCE, Arrays.asList("aud")); - introspectedValues.put(NOT_BEFORE, 29348723984L); + introspectedValues.put(OAuth2IntrospectionClaimNames.AUDIENCE, Arrays.asList("aud")); + introspectedValues.put(OAuth2IntrospectionClaimNames.NOT_BEFORE, 29348723984L); RestOperations restOperations = mock(RestOperations.class); OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, @@ -166,9 +161,10 @@ public class NimbusOpaqueTokenIntrospectorTests { OAuth2AuthenticatedPrincipal authority = introspectionClient.introspect("token"); assertThat(authority.getAttributes()).isNotNull().containsEntry(OAuth2IntrospectionClaimNames.ACTIVE, true) - .containsEntry(AUDIENCE, Arrays.asList("aud")) - .containsEntry(NOT_BEFORE, Instant.ofEpochSecond(29348723984L)) - .doesNotContainKey(OAuth2IntrospectionClaimNames.CLIENT_ID).doesNotContainKey(SCOPE); + .containsEntry(OAuth2IntrospectionClaimNames.AUDIENCE, Arrays.asList("aud")) + .containsEntry(OAuth2IntrospectionClaimNames.NOT_BEFORE, Instant.ofEpochSecond(29348723984L)) + .doesNotContainKey(OAuth2IntrospectionClaimNames.CLIENT_ID) + .doesNotContainKey(OAuth2IntrospectionClaimNames.SCOPE); } @Test diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusReactiveOpaqueTokenIntrospectorTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusReactiveOpaqueTokenIntrospectorTests.java index befa3bef92..69a96f5cba 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusReactiveOpaqueTokenIntrospectorTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusReactiveOpaqueTokenIntrospectorTests.java @@ -45,13 +45,6 @@ import static org.assertj.core.api.Assertions.assertThatCode; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.AUDIENCE; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.EXPIRES_AT; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.ISSUER; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.NOT_BEFORE; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.SCOPE; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.SUBJECT; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.USERNAME; /** * Tests for {@link NimbusReactiveOpaqueTokenIntrospector} @@ -94,12 +87,14 @@ public class NimbusReactiveOpaqueTokenIntrospectorTests { OAuth2AuthenticatedPrincipal authority = introspectionClient.introspect("token").block(); assertThat(authority.getAttributes()).isNotNull().containsEntry(OAuth2IntrospectionClaimNames.ACTIVE, true) - .containsEntry(AUDIENCE, Arrays.asList("https://protected.example.net/resource")) + .containsEntry(OAuth2IntrospectionClaimNames.AUDIENCE, + Arrays.asList("https://protected.example.net/resource")) .containsEntry(OAuth2IntrospectionClaimNames.CLIENT_ID, "l238j323ds-23ij4") - .containsEntry(EXPIRES_AT, Instant.ofEpochSecond(1419356238)) - .containsEntry(ISSUER, new URL("https://server.example.com/")) - .containsEntry(SCOPE, Arrays.asList("read", "write", "dolphin")) - .containsEntry(SUBJECT, "Z5O3upPC88QrAjx00dis").containsEntry(USERNAME, "jdoe") + .containsEntry(OAuth2IntrospectionClaimNames.EXPIRES_AT, Instant.ofEpochSecond(1419356238)) + .containsEntry(OAuth2IntrospectionClaimNames.ISSUER, new URL("https://server.example.com/")) + .containsEntry(OAuth2IntrospectionClaimNames.SCOPE, Arrays.asList("read", "write", "dolphin")) + .containsEntry(OAuth2IntrospectionClaimNames.SUBJECT, "Z5O3upPC88QrAjx00dis") + .containsEntry(OAuth2IntrospectionClaimNames.USERNAME, "jdoe") .containsEntry("extension_field", "twenty-seven"); } } @@ -133,8 +128,8 @@ public class NimbusReactiveOpaqueTokenIntrospectorTests { public void authenticateWhenActiveTokenThenParsesValuesInResponse() { Map introspectedValues = new HashMap<>(); introspectedValues.put(OAuth2IntrospectionClaimNames.ACTIVE, true); - introspectedValues.put(AUDIENCE, Arrays.asList("aud")); - introspectedValues.put(NOT_BEFORE, 29348723984L); + introspectedValues.put(OAuth2IntrospectionClaimNames.AUDIENCE, Arrays.asList("aud")); + introspectedValues.put(OAuth2IntrospectionClaimNames.NOT_BEFORE, 29348723984L); WebClient webClient = mockResponse(new JSONObject(introspectedValues).toJSONString()); NimbusReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector( @@ -142,9 +137,10 @@ public class NimbusReactiveOpaqueTokenIntrospectorTests { OAuth2AuthenticatedPrincipal authority = introspectionClient.introspect("token").block(); assertThat(authority.getAttributes()).isNotNull().containsEntry(OAuth2IntrospectionClaimNames.ACTIVE, true) - .containsEntry(AUDIENCE, Arrays.asList("aud")) - .containsEntry(NOT_BEFORE, Instant.ofEpochSecond(29348723984L)) - .doesNotContainKey(OAuth2IntrospectionClaimNames.CLIENT_ID).doesNotContainKey(SCOPE); + .containsEntry(OAuth2IntrospectionClaimNames.AUDIENCE, Arrays.asList("aud")) + .containsEntry(OAuth2IntrospectionClaimNames.NOT_BEFORE, Instant.ofEpochSecond(29348723984L)) + .doesNotContainKey(OAuth2IntrospectionClaimNames.CLIENT_ID) + .doesNotContainKey(OAuth2IntrospectionClaimNames.SCOPE); } @Test diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServerBearerExchangeFilterFunctionTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServerBearerExchangeFilterFunctionTests.java index 9d85454580..788598a31f 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServerBearerExchangeFilterFunctionTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServerBearerExchangeFilterFunctionTests.java @@ -25,6 +25,7 @@ import java.util.Map; import org.junit.Test; import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.ReactiveSecurityContextHolder; @@ -34,7 +35,6 @@ import org.springframework.security.oauth2.server.resource.web.MockExchangeFunct import org.springframework.web.reactive.function.client.ClientRequest; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.http.HttpMethod.GET; /** * Tests for {@link ServerBearerExchangeFilterFunction} @@ -60,7 +60,7 @@ public class ServerBearerExchangeFilterFunctionTests { @Test public void filterWhenUnauthenticatedThenAuthorizationHeaderNull() { - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build(); this.function.filter(request, this.exchange).block(); @@ -69,7 +69,7 @@ public class ServerBearerExchangeFilterFunctionTests { @Test public void filterWhenAuthenticatedThenAuthorizationHeaderNull() throws Exception { - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build(); this.function.filter(request, this.exchange) .subscriberContext(ReactiveSecurityContextHolder.withAuthentication(this.authentication)).block(); @@ -81,7 +81,7 @@ public class ServerBearerExchangeFilterFunctionTests { // gh-7353 @Test public void filterWhenAuthenticatedWithOtherTokenThenAuthorizationHeaderNull() throws Exception { - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build(); TestingAuthenticationToken token = new TestingAuthenticationToken("user", "pass"); this.function.filter(request, this.exchange) @@ -92,7 +92,7 @@ public class ServerBearerExchangeFilterFunctionTests { @Test public void filterWhenExistingAuthorizationThenSingleAuthorizationHeader() { - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) .header(HttpHeaders.AUTHORIZATION, "Existing").build(); this.function.filter(request, this.exchange) diff --git a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServletBearerExchangeFilterFunctionTests.java b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServletBearerExchangeFilterFunctionTests.java index 9868ebfc2c..645173d860 100644 --- a/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServletBearerExchangeFilterFunctionTests.java +++ b/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServletBearerExchangeFilterFunctionTests.java @@ -29,6 +29,7 @@ import org.mockito.junit.MockitoJUnitRunner; import reactor.util.context.Context; import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.core.OAuth2AccessToken; @@ -37,8 +38,6 @@ import org.springframework.security.oauth2.server.resource.web.MockExchangeFunct import org.springframework.web.reactive.function.client.ClientRequest; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.http.HttpMethod.GET; -import static org.springframework.security.oauth2.server.resource.web.reactive.function.client.ServletBearerExchangeFilterFunction.SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY; /** * Tests for {@link ServletBearerExchangeFilterFunction} @@ -65,7 +64,7 @@ public class ServletBearerExchangeFilterFunctionTests { @Test public void filterWhenUnauthenticatedThenAuthorizationHeaderNull() { - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build(); this.function.filter(request, this.exchange).block(); @@ -76,7 +75,7 @@ public class ServletBearerExchangeFilterFunctionTests { @Test public void filterWhenAuthenticatedWithOtherTokenThenAuthorizationHeaderNull() { TestingAuthenticationToken token = new TestingAuthenticationToken("user", "pass"); - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build(); this.function.filter(request, this.exchange).subscriberContext(context(token)).block(); @@ -85,7 +84,7 @@ public class ServletBearerExchangeFilterFunctionTests { @Test public void filterWhenAuthenticatedThenAuthorizationHeader() { - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")).build(); + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build(); this.function.filter(request, this.exchange).subscriberContext(context(this.authentication)).block(); @@ -95,7 +94,7 @@ public class ServletBearerExchangeFilterFunctionTests { @Test public void filterWhenExistingAuthorizationThenSingleAuthorizationHeader() { - ClientRequest request = ClientRequest.create(GET, URI.create("https://example.com")) + ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")) .header(HttpHeaders.AUTHORIZATION, "Existing").build(); this.function.filter(request, this.exchange).subscriberContext(context(this.authentication)).block(); @@ -107,7 +106,8 @@ public class ServletBearerExchangeFilterFunctionTests { private Context context(Authentication authentication) { Map, Object> contextAttributes = new HashMap<>(); contextAttributes.put(Authentication.class, authentication); - return Context.of(SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY, contextAttributes); + return Context.of(ServletBearerExchangeFilterFunction.SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY, + contextAttributes); } } diff --git a/rsocket/src/test/java/org/springframework/security/rsocket/authorization/AuthorizationPayloadInterceptorTests.java b/rsocket/src/test/java/org/springframework/security/rsocket/authorization/AuthorizationPayloadInterceptorTests.java index 36f98b2189..edaac04759 100644 --- a/rsocket/src/test/java/org/springframework/security/rsocket/authorization/AuthorizationPayloadInterceptorTests.java +++ b/rsocket/src/test/java/org/springframework/security/rsocket/authorization/AuthorizationPayloadInterceptorTests.java @@ -28,6 +28,8 @@ import reactor.util.context.Context; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.authentication.TestingAuthenticationToken; +import org.springframework.security.authorization.AuthenticatedReactiveAuthorizationManager; +import org.springframework.security.authorization.AuthorityReactiveAuthorizationManager; import org.springframework.security.authorization.ReactiveAuthorizationManager; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.rsocket.api.PayloadExchange; @@ -35,8 +37,6 @@ import org.springframework.security.rsocket.api.PayloadInterceptorChain; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; -import static org.springframework.security.authorization.AuthenticatedReactiveAuthorizationManager.authenticated; -import static org.springframework.security.authorization.AuthorityReactiveAuthorizationManager.hasRole; /** * @author Rob Winch @@ -61,7 +61,8 @@ public class AuthorizationPayloadInterceptorTests { public void interceptWhenAuthenticationEmptyAndSubscribedThenException() { given(this.chain.next(any())).willReturn(this.chainResult.mono()); - AuthorizationPayloadInterceptor interceptor = new AuthorizationPayloadInterceptor(authenticated()); + AuthorizationPayloadInterceptor interceptor = new AuthorizationPayloadInterceptor( + AuthenticatedReactiveAuthorizationManager.authenticated()); StepVerifier.create(interceptor.intercept(this.exchange, this.chain)) .then(() -> this.chainResult.assertWasNotSubscribed()) @@ -83,7 +84,8 @@ public class AuthorizationPayloadInterceptorTests { public void interceptWhenNotAuthorizedThenException() { given(this.chain.next(any())).willReturn(this.chainResult.mono()); - AuthorizationPayloadInterceptor interceptor = new AuthorizationPayloadInterceptor(hasRole("USER")); + AuthorizationPayloadInterceptor interceptor = new AuthorizationPayloadInterceptor( + AuthorityReactiveAuthorizationManager.hasRole("USER")); Context userContext = ReactiveSecurityContextHolder .withAuthentication(new TestingAuthenticationToken("user", "password")); @@ -97,7 +99,8 @@ public class AuthorizationPayloadInterceptorTests { public void interceptWhenAuthorizedThenContinues() { given(this.chain.next(any())).willReturn(this.chainResult.mono()); - AuthorizationPayloadInterceptor interceptor = new AuthorizationPayloadInterceptor(authenticated()); + AuthorizationPayloadInterceptor interceptor = new AuthorizationPayloadInterceptor( + AuthenticatedReactiveAuthorizationManager.authenticated()); Context userContext = ReactiveSecurityContextHolder .withAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER")); diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/core/OpenSamlInitializationService.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/core/OpenSamlInitializationService.java index 25cf7269f2..ba98b28ad8 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/core/OpenSamlInitializationService.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/core/OpenSamlInitializationService.java @@ -29,13 +29,10 @@ import org.apache.commons.logging.LogFactory; import org.opensaml.core.config.ConfigurationService; import org.opensaml.core.config.InitializationService; import org.opensaml.core.xml.config.XMLObjectProviderRegistry; +import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.springframework.security.saml2.Saml2Exception; -import static java.lang.Boolean.FALSE; -import static java.lang.Boolean.TRUE; -import static org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport.setParserPool; - /** * An initialization service for initializing OpenSAML. Each Spring Security * OpenSAML-based component invokes the {@link #initialize()} method at static @@ -130,12 +127,13 @@ public class OpenSamlInitializationService { parserPool.setMaxPoolSize(50); Map parserBuilderFeatures = new HashMap<>(); - parserBuilderFeatures.put("http://apache.org/xml/features/disallow-doctype-decl", TRUE); - parserBuilderFeatures.put(XMLConstants.FEATURE_SECURE_PROCESSING, TRUE); - parserBuilderFeatures.put("http://xml.org/sax/features/external-general-entities", FALSE); - parserBuilderFeatures.put("http://apache.org/xml/features/validation/schema/normalized-value", FALSE); - parserBuilderFeatures.put("http://xml.org/sax/features/external-parameter-entities", FALSE); - parserBuilderFeatures.put("http://apache.org/xml/features/dom/defer-node-expansion", FALSE); + parserBuilderFeatures.put("http://apache.org/xml/features/disallow-doctype-decl", Boolean.TRUE); + parserBuilderFeatures.put(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + parserBuilderFeatures.put("http://xml.org/sax/features/external-general-entities", Boolean.FALSE); + parserBuilderFeatures.put("http://apache.org/xml/features/validation/schema/normalized-value", + Boolean.FALSE); + parserBuilderFeatures.put("http://xml.org/sax/features/external-parameter-entities", Boolean.FALSE); + parserBuilderFeatures.put("http://apache.org/xml/features/dom/defer-node-expansion", Boolean.FALSE); parserPool.setBuilderFeatures(parserBuilderFeatures); try { @@ -144,7 +142,7 @@ public class OpenSamlInitializationService { catch (Exception e) { throw new Saml2Exception(e); } - setParserPool(parserPool); + XMLObjectProviderRegistrySupport.setParserPool(parserPool); registryConsumer.accept(ConfigurationService.get(XMLObjectProviderRegistry.class)); diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/core/Saml2X509Credential.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/core/Saml2X509Credential.java index eada82bdd5..d8031880f0 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/core/Saml2X509Credential.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/core/Saml2X509Credential.java @@ -17,17 +17,13 @@ package org.springframework.security.saml2.core; import java.security.PrivateKey; import java.security.cert.X509Certificate; +import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Objects; import java.util.Set; import org.springframework.util.Assert; -import static java.util.Arrays.asList; -import static org.springframework.util.Assert.notEmpty; -import static org.springframework.util.Assert.notNull; -import static org.springframework.util.Assert.state; - /** * An object for holding a public certificate, any associated private key, and its * intended (asList(types)); + this.credentialTypes = new LinkedHashSet<>(Arrays.asList(types)); } /** @@ -224,7 +220,7 @@ public final class Saml2X509Credential { break; } } - state(valid, () -> usage + " is not a valid usage for this credential"); + Assert.state(valid, () -> usage + " is not a valid usage for this credential"); } } diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/credentials/Saml2X509Credential.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/credentials/Saml2X509Credential.java index 03a5e5a3cc..9d07140b68 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/credentials/Saml2X509Credential.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/credentials/Saml2X509Credential.java @@ -17,17 +17,13 @@ package org.springframework.security.saml2.credentials; import java.security.PrivateKey; import java.security.cert.X509Certificate; +import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Objects; import java.util.Set; import org.springframework.util.Assert; -import static java.util.Arrays.asList; -import static org.springframework.util.Assert.notEmpty; -import static org.springframework.util.Assert.notNull; -import static org.springframework.util.Assert.state; - /** * Saml2X509Credential is meant to hold an X509 certificate, or an X509 certificate and a * private key. Per: @@ -98,14 +94,14 @@ public class Saml2X509Credential { private Saml2X509Credential(PrivateKey privateKey, boolean keyRequired, X509Certificate certificate, Saml2X509CredentialType... types) { - notNull(certificate, "certificate cannot be null"); - notEmpty(types, "credentials types cannot be empty"); + Assert.notNull(certificate, "certificate cannot be null"); + Assert.notEmpty(types, "credentials types cannot be empty"); if (keyRequired) { - notNull(privateKey, "privateKey cannot be null"); + Assert.notNull(privateKey, "privateKey cannot be null"); } this.privateKey = privateKey; this.certificate = certificate; - this.credentialTypes = new LinkedHashSet<>(asList(types)); + this.credentialTypes = new LinkedHashSet<>(Arrays.asList(types)); } /** @@ -198,7 +194,7 @@ public class Saml2X509Credential { break; } } - state(valid, () -> usage + " is not a valid usage for this credential"); + Assert.state(valid, () -> usage + " is not a valid usage for this credential"); } } diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationProvider.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationProvider.java index 842f58df26..6c5be4d1bb 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationProvider.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationProvider.java @@ -20,6 +20,7 @@ import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -58,6 +59,7 @@ import org.opensaml.saml.criterion.ProtocolCriterion; import org.opensaml.saml.metadata.criteria.role.impl.EvaluableProtocolRoleDescriptorCriterion; import org.opensaml.saml.saml2.assertion.ConditionValidator; import org.opensaml.saml.saml2.assertion.SAML20AssertionValidator; +import org.opensaml.saml.saml2.assertion.SAML2AssertionValidationParameters; import org.opensaml.saml.saml2.assertion.StatementValidator; import org.opensaml.saml.saml2.assertion.SubjectConfirmationValidator; import org.opensaml.saml.saml2.assertion.impl.AudienceRestrictionConditionValidator; @@ -107,28 +109,12 @@ import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMap import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.OpenSamlInitializationService; import org.springframework.security.saml2.core.Saml2Error; +import org.springframework.security.saml2.core.Saml2ErrorCodes; import org.springframework.security.saml2.core.Saml2X509Credential; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; -import static java.util.Arrays.asList; -import static java.util.Collections.singleton; -import static java.util.Collections.singletonList; -import static org.opensaml.saml.saml2.assertion.SAML2AssertionValidationParameters.CLOCK_SKEW; -import static org.opensaml.saml.saml2.assertion.SAML2AssertionValidationParameters.COND_VALID_AUDIENCES; -import static org.opensaml.saml.saml2.assertion.SAML2AssertionValidationParameters.SC_VALID_RECIPIENTS; -import static org.opensaml.saml.saml2.assertion.SAML2AssertionValidationParameters.SIGNATURE_REQUIRED; -import static org.springframework.security.saml2.core.Saml2ErrorCodes.DECRYPTION_ERROR; -import static org.springframework.security.saml2.core.Saml2ErrorCodes.INTERNAL_VALIDATION_ERROR; -import static org.springframework.security.saml2.core.Saml2ErrorCodes.INVALID_ASSERTION; -import static org.springframework.security.saml2.core.Saml2ErrorCodes.INVALID_DESTINATION; -import static org.springframework.security.saml2.core.Saml2ErrorCodes.INVALID_ISSUER; -import static org.springframework.security.saml2.core.Saml2ErrorCodes.INVALID_SIGNATURE; -import static org.springframework.security.saml2.core.Saml2ErrorCodes.MALFORMED_RESPONSE_DATA; -import static org.springframework.security.saml2.core.Saml2ErrorCodes.SUBJECT_NOT_FOUND; -import static org.springframework.util.Assert.notNull; - /** * Implementation of {@link AuthenticationProvider} for SAML authentications when * receiving a {@code Response} object containing an {@code Assertion}. This @@ -188,8 +174,8 @@ public final class OpenSamlAuthenticationProvider implements AuthenticationProvi private final ParserPool parserPool; - private Converter> authoritiesExtractor = (a -> singletonList( - new SimpleGrantedAuthority("ROLE_USER"))); + private Converter> authoritiesExtractor = (a -> Collections + .singletonList(new SimpleGrantedAuthority("ROLE_USER"))); private GrantedAuthoritiesMapper authoritiesMapper = (a -> a); @@ -268,7 +254,7 @@ public final class OpenSamlAuthenticationProvider implements AuthenticationProvi * user's authorities */ public void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) { - notNull(authoritiesMapper, "authoritiesMapper cannot be null"); + Assert.notNull(authoritiesMapper, "authoritiesMapper cannot be null"); this.authoritiesMapper = authoritiesMapper; } @@ -300,7 +286,7 @@ public final class OpenSamlAuthenticationProvider implements AuthenticationProvi throw e; } catch (Exception e) { - throw authException(INTERNAL_VALIDATION_ERROR, e.getMessage(), e); + throw authException(Saml2ErrorCodes.INTERNAL_VALIDATION_ERROR, e.getMessage(), e); } } @@ -324,7 +310,7 @@ public final class OpenSamlAuthenticationProvider implements AuthenticationProvi return (Response) this.responseUnmarshaller.unmarshall(element); } catch (Exception e) { - throw authException(MALFORMED_RESPONSE_DATA, e.getMessage(), e); + throw authException(Saml2ErrorCodes.MALFORMED_RESPONSE_DATA, e.getMessage(), e); } } @@ -340,15 +326,16 @@ public final class OpenSamlAuthenticationProvider implements AuthenticationProvi Decrypter decrypter = this.decrypterConverter.convert(token); List assertions = decryptAssertions(decrypter, response); if (!isSigned(responseSigned, assertions)) { - throw authException(INVALID_SIGNATURE, "Either the response or one of the assertions is unsigned. " - + "Please either sign the response or all of the assertions."); + throw authException(Saml2ErrorCodes.INVALID_SIGNATURE, + "Either the response or one of the assertions is unsigned. " + + "Please either sign the response or all of the assertions."); } validationExceptions.putAll(validateAssertions(token, response)); Assertion firstAssertion = CollectionUtils.firstElement(response.getAssertions()); NameID nameId = decryptPrincipal(decrypter, firstAssertion); if (nameId == null || nameId.getValue() == null) { - validationExceptions.put(SUBJECT_NOT_FOUND, authException(SUBJECT_NOT_FOUND, + validationExceptions.put(Saml2ErrorCodes.SUBJECT_NOT_FOUND, authException(Saml2ErrorCodes.SUBJECT_NOT_FOUND, "Assertion [" + firstAssertion.getID() + "] is missing a subject")); } @@ -385,8 +372,9 @@ public final class OpenSamlAuthenticationProvider implements AuthenticationProvi profileValidator.validate(response.getSignature()); } catch (Exception e) { - validationExceptions.put(INVALID_SIGNATURE, authException(INVALID_SIGNATURE, - "Invalid signature for SAML Response [" + response.getID() + "]: ", e)); + validationExceptions.put(Saml2ErrorCodes.INVALID_SIGNATURE, + authException(Saml2ErrorCodes.INVALID_SIGNATURE, + "Invalid signature for SAML Response [" + response.getID() + "]: ", e)); } try { @@ -396,13 +384,15 @@ public final class OpenSamlAuthenticationProvider implements AuthenticationProvi new EvaluableProtocolRoleDescriptorCriterion(new ProtocolCriterion(SAMLConstants.SAML20P_NS))); criteriaSet.add(new EvaluableUsageCredentialCriterion(new UsageCriterion(UsageType.SIGNING))); if (!this.signatureTrustEngineConverter.convert(token).validate(response.getSignature(), criteriaSet)) { - validationExceptions.put(INVALID_SIGNATURE, authException(INVALID_SIGNATURE, - "Invalid signature for SAML Response [" + response.getID() + "]")); + validationExceptions.put(Saml2ErrorCodes.INVALID_SIGNATURE, + authException(Saml2ErrorCodes.INVALID_SIGNATURE, + "Invalid signature for SAML Response [" + response.getID() + "]")); } } catch (Exception e) { - validationExceptions.put(INVALID_SIGNATURE, authException(INVALID_SIGNATURE, - "Invalid signature for SAML Response [" + response.getID() + "]: ", e)); + validationExceptions.put(Saml2ErrorCodes.INVALID_SIGNATURE, + authException(Saml2ErrorCodes.INVALID_SIGNATURE, + "Invalid signature for SAML Response [" + response.getID() + "]: ", e)); } } @@ -410,13 +400,15 @@ public final class OpenSamlAuthenticationProvider implements AuthenticationProvi String location = token.getRelyingPartyRegistration().getAssertionConsumerServiceLocation(); if (StringUtils.hasText(destination) && !destination.equals(location)) { String message = "Invalid destination [" + destination + "] for SAML response [" + response.getID() + "]"; - validationExceptions.put(INVALID_DESTINATION, authException(INVALID_DESTINATION, message)); + validationExceptions.put(Saml2ErrorCodes.INVALID_DESTINATION, + authException(Saml2ErrorCodes.INVALID_DESTINATION, message)); } String assertingPartyEntityId = token.getRelyingPartyRegistration().getAssertingPartyDetails().getEntityId(); if (!StringUtils.hasText(issuer) || !issuer.equals(assertingPartyEntityId)) { String message = String.format("Invalid issuer [%s] for SAML response [%s]", issuer, response.getID()); - validationExceptions.put(INVALID_ISSUER, authException(INVALID_ISSUER, message)); + validationExceptions.put(Saml2ErrorCodes.INVALID_ISSUER, + authException(Saml2ErrorCodes.INVALID_ISSUER, message)); } return validationExceptions; @@ -430,7 +422,7 @@ public final class OpenSamlAuthenticationProvider implements AuthenticationProvi assertions.add(assertion); } catch (DecryptionException e) { - throw authException(DECRYPTION_ERROR, e.getMessage(), e); + throw authException(Saml2ErrorCodes.DECRYPTION_ERROR, e.getMessage(), e); } } response.getAssertions().addAll(assertions); @@ -441,7 +433,7 @@ public final class OpenSamlAuthenticationProvider implements AuthenticationProvi Response response) { List assertions = response.getAssertions(); if (assertions.isEmpty()) { - throw authException(MALFORMED_RESPONSE_DATA, "No assertions found in response."); + throw authException(Saml2ErrorCodes.MALFORMED_RESPONSE_DATA, "No assertions found in response."); } Map validationExceptions = new LinkedHashMap<>(); @@ -461,13 +453,15 @@ public final class OpenSamlAuthenticationProvider implements AuthenticationProvi String message = String.format("Invalid assertion [%s] for SAML response [%s]: %s", assertion.getID(), ((Response) assertion.getParent()).getID(), context.getValidationFailureMessage()); - validationExceptions.put(INVALID_ASSERTION, authException(INVALID_ASSERTION, message)); + validationExceptions.put(Saml2ErrorCodes.INVALID_ASSERTION, + authException(Saml2ErrorCodes.INVALID_ASSERTION, message)); } } catch (Exception e) { String message = String.format("Invalid assertion [%s] for SAML response [%s]: %s", assertion.getID(), ((Response) assertion.getParent()).getID(), e.getMessage()); - validationExceptions.put(INVALID_ASSERTION, authException(INVALID_ASSERTION, message, e)); + validationExceptions.put(Saml2ErrorCodes.INVALID_ASSERTION, + authException(Saml2ErrorCodes.INVALID_ASSERTION, message, e)); } } @@ -501,7 +495,7 @@ public final class OpenSamlAuthenticationProvider implements AuthenticationProvi return nameId; } catch (DecryptionException e) { - throw authException(DECRYPTION_ERROR, e.getMessage(), e); + throw authException(Saml2ErrorCodes.DECRYPTION_ERROR, e.getMessage(), e); } } @@ -606,11 +600,15 @@ public final class OpenSamlAuthenticationProvider implements AuthenticationProvi String audience = tuple.authentication.getRelyingPartyRegistration().getEntityId(); String recipient = tuple.authentication.getRelyingPartyRegistration().getAssertionConsumerServiceLocation(); Map params = new HashMap<>(); - params.put(CLOCK_SKEW, OpenSamlAuthenticationProvider.this.responseTimeValidationSkew.toMillis()); - params.put(COND_VALID_AUDIENCES, singleton(audience)); - params.put(SC_VALID_RECIPIENTS, singleton(recipient)); - params.put(SIGNATURE_REQUIRED, false); // this verification is performed - // earlier + params.put(SAML2AssertionValidationParameters.CLOCK_SKEW, + OpenSamlAuthenticationProvider.this.responseTimeValidationSkew.toMillis()); + params.put(SAML2AssertionValidationParameters.COND_VALID_AUDIENCES, Collections.singleton(audience)); + params.put(SAML2AssertionValidationParameters.SC_VALID_RECIPIENTS, Collections.singleton(recipient)); + params.put(SAML2AssertionValidationParameters.SIGNATURE_REQUIRED, false); // this + // verification + // is + // performed + // earlier return new ValidationContext(params); } @@ -649,7 +647,7 @@ public final class OpenSamlAuthenticationProvider implements AuthenticationProvi private static class DecrypterConverter implements Converter { private final EncryptedKeyResolver encryptedKeyResolver = new ChainingEncryptedKeyResolver( - asList(new InlineEncryptedKeyResolver(), new EncryptedElementTypeEncryptedKeyResolver(), + Arrays.asList(new InlineEncryptedKeyResolver(), new EncryptedElementTypeEncryptedKeyResolver(), new SimpleRetrievalMethodEncryptedKeyResolver())); @Override diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationRequestFactory.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationRequestFactory.java index 9b23d8e37e..b92852e308 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationRequestFactory.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationRequestFactory.java @@ -59,13 +59,9 @@ import org.springframework.security.saml2.provider.service.authentication.Saml2R import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.util.Assert; +import org.springframework.util.StringUtils; import org.springframework.web.util.UriUtils; -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.springframework.security.saml2.provider.service.authentication.Saml2Utils.samlDeflate; -import static org.springframework.security.saml2.provider.service.authentication.Saml2Utils.samlEncode; -import static org.springframework.util.StringUtils.hasText; - /** * @since 5.2 */ @@ -130,7 +126,7 @@ public class OpenSamlAuthenticationRequestFactory implements Saml2Authentication ? serialize(sign(authnRequest, context.getRelyingPartyRegistration())) : serialize(authnRequest); return Saml2PostAuthenticationRequest.withAuthenticationRequestContext(context) - .samlRequest(samlEncode(xml.getBytes(UTF_8))).build(); + .samlRequest(Saml2Utils.samlEncode(xml.getBytes(StandardCharsets.UTF_8))).build(); } /** @@ -142,7 +138,7 @@ public class OpenSamlAuthenticationRequestFactory implements Saml2Authentication AuthnRequest authnRequest = createAuthnRequest(context); String xml = serialize(authnRequest); Builder result = Saml2RedirectAuthenticationRequest.withAuthenticationRequestContext(context); - String deflatedAndEncoded = samlEncode(samlDeflate(xml)); + String deflatedAndEncoded = Saml2Utils.samlEncode(Saml2Utils.samlDeflate(xml)); result.samlRequest(deflatedAndEncoded).relayState(context.getRelayState()); if (context.getRelyingPartyRegistration().getAssertingPartyDetails().getWantAuthnRequestsSigned()) { @@ -264,7 +260,7 @@ public class OpenSamlAuthenticationRequestFactory implements Saml2Authentication StringBuilder queryString = new StringBuilder(); queryString.append("SAMLRequest").append("=").append(UriUtils.encode(samlRequest, StandardCharsets.ISO_8859_1)) .append("&"); - if (hasText(relayState)) { + if (StringUtils.hasText(relayState)) { queryString.append("RelayState").append("=") .append(UriUtils.encode(relayState, StandardCharsets.ISO_8859_1)).append("&"); } @@ -277,7 +273,7 @@ public class OpenSamlAuthenticationRequestFactory implements Saml2Authentication Map result = new LinkedHashMap<>(); result.put("SAMLRequest", samlRequest); - if (hasText(relayState)) { + if (StringUtils.hasText(relayState)) { result.put("RelayState", relayState); } result.put("SigAlg", algorithmUri); diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2AuthenticationRequestFactory.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2AuthenticationRequestFactory.java index a57a113c0d..db2b13585b 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2AuthenticationRequestFactory.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2AuthenticationRequestFactory.java @@ -22,10 +22,6 @@ import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.Saml2X509Credential.Saml2X509CredentialType; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; -import static org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationRequest.withAuthenticationRequestContext; -import static org.springframework.security.saml2.provider.service.authentication.Saml2Utils.samlDeflate; -import static org.springframework.security.saml2.provider.service.authentication.Saml2Utils.samlEncode; - /** * Component that generates AuthenticationRequest, samlp:AuthnRequestType * XML, and accompanying signature data. as defined by @@ -81,9 +77,10 @@ public interface Saml2AuthenticationRequestFactory { default Saml2RedirectAuthenticationRequest createRedirectAuthenticationRequest( Saml2AuthenticationRequestContext context) { // backwards compatible with 5.2.x settings - Saml2AuthenticationRequest.Builder resultBuilder = withAuthenticationRequestContext(context); + Saml2AuthenticationRequest.Builder resultBuilder = Saml2AuthenticationRequest + .withAuthenticationRequestContext(context); String samlRequest = createAuthenticationRequest(resultBuilder.build()); - samlRequest = samlEncode(samlDeflate(samlRequest)); + samlRequest = Saml2Utils.samlEncode(Saml2Utils.samlDeflate(samlRequest)); return Saml2RedirectAuthenticationRequest.withAuthenticationRequestContext(context).samlRequest(samlRequest) .build(); } @@ -108,9 +105,10 @@ public interface Saml2AuthenticationRequestFactory { */ default Saml2PostAuthenticationRequest createPostAuthenticationRequest(Saml2AuthenticationRequestContext context) { // backwards compatible with 5.2.x settings - Saml2AuthenticationRequest.Builder resultBuilder = withAuthenticationRequestContext(context); + Saml2AuthenticationRequest.Builder resultBuilder = Saml2AuthenticationRequest + .withAuthenticationRequestContext(context); String samlRequest = createAuthenticationRequest(resultBuilder.build()); - samlRequest = samlEncode(samlRequest.getBytes(StandardCharsets.UTF_8)); + samlRequest = Saml2Utils.samlEncode(samlRequest.getBytes(StandardCharsets.UTF_8)); return Saml2PostAuthenticationRequest.withAuthenticationRequestContext(context).samlRequest(samlRequest) .build(); } diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2AuthenticationToken.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2AuthenticationToken.java index 22f042c328..8e32c57a7f 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2AuthenticationToken.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2AuthenticationToken.java @@ -24,8 +24,6 @@ import org.springframework.security.saml2.credentials.Saml2X509Credential; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.util.Assert; -import static org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration.withRegistrationId; - /** * Represents an incoming SAML 2.0 response containing an assertion that has not been * validated. {@link Saml2AuthenticationToken#isAuthenticated()} will always return false. @@ -78,8 +76,9 @@ public class Saml2AuthenticationToken extends AbstractAuthenticationToken { public Saml2AuthenticationToken(String saml2Response, String recipientUri, String idpEntityId, String localSpEntityId, List credentials) { super(null); - this.relyingPartyRegistration = withRegistrationId(idpEntityId).entityId(localSpEntityId) - .assertionConsumerServiceLocation(recipientUri).credentials(c -> c.addAll(credentials)) + this.relyingPartyRegistration = RelyingPartyRegistration.withRegistrationId(idpEntityId) + .entityId(localSpEntityId).assertionConsumerServiceLocation(recipientUri) + .credentials(c -> c.addAll(credentials)) .assertingPartyDetails( assertingParty -> assertingParty.entityId(idpEntityId).singleSignOnServiceLocation(idpEntityId)) .build(); diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2PostAuthenticationRequest.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2PostAuthenticationRequest.java index 99503faf40..bfaff2db48 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2PostAuthenticationRequest.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2PostAuthenticationRequest.java @@ -18,8 +18,6 @@ package org.springframework.security.saml2.provider.service.authentication; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; -import static org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding.POST; - /** * Data holder for information required to send an {@code AuthNRequest} over a POST * binding from the service provider to the identity provider @@ -40,7 +38,7 @@ public class Saml2PostAuthenticationRequest extends AbstractSaml2AuthenticationR */ @Override public Saml2MessageBinding getBinding() { - return POST; + return Saml2MessageBinding.POST; } /** diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2RedirectAuthenticationRequest.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2RedirectAuthenticationRequest.java index c9d2909156..b74518a459 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2RedirectAuthenticationRequest.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2RedirectAuthenticationRequest.java @@ -18,8 +18,6 @@ package org.springframework.security.saml2.provider.service.authentication; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; -import static org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding.REDIRECT; - /** * Data holder for information required to send an {@code AuthNRequest} over a REDIRECT * binding from the service provider to the identity provider @@ -63,7 +61,7 @@ public final class Saml2RedirectAuthenticationRequest extends AbstractSaml2Authe */ @Override public Saml2MessageBinding getBinding() { - return REDIRECT; + return Saml2MessageBinding.REDIRECT; } /** diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2Utils.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2Utils.java index 9bf270edeb..df0779d9ed 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2Utils.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/Saml2Utils.java @@ -18,6 +18,7 @@ package org.springframework.security.saml2.provider.service.authentication; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; import java.util.zip.Inflater; @@ -27,9 +28,6 @@ import org.apache.commons.codec.binary.Base64; import org.springframework.security.saml2.Saml2Exception; -import static java.nio.charset.StandardCharsets.UTF_8; -import static java.util.zip.Deflater.DEFLATED; - /** * @since 5.3 */ @@ -48,8 +46,8 @@ final class Saml2Utils { static byte[] samlDeflate(String s) { try { ByteArrayOutputStream b = new ByteArrayOutputStream(); - DeflaterOutputStream deflater = new DeflaterOutputStream(b, new Deflater(DEFLATED, true)); - deflater.write(s.getBytes(UTF_8)); + DeflaterOutputStream deflater = new DeflaterOutputStream(b, new Deflater(Deflater.DEFLATED, true)); + deflater.write(s.getBytes(StandardCharsets.UTF_8)); deflater.finish(); return b.toByteArray(); } @@ -64,7 +62,7 @@ final class Saml2Utils { InflaterOutputStream iout = new InflaterOutputStream(out, new Inflater(true)); iout.write(b); iout.finish(); - return new String(out.toByteArray(), UTF_8); + return new String(out.toByteArray(), StandardCharsets.UTF_8); } catch (IOException e) { throw new Saml2Exception("Unable to inflate string", e); diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/metadata/OpenSamlMetadataResolver.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/metadata/OpenSamlMetadataResolver.java index d30439d3ee..aa85c3bf82 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/metadata/OpenSamlMetadataResolver.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/metadata/OpenSamlMetadataResolver.java @@ -26,6 +26,7 @@ import javax.xml.namespace.QName; import net.shibboleth.utilities.java.support.xml.SerializeSupport; import org.opensaml.core.xml.XMLObjectBuilder; +import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.opensaml.saml.common.xml.SAMLConstants; import org.opensaml.saml.saml2.metadata.AssertionConsumerService; import org.opensaml.saml.saml2.metadata.EntityDescriptor; @@ -44,9 +45,6 @@ import org.springframework.security.saml2.core.Saml2X509Credential; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.util.Assert; -import static org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport.getBuilderFactory; -import static org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport.getMarshallerFactory; - /** * Resolves the SAML 2.0 Relying Party Metadata for a given * {@link RelyingPartyRegistration} using the OpenSAML API. @@ -64,8 +62,8 @@ public final class OpenSamlMetadataResolver implements Saml2MetadataResolver { private final EntityDescriptorMarshaller entityDescriptorMarshaller; public OpenSamlMetadataResolver() { - this.entityDescriptorMarshaller = (EntityDescriptorMarshaller) getMarshallerFactory() - .getMarshaller(EntityDescriptor.DEFAULT_ELEMENT_NAME); + this.entityDescriptorMarshaller = (EntityDescriptorMarshaller) XMLObjectProviderRegistrySupport + .getMarshallerFactory().getMarshaller(EntityDescriptor.DEFAULT_ELEMENT_NAME); Assert.notNull(this.entityDescriptorMarshaller, "entityDescriptorMarshaller cannot be null"); } @@ -135,7 +133,7 @@ public final class OpenSamlMetadataResolver implements Saml2MetadataResolver { @SuppressWarnings("unchecked") private T build(QName elementName) { - XMLObjectBuilder builder = getBuilderFactory().getBuilder(elementName); + XMLObjectBuilder builder = XMLObjectProviderRegistrySupport.getBuilderFactory().getBuilder(elementName); if (builder == null) { throw new Saml2Exception("Unable to resolve Builder for " + elementName); } diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/InMemoryRelyingPartyRegistrationRepository.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/InMemoryRelyingPartyRegistrationRepository.java index e8b199652a..495c86123b 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/InMemoryRelyingPartyRegistrationRepository.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/InMemoryRelyingPartyRegistrationRepository.java @@ -16,6 +16,7 @@ package org.springframework.security.saml2.provider.service.registration; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; @@ -24,10 +25,6 @@ import java.util.Map; import org.springframework.util.Assert; -import static java.util.Arrays.asList; -import static org.springframework.util.Assert.notEmpty; -import static org.springframework.util.Assert.notNull; - /** * @since 5.2 */ @@ -37,11 +34,11 @@ public class InMemoryRelyingPartyRegistrationRepository private final Map byRegistrationId; public InMemoryRelyingPartyRegistrationRepository(RelyingPartyRegistration... registrations) { - this(asList(registrations)); + this(Arrays.asList(registrations)); } public InMemoryRelyingPartyRegistrationRepository(Collection registrations) { - notEmpty(registrations, "registrations cannot be empty"); + Assert.notEmpty(registrations, "registrations cannot be empty"); this.byRegistrationId = createMappingToIdentityProvider(registrations); } @@ -49,9 +46,9 @@ public class InMemoryRelyingPartyRegistrationRepository Collection rps) { LinkedHashMap result = new LinkedHashMap<>(); for (RelyingPartyRegistration rp : rps) { - notNull(rp, "relying party collection cannot contain null values"); + Assert.notNull(rp, "relying party collection cannot contain null values"); String key = rp.getRegistrationId(); - notNull(rp, "relying party identifier cannot be null"); + Assert.notNull(rp, "relying party identifier cannot be null"); Assert.isNull(result.get(key), () -> "relying party duplicate identifier '" + key + "' detected."); result.put(key, rp); } diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverter.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverter.java index c62e7bbb50..c7919aec63 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverter.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverter.java @@ -27,6 +27,7 @@ import java.util.List; import net.shibboleth.utilities.java.support.xml.ParserPool; import org.opensaml.core.config.ConfigurationService; import org.opensaml.core.xml.config.XMLObjectProviderRegistry; +import org.opensaml.saml.common.xml.SAMLConstants; import org.opensaml.saml.saml2.metadata.EntityDescriptor; import org.opensaml.saml.saml2.metadata.IDPSSODescriptor; import org.opensaml.saml.saml2.metadata.KeyDescriptor; @@ -47,12 +48,6 @@ import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.OpenSamlInitializationService; import org.springframework.security.saml2.core.Saml2X509Credential; -import static java.lang.Boolean.TRUE; -import static org.opensaml.saml.common.xml.SAMLConstants.SAML20P_NS; -import static org.springframework.security.saml2.core.Saml2X509Credential.encryption; -import static org.springframework.security.saml2.core.Saml2X509Credential.verification; -import static org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration.withRegistrationId; - /** * An {@link HttpMessageConverter} that takes an {@code IDPSSODescriptor} in an HTTP * response and converts it into a {@link RelyingPartyRegistration.Builder}. @@ -133,7 +128,7 @@ public class OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverter HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { EntityDescriptor descriptor = entityDescriptor(inputMessage.getBody()); - IDPSSODescriptor idpssoDescriptor = descriptor.getIDPSSODescriptor(SAML20P_NS); + IDPSSODescriptor idpssoDescriptor = descriptor.getIDPSSODescriptor(SAMLConstants.SAML20P_NS); if (idpssoDescriptor == null) { throw new Saml2Exception("Metadata response is missing the necessary IDPSSODescriptor element"); } @@ -143,20 +138,20 @@ public class OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverter if (keyDescriptor.getUse().equals(UsageType.SIGNING)) { List certificates = certificates(keyDescriptor); for (X509Certificate certificate : certificates) { - verification.add(verification(certificate)); + verification.add(Saml2X509Credential.verification(certificate)); } } if (keyDescriptor.getUse().equals(UsageType.ENCRYPTION)) { List certificates = certificates(keyDescriptor); for (X509Certificate certificate : certificates) { - encryption.add(encryption(certificate)); + encryption.add(Saml2X509Credential.encryption(certificate)); } } if (keyDescriptor.getUse().equals(UsageType.UNSPECIFIED)) { List certificates = certificates(keyDescriptor); for (X509Certificate certificate : certificates) { - verification.add(verification(certificate)); - encryption.add(encryption(certificate)); + verification.add(Saml2X509Credential.verification(certificate)); + encryption.add(Saml2X509Credential.encryption(certificate)); } } } @@ -164,9 +159,9 @@ public class OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverter throw new Saml2Exception( "Metadata response is missing verification certificates, necessary for verifying SAML assertions"); } - RelyingPartyRegistration.Builder builder = withRegistrationId(descriptor.getEntityID()) + RelyingPartyRegistration.Builder builder = RelyingPartyRegistration.withRegistrationId(descriptor.getEntityID()) .assertingPartyDetails(party -> party.entityId(descriptor.getEntityID()) - .wantAuthnRequestsSigned(TRUE.equals(idpssoDescriptor.getWantAuthnRequestsSigned())) + .wantAuthnRequestsSigned(Boolean.TRUE.equals(idpssoDescriptor.getWantAuthnRequestsSigned())) .verificationX509Credentials(c -> c.addAll(verification)) .encryptionX509Credentials(c -> c.addAll(encryption))); for (SingleSignOnService singleSignOnService : idpssoDescriptor.getSingleSignOnServices()) { diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2ServletUtils.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2ServletUtils.java new file mode 100644 index 0000000000..5b58d68fec --- /dev/null +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2ServletUtils.java @@ -0,0 +1,74 @@ +/* + * Copyright 2002-2020 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.saml2.provider.service.servlet.filter; + +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; +import org.springframework.security.web.util.UrlUtils; +import org.springframework.util.StringUtils; +import org.springframework.web.util.UriComponents; +import org.springframework.web.util.UriComponentsBuilder; + +/** + * @since 5.3 + */ +final class Saml2ServletUtils { + + private static final char PATH_DELIMITER = '/'; + + static String resolveUrlTemplate(String template, String baseUrl, RelyingPartyRegistration relyingParty) { + if (!StringUtils.hasText(template)) { + return baseUrl; + } + + String entityId = relyingParty.getAssertingPartyDetails().getEntityId(); + String registrationId = relyingParty.getRegistrationId(); + Map uriVariables = new HashMap<>(); + UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(baseUrl).replaceQuery(null).fragment(null) + .build(); + String scheme = uriComponents.getScheme(); + uriVariables.put("baseScheme", scheme == null ? "" : scheme); + String host = uriComponents.getHost(); + uriVariables.put("baseHost", host == null ? "" : host); + // following logic is based on HierarchicalUriComponents#toUriString() + int port = uriComponents.getPort(); + uriVariables.put("basePort", port == -1 ? "" : ":" + port); + String path = uriComponents.getPath(); + if (StringUtils.hasLength(path)) { + if (path.charAt(0) != PATH_DELIMITER) { + path = PATH_DELIMITER + path; + } + } + uriVariables.put("basePath", path == null ? "" : path); + uriVariables.put("baseUrl", uriComponents.toUriString()); + uriVariables.put("entityId", StringUtils.hasText(entityId) ? entityId : ""); + uriVariables.put("registrationId", StringUtils.hasText(registrationId) ? registrationId : ""); + + return UriComponentsBuilder.fromUriString(template).buildAndExpand(uriVariables).toUriString(); + } + + static String getApplicationUri(HttpServletRequest request) { + UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request)) + .replacePath(request.getContextPath()).replaceQuery(null).fragment(null).build(); + return uriComponents.toUriString(); + } + +} diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationFilter.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationFilter.java index afea906f24..2c2f833c83 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationFilter.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationFilter.java @@ -22,6 +22,7 @@ import javax.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.saml2.core.Saml2Error; +import org.springframework.security.saml2.core.Saml2ErrorCodes; import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository; import org.springframework.security.saml2.provider.service.web.DefaultRelyingPartyRegistrationResolver; @@ -30,9 +31,7 @@ import org.springframework.security.web.authentication.AbstractAuthenticationPro import org.springframework.security.web.authentication.AuthenticationConverter; import org.springframework.security.web.authentication.session.ChangeSessionIdAuthenticationStrategy; import org.springframework.util.Assert; - -import static org.springframework.security.saml2.core.Saml2ErrorCodes.RELYING_PARTY_REGISTRATION_NOT_FOUND; -import static org.springframework.util.StringUtils.hasText; +import org.springframework.util.StringUtils; /** * @since 5.2 @@ -88,7 +87,8 @@ public class Saml2WebSsoAuthenticationFilter extends AbstractAuthenticationProce @Override protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) { - return (super.requiresAuthentication(request, response) && hasText(request.getParameter("SAMLResponse"))); + return (super.requiresAuthentication(request, response) + && StringUtils.hasText(request.getParameter("SAMLResponse"))); } @Override @@ -96,7 +96,7 @@ public class Saml2WebSsoAuthenticationFilter extends AbstractAuthenticationProce throws AuthenticationException { Authentication authentication = this.authenticationConverter.convert(request); if (authentication == null) { - Saml2Error saml2Error = new Saml2Error(RELYING_PARTY_REGISTRATION_NOT_FOUND, + Saml2Error saml2Error = new Saml2Error(Saml2ErrorCodes.RELYING_PARTY_REGISTRATION_NOT_FOUND, "No relying party registration found"); throw new Saml2AuthenticationException(saml2Error); } diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationRequestFilter.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationRequestFilter.java index 96e5d072a9..14b4e1396b 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationRequestFilter.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationRequestFilter.java @@ -17,6 +17,7 @@ package org.springframework.security.saml2.provider.service.servlet.filter; import java.io.IOException; +import java.nio.charset.StandardCharsets; import javax.servlet.FilterChain; import javax.servlet.ServletException; @@ -44,8 +45,6 @@ import org.springframework.web.util.HtmlUtils; import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.util.UriUtils; -import static java.nio.charset.StandardCharsets.ISO_8859_1; - /** * This {@code Filter} formulates a * SAML 2.0 @@ -176,7 +175,8 @@ public class Saml2WebSsoAuthenticationRequestFilter extends OncePerRequestFilter private void addParameter(String name, String value, UriComponentsBuilder builder) { Assert.hasText(name, "name cannot be empty or null"); if (StringUtils.hasText(value)) { - builder.queryParam(UriUtils.encode(name, ISO_8859_1), UriUtils.encode(value, ISO_8859_1)); + builder.queryParam(UriUtils.encode(name, StandardCharsets.ISO_8859_1), + UriUtils.encode(value, StandardCharsets.ISO_8859_1)); } } diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/DefaultRelyingPartyRegistrationResolver.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/DefaultRelyingPartyRegistrationResolver.java index e1b770f1cd..d5fa8df8b5 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/DefaultRelyingPartyRegistrationResolver.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/DefaultRelyingPartyRegistrationResolver.java @@ -25,6 +25,7 @@ import javax.servlet.http.HttpServletRequest; import org.springframework.core.convert.converter.Converter; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository; +import org.springframework.security.web.util.UrlUtils; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; @@ -32,10 +33,6 @@ import org.springframework.util.StringUtils; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; -import static org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration.withRelyingPartyRegistration; -import static org.springframework.security.web.util.UrlUtils.buildFullRequestUrl; -import static org.springframework.web.util.UriComponentsBuilder.fromHttpUrl; - /** * A {@link Converter} that resolves a {@link RelyingPartyRegistration} by extracting the * registration id from the request, querying a @@ -77,8 +74,9 @@ public final class DefaultRelyingPartyRegistrationResolver String relyingPartyEntityId = templateResolver.apply(relyingPartyRegistration.getEntityId()); String assertionConsumerServiceLocation = templateResolver .apply(relyingPartyRegistration.getAssertionConsumerServiceLocation()); - return withRelyingPartyRegistration(relyingPartyRegistration).entityId(relyingPartyEntityId) - .assertionConsumerServiceLocation(assertionConsumerServiceLocation).build(); + return RelyingPartyRegistration.withRelyingPartyRegistration(relyingPartyRegistration) + .entityId(relyingPartyEntityId).assertionConsumerServiceLocation(assertionConsumerServiceLocation) + .build(); } private Function templateResolver(String applicationUri, RelyingPartyRegistration relyingParty) { @@ -111,8 +109,8 @@ public final class DefaultRelyingPartyRegistrationResolver } private static String getApplicationUri(HttpServletRequest request) { - UriComponents uriComponents = fromHttpUrl(buildFullRequestUrl(request)).replacePath(request.getContextPath()) - .replaceQuery(null).fragment(null).build(); + UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request)) + .replacePath(request.getContextPath()).replaceQuery(null).fragment(null).build(); return uriComponents.toUriString(); } diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverter.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverter.java index 5e6e1d7816..5c13e0e61e 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverter.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverter.java @@ -18,6 +18,7 @@ package org.springframework.security.saml2.provider.service.web; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.zip.Inflater; import java.util.zip.InflaterOutputStream; @@ -33,8 +34,6 @@ import org.springframework.security.saml2.provider.service.registration.RelyingP import org.springframework.security.web.authentication.AuthenticationConverter; import org.springframework.util.Assert; -import static java.nio.charset.StandardCharsets.UTF_8; - /** * An {@link AuthenticationConverter} that generates a {@link Saml2AuthenticationToken} * appropriate for authenticated a SAML 2.0 Assertion against an @@ -84,7 +83,7 @@ public final class Saml2AuthenticationTokenConverter implements AuthenticationCo return samlInflate(b); } else { - return new String(b, UTF_8); + return new String(b, StandardCharsets.UTF_8); } } @@ -98,7 +97,7 @@ public final class Saml2AuthenticationTokenConverter implements AuthenticationCo InflaterOutputStream iout = new InflaterOutputStream(out, new Inflater(true)); iout.write(b); iout.finish(); - return new String(out.toByteArray(), UTF_8); + return new String(out.toByteArray(), StandardCharsets.UTF_8); } catch (IOException e) { throw new Saml2Exception("Unable to inflate string", e); diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/core/Saml2Utils.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/core/Saml2Utils.java index 7e0c1773ad..fd412e4183 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/core/Saml2Utils.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/core/Saml2Utils.java @@ -18,6 +18,7 @@ package org.springframework.security.saml2.core; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; import java.util.zip.Inflater; @@ -27,9 +28,6 @@ import org.apache.commons.codec.binary.Base64; import org.springframework.security.saml2.Saml2Exception; -import static java.nio.charset.StandardCharsets.UTF_8; -import static java.util.zip.Deflater.DEFLATED; - public final class Saml2Utils { private static Base64 BASE64 = new Base64(0, new byte[] { '\n' }); @@ -45,8 +43,8 @@ public final class Saml2Utils { public static byte[] samlDeflate(String s) { try { ByteArrayOutputStream b = new ByteArrayOutputStream(); - DeflaterOutputStream deflater = new DeflaterOutputStream(b, new Deflater(DEFLATED, true)); - deflater.write(s.getBytes(UTF_8)); + DeflaterOutputStream deflater = new DeflaterOutputStream(b, new Deflater(Deflater.DEFLATED, true)); + deflater.write(s.getBytes(StandardCharsets.UTF_8)); deflater.finish(); return b.toByteArray(); } @@ -61,7 +59,7 @@ public final class Saml2Utils { InflaterOutputStream iout = new InflaterOutputStream(out, new Inflater(true)); iout.write(b); iout.finish(); - return new String(out.toByteArray(), UTF_8); + return new String(out.toByteArray(), StandardCharsets.UTF_8); } catch (IOException e) { throw new Saml2Exception("Unable to inflate string", e); diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/core/Saml2X509CredentialTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/core/Saml2X509CredentialTests.java index feb48316bc..5f41ee0e08 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/core/Saml2X509CredentialTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/core/Saml2X509CredentialTests.java @@ -17,6 +17,7 @@ package org.springframework.security.saml2.core; import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; import java.security.PrivateKey; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; @@ -27,12 +28,7 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.springframework.security.converter.RsaKeyConverters; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.springframework.security.saml2.core.Saml2X509Credential.Saml2X509CredentialType.DECRYPTION; -import static org.springframework.security.saml2.core.Saml2X509Credential.Saml2X509CredentialType.ENCRYPTION; -import static org.springframework.security.saml2.core.Saml2X509Credential.Saml2X509CredentialType.SIGNING; -import static org.springframework.security.saml2.core.Saml2X509Credential.Saml2X509CredentialType.VERIFICATION; +import org.springframework.security.saml2.core.Saml2X509Credential.Saml2X509CredentialType; public class Saml2X509CredentialTests { @@ -60,7 +56,7 @@ public class Saml2X509CredentialTests { + "YX/sDTE2AdVBVGaMj1Cb51bPHnNC6Q5kXKQnj/YrLqRQND09Q7ParX0CQQC5NxZr\n" + "9jKqhHj8yQD6PlXTsY4Occ7DH6/IoDenfdEVD5qlet0zmd50HatN2Jiqm5ubN7CM\n" + "INrtuLp4YHbgk1mi\n" + "-----END PRIVATE KEY-----"; - this.key = RsaKeyConverters.pkcs8().convert(new ByteArrayInputStream(keyData.getBytes(UTF_8))); + this.key = RsaKeyConverters.pkcs8().convert(new ByteArrayInputStream(keyData.getBytes(StandardCharsets.UTF_8))); final CertificateFactory factory = CertificateFactory.getInstance("X.509"); String certificateData = "-----BEGIN CERTIFICATE-----\n" + "MIICgTCCAeoCCQCuVzyqFgMSyDANBgkqhkiG9w0BAQsFADCBhDELMAkGA1UEBhMC\n" @@ -78,23 +74,25 @@ public class Saml2X509CredentialTests { + "qK7UFgP1bRl5qksrYX5S0z2iGJh0GvonLUt3e20Ssfl5tTEDDnAEUMLfBkyaxEHD\n" + "RZ/nbTJ7VTeZOSyRoVn5XHhpuJ0B\n" + "-----END CERTIFICATE-----"; this.certificate = (X509Certificate) factory - .generateCertificate(new ByteArrayInputStream(certificateData.getBytes(UTF_8))); + .generateCertificate(new ByteArrayInputStream(certificateData.getBytes(StandardCharsets.UTF_8))); } @Test public void constructorWhenRelyingPartyWithCredentialsThenItSucceeds() { - new Saml2X509Credential(this.key, this.certificate, SIGNING); - new Saml2X509Credential(this.key, this.certificate, SIGNING, DECRYPTION); - new Saml2X509Credential(this.key, this.certificate, DECRYPTION); + new Saml2X509Credential(this.key, this.certificate, Saml2X509CredentialType.SIGNING); + new Saml2X509Credential(this.key, this.certificate, Saml2X509CredentialType.SIGNING, + Saml2X509CredentialType.DECRYPTION); + new Saml2X509Credential(this.key, this.certificate, Saml2X509CredentialType.DECRYPTION); Saml2X509Credential.signing(this.key, this.certificate); Saml2X509Credential.decryption(this.key, this.certificate); } @Test public void constructorWhenAssertingPartyWithCredentialsThenItSucceeds() { - new Saml2X509Credential(this.certificate, VERIFICATION); - new Saml2X509Credential(this.certificate, VERIFICATION, ENCRYPTION); - new Saml2X509Credential(this.certificate, ENCRYPTION); + new Saml2X509Credential(this.certificate, Saml2X509CredentialType.VERIFICATION); + new Saml2X509Credential(this.certificate, Saml2X509CredentialType.VERIFICATION, + Saml2X509CredentialType.ENCRYPTION); + new Saml2X509Credential(this.certificate, Saml2X509CredentialType.ENCRYPTION); Saml2X509Credential.verification(this.certificate); Saml2X509Credential.encryption(this.certificate); } @@ -102,49 +100,49 @@ public class Saml2X509CredentialTests { @Test public void constructorWhenRelyingPartyWithoutCredentialsThenItFails() { this.exception.expect(IllegalArgumentException.class); - new Saml2X509Credential(null, (X509Certificate) null, SIGNING); + new Saml2X509Credential(null, (X509Certificate) null, Saml2X509CredentialType.SIGNING); } @Test public void constructorWhenRelyingPartyWithoutPrivateKeyThenItFails() { this.exception.expect(IllegalArgumentException.class); - new Saml2X509Credential(null, this.certificate, SIGNING); + new Saml2X509Credential(null, this.certificate, Saml2X509CredentialType.SIGNING); } @Test public void constructorWhenRelyingPartyWithoutCertificateThenItFails() { this.exception.expect(IllegalArgumentException.class); - new Saml2X509Credential(this.key, null, SIGNING); + new Saml2X509Credential(this.key, null, Saml2X509CredentialType.SIGNING); } @Test public void constructorWhenAssertingPartyWithoutCertificateThenItFails() { this.exception.expect(IllegalArgumentException.class); - new Saml2X509Credential(null, SIGNING); + new Saml2X509Credential(null, Saml2X509CredentialType.SIGNING); } @Test public void constructorWhenRelyingPartyWithEncryptionUsageThenItFails() { this.exception.expect(IllegalStateException.class); - new Saml2X509Credential(this.key, this.certificate, ENCRYPTION); + new Saml2X509Credential(this.key, this.certificate, Saml2X509CredentialType.ENCRYPTION); } @Test public void constructorWhenRelyingPartyWithVerificationUsageThenItFails() { this.exception.expect(IllegalStateException.class); - new Saml2X509Credential(this.key, this.certificate, VERIFICATION); + new Saml2X509Credential(this.key, this.certificate, Saml2X509CredentialType.VERIFICATION); } @Test public void constructorWhenAssertingPartyWithSigningUsageThenItFails() { this.exception.expect(IllegalStateException.class); - new Saml2X509Credential(this.certificate, SIGNING); + new Saml2X509Credential(this.certificate, Saml2X509CredentialType.SIGNING); } @Test public void constructorWhenAssertingPartyWithDecryptionUsageThenItFails() { this.exception.expect(IllegalStateException.class); - new Saml2X509Credential(this.certificate, DECRYPTION); + new Saml2X509Credential(this.certificate, Saml2X509CredentialType.DECRYPTION); } @Test diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/core/TestSaml2X509Credentials.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/core/TestSaml2X509Credentials.java index 2df52901cd..b6b67df762 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/core/TestSaml2X509Credentials.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/core/TestSaml2X509Credentials.java @@ -17,6 +17,7 @@ package org.springframework.security.saml2.core; import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; import java.security.KeyException; import java.security.PrivateKey; import java.security.cert.CertificateException; @@ -26,37 +27,33 @@ import java.security.cert.X509Certificate; import org.opensaml.security.crypto.KeySupport; import org.springframework.security.saml2.Saml2Exception; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.springframework.security.saml2.core.Saml2X509Credential.Saml2X509CredentialType.DECRYPTION; -import static org.springframework.security.saml2.core.Saml2X509Credential.Saml2X509CredentialType.ENCRYPTION; -import static org.springframework.security.saml2.core.Saml2X509Credential.Saml2X509CredentialType.SIGNING; -import static org.springframework.security.saml2.core.Saml2X509Credential.Saml2X509CredentialType.VERIFICATION; +import org.springframework.security.saml2.core.Saml2X509Credential.Saml2X509CredentialType; public final class TestSaml2X509Credentials { public static Saml2X509Credential assertingPartySigningCredential() { - return new Saml2X509Credential(idpPrivateKey(), idpCertificate(), SIGNING); + return new Saml2X509Credential(idpPrivateKey(), idpCertificate(), Saml2X509CredentialType.SIGNING); } public static Saml2X509Credential assertingPartyEncryptingCredential() { - return new Saml2X509Credential(spCertificate(), ENCRYPTION); + return new Saml2X509Credential(spCertificate(), Saml2X509CredentialType.ENCRYPTION); } public static Saml2X509Credential assertingPartyPrivateCredential() { - return new Saml2X509Credential(idpPrivateKey(), idpCertificate(), SIGNING, DECRYPTION); + return new Saml2X509Credential(idpPrivateKey(), idpCertificate(), Saml2X509CredentialType.SIGNING, + Saml2X509CredentialType.DECRYPTION); } public static Saml2X509Credential relyingPartyVerifyingCredential() { - return new Saml2X509Credential(idpCertificate(), VERIFICATION); + return new Saml2X509Credential(idpCertificate(), Saml2X509CredentialType.VERIFICATION); } public static Saml2X509Credential relyingPartySigningCredential() { - return new Saml2X509Credential(spPrivateKey(), spCertificate(), SIGNING); + return new Saml2X509Credential(spPrivateKey(), spCertificate(), Saml2X509CredentialType.SIGNING); } public static Saml2X509Credential relyingPartyDecryptingCredential() { - return new Saml2X509Credential(spPrivateKey(), spCertificate(), DECRYPTION); + return new Saml2X509Credential(spPrivateKey(), spCertificate(), Saml2X509CredentialType.DECRYPTION); } private static X509Certificate certificate(String cert) { @@ -71,7 +68,7 @@ public final class TestSaml2X509Credentials { private static PrivateKey privateKey(String key) { try { - return KeySupport.decodePrivateKey(key.getBytes(UTF_8), new char[0]); + return KeySupport.decodePrivateKey(key.getBytes(StandardCharsets.UTF_8), new char[0]); } catch (KeyException e) { throw new Saml2Exception(e); diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/credentials/Saml2X509CredentialTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/credentials/Saml2X509CredentialTests.java index 7742ae3f40..dd9d9ba715 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/credentials/Saml2X509CredentialTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/credentials/Saml2X509CredentialTests.java @@ -17,6 +17,7 @@ package org.springframework.security.saml2.credentials; import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; import java.security.PrivateKey; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; @@ -27,12 +28,7 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.springframework.security.converter.RsaKeyConverters; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.springframework.security.saml2.credentials.Saml2X509Credential.Saml2X509CredentialType.DECRYPTION; -import static org.springframework.security.saml2.credentials.Saml2X509Credential.Saml2X509CredentialType.ENCRYPTION; -import static org.springframework.security.saml2.credentials.Saml2X509Credential.Saml2X509CredentialType.SIGNING; -import static org.springframework.security.saml2.credentials.Saml2X509Credential.Saml2X509CredentialType.VERIFICATION; +import org.springframework.security.saml2.credentials.Saml2X509Credential.Saml2X509CredentialType; public class Saml2X509CredentialTests { @@ -62,7 +58,7 @@ public class Saml2X509CredentialTests { + "YX/sDTE2AdVBVGaMj1Cb51bPHnNC6Q5kXKQnj/YrLqRQND09Q7ParX0CQQC5NxZr\n" + "9jKqhHj8yQD6PlXTsY4Occ7DH6/IoDenfdEVD5qlet0zmd50HatN2Jiqm5ubN7CM\n" + "INrtuLp4YHbgk1mi\n" + "-----END PRIVATE KEY-----"; - this.key = RsaKeyConverters.pkcs8().convert(new ByteArrayInputStream(keyData.getBytes(UTF_8))); + this.key = RsaKeyConverters.pkcs8().convert(new ByteArrayInputStream(keyData.getBytes(StandardCharsets.UTF_8))); final CertificateFactory factory = CertificateFactory.getInstance("X.509"); String certificateData = "-----BEGIN CERTIFICATE-----\n" + "MIICgTCCAeoCCQCuVzyqFgMSyDANBgkqhkiG9w0BAQsFADCBhDELMAkGA1UEBhMC\n" @@ -80,69 +76,71 @@ public class Saml2X509CredentialTests { + "qK7UFgP1bRl5qksrYX5S0z2iGJh0GvonLUt3e20Ssfl5tTEDDnAEUMLfBkyaxEHD\n" + "RZ/nbTJ7VTeZOSyRoVn5XHhpuJ0B\n" + "-----END CERTIFICATE-----"; this.certificate = (X509Certificate) factory - .generateCertificate(new ByteArrayInputStream(certificateData.getBytes(UTF_8))); + .generateCertificate(new ByteArrayInputStream(certificateData.getBytes(StandardCharsets.UTF_8))); } @Test public void constructorWhenRelyingPartyWithCredentialsThenItSucceeds() { - new Saml2X509Credential(this.key, this.certificate, SIGNING); - new Saml2X509Credential(this.key, this.certificate, SIGNING, DECRYPTION); - new Saml2X509Credential(this.key, this.certificate, DECRYPTION); + new Saml2X509Credential(this.key, this.certificate, Saml2X509CredentialType.SIGNING); + new Saml2X509Credential(this.key, this.certificate, Saml2X509CredentialType.SIGNING, + Saml2X509CredentialType.DECRYPTION); + new Saml2X509Credential(this.key, this.certificate, Saml2X509CredentialType.DECRYPTION); } @Test public void constructorWhenAssertingPartyWithCredentialsThenItSucceeds() { - new Saml2X509Credential(this.certificate, VERIFICATION); - new Saml2X509Credential(this.certificate, VERIFICATION, ENCRYPTION); - new Saml2X509Credential(this.certificate, ENCRYPTION); + new Saml2X509Credential(this.certificate, Saml2X509CredentialType.VERIFICATION); + new Saml2X509Credential(this.certificate, Saml2X509CredentialType.VERIFICATION, + Saml2X509CredentialType.ENCRYPTION); + new Saml2X509Credential(this.certificate, Saml2X509CredentialType.ENCRYPTION); } @Test public void constructorWhenRelyingPartyWithoutCredentialsThenItFails() { this.exception.expect(IllegalArgumentException.class); - new Saml2X509Credential(null, (X509Certificate) null, SIGNING); + new Saml2X509Credential(null, (X509Certificate) null, Saml2X509CredentialType.SIGNING); } @Test public void constructorWhenRelyingPartyWithoutPrivateKeyThenItFails() { this.exception.expect(IllegalArgumentException.class); - new Saml2X509Credential(null, this.certificate, SIGNING); + new Saml2X509Credential(null, this.certificate, Saml2X509CredentialType.SIGNING); } @Test public void constructorWhenRelyingPartyWithoutCertificateThenItFails() { this.exception.expect(IllegalArgumentException.class); - new Saml2X509Credential(this.key, null, SIGNING); + new Saml2X509Credential(this.key, null, Saml2X509CredentialType.SIGNING); } @Test public void constructorWhenAssertingPartyWithoutCertificateThenItFails() { this.exception.expect(IllegalArgumentException.class); - new Saml2X509Credential(null, SIGNING); + new Saml2X509Credential(null, Saml2X509CredentialType.SIGNING); } @Test public void constructorWhenRelyingPartyWithEncryptionUsageThenItFails() { this.exception.expect(IllegalStateException.class); - new Saml2X509Credential(this.key, this.certificate, ENCRYPTION); + new Saml2X509Credential(this.key, this.certificate, Saml2X509CredentialType.ENCRYPTION); } @Test public void constructorWhenRelyingPartyWithVerificationUsageThenItFails() { this.exception.expect(IllegalStateException.class); - new Saml2X509Credential(this.key, this.certificate, VERIFICATION); + new Saml2X509Credential(this.key, this.certificate, Saml2X509CredentialType.VERIFICATION); } @Test public void constructorWhenAssertingPartyWithSigningUsageThenItFails() { this.exception.expect(IllegalStateException.class); - new Saml2X509Credential(this.certificate, SIGNING); + new Saml2X509Credential(this.certificate, Saml2X509CredentialType.SIGNING); } @Test public void constructorWhenAssertingPartyWithDecryptionUsageThenItFails() { this.exception.expect(IllegalStateException.class); - new Saml2X509Credential(this.certificate, DECRYPTION); + new Saml2X509Credential(this.certificate, Saml2X509CredentialType.DECRYPTION); } } diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/credentials/TestSaml2X509Credentials.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/credentials/TestSaml2X509Credentials.java index 90fdd0fae5..5f57547185 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/credentials/TestSaml2X509Credentials.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/credentials/TestSaml2X509Credentials.java @@ -17,6 +17,7 @@ package org.springframework.security.saml2.credentials; import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; import java.security.KeyException; import java.security.PrivateKey; import java.security.cert.CertificateException; @@ -26,37 +27,33 @@ import java.security.cert.X509Certificate; import org.opensaml.security.crypto.KeySupport; import org.springframework.security.saml2.Saml2Exception; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.springframework.security.saml2.credentials.Saml2X509Credential.Saml2X509CredentialType.DECRYPTION; -import static org.springframework.security.saml2.credentials.Saml2X509Credential.Saml2X509CredentialType.ENCRYPTION; -import static org.springframework.security.saml2.credentials.Saml2X509Credential.Saml2X509CredentialType.SIGNING; -import static org.springframework.security.saml2.credentials.Saml2X509Credential.Saml2X509CredentialType.VERIFICATION; +import org.springframework.security.saml2.credentials.Saml2X509Credential.Saml2X509CredentialType; public final class TestSaml2X509Credentials { public static Saml2X509Credential assertingPartySigningCredential() { - return new Saml2X509Credential(idpPrivateKey(), idpCertificate(), SIGNING); + return new Saml2X509Credential(idpPrivateKey(), idpCertificate(), Saml2X509CredentialType.SIGNING); } public static Saml2X509Credential assertingPartyEncryptingCredential() { - return new Saml2X509Credential(spCertificate(), ENCRYPTION); + return new Saml2X509Credential(spCertificate(), Saml2X509CredentialType.ENCRYPTION); } public static Saml2X509Credential assertingPartyPrivateCredential() { - return new Saml2X509Credential(idpPrivateKey(), idpCertificate(), SIGNING, DECRYPTION); + return new Saml2X509Credential(idpPrivateKey(), idpCertificate(), Saml2X509CredentialType.SIGNING, + Saml2X509CredentialType.DECRYPTION); } public static Saml2X509Credential relyingPartyVerifyingCredential() { - return new Saml2X509Credential(idpCertificate(), VERIFICATION); + return new Saml2X509Credential(idpCertificate(), Saml2X509CredentialType.VERIFICATION); } public static Saml2X509Credential relyingPartySigningCredential() { - return new Saml2X509Credential(spPrivateKey(), spCertificate(), SIGNING); + return new Saml2X509Credential(spPrivateKey(), spCertificate(), Saml2X509CredentialType.SIGNING); } public static Saml2X509Credential relyingPartyDecryptingCredential() { - return new Saml2X509Credential(spPrivateKey(), spCertificate(), DECRYPTION); + return new Saml2X509Credential(spPrivateKey(), spCertificate(), Saml2X509CredentialType.DECRYPTION); } private static X509Certificate certificate(String cert) { @@ -71,7 +68,7 @@ public final class TestSaml2X509Credentials { private static PrivateKey privateKey(String key) { try { - return KeySupport.decodePrivateKey(key.getBytes(UTF_8), new char[0]); + return KeySupport.decodePrivateKey(key.getBytes(StandardCharsets.UTF_8), new char[0]); } catch (KeyException e) { throw new Saml2Exception(e); diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationProviderTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationProviderTests.java index b6081da1c3..04adbb8968 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationProviderTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationProviderTests.java @@ -47,6 +47,7 @@ import org.opensaml.core.xml.io.Marshaller; import org.opensaml.core.xml.io.MarshallingException; import org.opensaml.saml.common.assertion.ValidationContext; import org.opensaml.saml.common.assertion.ValidationResult; +import org.opensaml.saml.saml2.assertion.SAML2AssertionValidationParameters; import org.opensaml.saml.saml2.assertion.impl.OneTimeUseConditionValidator; import org.opensaml.saml.saml2.core.Assertion; import org.opensaml.saml.saml2.core.AttributeStatement; @@ -64,8 +65,9 @@ import org.xml.sax.InputSource; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.credentials.Saml2X509Credential; +import org.springframework.security.saml2.credentials.TestSaml2X509Credentials; +import org.springframework.util.StringUtils; -import static java.util.Collections.singleton; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.mockito.ArgumentMatchers.any; @@ -73,21 +75,6 @@ import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -import static org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport.getBuilderFactory; -import static org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport.getMarshallerFactory; -import static org.opensaml.saml.saml2.assertion.SAML2AssertionValidationParameters.SC_VALID_RECIPIENTS; -import static org.opensaml.saml.saml2.assertion.SAML2AssertionValidationParameters.SIGNATURE_REQUIRED; -import static org.springframework.security.saml2.credentials.TestSaml2X509Credentials.assertingPartyEncryptingCredential; -import static org.springframework.security.saml2.credentials.TestSaml2X509Credentials.assertingPartyPrivateCredential; -import static org.springframework.security.saml2.credentials.TestSaml2X509Credentials.assertingPartySigningCredential; -import static org.springframework.security.saml2.credentials.TestSaml2X509Credentials.relyingPartyDecryptingCredential; -import static org.springframework.security.saml2.credentials.TestSaml2X509Credentials.relyingPartyVerifyingCredential; -import static org.springframework.security.saml2.provider.service.authentication.TestOpenSamlObjects.assertion; -import static org.springframework.security.saml2.provider.service.authentication.TestOpenSamlObjects.attributeStatements; -import static org.springframework.security.saml2.provider.service.authentication.TestOpenSamlObjects.encrypted; -import static org.springframework.security.saml2.provider.service.authentication.TestOpenSamlObjects.response; -import static org.springframework.security.saml2.provider.service.authentication.TestOpenSamlObjects.signed; -import static org.springframework.util.StringUtils.hasText; /** * Tests for {@link OpenSamlAuthenticationProvider} @@ -128,16 +115,18 @@ public class OpenSamlAuthenticationProviderTests { public void authenticateWhenUnknownDataClassThenThrowAuthenticationException() { this.exception.expect(authenticationMatcher(Saml2ErrorCodes.MALFORMED_RESPONSE_DATA)); - Assertion assertion = (Assertion) getBuilderFactory().getBuilder(Assertion.DEFAULT_ELEMENT_NAME) - .buildObject(Assertion.DEFAULT_ELEMENT_NAME); - this.provider.authenticate(token(serialize(assertion), relyingPartyVerifyingCredential())); + Assertion assertion = (Assertion) XMLObjectProviderRegistrySupport.getBuilderFactory() + .getBuilder(Assertion.DEFAULT_ELEMENT_NAME).buildObject(Assertion.DEFAULT_ELEMENT_NAME); + this.provider + .authenticate(token(serialize(assertion), TestSaml2X509Credentials.relyingPartyVerifyingCredential())); } @Test public void authenticateWhenXmlErrorThenThrowAuthenticationException() { this.exception.expect(authenticationMatcher(Saml2ErrorCodes.MALFORMED_RESPONSE_DATA)); - Saml2AuthenticationToken token = token("invalid xml", relyingPartyVerifyingCredential()); + Saml2AuthenticationToken token = token("invalid xml", + TestSaml2X509Credentials.relyingPartyVerifyingCredential()); this.provider.authenticate(token); } @@ -145,10 +134,11 @@ public class OpenSamlAuthenticationProviderTests { public void authenticateWhenInvalidDestinationThenThrowAuthenticationException() { this.exception.expect(authenticationMatcher(Saml2ErrorCodes.INVALID_DESTINATION)); - Response response = response(DESTINATION + "invalid", ASSERTING_PARTY_ENTITY_ID); - response.getAssertions().add(assertion()); - signed(response, assertingPartySigningCredential(), RELYING_PARTY_ENTITY_ID); - Saml2AuthenticationToken token = token(response, relyingPartyVerifyingCredential()); + Response response = TestOpenSamlObjects.response(DESTINATION + "invalid", ASSERTING_PARTY_ENTITY_ID); + response.getAssertions().add(TestOpenSamlObjects.assertion()); + TestOpenSamlObjects.signed(response, TestSaml2X509Credentials.assertingPartySigningCredential(), + RELYING_PARTY_ENTITY_ID); + Saml2AuthenticationToken token = token(response, TestSaml2X509Credentials.relyingPartyVerifyingCredential()); this.provider.authenticate(token); } @@ -157,7 +147,8 @@ public class OpenSamlAuthenticationProviderTests { this.exception.expect( authenticationMatcher(Saml2ErrorCodes.MALFORMED_RESPONSE_DATA, "No assertions found in response.")); - Saml2AuthenticationToken token = token(response(), assertingPartySigningCredential()); + Saml2AuthenticationToken token = token(TestOpenSamlObjects.response(), + TestSaml2X509Credentials.assertingPartySigningCredential()); this.provider.authenticate(token); } @@ -165,9 +156,9 @@ public class OpenSamlAuthenticationProviderTests { public void authenticateWhenInvalidSignatureOnAssertionThenThrowAuthenticationException() { this.exception.expect(authenticationMatcher(Saml2ErrorCodes.INVALID_SIGNATURE)); - Response response = response(); - response.getAssertions().add(assertion()); - Saml2AuthenticationToken token = token(response, relyingPartyVerifyingCredential()); + Response response = TestOpenSamlObjects.response(); + response.getAssertions().add(TestOpenSamlObjects.assertion()); + Saml2AuthenticationToken token = token(response, TestSaml2X509Credentials.relyingPartyVerifyingCredential()); this.provider.authenticate(token); } @@ -175,13 +166,14 @@ public class OpenSamlAuthenticationProviderTests { public void authenticateWhenOpenSAMLValidationErrorThenThrowAuthenticationException() throws Exception { this.exception.expect(authenticationMatcher(Saml2ErrorCodes.INVALID_ASSERTION)); - Response response = response(); - Assertion assertion = assertion(); + Response response = TestOpenSamlObjects.response(); + Assertion assertion = TestOpenSamlObjects.assertion(); assertion.getSubject().getSubjectConfirmations().get(0).getSubjectConfirmationData() .setNotOnOrAfter(DateTime.now().minus(Duration.standardDays(3))); - signed(assertion, assertingPartySigningCredential(), RELYING_PARTY_ENTITY_ID); + TestOpenSamlObjects.signed(assertion, TestSaml2X509Credentials.assertingPartySigningCredential(), + RELYING_PARTY_ENTITY_ID); response.getAssertions().add(assertion); - Saml2AuthenticationToken token = token(response, relyingPartyVerifyingCredential()); + Saml2AuthenticationToken token = token(response, TestSaml2X509Credentials.relyingPartyVerifyingCredential()); this.provider.authenticate(token); } @@ -189,12 +181,13 @@ public class OpenSamlAuthenticationProviderTests { public void authenticateWhenMissingSubjectThenThrowAuthenticationException() { this.exception.expect(authenticationMatcher(Saml2ErrorCodes.SUBJECT_NOT_FOUND)); - Response response = response(); - Assertion assertion = assertion(); + Response response = TestOpenSamlObjects.response(); + Assertion assertion = TestOpenSamlObjects.assertion(); assertion.setSubject(null); - signed(assertion, assertingPartySigningCredential(), RELYING_PARTY_ENTITY_ID); + TestOpenSamlObjects.signed(assertion, TestSaml2X509Credentials.assertingPartySigningCredential(), + RELYING_PARTY_ENTITY_ID); response.getAssertions().add(assertion); - Saml2AuthenticationToken token = token(response, relyingPartyVerifyingCredential()); + Saml2AuthenticationToken token = token(response, TestSaml2X509Credentials.relyingPartyVerifyingCredential()); this.provider.authenticate(token); } @@ -202,36 +195,39 @@ public class OpenSamlAuthenticationProviderTests { public void authenticateWhenUsernameMissingThenThrowAuthenticationException() throws Exception { this.exception.expect(authenticationMatcher(Saml2ErrorCodes.SUBJECT_NOT_FOUND)); - Response response = response(); - Assertion assertion = assertion(); + Response response = TestOpenSamlObjects.response(); + Assertion assertion = TestOpenSamlObjects.assertion(); assertion.getSubject().getNameID().setValue(null); - signed(assertion, assertingPartySigningCredential(), RELYING_PARTY_ENTITY_ID); + TestOpenSamlObjects.signed(assertion, TestSaml2X509Credentials.assertingPartySigningCredential(), + RELYING_PARTY_ENTITY_ID); response.getAssertions().add(assertion); - Saml2AuthenticationToken token = token(response, relyingPartyVerifyingCredential()); + Saml2AuthenticationToken token = token(response, TestSaml2X509Credentials.relyingPartyVerifyingCredential()); this.provider.authenticate(token); } @Test public void authenticateWhenAssertionContainsValidationAddressThenItSucceeds() throws Exception { - Response response = response(); - Assertion assertion = assertion(); + Response response = TestOpenSamlObjects.response(); + Assertion assertion = TestOpenSamlObjects.assertion(); assertion.getSubject().getSubjectConfirmations() .forEach(sc -> sc.getSubjectConfirmationData().setAddress("10.10.10.10")); - signed(assertion, assertingPartySigningCredential(), RELYING_PARTY_ENTITY_ID); + TestOpenSamlObjects.signed(assertion, TestSaml2X509Credentials.assertingPartySigningCredential(), + RELYING_PARTY_ENTITY_ID); response.getAssertions().add(assertion); - Saml2AuthenticationToken token = token(response, relyingPartyVerifyingCredential()); + Saml2AuthenticationToken token = token(response, TestSaml2X509Credentials.relyingPartyVerifyingCredential()); this.provider.authenticate(token); } @Test public void authenticateWhenAssertionContainsAttributesThenItSucceeds() { - Response response = response(); - Assertion assertion = assertion(); - List attributes = attributeStatements(); + Response response = TestOpenSamlObjects.response(); + Assertion assertion = TestOpenSamlObjects.assertion(); + List attributes = TestOpenSamlObjects.attributeStatements(); assertion.getAttributeStatements().addAll(attributes); - signed(assertion, assertingPartySigningCredential(), RELYING_PARTY_ENTITY_ID); + TestOpenSamlObjects.signed(assertion, TestSaml2X509Credentials.assertingPartySigningCredential(), + RELYING_PARTY_ENTITY_ID); response.getAssertions().add(assertion); - Saml2AuthenticationToken token = token(response, relyingPartyVerifyingCredential()); + Saml2AuthenticationToken token = token(response, TestSaml2X509Credentials.relyingPartyVerifyingCredential()); Authentication authentication = this.provider.authenticate(token); Saml2AuthenticatedPrincipal principal = (Saml2AuthenticatedPrincipal) authentication.getPrincipal(); @@ -250,13 +246,14 @@ public class OpenSamlAuthenticationProviderTests { @Test public void authenticateWhenAttributeValueMarshallerConfiguredThenUses() throws Exception { - Response response = response(); - Assertion assertion = assertion(); - List attributes = attributeStatements(); + Response response = TestOpenSamlObjects.response(); + Assertion assertion = TestOpenSamlObjects.assertion(); + List attributes = TestOpenSamlObjects.attributeStatements(); assertion.getAttributeStatements().addAll(attributes); - signed(assertion, assertingPartySigningCredential(), RELYING_PARTY_ENTITY_ID); + TestOpenSamlObjects.signed(assertion, TestSaml2X509Credentials.assertingPartySigningCredential(), + RELYING_PARTY_ENTITY_ID); response.getAssertions().add(assertion); - Saml2AuthenticationToken token = token(response, relyingPartyVerifyingCredential()); + Saml2AuthenticationToken token = token(response, TestSaml2X509Credentials.relyingPartyVerifyingCredential()); Element attributeElement = element("value"); Marshaller marshaller = mock(Marshaller.class); @@ -278,47 +275,54 @@ public class OpenSamlAuthenticationProviderTests { public void authenticateWhenEncryptedAssertionWithoutSignatureThenItFails() throws Exception { this.exception.expect(authenticationMatcher(Saml2ErrorCodes.INVALID_SIGNATURE)); - Response response = response(); - EncryptedAssertion encryptedAssertion = encrypted(assertion(), assertingPartyEncryptingCredential()); + Response response = TestOpenSamlObjects.response(); + EncryptedAssertion encryptedAssertion = TestOpenSamlObjects.encrypted(TestOpenSamlObjects.assertion(), + TestSaml2X509Credentials.assertingPartyEncryptingCredential()); response.getEncryptedAssertions().add(encryptedAssertion); - Saml2AuthenticationToken token = token(response, relyingPartyDecryptingCredential()); + Saml2AuthenticationToken token = token(response, TestSaml2X509Credentials.relyingPartyDecryptingCredential()); this.provider.authenticate(token); } @Test public void authenticateWhenEncryptedAssertionWithSignatureThenItSucceeds() throws Exception { - Response response = response(); - Assertion assertion = signed(assertion(), assertingPartySigningCredential(), RELYING_PARTY_ENTITY_ID); - EncryptedAssertion encryptedAssertion = encrypted(assertion, assertingPartyEncryptingCredential()); + Response response = TestOpenSamlObjects.response(); + Assertion assertion = TestOpenSamlObjects.signed(TestOpenSamlObjects.assertion(), + TestSaml2X509Credentials.assertingPartySigningCredential(), RELYING_PARTY_ENTITY_ID); + EncryptedAssertion encryptedAssertion = TestOpenSamlObjects.encrypted(assertion, + TestSaml2X509Credentials.assertingPartyEncryptingCredential()); response.getEncryptedAssertions().add(encryptedAssertion); - Saml2AuthenticationToken token = token(response, relyingPartyVerifyingCredential(), - relyingPartyDecryptingCredential()); + Saml2AuthenticationToken token = token(response, TestSaml2X509Credentials.relyingPartyVerifyingCredential(), + TestSaml2X509Credentials.relyingPartyDecryptingCredential()); this.provider.authenticate(token); } @Test public void authenticateWhenEncryptedAssertionWithResponseSignatureThenItSucceeds() throws Exception { - Response response = response(); - EncryptedAssertion encryptedAssertion = encrypted(assertion(), assertingPartyEncryptingCredential()); + Response response = TestOpenSamlObjects.response(); + EncryptedAssertion encryptedAssertion = TestOpenSamlObjects.encrypted(TestOpenSamlObjects.assertion(), + TestSaml2X509Credentials.assertingPartyEncryptingCredential()); response.getEncryptedAssertions().add(encryptedAssertion); - signed(response, assertingPartySigningCredential(), RELYING_PARTY_ENTITY_ID); - Saml2AuthenticationToken token = token(response, relyingPartyVerifyingCredential(), - relyingPartyDecryptingCredential()); + TestOpenSamlObjects.signed(response, TestSaml2X509Credentials.assertingPartySigningCredential(), + RELYING_PARTY_ENTITY_ID); + Saml2AuthenticationToken token = token(response, TestSaml2X509Credentials.relyingPartyVerifyingCredential(), + TestSaml2X509Credentials.relyingPartyDecryptingCredential()); this.provider.authenticate(token); } @Test public void authenticateWhenEncryptedNameIdWithSignatureThenItSucceeds() throws Exception { - Response response = response(); - Assertion assertion = assertion(); + Response response = TestOpenSamlObjects.response(); + Assertion assertion = TestOpenSamlObjects.assertion(); NameID nameId = assertion.getSubject().getNameID(); - EncryptedID encryptedID = encrypted(nameId, assertingPartyEncryptingCredential()); + EncryptedID encryptedID = TestOpenSamlObjects.encrypted(nameId, + TestSaml2X509Credentials.assertingPartyEncryptingCredential()); assertion.getSubject().setNameID(null); assertion.getSubject().setEncryptedID(encryptedID); response.getAssertions().add(assertion); - signed(assertion, assertingPartySigningCredential(), RELYING_PARTY_ENTITY_ID); - Saml2AuthenticationToken token = token(response, relyingPartyVerifyingCredential(), - relyingPartyDecryptingCredential()); + TestOpenSamlObjects.signed(assertion, TestSaml2X509Credentials.assertingPartySigningCredential(), + RELYING_PARTY_ENTITY_ID); + Saml2AuthenticationToken token = token(response, TestSaml2X509Credentials.relyingPartyVerifyingCredential(), + TestSaml2X509Credentials.relyingPartyDecryptingCredential()); this.provider.authenticate(token); } @@ -327,10 +331,12 @@ public class OpenSamlAuthenticationProviderTests { this.exception .expect(authenticationMatcher(Saml2ErrorCodes.DECRYPTION_ERROR, "Failed to decrypt EncryptedData")); - Response response = response(); - EncryptedAssertion encryptedAssertion = encrypted(assertion(), assertingPartyEncryptingCredential()); + Response response = TestOpenSamlObjects.response(); + EncryptedAssertion encryptedAssertion = TestOpenSamlObjects.encrypted(TestOpenSamlObjects.assertion(), + TestSaml2X509Credentials.assertingPartyEncryptingCredential()); response.getEncryptedAssertions().add(encryptedAssertion); - Saml2AuthenticationToken token = token(serialize(response), relyingPartyVerifyingCredential()); + Saml2AuthenticationToken token = token(serialize(response), + TestSaml2X509Credentials.relyingPartyVerifyingCredential()); this.provider.authenticate(token); } @@ -339,21 +345,25 @@ public class OpenSamlAuthenticationProviderTests { this.exception .expect(authenticationMatcher(Saml2ErrorCodes.DECRYPTION_ERROR, "Failed to decrypt EncryptedData")); - Response response = response(); - EncryptedAssertion encryptedAssertion = encrypted(assertion(), assertingPartyEncryptingCredential()); + Response response = TestOpenSamlObjects.response(); + EncryptedAssertion encryptedAssertion = TestOpenSamlObjects.encrypted(TestOpenSamlObjects.assertion(), + TestSaml2X509Credentials.assertingPartyEncryptingCredential()); response.getEncryptedAssertions().add(encryptedAssertion); - Saml2AuthenticationToken token = token(serialize(response), assertingPartyPrivateCredential()); + Saml2AuthenticationToken token = token(serialize(response), + TestSaml2X509Credentials.assertingPartyPrivateCredential()); this.provider.authenticate(token); } @Test public void writeObjectWhenTypeIsSaml2AuthenticationThenNoException() throws IOException { - Response response = response(); - Assertion assertion = signed(assertion(), assertingPartySigningCredential(), RELYING_PARTY_ENTITY_ID); - EncryptedAssertion encryptedAssertion = encrypted(assertion, assertingPartyEncryptingCredential()); + Response response = TestOpenSamlObjects.response(); + Assertion assertion = TestOpenSamlObjects.signed(TestOpenSamlObjects.assertion(), + TestSaml2X509Credentials.assertingPartySigningCredential(), RELYING_PARTY_ENTITY_ID); + EncryptedAssertion encryptedAssertion = TestOpenSamlObjects.encrypted(assertion, + TestSaml2X509Credentials.assertingPartyEncryptingCredential()); response.getEncryptedAssertions().add(encryptedAssertion); - Saml2AuthenticationToken token = token(response, relyingPartyVerifyingCredential(), - relyingPartyDecryptingCredential()); + Saml2AuthenticationToken token = token(response, TestSaml2X509Credentials.relyingPartyVerifyingCredential(), + TestSaml2X509Credentials.relyingPartyDecryptingCredential()); Saml2Authentication authentication = (Saml2Authentication) this.provider.authenticate(token); // the following code will throw an exception if authentication isn't serializable @@ -368,13 +378,14 @@ public class OpenSamlAuthenticationProviderTests { OneTimeUseConditionValidator validator = mock(OneTimeUseConditionValidator.class); OpenSamlAuthenticationProvider provider = new OpenSamlAuthenticationProvider(); provider.setConditionValidators(Collections.singleton(validator)); - Response response = response(); - Assertion assertion = assertion(); + Response response = TestOpenSamlObjects.response(); + Assertion assertion = TestOpenSamlObjects.assertion(); OneTimeUse oneTimeUse = build(OneTimeUse.DEFAULT_ELEMENT_NAME); assertion.getConditions().getConditions().add(oneTimeUse); response.getAssertions().add(assertion); - signed(response, assertingPartySigningCredential(), ASSERTING_PARTY_ENTITY_ID); - Saml2AuthenticationToken token = token(response, relyingPartyVerifyingCredential()); + TestOpenSamlObjects.signed(response, TestSaml2X509Credentials.assertingPartySigningCredential(), + ASSERTING_PARTY_ENTITY_ID); + Saml2AuthenticationToken token = token(response, TestSaml2X509Credentials.relyingPartyVerifyingCredential()); given(validator.getServicedCondition()).willReturn(OneTimeUse.DEFAULT_ELEMENT_NAME); given(validator.validate(any(Condition.class), any(Assertion.class), any(ValidationContext.class))) .willReturn(ValidationResult.VALID); @@ -385,17 +396,18 @@ public class OpenSamlAuthenticationProviderTests { @Test public void authenticateWhenValidationContextCustomizedThenUsers() { Map parameters = new HashMap<>(); - parameters.put(SC_VALID_RECIPIENTS, singleton(DESTINATION)); - parameters.put(SIGNATURE_REQUIRED, false); + parameters.put(SAML2AssertionValidationParameters.SC_VALID_RECIPIENTS, Collections.singleton(DESTINATION)); + parameters.put(SAML2AssertionValidationParameters.SIGNATURE_REQUIRED, false); ValidationContext context = mock(ValidationContext.class); given(context.getStaticParameters()).willReturn(parameters); OpenSamlAuthenticationProvider provider = new OpenSamlAuthenticationProvider(); provider.setValidationContextConverter(tuple -> context); - Response response = response(); - Assertion assertion = assertion(); + Response response = TestOpenSamlObjects.response(); + Assertion assertion = TestOpenSamlObjects.assertion(); response.getAssertions().add(assertion); - signed(response, assertingPartySigningCredential(), ASSERTING_PARTY_ENTITY_ID); - Saml2AuthenticationToken token = token(response, relyingPartyVerifyingCredential()); + TestOpenSamlObjects.signed(response, TestSaml2X509Credentials.assertingPartySigningCredential(), + ASSERTING_PARTY_ENTITY_ID); + Saml2AuthenticationToken token = token(response, TestSaml2X509Credentials.relyingPartyVerifyingCredential()); provider.authenticate(token); verify(context, atLeastOnce()).getStaticParameters(); } @@ -415,12 +427,12 @@ public class OpenSamlAuthenticationProviderTests { } private T build(QName qName) { - return (T) getBuilderFactory().getBuilder(qName).buildObject(qName); + return (T) XMLObjectProviderRegistrySupport.getBuilderFactory().getBuilder(qName).buildObject(qName); } private String serialize(XMLObject object) { try { - Marshaller marshaller = getMarshallerFactory().getMarshaller(object); + Marshaller marshaller = XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(object); Element element = marshaller.marshall(object); return SerializeSupport.nodeToString(element); } @@ -444,7 +456,7 @@ public class OpenSamlAuthenticationProviderTests { if (!code.equals(ex.getError().getErrorCode())) { return false; } - if (hasText(description)) { + if (StringUtils.hasText(description)) { if (!description.equals(ex.getError().getDescription())) { return false; } diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationRequestFactoryTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationRequestFactoryTests.java index 1ec40b8fd2..d8715a4f5c 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationRequestFactoryTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlAuthenticationRequestFactoryTests.java @@ -17,6 +17,7 @@ package org.springframework.security.saml2.provider.service.authentication; import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; import java.util.function.Consumer; import java.util.function.Function; @@ -25,6 +26,7 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.opensaml.saml.common.xml.SAMLConstants; import org.opensaml.saml.saml2.core.AuthnRequest; import org.opensaml.saml.saml2.core.impl.AuthnRequestUnmarshaller; @@ -32,24 +34,16 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.springframework.security.saml2.Saml2Exception; +import org.springframework.security.saml2.credentials.TestSaml2X509Credentials; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; -import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.hamcrest.CoreMatchers.containsString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -import static org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport.getParserPool; -import static org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport.getUnmarshallerFactory; -import static org.springframework.security.saml2.credentials.TestSaml2X509Credentials.relyingPartySigningCredential; -import static org.springframework.security.saml2.provider.service.authentication.Saml2Utils.samlDecode; -import static org.springframework.security.saml2.provider.service.authentication.Saml2Utils.samlInflate; -import static org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration.withRelyingPartyRegistration; -import static org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding.POST; -import static org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding.REDIRECT; /** * Tests for {@link OpenSamlAuthenticationRequestFactory} @@ -66,8 +60,8 @@ public class OpenSamlAuthenticationRequestFactoryTests { private RelyingPartyRegistration relyingPartyRegistration; - private AuthnRequestUnmarshaller unmarshaller = (AuthnRequestUnmarshaller) getUnmarshallerFactory() - .getUnmarshaller(AuthnRequest.DEFAULT_ELEMENT_NAME); + private AuthnRequestUnmarshaller unmarshaller = (AuthnRequestUnmarshaller) XMLObjectProviderRegistrySupport + .getUnmarshallerFactory().getUnmarshaller(AuthnRequest.DEFAULT_ELEMENT_NAME); @Rule public ExpectedException exception = ExpectedException.none(); @@ -78,7 +72,7 @@ public class OpenSamlAuthenticationRequestFactoryTests { .assertionConsumerServiceLocation("template") .providerDetails(c -> c.webSsoUrl("https://destination/sso")) .providerDetails(c -> c.entityId("remote-entity-id")).localEntityIdTemplate("local-entity-id") - .credentials(c -> c.add(relyingPartySigningCredential())); + .credentials(c -> c.add(TestSaml2X509Credentials.relyingPartySigningCredential())); this.relyingPartyRegistration = this.relyingPartyRegistrationBuilder.build(); this.contextBuilder = Saml2AuthenticationRequestContext.builder().issuer("https://issuer") .relyingPartyRegistration(this.relyingPartyRegistration) @@ -104,58 +98,64 @@ public class OpenSamlAuthenticationRequestFactoryTests { assertThat(result.getRelayState()).isEqualTo("Relay State Value"); assertThat(result.getSigAlg()).isNotEmpty(); assertThat(result.getSignature()).isNotEmpty(); - assertThat(result.getBinding()).isEqualTo(REDIRECT); + assertThat(result.getBinding()).isEqualTo(Saml2MessageBinding.REDIRECT); } @Test public void createRedirectAuthenticationRequestWhenNotSignRequestThenNoSignatureIsPresent() { this.context = this.contextBuilder.relayState("Relay State Value") - .relyingPartyRegistration(withRelyingPartyRegistration(this.relyingPartyRegistration) - .providerDetails(c -> c.signAuthNRequest(false)).build()) + .relyingPartyRegistration( + RelyingPartyRegistration.withRelyingPartyRegistration(this.relyingPartyRegistration) + .providerDetails(c -> c.signAuthNRequest(false)).build()) .build(); Saml2RedirectAuthenticationRequest result = this.factory.createRedirectAuthenticationRequest(this.context); assertThat(result.getSamlRequest()).isNotEmpty(); assertThat(result.getRelayState()).isEqualTo("Relay State Value"); assertThat(result.getSigAlg()).isNull(); assertThat(result.getSignature()).isNull(); - assertThat(result.getBinding()).isEqualTo(REDIRECT); + assertThat(result.getBinding()).isEqualTo(Saml2MessageBinding.REDIRECT); } @Test public void createPostAuthenticationRequestWhenNotSignRequestThenNoSignatureIsPresent() { this.context = this.contextBuilder.relayState("Relay State Value") - .relyingPartyRegistration(withRelyingPartyRegistration(this.relyingPartyRegistration) - .providerDetails(c -> c.signAuthNRequest(false)).build()) + .relyingPartyRegistration( + RelyingPartyRegistration.withRelyingPartyRegistration(this.relyingPartyRegistration) + .providerDetails(c -> c.signAuthNRequest(false)).build()) .build(); Saml2PostAuthenticationRequest result = this.factory.createPostAuthenticationRequest(this.context); assertThat(result.getSamlRequest()).isNotEmpty(); assertThat(result.getRelayState()).isEqualTo("Relay State Value"); - assertThat(result.getBinding()).isEqualTo(POST); - assertThat(new String(samlDecode(result.getSamlRequest()), UTF_8)).doesNotContain("ds:Signature"); + assertThat(result.getBinding()).isEqualTo(Saml2MessageBinding.POST); + assertThat(new String(Saml2Utils.samlDecode(result.getSamlRequest()), StandardCharsets.UTF_8)) + .doesNotContain("ds:Signature"); } @Test public void createPostAuthenticationRequestWhenSignRequestThenSignatureIsPresent() { this.context = this.contextBuilder.relayState("Relay State Value") - .relyingPartyRegistration(withRelyingPartyRegistration(this.relyingPartyRegistration).build()).build(); + .relyingPartyRegistration( + RelyingPartyRegistration.withRelyingPartyRegistration(this.relyingPartyRegistration).build()) + .build(); Saml2PostAuthenticationRequest result = this.factory.createPostAuthenticationRequest(this.context); assertThat(result.getSamlRequest()).isNotEmpty(); assertThat(result.getRelayState()).isEqualTo("Relay State Value"); - assertThat(result.getBinding()).isEqualTo(POST); - assertThat(new String(samlDecode(result.getSamlRequest()), UTF_8)).contains("ds:Signature"); + assertThat(result.getBinding()).isEqualTo(Saml2MessageBinding.POST); + assertThat(new String(Saml2Utils.samlDecode(result.getSamlRequest()), StandardCharsets.UTF_8)) + .contains("ds:Signature"); } @Test public void createAuthenticationRequestWhenDefaultThenReturnsPostBinding() { - AuthnRequest authn = getAuthNRequest(POST); + AuthnRequest authn = getAuthNRequest(Saml2MessageBinding.POST); Assert.assertEquals(SAMLConstants.SAML2_POST_BINDING_URI, authn.getProtocolBinding()); } @Test public void createAuthenticationRequestWhenSetUriThenReturnsCorrectBinding() { this.factory.setProtocolBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - AuthnRequest authn = getAuthNRequest(POST); + AuthnRequest authn = getAuthNRequest(Saml2MessageBinding.POST); Assert.assertEquals(SAMLConstants.SAML2_REDIRECT_BINDING_URI, authn.getProtocolBinding()); } @@ -199,29 +199,30 @@ public class OpenSamlAuthenticationRequestFactoryTests { @Test public void createPostAuthenticationRequestWhenAssertionConsumerServiceBindingThenUses() { RelyingPartyRegistration relyingPartyRegistration = this.relyingPartyRegistrationBuilder - .assertionConsumerServiceBinding(REDIRECT).build(); + .assertionConsumerServiceBinding(Saml2MessageBinding.REDIRECT).build(); Saml2AuthenticationRequestContext context = this.contextBuilder .relyingPartyRegistration(relyingPartyRegistration).build(); Saml2PostAuthenticationRequest request = this.factory.createPostAuthenticationRequest(context); String samlRequest = request.getSamlRequest(); - String inflated = new String(samlDecode(samlRequest)); + String inflated = new String(Saml2Utils.samlDecode(samlRequest)); assertThat(inflated).contains("ProtocolBinding=\"" + SAMLConstants.SAML2_REDIRECT_BINDING_URI + "\""); } private AuthnRequest getAuthNRequest(Saml2MessageBinding binding) { - AbstractSaml2AuthenticationRequest result = (binding == REDIRECT) + AbstractSaml2AuthenticationRequest result = (binding == Saml2MessageBinding.REDIRECT) ? this.factory.createRedirectAuthenticationRequest(this.context) : this.factory.createPostAuthenticationRequest(this.context); String samlRequest = result.getSamlRequest(); assertThat(samlRequest).isNotEmpty(); - if (result.getBinding() == REDIRECT) { - samlRequest = samlInflate(samlDecode(samlRequest)); + if (result.getBinding() == Saml2MessageBinding.REDIRECT) { + samlRequest = Saml2Utils.samlInflate(Saml2Utils.samlDecode(samlRequest)); } else { - samlRequest = new String(samlDecode(samlRequest), UTF_8); + samlRequest = new String(Saml2Utils.samlDecode(samlRequest), StandardCharsets.UTF_8); } try { - Document document = getParserPool().parse(new ByteArrayInputStream(samlRequest.getBytes(UTF_8))); + Document document = XMLObjectProviderRegistrySupport.getParserPool() + .parse(new ByteArrayInputStream(samlRequest.getBytes(StandardCharsets.UTF_8))); Element element = document.getDocumentElement(); return (AuthnRequest) this.unmarshaller.unmarshall(element); } diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/Saml2AuthenticationRequestFactoryTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/Saml2AuthenticationRequestFactoryTests.java index 2a13ed2220..383b0ed5f9 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/Saml2AuthenticationRequestFactoryTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/Saml2AuthenticationRequestFactoryTests.java @@ -20,12 +20,10 @@ import java.util.UUID; import org.junit.Test; +import org.springframework.security.saml2.credentials.TestSaml2X509Credentials; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.saml2.credentials.TestSaml2X509Credentials.relyingPartySigningCredential; -import static org.springframework.security.saml2.provider.service.authentication.Saml2Utils.samlDecode; -import static org.springframework.security.saml2.provider.service.authentication.Saml2Utils.samlInflate; /** * Tests for {@link Saml2AuthenticationRequestFactory} default interface methods @@ -36,7 +34,7 @@ public class Saml2AuthenticationRequestFactoryTests { .assertionConsumerServiceUrlTemplate("template") .providerDetails(c -> c.webSsoUrl("https://example.com/destination")) .providerDetails(c -> c.entityId("remote-entity-id")).localEntityIdTemplate("local-entity-id") - .credentials(c -> c.add(relyingPartySigningCredential())).build(); + .credentials(c -> c.add(TestSaml2X509Credentials.relyingPartySigningCredential())).build(); @Test public void createAuthenticationRequestParametersWhenRedirectDefaultIsUsedMessageIsDeflatedAndEncoded() { @@ -47,8 +45,8 @@ public class Saml2AuthenticationRequestFactoryTests { .assertionConsumerServiceUrl("https://example.com/acs-url").build(); Saml2RedirectAuthenticationRequest response = factory.createRedirectAuthenticationRequest(request); String resultValue = response.getSamlRequest(); - byte[] decoded = samlDecode(resultValue); - String inflated = samlInflate(decoded); + byte[] decoded = Saml2Utils.samlDecode(resultValue); + String inflated = Saml2Utils.samlInflate(decoded); assertThat(inflated).isEqualTo(value); } @@ -61,7 +59,7 @@ public class Saml2AuthenticationRequestFactoryTests { .assertionConsumerServiceUrl("https://example.com/acs-url").build(); Saml2PostAuthenticationRequest response = factory.createPostAuthenticationRequest(request); String resultValue = response.getSamlRequest(); - byte[] decoded = samlDecode(resultValue); + byte[] decoded = Saml2Utils.samlDecode(resultValue); assertThat(new String(decoded)).isEqualTo(value); } diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/TestOpenSamlObjects.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/TestOpenSamlObjects.java index c5356f4cea..6cb77f7558 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/TestOpenSamlObjects.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/TestOpenSamlObjects.java @@ -30,6 +30,7 @@ import org.apache.xml.security.encryption.XMLCipherParameters; import org.joda.time.DateTime; import org.joda.time.Duration; import org.opensaml.core.xml.XMLObject; +import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.opensaml.core.xml.io.MarshallingException; import org.opensaml.core.xml.schema.XSAny; import org.opensaml.core.xml.schema.XSBoolean; @@ -79,8 +80,6 @@ import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.OpenSamlInitializationService; import org.springframework.security.saml2.core.Saml2X509Credential; -import static org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport.getBuilderFactory; - final class TestOpenSamlObjects { static { @@ -368,7 +367,7 @@ final class TestOpenSamlObjects { } static T build(QName qName) { - return (T) getBuilderFactory().getBuilder(qName).buildObject(qName); + return (T) XMLObjectProviderRegistrySupport.getBuilderFactory().getBuilder(qName).buildObject(qName); } } diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/TestSaml2AuthenticationRequestContexts.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/TestSaml2AuthenticationRequestContexts.java index d5f784373a..451ef004eb 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/TestSaml2AuthenticationRequestContexts.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/TestSaml2AuthenticationRequestContexts.java @@ -16,7 +16,7 @@ package org.springframework.security.saml2.provider.service.authentication; -import static org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations.relyingPartyRegistration; +import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; /** * Test {@link Saml2AuthenticationRequestContext}s @@ -25,7 +25,7 @@ public class TestSaml2AuthenticationRequestContexts { public static Saml2AuthenticationRequestContext.Builder authenticationRequestContext() { return Saml2AuthenticationRequestContext.builder().relayState("relayState").issuer("issuer") - .relyingPartyRegistration(relyingPartyRegistration().build()) + .relyingPartyRegistration(TestRelyingPartyRegistrations.relyingPartyRegistration().build()) .assertionConsumerServiceUrl("assertionConsumerServiceUrl"); } diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/metadata/OpenSamlMetadataResolverTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/metadata/OpenSamlMetadataResolverTests.java index f062d23502..4d66195f89 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/metadata/OpenSamlMetadataResolverTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/metadata/OpenSamlMetadataResolverTests.java @@ -18,13 +18,12 @@ package org.springframework.security.saml2.provider.service.metadata; import org.junit.Test; +import org.springframework.security.saml2.core.TestSaml2X509Credentials; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; +import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; +import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.saml2.core.TestSaml2X509Credentials.relyingPartyVerifyingCredential; -import static org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding.REDIRECT; -import static org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations.full; -import static org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations.noCredentials; /** * Tests for {@link OpenSamlMetadataResolver} @@ -34,7 +33,8 @@ public class OpenSamlMetadataResolverTests { @Test public void resolveWhenRelyingPartyThenMetadataMatches() { // given - RelyingPartyRegistration relyingPartyRegistration = full().assertionConsumerServiceBinding(REDIRECT).build(); + RelyingPartyRegistration relyingPartyRegistration = TestRelyingPartyRegistrations.full() + .assertionConsumerServiceBinding(Saml2MessageBinding.REDIRECT).build(); OpenSamlMetadataResolver openSamlMetadataResolver = new OpenSamlMetadataResolver(); // when @@ -52,9 +52,9 @@ public class OpenSamlMetadataResolverTests { @Test public void resolveWhenRelyingPartyNoCredentialsThenMetadataMatches() { // given - RelyingPartyRegistration relyingPartyRegistration = noCredentials() - .assertingPartyDetails( - party -> party.verificationX509Credentials(c -> c.add(relyingPartyVerifyingCredential()))) + RelyingPartyRegistration relyingPartyRegistration = TestRelyingPartyRegistrations.noCredentials() + .assertingPartyDetails(party -> party.verificationX509Credentials( + c -> c.add(TestSaml2X509Credentials.relyingPartyVerifyingCredential()))) .build(); OpenSamlMetadataResolver openSamlMetadataResolver = new OpenSamlMetadataResolver(); diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverterTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverterTests.java index 7241cfc1a9..0d5733b82e 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverterTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverterTests.java @@ -25,12 +25,12 @@ import java.util.Base64; import org.junit.Before; import org.junit.Test; +import org.springframework.http.HttpStatus; import org.springframework.mock.http.client.MockClientHttpResponse; import org.springframework.security.saml2.Saml2Exception; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; -import static org.springframework.http.HttpStatus.OK; public class OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverterTests { @@ -62,7 +62,7 @@ public class OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverterTests { @Test public void readWhenMissingIDPSSODescriptorThenException() { MockClientHttpResponse response = new MockClientHttpResponse( - (String.format(ENTITY_DESCRIPTOR_TEMPLATE, "")).getBytes(), OK); + (String.format(ENTITY_DESCRIPTOR_TEMPLATE, "")).getBytes(), HttpStatus.OK); assertThatCode(() -> this.converter.read(RelyingPartyRegistration.Builder.class, response)) .isInstanceOf(Saml2Exception.class) .hasMessageContaining("Metadata response is missing the necessary IDPSSODescriptor element"); @@ -71,7 +71,7 @@ public class OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverterTests { @Test public void readWhenMissingVerificationKeyThenException() { String payload = String.format(ENTITY_DESCRIPTOR_TEMPLATE, String.format(IDP_SSO_DESCRIPTOR_TEMPLATE, "")); - MockClientHttpResponse response = new MockClientHttpResponse(payload.getBytes(), OK); + MockClientHttpResponse response = new MockClientHttpResponse(payload.getBytes(), HttpStatus.OK); assertThatCode(() -> this.converter.read(RelyingPartyRegistration.Builder.class, response)) .isInstanceOf(Saml2Exception.class).hasMessageContaining( "Metadata response is missing verification certificates, necessary for verifying SAML assertions"); @@ -81,7 +81,7 @@ public class OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverterTests { public void readWhenMissingSingleSignOnServiceThenException() { String payload = String.format(ENTITY_DESCRIPTOR_TEMPLATE, String.format(IDP_SSO_DESCRIPTOR_TEMPLATE, String.format(KEY_DESCRIPTOR_TEMPLATE, "use=\"signing\""))); - MockClientHttpResponse response = new MockClientHttpResponse(payload.getBytes(), OK); + MockClientHttpResponse response = new MockClientHttpResponse(payload.getBytes(), HttpStatus.OK); assertThatCode(() -> this.converter.read(RelyingPartyRegistration.Builder.class, response)) .isInstanceOf(Saml2Exception.class).hasMessageContaining( "Metadata response is missing a SingleSignOnService, necessary for sending AuthnRequests"); @@ -94,7 +94,7 @@ public class OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverterTests { String.format(KEY_DESCRIPTOR_TEMPLATE, "use=\"signing\"") + String.format(KEY_DESCRIPTOR_TEMPLATE, "use=\"encryption\"") + String.format(SINGLE_SIGN_ON_SERVICE_TEMPLATE))); - MockClientHttpResponse response = new MockClientHttpResponse(payload.getBytes(), OK); + MockClientHttpResponse response = new MockClientHttpResponse(payload.getBytes(), HttpStatus.OK); RelyingPartyRegistration registration = this.converter.read(RelyingPartyRegistration.Builder.class, response) .registrationId("one").build(); RelyingPartyRegistration.AssertingPartyDetails details = registration.getAssertingPartyDetails(); @@ -114,7 +114,7 @@ public class OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverterTests { public void readWhenKeyDescriptorHasNoUseThenConfiguresBothKeyTypes() throws Exception { String payload = String.format(ENTITY_DESCRIPTOR_TEMPLATE, String.format(IDP_SSO_DESCRIPTOR_TEMPLATE, String.format(KEY_DESCRIPTOR_TEMPLATE, "") + String.format(SINGLE_SIGN_ON_SERVICE_TEMPLATE))); - MockClientHttpResponse response = new MockClientHttpResponse(payload.getBytes(), OK); + MockClientHttpResponse response = new MockClientHttpResponse(payload.getBytes(), HttpStatus.OK); RelyingPartyRegistration registration = this.converter.read(RelyingPartyRegistration.Builder.class, response) .registrationId("one").build(); RelyingPartyRegistration.AssertingPartyDetails details = registration.getAssertingPartyDetails(); diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistrationTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistrationTests.java index cad36be5d4..cc85cac289 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistrationTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistrationTests.java @@ -18,19 +18,17 @@ package org.springframework.security.saml2.provider.service.registration; import org.junit.Test; +import org.springframework.security.saml2.credentials.TestSaml2X509Credentials; import org.springframework.security.saml2.provider.service.servlet.filter.Saml2WebSsoAuthenticationFilter; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.saml2.credentials.TestSaml2X509Credentials.relyingPartyVerifyingCredential; -import static org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration.withRegistrationId; -import static org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding.POST; -import static org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations.relyingPartyRegistration; public class RelyingPartyRegistrationTests { @Test public void withRelyingPartyRegistrationWorks() { - RelyingPartyRegistration registration = relyingPartyRegistration().providerDetails(p -> p.binding(POST)) + RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration() + .providerDetails(p -> p.binding(Saml2MessageBinding.POST)) .providerDetails(p -> p.signAuthNRequest(false)) .assertionConsumerServiceBinding(Saml2MessageBinding.REDIRECT).build(); RelyingPartyRegistration copy = RelyingPartyRegistration.withRelyingPartyRegistration(registration).build(); @@ -59,7 +57,8 @@ public class RelyingPartyRegistrationTests { .isEqualTo("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/SSOService.php"); assertThat(copy.getProviderDetails().getBinding()).isEqualTo(registration.getProviderDetails().getBinding()) .isEqualTo(copy.getAssertingPartyDetails().getSingleSignOnServiceBinding()) - .isEqualTo(registration.getAssertingPartyDetails().getSingleSignOnServiceBinding()).isEqualTo(POST); + .isEqualTo(registration.getAssertingPartyDetails().getSingleSignOnServiceBinding()) + .isEqualTo(Saml2MessageBinding.POST); assertThat(copy.getProviderDetails().isSignAuthNRequest()) .isEqualTo(registration.getProviderDetails().isSignAuthNRequest()) .isEqualTo(copy.getAssertingPartyDetails().getWantAuthnRequestsSigned()) @@ -76,13 +75,13 @@ public class RelyingPartyRegistrationTests { @Test public void buildWhenUsingDefaultsThenAssertionConsumerServiceBindingDefaultsToPost() { - RelyingPartyRegistration relyingPartyRegistration = withRegistrationId("id").entityId("entity-id") - .assertionConsumerServiceLocation("location") + RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistration.withRegistrationId("id") + .entityId("entity-id").assertionConsumerServiceLocation("location") .assertingPartyDetails( assertingParty -> assertingParty.entityId("entity-id").singleSignOnServiceLocation("location")) - .credentials(c -> c.add(relyingPartyVerifyingCredential())).build(); + .credentials(c -> c.add(TestSaml2X509Credentials.relyingPartyVerifyingCredential())).build(); - assertThat(relyingPartyRegistration.getAssertionConsumerServiceBinding()).isEqualTo(POST); + assertThat(relyingPartyRegistration.getAssertionConsumerServiceBinding()).isEqualTo(Saml2MessageBinding.POST); } } diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistrationsTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistrationsTests.java index 1af5ede3b7..52c08c80ae 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistrationsTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistrationsTests.java @@ -23,7 +23,7 @@ import org.junit.Test; import org.springframework.security.saml2.Saml2Exception; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatCode; /** * Tests for {@link RelyingPartyRegistration} diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/TestRelyingPartyRegistrations.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/TestRelyingPartyRegistrations.java index dd0f502553..62b3e4f2a2 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/TestRelyingPartyRegistrations.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/TestRelyingPartyRegistrations.java @@ -16,13 +16,10 @@ package org.springframework.security.saml2.provider.service.registration; -import org.springframework.security.saml2.core.TestSaml2X509Credentials; import org.springframework.security.saml2.credentials.Saml2X509Credential; +import org.springframework.security.saml2.credentials.TestSaml2X509Credentials; import org.springframework.security.saml2.provider.service.servlet.filter.Saml2WebSsoAuthenticationFilter; -import static org.springframework.security.saml2.credentials.TestSaml2X509Credentials.relyingPartySigningCredential; -import static org.springframework.security.saml2.credentials.TestSaml2X509Credentials.relyingPartyVerifyingCredential; - /** * Preconfigured test data for {@link RelyingPartyRegistration} objects */ @@ -32,12 +29,12 @@ public class TestRelyingPartyRegistrations { String registrationId = "simplesamlphp"; String rpEntityId = "{baseUrl}/saml2/service-provider-metadata/{registrationId}"; - Saml2X509Credential signingCredential = relyingPartySigningCredential(); + Saml2X509Credential signingCredential = TestSaml2X509Credentials.relyingPartySigningCredential(); String assertionConsumerServiceLocation = "{baseUrl}" + Saml2WebSsoAuthenticationFilter.DEFAULT_FILTER_PROCESSES_URI; String apEntityId = "https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/metadata.php"; - Saml2X509Credential verificationCertificate = relyingPartyVerifyingCredential(); + Saml2X509Credential verificationCertificate = TestSaml2X509Credentials.relyingPartyVerifyingCredential(); String singleSignOnServiceLocation = "https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/SSOService.php"; return RelyingPartyRegistration.withRegistrationId(registrationId).entityId(rpEntityId) @@ -55,10 +52,13 @@ public class TestRelyingPartyRegistrations { public static RelyingPartyRegistration.Builder full() { return noCredentials() - .signingX509Credentials(c -> c.add(TestSaml2X509Credentials.relyingPartySigningCredential())) - .decryptionX509Credentials(c -> c.add(TestSaml2X509Credentials.relyingPartyDecryptingCredential())) + .signingX509Credentials(c -> c.add(org.springframework.security.saml2.core.TestSaml2X509Credentials + .relyingPartySigningCredential())) + .decryptionX509Credentials(c -> c.add(org.springframework.security.saml2.core.TestSaml2X509Credentials + .relyingPartyDecryptingCredential())) .assertingPartyDetails(party -> party.verificationX509Credentials( - c -> c.add(TestSaml2X509Credentials.relyingPartyVerifyingCredential()))); + c -> c.add(org.springframework.security.saml2.core.TestSaml2X509Credentials + .relyingPartyVerifyingCredential()))); } } diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationRequestFilterTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationRequestFilterTests.java index 69368eec00..78a1e50025 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationRequestFilterTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/filter/Saml2WebSsoAuthenticationRequestFilterTests.java @@ -27,10 +27,13 @@ import org.junit.Test; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.security.saml2.credentials.TestSaml2X509Credentials; import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationRequestFactory; import org.springframework.security.saml2.provider.service.authentication.Saml2PostAuthenticationRequest; +import org.springframework.security.saml2.provider.service.authentication.TestSaml2AuthenticationRequestContexts; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository; +import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.security.saml2.provider.service.web.Saml2AuthenticationRequestContextResolver; import org.springframework.web.util.HtmlUtils; import org.springframework.web.util.UriUtils; @@ -42,9 +45,6 @@ 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.springframework.security.saml2.credentials.TestSaml2X509Credentials.assertingPartyPrivateCredential; -import static org.springframework.security.saml2.provider.service.authentication.TestSaml2AuthenticationRequestContexts.authenticationRequestContext; -import static org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding.POST; public class Saml2WebSsoAuthenticationRequestFilterTests { @@ -78,7 +78,7 @@ public class Saml2WebSsoAuthenticationRequestFilterTests { this.rpBuilder = RelyingPartyRegistration.withRegistrationId("registration-id") .providerDetails(c -> c.entityId("idp-entity-id")).providerDetails(c -> c.webSsoUrl(IDP_SSO_URL)) .assertionConsumerServiceUrlTemplate("template") - .credentials(c -> c.add(assertingPartyPrivateCredential())); + .credentials(c -> c.add(TestSaml2X509Credentials.assertingPartyPrivateCredential())); } @Test @@ -133,7 +133,7 @@ public class Saml2WebSsoAuthenticationRequestFilterTests { @Test public void doFilterWhenPostFormDataIsPresent() throws Exception { given(this.repository.findByRegistrationId("registration-id")) - .willReturn(this.rpBuilder.providerDetails(c -> c.binding(POST)).build()); + .willReturn(this.rpBuilder.providerDetails(c -> c.binding(Saml2MessageBinding.POST)).build()); final String relayStateValue = "https://my-relay-state.example.com?with=param&other=param&javascript{alert('1');}"; final String relayStateEncoded = HtmlUtils.htmlEscape(relayStateValue); this.request.setParameter("RelayState", relayStateValue); @@ -147,7 +147,8 @@ public class Saml2WebSsoAuthenticationRequestFilterTests { @Test public void doFilterWhenSetAuthenticationRequestFactoryThenUses() throws Exception { - RelyingPartyRegistration relyingParty = this.rpBuilder.providerDetails(c -> c.binding(POST)).build(); + RelyingPartyRegistration relyingParty = this.rpBuilder.providerDetails(c -> c.binding(Saml2MessageBinding.POST)) + .build(); Saml2PostAuthenticationRequest authenticationRequest = mock(Saml2PostAuthenticationRequest.class); given(authenticationRequest.getAuthenticationRequestUri()).willReturn("uri"); given(authenticationRequest.getRelayState()).willReturn("relay"); @@ -166,13 +167,14 @@ public class Saml2WebSsoAuthenticationRequestFilterTests { @Test public void doFilterWhenCustomAuthenticationRequestFactoryThenUses() throws Exception { - RelyingPartyRegistration relyingParty = this.rpBuilder.providerDetails(c -> c.binding(POST)).build(); + RelyingPartyRegistration relyingParty = this.rpBuilder.providerDetails(c -> c.binding(Saml2MessageBinding.POST)) + .build(); Saml2PostAuthenticationRequest authenticationRequest = mock(Saml2PostAuthenticationRequest.class); given(authenticationRequest.getAuthenticationRequestUri()).willReturn("uri"); given(authenticationRequest.getRelayState()).willReturn("relay"); given(authenticationRequest.getSamlRequest()).willReturn("saml"); - given(this.resolver.resolve(this.request)) - .willReturn(authenticationRequestContext().relyingPartyRegistration(relyingParty).build()); + given(this.resolver.resolve(this.request)).willReturn(TestSaml2AuthenticationRequestContexts + .authenticationRequestContext().relyingPartyRegistration(relyingParty).build()); given(this.factory.createPostAuthenticationRequest(any())).willReturn(authenticationRequest); Saml2WebSsoAuthenticationRequestFilter filter = new Saml2WebSsoAuthenticationRequestFilter(this.resolver, diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/DefaultRelyingPartyRegistrationResolverTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/DefaultRelyingPartyRegistrationResolverTests.java index 99f5e261a0..9f916f5974 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/DefaultRelyingPartyRegistrationResolverTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/DefaultRelyingPartyRegistrationResolverTests.java @@ -22,17 +22,18 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.saml2.provider.service.registration.InMemoryRelyingPartyRegistrationRepository; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository; +import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; -import static org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations.relyingPartyRegistration; /** * Tests for {@link DefaultRelyingPartyRegistrationResolver} */ public class DefaultRelyingPartyRegistrationResolverTests { - private final RelyingPartyRegistration registration = relyingPartyRegistration().build(); + private final RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration() + .build(); private final RelyingPartyRegistrationRepository repository = new InMemoryRelyingPartyRegistrationRepository( this.registration); diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/DefaultSaml2AuthenticationRequestContextResolverTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/DefaultSaml2AuthenticationRequestContextResolverTests.java index 8b70331dcd..e12618d650 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/DefaultSaml2AuthenticationRequestContextResolverTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/DefaultSaml2AuthenticationRequestContextResolverTests.java @@ -20,12 +20,12 @@ import org.junit.Before; import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.security.saml2.credentials.TestSaml2X509Credentials; import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationRequestContext; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; -import static org.springframework.security.saml2.credentials.TestSaml2X509Credentials.relyingPartyVerifyingCredential; /** * Tests for {@link DefaultSaml2AuthenticationRequestContextResolver} @@ -61,7 +61,7 @@ public class DefaultSaml2AuthenticationRequestContextResolverTests { .providerDetails(c -> c.entityId(ASSERTING_PARTY_ENTITY_ID)) .providerDetails(c -> c.webSsoUrl(ASSERTING_PARTY_SSO_URL)) .assertionConsumerServiceUrlTemplate(RELYING_PARTY_SSO_URL) - .credentials(c -> c.add(relyingPartyVerifyingCredential())); + .credentials(c -> c.add(TestSaml2X509Credentials.relyingPartyVerifyingCredential())); } @Test diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverterTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverterTests.java index a653845697..a3a969b2f7 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverterTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverterTests.java @@ -32,15 +32,14 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.saml2.core.Saml2Utils; import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationToken; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; +import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import org.springframework.util.StreamUtils; import org.springframework.web.util.UriUtils; -import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; -import static org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations.relyingPartyRegistration; @RunWith(MockitoJUnitRunner.class) public class Saml2AuthenticationTokenConverterTests { @@ -48,7 +47,8 @@ public class Saml2AuthenticationTokenConverterTests { @Mock Converter relyingPartyRegistrationResolver; - RelyingPartyRegistration relyingPartyRegistration = relyingPartyRegistration().build(); + RelyingPartyRegistration relyingPartyRegistration = TestRelyingPartyRegistrations.relyingPartyRegistration() + .build(); @Test public void convertWhenSamlResponseThenToken() { @@ -57,7 +57,7 @@ public class Saml2AuthenticationTokenConverterTests { given(this.relyingPartyRegistrationResolver.convert(any(HttpServletRequest.class))) .willReturn(this.relyingPartyRegistration); MockHttpServletRequest request = new MockHttpServletRequest(); - request.setParameter("SAMLResponse", Saml2Utils.samlEncode("response".getBytes(UTF_8))); + request.setParameter("SAMLResponse", Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8))); Saml2AuthenticationToken token = converter.convert(request); assertThat(token.getSaml2Response()).isEqualTo("response"); assertThat(token.getRelyingPartyRegistration().getRegistrationId()) @@ -126,7 +126,7 @@ public class Saml2AuthenticationTokenConverterTests { private String getSsoCircleEncodedXml() throws IOException { ClassPathResource resource = new ClassPathResource("saml2-response-sso-circle.encoded"); String response = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8); - return UriUtils.decode(response, UTF_8); + return UriUtils.decode(response, StandardCharsets.UTF_8); } } diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2MetadataFilterTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2MetadataFilterTests.java index 3e4fe4d575..672b53f6f7 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2MetadataFilterTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2MetadataFilterTests.java @@ -23,9 +23,11 @@ import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.security.saml2.core.TestSaml2X509Credentials; import org.springframework.security.saml2.provider.service.metadata.Saml2MetadataResolver; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository; +import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import static org.assertj.core.api.Assertions.assertThat; @@ -34,8 +36,6 @@ 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.springframework.security.saml2.core.TestSaml2X509Credentials.relyingPartyVerifyingCredential; -import static org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations.noCredentials; /** * Tests for {@link Saml2MetadataFilter} @@ -108,9 +108,9 @@ public class Saml2MetadataFilterTests { public void doFilterWhenRelyingPartyRegistrationFoundThenInvokesMetadataResolver() throws Exception { // given this.request.setPathInfo("/saml2/service-provider-metadata/validRegistration"); - RelyingPartyRegistration validRegistration = noCredentials() - .assertingPartyDetails( - party -> party.verificationX509Credentials(c -> c.add(relyingPartyVerifyingCredential()))) + RelyingPartyRegistration validRegistration = TestRelyingPartyRegistrations.noCredentials() + .assertingPartyDetails(party -> party.verificationX509Credentials( + c -> c.add(TestSaml2X509Credentials.relyingPartyVerifyingCredential()))) .build(); String generatedMetadata = "test"; diff --git a/test/src/main/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurers.java b/test/src/main/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurers.java index c6de53ae1d..33c7cd330f 100644 --- a/test/src/main/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurers.java +++ b/test/src/main/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurers.java @@ -67,6 +67,7 @@ import org.springframework.security.oauth2.core.user.DefaultOAuth2User; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.security.oauth2.core.user.OAuth2UserAuthority; import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.jwt.JwtClaimNames; import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter; @@ -89,9 +90,6 @@ import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; import org.springframework.web.server.adapter.WebHttpHandlerBuilder; -import static java.lang.Boolean.TRUE; -import static org.springframework.security.oauth2.jwt.JwtClaimNames.SUB; - /** * Test utilities for working with Spring Security and * {@link org.springframework.test.web.reactive.server.WebTestClient.Builder#apply(WebTestClientConfigurer)}. @@ -469,8 +467,8 @@ public class SecurityMockServerConfigurers { * @return the {@link JwtMutator} for further configuration */ public JwtMutator jwt(Consumer jwtBuilderConsumer) { - Jwt.Builder jwtBuilder = Jwt.withTokenValue("token").header("alg", "none").claim(SUB, "user").claim("scope", - "read"); + Jwt.Builder jwtBuilder = Jwt.withTokenValue("token").header("alg", "none").claim(JwtClaimNames.SUB, "user") + .claim("scope", "read"); jwtBuilderConsumer.accept(jwtBuilder); this.jwt = jwtBuilder.build(); return this; @@ -1178,11 +1176,11 @@ public class SecurityMockServerConfigurers { } public static void enable(ServerWebExchange exchange) { - exchange.getAttributes().put(ENABLED_ATTR_NAME, TRUE); + exchange.getAttributes().put(ENABLED_ATTR_NAME, Boolean.TRUE); } public boolean isEnabled(ServerWebExchange exchange) { - return TRUE.equals(exchange.getAttribute(ENABLED_ATTR_NAME)); + return Boolean.TRUE.equals(exchange.getAttribute(ENABLED_ATTR_NAME)); } } diff --git a/test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessors.java b/test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessors.java index 6a02265a14..ee790115e2 100644 --- a/test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessors.java +++ b/test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessors.java @@ -79,6 +79,7 @@ import org.springframework.security.oauth2.core.user.DefaultOAuth2User; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.security.oauth2.core.user.OAuth2UserAuthority; import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.jwt.JwtClaimNames; import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter; @@ -105,9 +106,6 @@ import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; -import static java.lang.Boolean.TRUE; -import static org.springframework.security.oauth2.jwt.JwtClaimNames.SUB; - /** * Contains {@link MockMvc} {@link RequestPostProcessor} implementations for Spring * Security. @@ -570,11 +568,11 @@ public final class SecurityMockMvcRequestPostProcessors { } public static void enable(HttpServletRequest request) { - request.setAttribute(ENABLED_ATTR_NAME, TRUE); + request.setAttribute(ENABLED_ATTR_NAME, Boolean.TRUE); } public boolean isEnabled(HttpServletRequest request) { - return TRUE.equals(request.getAttribute(ENABLED_ATTR_NAME)); + return Boolean.TRUE.equals(request.getAttribute(ENABLED_ATTR_NAME)); } } @@ -1071,8 +1069,8 @@ public final class SecurityMockMvcRequestPostProcessors { * @return the {@link JwtRequestPostProcessor} for additional customization */ public JwtRequestPostProcessor jwt(Consumer jwtBuilderConsumer) { - Jwt.Builder jwtBuilder = Jwt.withTokenValue("token").header("alg", "none").claim(SUB, "user").claim("scope", - "read"); + Jwt.Builder jwtBuilder = Jwt.withTokenValue("token").header("alg", "none").claim(JwtClaimNames.SUB, "user") + .claim("scope", "read"); jwtBuilderConsumer.accept(jwtBuilder); this.jwt = jwtBuilder.build(); return this; @@ -1661,11 +1659,11 @@ public final class SecurityMockMvcRequestPostProcessors { } public static void enable(HttpServletRequest request) { - request.setAttribute(ENABLED_ATTR_NAME, TRUE); + request.setAttribute(ENABLED_ATTR_NAME, Boolean.TRUE); } public boolean isEnabled(HttpServletRequest request) { - return TRUE.equals(request.getAttribute(ENABLED_ATTR_NAME)); + return Boolean.TRUE.equals(request.getAttribute(ENABLED_ATTR_NAME)); } } diff --git a/test/src/main/java/org/springframework/security/test/web/servlet/response/SecurityMockMvcResultMatchers.java b/test/src/main/java/org/springframework/security/test/web/servlet/response/SecurityMockMvcResultMatchers.java index a284463c3b..a767f23604 100644 --- a/test/src/main/java/org/springframework/security/test/web/servlet/response/SecurityMockMvcResultMatchers.java +++ b/test/src/main/java/org/springframework/security/test/web/servlet/response/SecurityMockMvcResultMatchers.java @@ -28,13 +28,11 @@ import org.springframework.security.core.context.SecurityContext; import org.springframework.security.test.web.support.WebTestUtils; import org.springframework.security.web.context.HttpRequestResponseHolder; import org.springframework.security.web.context.SecurityContextRepository; +import org.springframework.test.util.AssertionErrors; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.ResultMatcher; -import static org.springframework.test.util.AssertionErrors.assertEquals; -import static org.springframework.test.util.AssertionErrors.assertTrue; - /** * Security related {@link MockMvc} {@link ResultMatcher}s. * @@ -97,42 +95,46 @@ public final class SecurityMockMvcResultMatchers { Authentication auth = context.getAuthentication(); - assertTrue("Authentication should not be null", auth != null); + AssertionErrors.assertTrue("Authentication should not be null", auth != null); if (this.assertAuthentication != null) { this.assertAuthentication.accept(auth); } if (this.expectedContext != null) { - assertEquals(this.expectedContext + " does not equal " + context, this.expectedContext, context); + AssertionErrors.assertEquals(this.expectedContext + " does not equal " + context, this.expectedContext, + context); } if (this.expectedAuthentication != null) { - assertEquals(this.expectedAuthentication + " does not equal " + context.getAuthentication(), + AssertionErrors.assertEquals( + this.expectedAuthentication + " does not equal " + context.getAuthentication(), this.expectedAuthentication, context.getAuthentication()); } if (this.expectedAuthenticationPrincipal != null) { - assertTrue("Authentication cannot be null", context.getAuthentication() != null); - assertEquals( + AssertionErrors.assertTrue("Authentication cannot be null", context.getAuthentication() != null); + AssertionErrors.assertEquals( this.expectedAuthenticationPrincipal + " does not equal " + context.getAuthentication().getPrincipal(), this.expectedAuthenticationPrincipal, context.getAuthentication().getPrincipal()); } if (this.expectedAuthenticationName != null) { - assertTrue("Authentication cannot be null", auth != null); + AssertionErrors.assertTrue("Authentication cannot be null", auth != null); String name = auth.getName(); - assertEquals(this.expectedAuthenticationName + " does not equal " + name, + AssertionErrors.assertEquals(this.expectedAuthenticationName + " does not equal " + name, this.expectedAuthenticationName, name); } if (this.expectedGrantedAuthorities != null) { - assertTrue("Authentication cannot be null", auth != null); + AssertionErrors.assertTrue("Authentication cannot be null", auth != null); Collection authorities = auth.getAuthorities(); - assertTrue(authorities + " does not contain the same authorities as " + this.expectedGrantedAuthorities, + AssertionErrors.assertTrue( + authorities + " does not contain the same authorities as " + this.expectedGrantedAuthorities, authorities.containsAll(this.expectedGrantedAuthorities)); - assertTrue(this.expectedGrantedAuthorities + " does not contain the same authorities as " + authorities, + AssertionErrors.assertTrue( + this.expectedGrantedAuthorities + " does not contain the same authorities as " + authorities, this.expectedGrantedAuthorities.containsAll(authorities)); } } @@ -240,7 +242,7 @@ public final class SecurityMockMvcResultMatchers { SecurityContext context = load(result); Authentication authentication = context.getAuthentication(); - assertTrue("Expected anonymous Authentication got " + context, + AssertionErrors.assertTrue("Expected anonymous Authentication got " + context, authentication == null || this.trustResolver.isAnonymous(authentication)); } diff --git a/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurerOpaqueTokenTests.java b/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurerOpaqueTokenTests.java index a976d14356..46db6349b0 100644 --- a/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurerOpaqueTokenTests.java +++ b/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurerOpaqueTokenTests.java @@ -28,16 +28,14 @@ import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; +import org.springframework.security.oauth2.core.TestOAuth2AuthenticatedPrincipals; import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication; +import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames; import org.springframework.security.web.reactive.result.method.annotation.CurrentSecurityContextArgumentResolver; import org.springframework.security.web.server.context.SecurityContextServerWebExchangeWebFilter; import org.springframework.test.web.reactive.server.WebTestClient; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.oauth2.core.TestOAuth2AuthenticatedPrincipals.active; -import static org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionClaimNames.SUBJECT; -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.mockOpaqueToken; -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.springSecurity; /** * @author Josh Cummings @@ -54,25 +52,27 @@ public class SecurityMockServerConfigurerOpaqueTokenTests extends AbstractMockSe .webFilter(new SecurityContextServerWebExchangeWebFilter()) .argumentResolvers(resolvers -> resolvers .addCustomResolver(new CurrentSecurityContextArgumentResolver(new ReactiveAdapterRegistry()))) - .apply(springSecurity()).configureClient() + .apply(SecurityMockServerConfigurers.springSecurity()).configureClient() .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build(); @Test public void mockOpaqueTokenWhenUsingDefaultsThenBearerTokenAuthentication() { - this.client.mutateWith(mockOpaqueToken()).get().exchange().expectStatus().isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.mockOpaqueToken()).get().exchange().expectStatus().isOk(); SecurityContext context = this.securityContextController.removeSecurityContext(); assertThat(context.getAuthentication()).isInstanceOf(BearerTokenAuthentication.class); BearerTokenAuthentication token = (BearerTokenAuthentication) context.getAuthentication(); assertThat(token.getAuthorities()).isNotEmpty(); assertThat(token.getToken()).isNotNull(); - assertThat(token.getTokenAttributes().get(SUBJECT)).isEqualTo("user"); + assertThat(token.getTokenAttributes().get(OAuth2IntrospectionClaimNames.SUBJECT)).isEqualTo("user"); } @Test public void mockOpaqueTokenWhenAuthoritiesThenBearerTokenAuthentication() { - this.client.mutateWith(mockOpaqueToken().authorities(this.authority1, this.authority2)).get().exchange() - .expectStatus().isOk(); + this.client + .mutateWith( + SecurityMockServerConfigurers.mockOpaqueToken().authorities(this.authority1, this.authority2)) + .get().exchange().expectStatus().isOk(); SecurityContext context = this.securityContextController.removeSecurityContext(); assertThat((List) context.getAuthentication().getAuthorities()).containsOnly(this.authority1, @@ -82,19 +82,22 @@ public class SecurityMockServerConfigurerOpaqueTokenTests extends AbstractMockSe @Test public void mockOpaqueTokenWhenAttributesThenBearerTokenAuthentication() { String sub = new String("my-subject"); - this.client.mutateWith(mockOpaqueToken().attributes(attributes -> attributes.put(SUBJECT, sub))).get() - .exchange().expectStatus().isOk(); + this.client + .mutateWith(SecurityMockServerConfigurers.mockOpaqueToken() + .attributes(attributes -> attributes.put(OAuth2IntrospectionClaimNames.SUBJECT, sub))) + .get().exchange().expectStatus().isOk(); SecurityContext context = this.securityContextController.removeSecurityContext(); assertThat(context.getAuthentication()).isInstanceOf(BearerTokenAuthentication.class); BearerTokenAuthentication token = (BearerTokenAuthentication) context.getAuthentication(); - assertThat(token.getTokenAttributes().get(SUBJECT)).isSameAs(sub); + assertThat(token.getTokenAttributes().get(OAuth2IntrospectionClaimNames.SUBJECT)).isSameAs(sub); } @Test public void mockOpaqueTokenWhenPrincipalThenBearerTokenAuthentication() { - OAuth2AuthenticatedPrincipal principal = active(); - this.client.mutateWith(mockOpaqueToken().principal(principal)).get().exchange().expectStatus().isOk(); + OAuth2AuthenticatedPrincipal principal = TestOAuth2AuthenticatedPrincipals.active(); + this.client.mutateWith(SecurityMockServerConfigurers.mockOpaqueToken().principal(principal)).get().exchange() + .expectStatus().isOk(); SecurityContext context = this.securityContextController.removeSecurityContext(); assertThat(context.getAuthentication()).isInstanceOf(BearerTokenAuthentication.class); @@ -104,25 +107,30 @@ public class SecurityMockServerConfigurerOpaqueTokenTests extends AbstractMockSe @Test public void mockOpaqueTokenWhenPrincipalSpecifiedThenLastCalledTakesPrecedence() { - OAuth2AuthenticatedPrincipal principal = active(a -> a.put("scope", "user")); + OAuth2AuthenticatedPrincipal principal = TestOAuth2AuthenticatedPrincipals.active(a -> a.put("scope", "user")); - this.client.mutateWith(mockOpaqueToken().attributes(a -> a.put(SUBJECT, "foo")).principal(principal)).get() - .exchange().expectStatus().isOk(); + this.client + .mutateWith(SecurityMockServerConfigurers.mockOpaqueToken() + .attributes(a -> a.put(OAuth2IntrospectionClaimNames.SUBJECT, "foo")).principal(principal)) + .get().exchange().expectStatus().isOk(); SecurityContext context = this.securityContextController.removeSecurityContext(); assertThat(context.getAuthentication()).isInstanceOf(BearerTokenAuthentication.class); BearerTokenAuthentication token = (BearerTokenAuthentication) context.getAuthentication(); - assertThat((String) ((OAuth2AuthenticatedPrincipal) token.getPrincipal()).getAttribute(SUBJECT)) - .isEqualTo(principal.getAttribute(SUBJECT)); + assertThat((String) ((OAuth2AuthenticatedPrincipal) token.getPrincipal()) + .getAttribute(OAuth2IntrospectionClaimNames.SUBJECT)) + .isEqualTo(principal.getAttribute(OAuth2IntrospectionClaimNames.SUBJECT)); - this.client.mutateWith(mockOpaqueToken().principal(principal).attributes(a -> a.put(SUBJECT, "bar"))).get() - .exchange().expectStatus().isOk(); + this.client + .mutateWith(SecurityMockServerConfigurers.mockOpaqueToken().principal(principal) + .attributes(a -> a.put(OAuth2IntrospectionClaimNames.SUBJECT, "bar"))) + .get().exchange().expectStatus().isOk(); context = this.securityContextController.removeSecurityContext(); assertThat(context.getAuthentication()).isInstanceOf(BearerTokenAuthentication.class); token = (BearerTokenAuthentication) context.getAuthentication(); - assertThat((String) ((OAuth2AuthenticatedPrincipal) token.getPrincipal()).getAttribute(SUBJECT)) - .isEqualTo("bar"); + assertThat((String) ((OAuth2AuthenticatedPrincipal) token.getPrincipal()) + .getAttribute(OAuth2IntrospectionClaimNames.SUBJECT)).isEqualTo("bar"); } } diff --git a/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersAnnotatedTests.java b/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersAnnotatedTests.java index 480cf1ed63..f5e4425ec6 100644 --- a/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersAnnotatedTests.java +++ b/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersAnnotatedTests.java @@ -32,9 +32,6 @@ import org.springframework.security.web.server.context.SecurityContextServerWebE import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.mockAuthentication; -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.springSecurity; - /** * @author Rob Winch * @since 5.0 @@ -44,7 +41,8 @@ import static org.springframework.security.test.web.reactive.server.SecurityMock public class SecurityMockServerConfigurersAnnotatedTests extends AbstractMockServerConfigurersTests { WebTestClient client = WebTestClient.bindToController(this.controller) - .webFilter(new SecurityContextServerWebExchangeWebFilter()).apply(springSecurity()).configureClient() + .webFilter(new SecurityContextServerWebExchangeWebFilter()) + .apply(SecurityMockServerConfigurers.springSecurity()).configureClient() .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build(); @Test @@ -62,8 +60,9 @@ public class SecurityMockServerConfigurersAnnotatedTests extends AbstractMockSer TestingAuthenticationToken authentication = new TestingAuthenticationToken("authentication", "secret", "ROLE_USER"); this.client = WebTestClient.bindToController(this.controller) - .webFilter(new SecurityContextServerWebExchangeWebFilter()).apply(springSecurity()) - .apply(mockAuthentication(authentication)).configureClient() + .webFilter(new SecurityContextServerWebExchangeWebFilter()) + .apply(SecurityMockServerConfigurers.springSecurity()) + .apply(SecurityMockServerConfigurers.mockAuthentication(authentication)).configureClient() .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build(); this.client.get().exchange().expectStatus().isOk(); @@ -76,7 +75,8 @@ public class SecurityMockServerConfigurersAnnotatedTests extends AbstractMockSer public void withMockUserWhenMutateWithMockPrincipalThenOverridesAnnotation() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("authentication", "secret", "ROLE_USER"); - this.client.mutateWith(mockAuthentication(authentication)).get().exchange().expectStatus().isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.mockAuthentication(authentication)).get().exchange() + .expectStatus().isOk(); this.controller.assertPrincipalIsEqualTo(authentication); } @@ -86,7 +86,8 @@ public class SecurityMockServerConfigurersAnnotatedTests extends AbstractMockSer public void withMockUserWhenMutateWithMockPrincipalAndNoMutateThenOverridesAnnotationAndUsesAnnotation() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("authentication", "secret", "ROLE_USER"); - this.client.mutateWith(mockAuthentication(authentication)).get().exchange().expectStatus().isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.mockAuthentication(authentication)).get().exchange() + .expectStatus().isOk(); this.controller.assertPrincipalIsEqualTo(authentication); @@ -110,8 +111,9 @@ public class SecurityMockServerConfigurersAnnotatedTests extends AbstractMockSer TestingAuthenticationToken authentication = new TestingAuthenticationToken("authentication", "secret", "ROLE_USER"); - ForkJoinPool.commonPool().submit( - () -> this.client.mutateWith(mockAuthentication(authentication)).get().exchange().expectStatus().isOk()) + ForkJoinPool.commonPool() + .submit(() -> this.client.mutateWith(SecurityMockServerConfigurers.mockAuthentication(authentication)) + .get().exchange().expectStatus().isOk()) .join(); this.controller.assertPrincipalIsEqualTo(authentication); diff --git a/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersClassAnnotatedTests.java b/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersClassAnnotatedTests.java index 68857affa6..8699062b6f 100644 --- a/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersClassAnnotatedTests.java +++ b/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersClassAnnotatedTests.java @@ -32,8 +32,6 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.mockUser; -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.springSecurity; /** * @author Rob Winch @@ -45,7 +43,8 @@ import static org.springframework.security.test.web.reactive.server.SecurityMock public class SecurityMockServerConfigurersClassAnnotatedTests extends AbstractMockServerConfigurersTests { WebTestClient client = WebTestClient.bindToController(this.controller) - .webFilter(new SecurityContextServerWebExchangeWebFilter()).apply(springSecurity()).configureClient() + .webFilter(new SecurityContextServerWebExchangeWebFilter()) + .apply(SecurityMockServerConfigurers.springSecurity()).configureClient() .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build(); @Test @@ -69,8 +68,9 @@ public class SecurityMockServerConfigurersClassAnnotatedTests extends AbstractMo @Test public void withMockUserWhenMutateWithThenMustateWithOverrides() { - this.client.mutateWith(mockUser("mutateWith-mockUser")).get().exchange().expectStatus().isOk() - .expectBody(String.class).consumeWith(response -> assertThat(response.getResponseBody()) + this.client.mutateWith(SecurityMockServerConfigurers.mockUser("mutateWith-mockUser")).get().exchange() + .expectStatus().isOk().expectBody(String.class) + .consumeWith(response -> assertThat(response.getResponseBody()) .contains("\"username\":\"mutateWith-mockUser\"")); Principal principal = this.controller.removePrincipal(); diff --git a/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersJwtTests.java b/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersJwtTests.java index 7c64ffeda4..6ae453a237 100644 --- a/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersJwtTests.java +++ b/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersJwtTests.java @@ -37,8 +37,6 @@ import org.springframework.security.web.server.context.SecurityContextServerWebE import org.springframework.test.web.reactive.server.WebTestClient; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.mockJwt; -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.springSecurity; /** * @author Jérôme Wacongne <ch4mp@c4-soft.com> @@ -58,12 +56,12 @@ public class SecurityMockServerConfigurersJwtTests extends AbstractMockServerCon .webFilter(new SecurityContextServerWebExchangeWebFilter()) .argumentResolvers(resolvers -> resolvers .addCustomResolver(new CurrentSecurityContextArgumentResolver(new ReactiveAdapterRegistry()))) - .apply(springSecurity()).configureClient() + .apply(SecurityMockServerConfigurers.springSecurity()).configureClient() .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build(); @Test public void mockJwtWhenUsingDefaultsTheCreatesJwtAuthentication() { - this.client.mutateWith(mockJwt()).get().exchange().expectStatus().isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.mockJwt()).get().exchange().expectStatus().isOk(); SecurityContext context = this.securityContextController.removeSecurityContext(); assertThat(context.getAuthentication()).isInstanceOf(JwtAuthenticationToken.class); @@ -77,7 +75,8 @@ public class SecurityMockServerConfigurersJwtTests extends AbstractMockServerCon @Test public void mockJwtWhenProvidingBuilderConsumerThenProducesJwtAuthentication() { String name = new String("user"); - this.client.mutateWith(mockJwt().jwt(jwt -> jwt.subject(name))).get().exchange().expectStatus().isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.mockJwt().jwt(jwt -> jwt.subject(name))).get().exchange() + .expectStatus().isOk(); SecurityContext context = this.securityContextController.removeSecurityContext(); assertThat(context.getAuthentication()).isInstanceOf(JwtAuthenticationToken.class); @@ -87,8 +86,9 @@ public class SecurityMockServerConfigurersJwtTests extends AbstractMockServerCon @Test public void mockJwtWhenProvidingCustomAuthoritiesThenProducesJwtAuthentication() { - this.client.mutateWith(mockJwt().jwt(jwt -> jwt.claim("scope", "ignored authorities")) - .authorities(this.authority1, this.authority2)).get().exchange().expectStatus().isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.mockJwt() + .jwt(jwt -> jwt.claim("scope", "ignored authorities")).authorities(this.authority1, this.authority2)) + .get().exchange().expectStatus().isOk(); SecurityContext context = this.securityContextController.removeSecurityContext(); assertThat((List) context.getAuthentication().getAuthorities()).containsOnly(this.authority1, @@ -97,8 +97,10 @@ public class SecurityMockServerConfigurersJwtTests extends AbstractMockServerCon @Test public void mockJwtWhenProvidingScopedAuthoritiesThenProducesJwtAuthentication() { - this.client.mutateWith(mockJwt().jwt(jwt -> jwt.claim("scope", "scoped authorities"))).get().exchange() - .expectStatus().isOk(); + this.client + .mutateWith( + SecurityMockServerConfigurers.mockJwt().jwt(jwt -> jwt.claim("scope", "scoped authorities"))) + .get().exchange().expectStatus().isOk(); SecurityContext context = this.securityContextController.removeSecurityContext(); assertThat((List) context.getAuthentication().getAuthorities()).containsOnly( @@ -107,8 +109,11 @@ public class SecurityMockServerConfigurersJwtTests extends AbstractMockServerCon @Test public void mockJwtWhenProvidingGrantedAuthoritiesThenProducesJwtAuthentication() { - this.client.mutateWith(mockJwt().jwt(jwt -> jwt.claim("scope", "ignored authorities")) - .authorities(jwt -> Arrays.asList(this.authority1))).get().exchange().expectStatus().isOk(); + this.client + .mutateWith( + SecurityMockServerConfigurers.mockJwt().jwt(jwt -> jwt.claim("scope", "ignored authorities")) + .authorities(jwt -> Arrays.asList(this.authority1))) + .get().exchange().expectStatus().isOk(); SecurityContext context = this.securityContextController.removeSecurityContext(); assertThat((List) context.getAuthentication().getAuthorities()).containsOnly(this.authority1); @@ -117,7 +122,8 @@ public class SecurityMockServerConfigurersJwtTests extends AbstractMockServerCon @Test public void mockJwtWhenProvidingPreparedJwtThenProducesJwtAuthentication() { Jwt originalToken = TestJwts.jwt().header("header1", "value1").subject("some_user").build(); - this.client.mutateWith(mockJwt().jwt(originalToken)).get().exchange().expectStatus().isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.mockJwt().jwt(originalToken)).get().exchange() + .expectStatus().isOk(); SecurityContext context = this.securityContextController.removeSecurityContext(); assertThat(context.getAuthentication()).isInstanceOf(JwtAuthenticationToken.class); diff --git a/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersOAuth2ClientTests.java b/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersOAuth2ClientTests.java index 0183ef8aaa..ae7b45cd82 100644 --- a/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersOAuth2ClientTests.java +++ b/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersOAuth2ClientTests.java @@ -30,9 +30,11 @@ import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient; import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository; +import org.springframework.security.oauth2.client.registration.TestClientRegistrations; import org.springframework.security.oauth2.client.web.reactive.result.method.annotation.OAuth2AuthorizedClientArgumentResolver; import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository; import org.springframework.security.oauth2.core.OAuth2AccessToken; +import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; import org.springframework.security.web.server.context.SecurityContextServerWebExchangeWebFilter; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.bind.annotation.GetMapping; @@ -47,10 +49,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; -import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration; -import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.noScopes; -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.mockOAuth2Client; -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.springSecurity; @RunWith(MockitoJUnitRunner.class) public class SecurityMockServerConfigurersOAuth2ClientTests extends AbstractMockServerConfigurersTests { @@ -70,7 +68,8 @@ public class SecurityMockServerConfigurersOAuth2ClientTests extends AbstractMock this.client = WebTestClient.bindToController(this.controller) .argumentResolvers(c -> c.addCustomResolver(new OAuth2AuthorizedClientArgumentResolver( this.clientRegistrationRepository, this.authorizedClientRepository))) - .webFilter(new SecurityContextServerWebExchangeWebFilter()).apply(springSecurity()).configureClient() + .webFilter(new SecurityContextServerWebExchangeWebFilter()) + .apply(SecurityMockServerConfigurers.springSecurity()).configureClient() .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build(); } @@ -78,15 +77,15 @@ public class SecurityMockServerConfigurersOAuth2ClientTests extends AbstractMock public void oauth2ClientWhenUsingDefaultsThenException() throws Exception { WebHttpHandlerBuilder builder = WebHttpHandlerBuilder.webHandler(new DispatcherHandler()); - assertThatCode(() -> mockOAuth2Client().beforeServerCreated(builder)) + assertThatCode(() -> SecurityMockServerConfigurers.mockOAuth2Client().beforeServerCreated(builder)) .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("ClientRegistration"); } @Test public void oauth2ClientWhenUsingRegistrationIdThenProducesAuthorizedClient() throws Exception { - this.client.mutateWith(mockOAuth2Client("registration-id")).get().uri("/client").exchange().expectStatus() - .isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Client("registration-id")).get().uri("/client") + .exchange().expectStatus().isOk(); OAuth2AuthorizedClient client = this.controller.authorizedClient; assertThat(client).isNotNull(); @@ -98,10 +97,10 @@ public class SecurityMockServerConfigurersOAuth2ClientTests extends AbstractMock @Test public void oauth2ClientWhenClientRegistrationThenUses() throws Exception { - ClientRegistration clientRegistration = clientRegistration().registrationId("registration-id") - .clientId("client-id").build(); - this.client.mutateWith(mockOAuth2Client().clientRegistration(clientRegistration)).get().uri("/client") - .exchange().expectStatus().isOk(); + ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration() + .registrationId("registration-id").clientId("client-id").build(); + this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Client().clientRegistration(clientRegistration)) + .get().uri("/client").exchange().expectStatus().isOk(); OAuth2AuthorizedClient client = this.controller.authorizedClient; assertThat(client).isNotNull(); @@ -113,7 +112,9 @@ public class SecurityMockServerConfigurersOAuth2ClientTests extends AbstractMock @Test public void oauth2ClientWhenClientRegistrationConsumerThenUses() throws Exception { - this.client.mutateWith(mockOAuth2Client("registration-id").clientRegistration(c -> c.clientId("client-id"))) + this.client + .mutateWith(SecurityMockServerConfigurers.mockOAuth2Client("registration-id") + .clientRegistration(c -> c.clientId("client-id"))) .get().uri("/client").exchange().expectStatus().isOk(); OAuth2AuthorizedClient client = this.controller.authorizedClient; @@ -126,16 +127,20 @@ public class SecurityMockServerConfigurersOAuth2ClientTests extends AbstractMock @Test public void oauth2ClientWhenPrincipalNameThenUses() throws Exception { - this.client.mutateWith(mockOAuth2Client("registration-id").principalName("test-subject")).get().uri("/client") - .exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("test-subject"); + this.client + .mutateWith( + SecurityMockServerConfigurers.mockOAuth2Client("registration-id").principalName("test-subject")) + .get().uri("/client").exchange().expectStatus().isOk().expectBody(String.class) + .isEqualTo("test-subject"); } @Test public void oauth2ClientWhenAccessTokenThenUses() throws Exception { - OAuth2AccessToken accessToken = noScopes(); - this.client.mutateWith(mockOAuth2Client("registration-id").accessToken(accessToken)).get().uri("/client") - .exchange().expectStatus().isOk(); + OAuth2AccessToken accessToken = TestOAuth2AccessTokens.noScopes(); + this.client + .mutateWith(SecurityMockServerConfigurers.mockOAuth2Client("registration-id").accessToken(accessToken)) + .get().uri("/client").exchange().expectStatus().isOk(); OAuth2AuthorizedClient client = this.controller.authorizedClient; assertThat(client).isNotNull(); @@ -146,14 +151,15 @@ public class SecurityMockServerConfigurersOAuth2ClientTests extends AbstractMock @Test public void oauth2ClientWhenUsedOnceThenDoesNotAffectRemainingTests() throws Exception { - this.client.mutateWith(mockOAuth2Client("registration-id")).get().uri("/client").exchange().expectStatus() - .isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Client("registration-id")).get().uri("/client") + .exchange().expectStatus().isOk(); OAuth2AuthorizedClient client = this.controller.authorizedClient; assertThat(client).isNotNull(); assertThat(client.getClientRegistration().getClientId()).isEqualTo("test-client"); - client = new OAuth2AuthorizedClient(clientRegistration().build(), "sub", noScopes()); + client = new OAuth2AuthorizedClient(TestClientRegistrations.clientRegistration().build(), "sub", + TestOAuth2AccessTokens.noScopes()); given(this.authorizedClientRepository.loadAuthorizedClient(eq("registration-id"), any(Authentication.class), any(ServerWebExchange.class))).willReturn(Mono.just(client)); this.client.get().uri("/client").exchange().expectStatus().isOk(); diff --git a/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersOAuth2LoginTests.java b/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersOAuth2LoginTests.java index a07af62850..d967c49cbf 100644 --- a/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersOAuth2LoginTests.java +++ b/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersOAuth2LoginTests.java @@ -44,8 +44,6 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.mockOAuth2Login; -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.springSecurity; @RunWith(MockitoJUnitRunner.class) public class SecurityMockServerConfigurersOAuth2LoginTests extends AbstractMockServerConfigurersTests { @@ -65,13 +63,15 @@ public class SecurityMockServerConfigurersOAuth2LoginTests extends AbstractMockS this.client = WebTestClient.bindToController(this.controller) .argumentResolvers(c -> c.addCustomResolver(new OAuth2AuthorizedClientArgumentResolver( this.clientRegistrationRepository, this.authorizedClientRepository))) - .webFilter(new SecurityContextServerWebExchangeWebFilter()).apply(springSecurity()).configureClient() + .webFilter(new SecurityContextServerWebExchangeWebFilter()) + .apply(SecurityMockServerConfigurers.springSecurity()).configureClient() .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build(); } @Test public void oauth2LoginWhenUsingDefaultsThenProducesDefaultAuthentication() { - this.client.mutateWith(mockOAuth2Login()).get().uri("/token").exchange().expectStatus().isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login()).get().uri("/token").exchange() + .expectStatus().isOk(); OAuth2AuthenticationToken token = this.controller.token; assertThat(token).isNotNull(); @@ -84,7 +84,8 @@ public class SecurityMockServerConfigurersOAuth2LoginTests extends AbstractMockS @Test public void oauth2LoginWhenUsingDefaultsThenProducesDefaultAuthorizedClient() { - this.client.mutateWith(mockOAuth2Login()).get().uri("/client").exchange().expectStatus().isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login()).get().uri("/client").exchange() + .expectStatus().isOk(); OAuth2AuthorizedClient client = this.controller.authorizedClient; assertThat(client).isNotNull(); @@ -95,8 +96,10 @@ public class SecurityMockServerConfigurersOAuth2LoginTests extends AbstractMockS @Test public void oauth2LoginWhenAuthoritiesSpecifiedThenGrantsAccess() { - this.client.mutateWith(mockOAuth2Login().authorities(new SimpleGrantedAuthority("SCOPE_admin"))).get() - .uri("/token").exchange().expectStatus().isOk(); + this.client + .mutateWith(SecurityMockServerConfigurers.mockOAuth2Login() + .authorities(new SimpleGrantedAuthority("SCOPE_admin"))) + .get().uri("/token").exchange().expectStatus().isOk(); OAuth2AuthenticationToken token = this.controller.token; assertThat((Collection) token.getPrincipal().getAuthorities()) @@ -105,8 +108,10 @@ public class SecurityMockServerConfigurersOAuth2LoginTests extends AbstractMockS @Test public void oauth2LoginWhenAttributeSpecifiedThenUserHasAttribute() { - this.client.mutateWith(mockOAuth2Login().attributes(a -> a.put("iss", "https://idp.example.org"))).get() - .uri("/token").exchange().expectStatus().isOk(); + this.client + .mutateWith(SecurityMockServerConfigurers.mockOAuth2Login() + .attributes(a -> a.put("iss", "https://idp.example.org"))) + .get().uri("/token").exchange().expectStatus().isOk(); OAuth2AuthenticationToken token = this.controller.token; assertThat(token.getPrincipal().getAttributes()).containsEntry("iss", "https://idp.example.org"); @@ -117,14 +122,14 @@ public class SecurityMockServerConfigurersOAuth2LoginTests extends AbstractMockS OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.commaSeparatedStringToAuthorityList("SCOPE_read"), Collections.singletonMap("custom-attribute", "test-subject"), "custom-attribute"); - this.client.mutateWith(mockOAuth2Login().oauth2User(oauth2User)).get().uri("/token").exchange().expectStatus() - .isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oauth2User)).get() + .uri("/token").exchange().expectStatus().isOk(); OAuth2AuthenticationToken token = this.controller.token; assertThat(token.getPrincipal().getName()).isEqualTo("test-subject"); - this.client.mutateWith(mockOAuth2Login().oauth2User(oauth2User)).get().uri("/client").exchange().expectStatus() - .isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oauth2User)).get() + .uri("/client").exchange().expectStatus().isOk(); OAuth2AuthorizedClient client = this.controller.authorizedClient; assertThat(client.getPrincipalName()).isEqualTo("test-subject"); @@ -135,14 +140,14 @@ public class SecurityMockServerConfigurersOAuth2LoginTests extends AbstractMockS OAuth2User oauth2User = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("SCOPE_read"), Collections.singletonMap("sub", "subject"), "sub"); - this.client.mutateWith(mockOAuth2Login().attributes(a -> a.put("subject", "foo")).oauth2User(oauth2User)).get() - .uri("/token").exchange().expectStatus().isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().attributes(a -> a.put("subject", "foo")) + .oauth2User(oauth2User)).get().uri("/token").exchange().expectStatus().isOk(); OAuth2AuthenticationToken token = this.controller.token; assertThat(token.getPrincipal().getAttributes()).containsEntry("sub", "subject"); - this.client.mutateWith(mockOAuth2Login().oauth2User(oauth2User).attributes(a -> a.put("sub", "bar"))).get() - .uri("/token").exchange().expectStatus().isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oauth2User) + .attributes(a -> a.put("sub", "bar"))).get().uri("/token").exchange().expectStatus().isOk(); token = this.controller.token; assertThat(token.getPrincipal().getAttributes()).containsEntry("sub", "bar"); diff --git a/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersOidcLoginTests.java b/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersOidcLoginTests.java index 3758384d10..8c6c9c5cce 100644 --- a/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersOidcLoginTests.java +++ b/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersOidcLoginTests.java @@ -36,6 +36,7 @@ import org.springframework.security.oauth2.client.registration.ReactiveClientReg import org.springframework.security.oauth2.client.web.reactive.result.method.annotation.OAuth2AuthorizedClientArgumentResolver; import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository; import org.springframework.security.oauth2.core.oidc.OidcIdToken; +import org.springframework.security.oauth2.core.oidc.TestOidcIdTokens; import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser; import org.springframework.security.oauth2.core.oidc.user.OidcUser; import org.springframework.security.web.server.context.SecurityContextServerWebExchangeWebFilter; @@ -44,10 +45,6 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.oauth2.core.oidc.TestOidcIdTokens.idToken; -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.mockOAuth2Login; -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.mockOidcLogin; -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.springSecurity; @RunWith(MockitoJUnitRunner.class) public class SecurityMockServerConfigurersOidcLoginTests extends AbstractMockServerConfigurersTests { @@ -67,13 +64,15 @@ public class SecurityMockServerConfigurersOidcLoginTests extends AbstractMockSer this.client = WebTestClient.bindToController(this.controller) .argumentResolvers(c -> c.addCustomResolver(new OAuth2AuthorizedClientArgumentResolver( this.clientRegistrationRepository, this.authorizedClientRepository))) - .webFilter(new SecurityContextServerWebExchangeWebFilter()).apply(springSecurity()).configureClient() + .webFilter(new SecurityContextServerWebExchangeWebFilter()) + .apply(SecurityMockServerConfigurers.springSecurity()).configureClient() .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build(); } @Test public void oidcLoginWhenUsingDefaultsThenProducesDefaultAuthentication() { - this.client.mutateWith(mockOidcLogin()).get().uri("/token").exchange().expectStatus().isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.mockOidcLogin()).get().uri("/token").exchange() + .expectStatus().isOk(); OAuth2AuthenticationToken token = this.controller.token; assertThat(token).isNotNull(); @@ -87,7 +86,8 @@ public class SecurityMockServerConfigurersOidcLoginTests extends AbstractMockSer @Test public void oidcLoginWhenUsingDefaultsThenProducesDefaultAuthorizedClient() { - this.client.mutateWith(mockOidcLogin()).get().uri("/client").exchange().expectStatus().isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.mockOidcLogin()).get().uri("/client").exchange() + .expectStatus().isOk(); OAuth2AuthorizedClient client = this.controller.authorizedClient; assertThat(client).isNotNull(); @@ -98,8 +98,10 @@ public class SecurityMockServerConfigurersOidcLoginTests extends AbstractMockSer @Test public void oidcLoginWhenAuthoritiesSpecifiedThenGrantsAccess() { - this.client.mutateWith(mockOidcLogin().authorities(new SimpleGrantedAuthority("SCOPE_admin"))).get() - .uri("/token").exchange().expectStatus().isOk(); + this.client + .mutateWith(SecurityMockServerConfigurers.mockOidcLogin() + .authorities(new SimpleGrantedAuthority("SCOPE_admin"))) + .get().uri("/token").exchange().expectStatus().isOk(); OAuth2AuthenticationToken token = this.controller.token; assertThat((Collection) token.getPrincipal().getAuthorities()) @@ -108,8 +110,10 @@ public class SecurityMockServerConfigurersOidcLoginTests extends AbstractMockSer @Test public void oidcLoginWhenIdTokenSpecifiedThenUserHasClaims() { - this.client.mutateWith(mockOidcLogin().idToken(i -> i.issuer("https://idp.example.org"))).get().uri("/token") - .exchange().expectStatus().isOk(); + this.client + .mutateWith( + SecurityMockServerConfigurers.mockOidcLogin().idToken(i -> i.issuer("https://idp.example.org"))) + .get().uri("/token").exchange().expectStatus().isOk(); OAuth2AuthenticationToken token = this.controller.token; assertThat(token.getPrincipal().getAttributes()).containsEntry("iss", "https://idp.example.org"); @@ -117,8 +121,8 @@ public class SecurityMockServerConfigurersOidcLoginTests extends AbstractMockSer @Test public void oidcLoginWhenUserInfoSpecifiedThenUserHasClaims() throws Exception { - this.client.mutateWith(mockOidcLogin().userInfoToken(u -> u.email("email@email"))).get().uri("/token") - .exchange().expectStatus().isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.mockOidcLogin().userInfoToken(u -> u.email("email@email"))) + .get().uri("/token").exchange().expectStatus().isOk(); OAuth2AuthenticationToken token = this.controller.token; assertThat(token.getPrincipal().getAttributes()).containsEntry("email", "email@email"); @@ -130,14 +134,14 @@ public class SecurityMockServerConfigurersOidcLoginTests extends AbstractMockSer OidcIdToken.withTokenValue("id-token").claim("custom-attribute", "test-subject").build(), "custom-attribute"); - this.client.mutateWith(mockOAuth2Login().oauth2User(oidcUser)).get().uri("/token").exchange().expectStatus() - .isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oidcUser)).get().uri("/token") + .exchange().expectStatus().isOk(); OAuth2AuthenticationToken token = this.controller.token; assertThat(token.getPrincipal().getName()).isEqualTo("test-subject"); - this.client.mutateWith(mockOAuth2Login().oauth2User(oidcUser)).get().uri("/client").exchange().expectStatus() - .isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.mockOAuth2Login().oauth2User(oidcUser)).get() + .uri("/client").exchange().expectStatus().isOk(); OAuth2AuthorizedClient client = this.controller.authorizedClient; assertThat(client.getPrincipalName()).isEqualTo("test-subject"); @@ -146,16 +150,21 @@ public class SecurityMockServerConfigurersOidcLoginTests extends AbstractMockSer // gh-7794 @Test public void oidcLoginWhenOidcUserSpecifiedThenLastCalledTakesPrecedence() throws Exception { - OidcUser oidcUser = new DefaultOidcUser(AuthorityUtils.createAuthorityList("SCOPE_read"), idToken().build()); + OidcUser oidcUser = new DefaultOidcUser(AuthorityUtils.createAuthorityList("SCOPE_read"), + TestOidcIdTokens.idToken().build()); - this.client.mutateWith(mockOidcLogin().idToken(i -> i.subject("foo")).oidcUser(oidcUser)).get().uri("/token") - .exchange().expectStatus().isOk(); + this.client + .mutateWith( + SecurityMockServerConfigurers.mockOidcLogin().idToken(i -> i.subject("foo")).oidcUser(oidcUser)) + .get().uri("/token").exchange().expectStatus().isOk(); OAuth2AuthenticationToken token = this.controller.token; assertThat(token.getPrincipal().getAttributes()).containsEntry("sub", "subject"); - this.client.mutateWith(mockOidcLogin().oidcUser(oidcUser).idToken(i -> i.subject("bar"))).get().uri("/token") - .exchange().expectStatus().isOk(); + this.client + .mutateWith( + SecurityMockServerConfigurers.mockOidcLogin().oidcUser(oidcUser).idToken(i -> i.subject("bar"))) + .get().uri("/token").exchange().expectStatus().isOk(); token = this.controller.token; assertThat(token.getPrincipal().getAttributes()).containsEntry("sub", "bar"); diff --git a/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersTests.java b/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersTests.java index 68354f6021..555d96f2f6 100644 --- a/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersTests.java +++ b/test/src/test/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurersTests.java @@ -31,10 +31,6 @@ import org.springframework.security.web.server.csrf.CsrfWebFilter; import org.springframework.test.web.reactive.server.WebTestClient; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf; -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.mockAuthentication; -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.mockUser; -import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.springSecurity; /** * @author Rob Winch @@ -43,14 +39,16 @@ import static org.springframework.security.test.web.reactive.server.SecurityMock public class SecurityMockServerConfigurersTests extends AbstractMockServerConfigurersTests { WebTestClient client = WebTestClient.bindToController(this.controller) - .webFilter(new CsrfWebFilter(), new SecurityContextServerWebExchangeWebFilter()).apply(springSecurity()) - .configureClient().defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build(); + .webFilter(new CsrfWebFilter(), new SecurityContextServerWebExchangeWebFilter()) + .apply(SecurityMockServerConfigurers.springSecurity()).configureClient() + .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build(); @Test public void mockAuthenticationWhenLocalThenSuccess() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("authentication", "secret", "ROLE_USER"); - this.client.mutateWith(mockAuthentication(authentication)).get().exchange().expectStatus().isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.mockAuthentication(authentication)).get().exchange() + .expectStatus().isOk(); this.controller.assertPrincipalIsEqualTo(authentication); } @@ -59,8 +57,9 @@ public class SecurityMockServerConfigurersTests extends AbstractMockServerConfig TestingAuthenticationToken authentication = new TestingAuthenticationToken("authentication", "secret", "ROLE_USER"); this.client = WebTestClient.bindToController(this.controller) - .webFilter(new SecurityContextServerWebExchangeWebFilter()).apply(springSecurity()) - .apply(mockAuthentication(authentication)).configureClient() + .webFilter(new SecurityContextServerWebExchangeWebFilter()) + .apply(SecurityMockServerConfigurers.springSecurity()) + .apply(SecurityMockServerConfigurers.mockAuthentication(authentication)).configureClient() .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build(); this.client.get().exchange().expectStatus().isOk(); this.controller.assertPrincipalIsEqualTo(authentication); @@ -68,7 +67,7 @@ public class SecurityMockServerConfigurersTests extends AbstractMockServerConfig @Test public void mockUserWhenDefaultsThenSuccess() { - this.client.mutateWith(mockUser()).get().exchange().expectStatus().isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.mockUser()).get().exchange().expectStatus().isOk(); Principal actual = this.controller.removePrincipal(); @@ -78,7 +77,8 @@ public class SecurityMockServerConfigurersTests extends AbstractMockServerConfig @Test public void mockUserWhenGlobalThenSuccess() { this.client = WebTestClient.bindToController(this.controller) - .webFilter(new SecurityContextServerWebExchangeWebFilter()).apply(springSecurity()).apply(mockUser()) + .webFilter(new SecurityContextServerWebExchangeWebFilter()) + .apply(SecurityMockServerConfigurers.springSecurity()).apply(SecurityMockServerConfigurers.mockUser()) .configureClient().defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).build(); this.client.get().exchange().expectStatus().isOk(); @@ -89,7 +89,8 @@ public class SecurityMockServerConfigurersTests extends AbstractMockServerConfig @Test public void mockUserStringWhenLocalThenSuccess() { - this.client.mutateWith(mockUser(this.userBuilder.build().getUsername())).get().exchange().expectStatus().isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.mockUser(this.userBuilder.build().getUsername())).get() + .exchange().expectStatus().isOk(); Principal actual = this.controller.removePrincipal(); @@ -99,8 +100,9 @@ public class SecurityMockServerConfigurersTests extends AbstractMockServerConfig @Test public void mockUserStringWhenCustomThenSuccess() { this.userBuilder = User.withUsername("admin").password("secret").roles("USER", "ADMIN"); - this.client.mutateWith(mockUser("admin").password("secret").roles("USER", "ADMIN")).get().exchange() - .expectStatus().isOk(); + this.client + .mutateWith(SecurityMockServerConfigurers.mockUser("admin").password("secret").roles("USER", "ADMIN")) + .get().exchange().expectStatus().isOk(); Principal actual = this.controller.removePrincipal(); @@ -110,7 +112,8 @@ public class SecurityMockServerConfigurersTests extends AbstractMockServerConfig @Test public void mockUserUserDetailsLocalThenSuccess() { UserDetails userDetails = this.userBuilder.build(); - this.client.mutateWith(mockUser(userDetails)).get().exchange().expectStatus().isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.mockUser(userDetails)).get().exchange().expectStatus() + .isOk(); Principal actual = this.controller.removePrincipal(); @@ -122,14 +125,15 @@ public class SecurityMockServerConfigurersTests extends AbstractMockServerConfig this.client.post().exchange().expectStatus().isEqualTo(HttpStatus.FORBIDDEN).expectBody() .consumeWith(b -> assertThat(new String(b.getResponseBody())).contains("CSRF")); - this.client.mutateWith(csrf()).post().exchange().expectStatus().isOk(); + this.client.mutateWith(SecurityMockServerConfigurers.csrf()).post().exchange().expectStatus().isOk(); } @Test public void csrfWhenGlobalThenDisablesCsrf() { this.client = WebTestClient.bindToController(this.controller).webFilter(new CsrfWebFilter()) - .apply(springSecurity()).apply(csrf()).configureClient().build(); + .apply(SecurityMockServerConfigurers.springSecurity()).apply(SecurityMockServerConfigurers.csrf()) + .configureClient().build(); this.client.get().exchange().expectStatus().isOk(); diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestBuildersFormLoginTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestBuildersFormLoginTests.java index 24b64f990a..fb6ba5b68b 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestBuildersFormLoginTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestBuildersFormLoginTests.java @@ -34,9 +34,9 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.assertj.core.api.Assertions.assertThat; 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.powermock.api.mockito.PowerMockito.when; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; public class SecurityMockMvcRequestBuildersFormLoginTests { @@ -100,7 +100,7 @@ public class SecurityMockMvcRequestBuildersFormLoginTests { @Test public void postProcessorsAreMergedDuringMockMvcPerform() throws Exception { RequestPostProcessor postProcessor = mock(RequestPostProcessor.class); - when(postProcessor.postProcessRequest(any())).thenAnswer(i -> i.getArgument(0)); + given(postProcessor.postProcessRequest(any())).willAnswer(i -> i.getArgument(0)); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new Object()) .defaultRequest(MockMvcRequestBuilders.get("/").with(postProcessor)).build(); diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestBuildersFormLogoutTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestBuildersFormLogoutTests.java index 5739ef9dc4..b339e2a254 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestBuildersFormLogoutTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestBuildersFormLogoutTests.java @@ -34,9 +34,9 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.assertj.core.api.Assertions.assertThat; 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.powermock.api.mockito.PowerMockito.when; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.logout; public class SecurityMockMvcRequestBuildersFormLogoutTests { @@ -93,7 +93,7 @@ public class SecurityMockMvcRequestBuildersFormLogoutTests { @Test public void postProcessorsAreMergedDuringMockMvcPerform() throws Exception { RequestPostProcessor postProcessor = mock(RequestPostProcessor.class); - when(postProcessor.postProcessRequest(any())).thenAnswer(i -> i.getArgument(0)); + given(postProcessor.postProcessRequest(any())).willAnswer(i -> i.getArgument(0)); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new Object()) .defaultRequest(MockMvcRequestBuilders.get("/").with(postProcessor)).build(); diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsAuthenticationTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsAuthenticationTests.java index 73c8dc0544..8481800535 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsAuthenticationTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsAuthenticationTests.java @@ -24,6 +24,7 @@ import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; +import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest; import org.powermock.modules.junit4.PowerMockRunner; @@ -39,8 +40,6 @@ 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.verify; -import static org.powermock.api.mockito.PowerMockito.spy; -import static org.powermock.api.mockito.PowerMockito.when; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; @RunWith(PowerMockRunner.class) @@ -82,8 +81,8 @@ public class SecurityMockMvcRequestPostProcessorsAuthenticationTests { } private void mockWebTestUtils() { - spy(WebTestUtils.class); - when(WebTestUtils.getSecurityContextRepository(this.request)).thenReturn(this.repository); + PowerMockito.spy(WebTestUtils.class); + PowerMockito.when(WebTestUtils.getSecurityContextRepository(this.request)).thenReturn(this.repository); } } diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOAuth2ClientTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOAuth2ClientTests.java index 814f1340ad..8b4444036c 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOAuth2ClientTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOAuth2ClientTests.java @@ -33,8 +33,10 @@ import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient; import org.springframework.security.oauth2.client.registration.ClientRegistration; import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; +import org.springframework.security.oauth2.client.registration.TestClientRegistrations; import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository; import org.springframework.security.oauth2.core.OAuth2AccessToken; +import org.springframework.security.oauth2.core.TestOAuth2AccessTokens; import org.springframework.security.test.context.TestSecurityContextHolder; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -52,8 +54,6 @@ 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.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration; -import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.noScopes; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.oauth2Client; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -109,8 +109,8 @@ public class SecurityMockMvcRequestPostProcessorsOAuth2ClientTests { @Test public void oauth2ClientWhenClientRegistrationThenUses() throws Exception { - ClientRegistration clientRegistration = clientRegistration().registrationId("registration-id") - .clientId("client-id").build(); + ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration() + .registrationId("registration-id").clientId("client-id").build(); this.mvc.perform(get("/client-id").with(oauth2Client().clientRegistration(clientRegistration))) .andExpect(content().string("client-id")); } @@ -131,7 +131,7 @@ public class SecurityMockMvcRequestPostProcessorsOAuth2ClientTests { @Test public void oauth2ClientWhenAccessTokenThenUses() throws Exception { - OAuth2AccessToken accessToken = noScopes(); + OAuth2AccessToken accessToken = TestOAuth2AccessTokens.noScopes(); this.mvc.perform(get("/access-token").with(oauth2Client("registration-id").accessToken(accessToken))) .andExpect(content().string("no-scopes")); } @@ -141,7 +141,8 @@ public class SecurityMockMvcRequestPostProcessorsOAuth2ClientTests { this.mvc.perform(get("/client-id").with(oauth2Client("registration-id"))) .andExpect(content().string("test-client")); - OAuth2AuthorizedClient client = new OAuth2AuthorizedClient(clientRegistration().build(), "sub", noScopes()); + OAuth2AuthorizedClient client = new OAuth2AuthorizedClient(TestClientRegistrations.clientRegistration().build(), + "sub", TestOAuth2AccessTokens.noScopes()); OAuth2AuthorizedClientRepository repository = this.context.getBean(OAuth2AuthorizedClientRepository.class); given(repository.loadAuthorizedClient(eq("registration-id"), any(Authentication.class), any(HttpServletRequest.class))).willReturn(client); diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOAuth2LoginTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOAuth2LoginTests.java index d01a9809c6..e6dd8ea861 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOAuth2LoginTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOAuth2LoginTests.java @@ -37,6 +37,7 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient; import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; +import org.springframework.security.oauth2.client.registration.TestClientRegistrations; import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository; import org.springframework.security.oauth2.core.user.DefaultOAuth2User; import org.springframework.security.oauth2.core.user.OAuth2User; @@ -52,7 +53,6 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import static org.mockito.Mockito.mock; -import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.oauth2Login; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -128,7 +128,8 @@ public class SecurityMockMvcRequestPostProcessorsOAuth2LoginTests { @Test public void oauth2LoginWhenClientRegistrationSpecifiedThenUses() throws Exception { - this.mvc.perform(get("/client-id").with(oauth2Login().clientRegistration(clientRegistration().build()))) + this.mvc.perform(get("/client-id") + .with(oauth2Login().clientRegistration(TestClientRegistrations.clientRegistration().build()))) .andExpect(content().string("client-id")); } diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOidcLoginTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOidcLoginTests.java index efecfc0395..fefe3b5ab3 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOidcLoginTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOidcLoginTests.java @@ -38,6 +38,7 @@ import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2Aut import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository; import org.springframework.security.oauth2.core.oidc.OidcIdToken; +import org.springframework.security.oauth2.core.oidc.TestOidcIdTokens; import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser; import org.springframework.security.oauth2.core.oidc.user.OidcUser; import org.springframework.security.test.context.TestSecurityContextHolder; @@ -53,7 +54,6 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import static org.mockito.Mockito.mock; -import static org.springframework.security.oauth2.core.oidc.TestOidcIdTokens.idToken; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.oidcLogin; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -140,7 +140,8 @@ public class SecurityMockMvcRequestPostProcessorsOidcLoginTests { // gh-7794 @Test public void oidcLoginWhenOidcUserSpecifiedThenLastCalledTakesPrecedence() throws Exception { - OidcUser oidcUser = new DefaultOidcUser(AuthorityUtils.createAuthorityList("SCOPE_read"), idToken().build()); + OidcUser oidcUser = new DefaultOidcUser(AuthorityUtils.createAuthorityList("SCOPE_read"), + TestOidcIdTokens.idToken().build()); this.mvc.perform(get("/id-token/sub").with(oidcLogin().idToken(i -> i.subject("foo")).oidcUser(oidcUser))) .andExpect(status().isOk()).andExpect(content().string("subject")); diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOpaqueTokenTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOpaqueTokenTests.java index 53dd72627f..4acdb63396 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOpaqueTokenTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOpaqueTokenTests.java @@ -33,6 +33,7 @@ import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; +import org.springframework.security.oauth2.core.TestOAuth2AuthenticatedPrincipals; import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -45,9 +46,8 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.powermock.api.mockito.PowerMockito.when; -import static org.springframework.security.oauth2.core.TestOAuth2AuthenticatedPrincipals.active; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.opaqueToken; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -98,8 +98,8 @@ public class SecurityMockMvcRequestPostProcessorsOpaqueTokenTests { public void opaqueTokenWhenPrincipalSpecifiedThenAuthenticationHasPrincipal() throws Exception { Collection authorities = Collections.singleton(new SimpleGrantedAuthority("SCOPE_read")); OAuth2AuthenticatedPrincipal principal = mock(OAuth2AuthenticatedPrincipal.class); - when(principal.getName()).thenReturn("ben"); - when(principal.getAuthorities()).thenReturn(authorities); + given(principal.getName()).willReturn("ben"); + given(principal.getAuthorities()).willReturn(authorities); this.mvc.perform(get("/name").with(opaqueToken().principal(principal))).andExpect(content().string("ben")); } @@ -107,7 +107,7 @@ public class SecurityMockMvcRequestPostProcessorsOpaqueTokenTests { // gh-7800 @Test public void opaqueTokenWhenPrincipalSpecifiedThenLastCalledTakesPrecedence() throws Exception { - OAuth2AuthenticatedPrincipal principal = active(a -> a.put("scope", "user")); + OAuth2AuthenticatedPrincipal principal = TestOAuth2AuthenticatedPrincipals.active(a -> a.put("scope", "user")); this.mvc.perform( get("/opaque-token/sub").with(opaqueToken().attributes(a -> a.put("sub", "foo")).principal(principal))) diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsSecurityContextTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsSecurityContextTests.java index 5a71745175..376287a2a6 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsSecurityContextTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsSecurityContextTests.java @@ -24,6 +24,7 @@ import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; +import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest; import org.powermock.modules.junit4.PowerMockRunner; @@ -38,8 +39,6 @@ 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.verify; -import static org.powermock.api.mockito.PowerMockito.spy; -import static org.powermock.api.mockito.PowerMockito.when; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.securityContext; @RunWith(PowerMockRunner.class) @@ -81,8 +80,8 @@ public class SecurityMockMvcRequestPostProcessorsSecurityContextTests { } private void mockWebTestUtils() { - spy(WebTestUtils.class); - when(WebTestUtils.getSecurityContextRepository(this.request)).thenReturn(this.repository); + PowerMockito.spy(WebTestUtils.class); + PowerMockito.when(WebTestUtils.getSecurityContextRepository(this.request)).thenReturn(this.repository); } } diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsTestSecurityContextTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsTestSecurityContextTests.java index 08f76801c5..68fda69b26 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsTestSecurityContextTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsTestSecurityContextTests.java @@ -22,6 +22,7 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; +import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest; import org.powermock.modules.junit4.PowerMockRunner; @@ -36,8 +37,6 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; -import static org.powermock.api.mockito.PowerMockito.spy; -import static org.powermock.api.mockito.PowerMockito.when; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.testSecurityContext; @RunWith(PowerMockRunner.class) @@ -84,8 +83,8 @@ public class SecurityMockMvcRequestPostProcessorsTestSecurityContextTests { } private void mockWebTestUtils() { - spy(WebTestUtils.class); - when(WebTestUtils.getSecurityContextRepository(this.request)).thenReturn(this.repository); + PowerMockito.spy(WebTestUtils.class); + PowerMockito.when(WebTestUtils.getSecurityContextRepository(this.request)).thenReturn(this.repository); } } diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsUserDetailsTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsUserDetailsTests.java index b3e27f1c96..4f23b5284e 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsUserDetailsTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsUserDetailsTests.java @@ -24,6 +24,7 @@ import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; +import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest; import org.powermock.modules.junit4.PowerMockRunner; @@ -40,8 +41,6 @@ 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.verify; -import static org.powermock.api.mockito.PowerMockito.spy; -import static org.powermock.api.mockito.PowerMockito.when; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; @RunWith(PowerMockRunner.class) @@ -84,8 +83,8 @@ public class SecurityMockMvcRequestPostProcessorsUserDetailsTests { } private void mockWebTestUtils() { - spy(WebTestUtils.class); - when(WebTestUtils.getSecurityContextRepository(this.request)).thenReturn(this.repository); + PowerMockito.spy(WebTestUtils.class); + PowerMockito.when(WebTestUtils.getSecurityContextRepository(this.request)).thenReturn(this.repository); } } diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsUserTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsUserTests.java index 3d3b4266ae..7e3b0c1eab 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsUserTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsUserTests.java @@ -27,6 +27,7 @@ import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; +import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest; import org.powermock.modules.junit4.PowerMockRunner; @@ -43,8 +44,6 @@ 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.verify; -import static org.powermock.api.mockito.PowerMockito.spy; -import static org.powermock.api.mockito.PowerMockito.when; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; @RunWith(PowerMockRunner.class) @@ -141,8 +140,8 @@ public class SecurityMockMvcRequestPostProcessorsUserTests { } private void mockWebTestUtils() { - spy(WebTestUtils.class); - when(WebTestUtils.getSecurityContextRepository(this.request)).thenReturn(this.repository); + PowerMockito.spy(WebTestUtils.class); + PowerMockito.when(WebTestUtils.getSecurityContextRepository(this.request)).thenReturn(this.repository); } } diff --git a/test/src/test/java/org/springframework/security/test/web/servlet/showcase/login/CustomLoginRequestBuilderAuthenticationTests.java b/test/src/test/java/org/springframework/security/test/web/servlet/showcase/login/CustomLoginRequestBuilderAuthenticationTests.java index 7e46f5bcc2..48043ce380 100644 --- a/test/src/test/java/org/springframework/security/test/web/servlet/showcase/login/CustomLoginRequestBuilderAuthenticationTests.java +++ b/test/src/test/java/org/springframework/security/test/web/servlet/showcase/login/CustomLoginRequestBuilderAuthenticationTests.java @@ -28,7 +28,6 @@ import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.provisioning.InMemoryUserDetailsManager; -import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders; import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.FormLoginRequestBuilder; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -38,6 +37,7 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated; import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; @@ -72,7 +72,7 @@ public class CustomLoginRequestBuilderAuthenticationTests { } static FormLoginRequestBuilder login() { - return SecurityMockMvcRequestBuilders.formLogin("/authenticate").userParameter("user").passwordParam("pass"); + return formLogin("/authenticate").userParameter("user").passwordParam("pass"); } @EnableWebSecurity diff --git a/test/src/test/java/org/springframework/security/test/web/support/WebTestUtilsTests.java b/test/src/test/java/org/springframework/security/test/web/support/WebTestUtilsTests.java index bed3c0dc20..9e483e0b9d 100644 --- a/test/src/test/java/org/springframework/security/test/web/support/WebTestUtilsTests.java +++ b/test/src/test/java/org/springframework/security/test/web/support/WebTestUtilsTests.java @@ -42,8 +42,6 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.test.web.support.WebTestUtils.getCsrfTokenRepository; -import static org.springframework.security.test.web.support.WebTestUtils.getSecurityContextRepository; @RunWith(MockitoJUnitRunner.class) public class WebTestUtilsTests { @@ -72,19 +70,22 @@ public class WebTestUtilsTests { @Test public void getCsrfTokenRepositorytNoWac() { - assertThat(getCsrfTokenRepository(this.request)).isInstanceOf(HttpSessionCsrfTokenRepository.class); + assertThat(WebTestUtils.getCsrfTokenRepository(this.request)) + .isInstanceOf(HttpSessionCsrfTokenRepository.class); } @Test public void getCsrfTokenRepositorytNoSecurity() { loadConfig(Config.class); - assertThat(getCsrfTokenRepository(this.request)).isInstanceOf(HttpSessionCsrfTokenRepository.class); + assertThat(WebTestUtils.getCsrfTokenRepository(this.request)) + .isInstanceOf(HttpSessionCsrfTokenRepository.class); } @Test public void getCsrfTokenRepositorytSecurityNoCsrf() { loadConfig(SecurityNoCsrfConfig.class); - assertThat(getCsrfTokenRepository(this.request)).isInstanceOf(HttpSessionCsrfTokenRepository.class); + assertThat(WebTestUtils.getCsrfTokenRepository(this.request)) + .isInstanceOf(HttpSessionCsrfTokenRepository.class); } @Test @@ -92,26 +93,29 @@ public class WebTestUtilsTests { CustomSecurityConfig.CONTEXT_REPO = this.contextRepo; CustomSecurityConfig.CSRF_REPO = this.csrfRepo; loadConfig(CustomSecurityConfig.class); - assertThat(getCsrfTokenRepository(this.request)).isSameAs(this.csrfRepo); + assertThat(WebTestUtils.getCsrfTokenRepository(this.request)).isSameAs(this.csrfRepo); } // getSecurityContextRepository @Test public void getSecurityContextRepositoryNoWac() { - assertThat(getSecurityContextRepository(this.request)).isInstanceOf(HttpSessionSecurityContextRepository.class); + assertThat(WebTestUtils.getSecurityContextRepository(this.request)) + .isInstanceOf(HttpSessionSecurityContextRepository.class); } @Test public void getSecurityContextRepositoryNoSecurity() { loadConfig(Config.class); - assertThat(getSecurityContextRepository(this.request)).isInstanceOf(HttpSessionSecurityContextRepository.class); + assertThat(WebTestUtils.getSecurityContextRepository(this.request)) + .isInstanceOf(HttpSessionSecurityContextRepository.class); } @Test public void getSecurityContextRepositorySecurityNoCsrf() { loadConfig(SecurityNoCsrfConfig.class); - assertThat(getSecurityContextRepository(this.request)).isInstanceOf(HttpSessionSecurityContextRepository.class); + assertThat(WebTestUtils.getSecurityContextRepository(this.request)) + .isInstanceOf(HttpSessionSecurityContextRepository.class); } @Test @@ -119,7 +123,7 @@ public class WebTestUtilsTests { CustomSecurityConfig.CONTEXT_REPO = this.contextRepo; CustomSecurityConfig.CSRF_REPO = this.csrfRepo; loadConfig(CustomSecurityConfig.class); - assertThat(getSecurityContextRepository(this.request)).isSameAs(this.contextRepo); + assertThat(WebTestUtils.getSecurityContextRepository(this.request)).isSameAs(this.contextRepo); } // gh-3343 diff --git a/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationConverter.java b/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationConverter.java index 4ed29678c3..09281ac742 100644 --- a/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationConverter.java +++ b/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationConverter.java @@ -21,6 +21,7 @@ import java.util.Base64; import javax.servlet.http.HttpServletRequest; +import org.springframework.http.HttpHeaders; import org.springframework.security.authentication.AuthenticationDetailsSource; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -29,8 +30,6 @@ import org.springframework.security.web.authentication.WebAuthenticationDetailsS import org.springframework.util.Assert; import org.springframework.util.StringUtils; -import static org.springframework.http.HttpHeaders.AUTHORIZATION; - /** * Converts from a HttpServletRequest to {@link UsernamePasswordAuthenticationToken} that * can be authenticated. Null authentication possible if there was no Authorization header @@ -76,7 +75,7 @@ public class BasicAuthenticationConverter implements AuthenticationConverter { @Override public UsernamePasswordAuthenticationToken convert(HttpServletRequest request) { - String header = request.getHeader(AUTHORIZATION); + String header = request.getHeader(HttpHeaders.AUTHORIZATION); if (header == null) { return null; } diff --git a/web/src/main/java/org/springframework/security/web/csrf/CsrfFilter.java b/web/src/main/java/org/springframework/security/web/csrf/CsrfFilter.java index a780d56ebd..280535b38e 100644 --- a/web/src/main/java/org/springframework/security/web/csrf/CsrfFilter.java +++ b/web/src/main/java/org/springframework/security/web/csrf/CsrfFilter.java @@ -35,8 +35,6 @@ import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; import org.springframework.web.filter.OncePerRequestFilter; -import static java.lang.Boolean.TRUE; - /** *

* Applies @@ -91,7 +89,7 @@ public final class CsrfFilter extends OncePerRequestFilter { @Override protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException { - return TRUE.equals(request.getAttribute(SHOULD_NOT_FILTER)); + return Boolean.TRUE.equals(request.getAttribute(SHOULD_NOT_FILTER)); } @Override @@ -135,7 +133,7 @@ public final class CsrfFilter extends OncePerRequestFilter { } public static void skipRequest(HttpServletRequest request) { - request.setAttribute(SHOULD_NOT_FILTER, TRUE); + request.setAttribute(SHOULD_NOT_FILTER, Boolean.TRUE); } /** diff --git a/web/src/main/java/org/springframework/security/web/server/authentication/AuthenticationConverterServerWebExchangeMatcher.java b/web/src/main/java/org/springframework/security/web/server/authentication/AuthenticationConverterServerWebExchangeMatcher.java index 47f7eb3fdf..951eb75b69 100644 --- a/web/src/main/java/org/springframework/security/web/server/authentication/AuthenticationConverterServerWebExchangeMatcher.java +++ b/web/src/main/java/org/springframework/security/web/server/authentication/AuthenticationConverterServerWebExchangeMatcher.java @@ -23,9 +23,6 @@ import org.springframework.security.web.server.util.matcher.ServerWebExchangeMat import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; -import static org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult.match; -import static org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult.notMatch; - /** * Matches if the {@link ServerAuthenticationConverter} can convert a * {@link ServerWebExchange} to an {@link Authentication}. @@ -46,8 +43,8 @@ public final class AuthenticationConverterServerWebExchangeMatcher implements Se @Override public Mono matches(ServerWebExchange exchange) { - return this.serverAuthenticationConverter.convert(exchange).flatMap(a -> match()).onErrorResume(e -> notMatch()) - .switchIfEmpty(notMatch()); + return this.serverAuthenticationConverter.convert(exchange).flatMap(a -> MatchResult.match()) + .onErrorResume(e -> MatchResult.notMatch()).switchIfEmpty(MatchResult.notMatch()); } } diff --git a/web/src/main/java/org/springframework/security/web/server/csrf/CsrfWebFilter.java b/web/src/main/java/org/springframework/security/web/server/csrf/CsrfWebFilter.java index 007b205128..8bdab6fa1f 100644 --- a/web/src/main/java/org/springframework/security/web/server/csrf/CsrfWebFilter.java +++ b/web/src/main/java/org/springframework/security/web/server/csrf/CsrfWebFilter.java @@ -36,8 +36,6 @@ import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; -import static java.lang.Boolean.TRUE; - /** *

* Applies @@ -114,7 +112,7 @@ public class CsrfWebFilter implements WebFilter { @Override public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { - if (TRUE.equals(exchange.getAttribute(SHOULD_NOT_FILTER))) { + if (Boolean.TRUE.equals(exchange.getAttribute(SHOULD_NOT_FILTER))) { return chain.filter(exchange).then(Mono.empty()); } @@ -126,7 +124,7 @@ public class CsrfWebFilter implements WebFilter { } public static void skipExchange(ServerWebExchange exchange) { - exchange.getAttributes().put(SHOULD_NOT_FILTER, TRUE); + exchange.getAttributes().put(SHOULD_NOT_FILTER, Boolean.TRUE); } private Mono validateToken(ServerWebExchange exchange) { diff --git a/web/src/main/java/org/springframework/security/web/server/transport/HttpsRedirectWebFilter.java b/web/src/main/java/org/springframework/security/web/server/transport/HttpsRedirectWebFilter.java index 57c88ae447..94ba6af9f6 100644 --- a/web/src/main/java/org/springframework/security/web/server/transport/HttpsRedirectWebFilter.java +++ b/web/src/main/java/org/springframework/security/web/server/transport/HttpsRedirectWebFilter.java @@ -25,14 +25,13 @@ import org.springframework.security.web.PortMapperImpl; import org.springframework.security.web.server.DefaultServerRedirectStrategy; import org.springframework.security.web.server.ServerRedirectStrategy; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; +import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; import org.springframework.web.util.UriComponentsBuilder; -import static org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers.anyExchange; - /** * Redirects any non-HTTPS request to its HTTPS equivalent. * @@ -48,7 +47,7 @@ public final class HttpsRedirectWebFilter implements WebFilter { private PortMapper portMapper = new PortMapperImpl(); - private ServerWebExchangeMatcher requiresHttpsRedirectMatcher = anyExchange(); + private ServerWebExchangeMatcher requiresHttpsRedirectMatcher = ServerWebExchangeMatchers.anyExchange(); private final ServerRedirectStrategy redirectStrategy = new DefaultServerRedirectStrategy(); diff --git a/web/src/test/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServicesTests.java b/web/src/test/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServicesTests.java index 0f4608bee7..516dba5a08 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServicesTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServicesTests.java @@ -40,9 +40,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.DEFAULT_PARAMETER; -import static org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY; -import static org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.TWO_WEEKS_S; /** * Tests @@ -110,7 +107,7 @@ public class TokenBasedRememberMeServicesTests { Authentication result = this.services.autoLogin(new MockHttpServletRequest(), response); assertThat(result).isNull(); // No cookie set - assertThat(response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull(); + assertThat(response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull(); } @Test @@ -123,27 +120,28 @@ public class TokenBasedRememberMeServicesTests { Authentication result = this.services.autoLogin(request, response); assertThat(result).isNull(); - assertThat(response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull(); + assertThat(response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY)).isNull(); } @Test public void autoLoginReturnsNullForExpiredCookieAndClearsCookie() { - Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForToken( - System.currentTimeMillis() - 1000000, "someone", "password", "key")); + Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, + generateCorrectCookieContentForToken(System.currentTimeMillis() - 1000000, "someone", "password", + "key")); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(cookie); MockHttpServletResponse response = new MockHttpServletResponse(); assertThat(this.services.autoLogin(request, response)).isNull(); - Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); + Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(returnedCookie).isNotNull(); assertThat(returnedCookie.getMaxAge()).isZero(); } @Test public void autoLoginReturnsNullAndClearsCookieIfMissingThreeTokensInCookieValue() { - Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, + Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, new String(Base64.encodeBase64("x".getBytes()))); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(cookie); @@ -151,21 +149,22 @@ public class TokenBasedRememberMeServicesTests { MockHttpServletResponse response = new MockHttpServletResponse(); assertThat(this.services.autoLogin(request, response)).isNull(); - Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); + Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(returnedCookie).isNotNull(); assertThat(returnedCookie.getMaxAge()).isZero(); } @Test public void autoLoginClearsNonBase64EncodedCookie() { - Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, "NOT_BASE_64_ENCODED"); + Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, + "NOT_BASE_64_ENCODED"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(cookie); MockHttpServletResponse response = new MockHttpServletResponse(); assertThat(this.services.autoLogin(request, response)).isNull(); - Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); + Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(returnedCookie).isNotNull(); assertThat(returnedCookie.getMaxAge()).isZero(); } @@ -173,8 +172,9 @@ public class TokenBasedRememberMeServicesTests { @Test public void autoLoginClearsCookieIfSignatureBlocksDoesNotMatchExpectedValue() { udsWillReturnUser(); - Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForToken( - System.currentTimeMillis() + 1000000, "someone", "password", "WRONG_KEY")); + Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, + generateCorrectCookieContentForToken(System.currentTimeMillis() + 1000000, "someone", "password", + "WRONG_KEY")); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(cookie); @@ -182,14 +182,14 @@ public class TokenBasedRememberMeServicesTests { assertThat(this.services.autoLogin(request, response)).isNull(); - Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); + Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(returnedCookie).isNotNull(); assertThat(returnedCookie.getMaxAge()).isZero(); } @Test public void autoLoginClearsCookieIfTokenDoesNotContainANumberInCookieValue() { - Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, + Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, new String(Base64.encodeBase64("username:NOT_A_NUMBER:signature".getBytes()))); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(cookie); @@ -197,7 +197,7 @@ public class TokenBasedRememberMeServicesTests { MockHttpServletResponse response = new MockHttpServletResponse(); assertThat(this.services.autoLogin(request, response)).isNull(); - Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); + Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(returnedCookie).isNotNull(); assertThat(returnedCookie.getMaxAge()).isZero(); } @@ -205,8 +205,9 @@ public class TokenBasedRememberMeServicesTests { @Test public void autoLoginClearsCookieIfUserNotFound() { udsWillThrowNotFound(); - Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForToken( - System.currentTimeMillis() + 1000000, "someone", "password", "key")); + Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, + generateCorrectCookieContentForToken(System.currentTimeMillis() + 1000000, "someone", "password", + "key")); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(cookie); @@ -214,7 +215,7 @@ public class TokenBasedRememberMeServicesTests { assertThat(this.services.autoLogin(request, response)).isNull(); - Cookie returnedCookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); + Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(returnedCookie).isNotNull(); assertThat(returnedCookie.getMaxAge()).isZero(); } @@ -222,8 +223,9 @@ public class TokenBasedRememberMeServicesTests { @Test(expected = IllegalArgumentException.class) public void autoLoginClearsCookieIfUserServiceMisconfigured() { udsWillReturnNull(); - Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForToken( - System.currentTimeMillis() + 1000000, "someone", "password", "key")); + Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, + generateCorrectCookieContentForToken(System.currentTimeMillis() + 1000000, "someone", "password", + "key")); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(cookie); @@ -235,8 +237,9 @@ public class TokenBasedRememberMeServicesTests { @Test public void autoLoginWithValidTokenAndUserSucceeds() { udsWillReturnUser(); - Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, generateCorrectCookieContentForToken( - System.currentTimeMillis() + 1000000, "someone", "password", "key")); + Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, + generateCorrectCookieContentForToken(System.currentTimeMillis() + 1000000, "someone", "password", + "key")); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(cookie); @@ -254,7 +257,7 @@ public class TokenBasedRememberMeServicesTests { assertThat(this.services.getKey()).isEqualTo("key"); - assertThat(this.services.getParameter()).isEqualTo(DEFAULT_PARAMETER); + assertThat(this.services.getParameter()).isEqualTo(AbstractRememberMeServices.DEFAULT_PARAMETER); this.services.setParameter("some_param"); assertThat(this.services.getParameter()).isEqualTo("some_param"); @@ -268,7 +271,7 @@ public class TokenBasedRememberMeServicesTests { MockHttpServletResponse response = new MockHttpServletResponse(); this.services.loginFail(request, response); - Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); + Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(cookie).isNotNull(); assertThat(cookie.getMaxAge()).isZero(); } @@ -278,12 +281,12 @@ public class TokenBasedRememberMeServicesTests { TokenBasedRememberMeServices services = new TokenBasedRememberMeServices("key", new AbstractRememberMeServicesTests.MockUserDetailsService(null, false)); MockHttpServletRequest request = new MockHttpServletRequest(); - request.addParameter(DEFAULT_PARAMETER, "false"); + request.addParameter(AbstractRememberMeServices.DEFAULT_PARAMETER, "false"); MockHttpServletResponse response = new MockHttpServletResponse(); services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password", "ROLE_ABC")); - Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); + Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(cookie).isNull(); } @@ -298,7 +301,7 @@ public class TokenBasedRememberMeServicesTests { this.services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password", "ROLE_ABC")); - Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); + Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); String expiryTime = this.services.decodeCookie(cookie.getValue())[1]; long expectedExpiryTime = 1000L * 500000000; expectedExpiryTime += System.currentTimeMillis(); @@ -318,7 +321,7 @@ public class TokenBasedRememberMeServicesTests { this.services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password", "ROLE_ABC")); - Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); + Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(cookie).isNotNull(); assertThat(cookie.getMaxAge()).isEqualTo(this.services.getTokenValiditySeconds()); assertThat(Base64.isArrayByteBase64(cookie.getValue().getBytes())).isTrue(); @@ -336,18 +339,18 @@ public class TokenBasedRememberMeServicesTests { @Test public void negativeValidityPeriodIsSetOnCookieButExpiryTimeRemainsAtTwoWeeks() { MockHttpServletRequest request = new MockHttpServletRequest(); - request.addParameter(DEFAULT_PARAMETER, "true"); + request.addParameter(AbstractRememberMeServices.DEFAULT_PARAMETER, "true"); MockHttpServletResponse response = new MockHttpServletResponse(); this.services.setTokenValiditySeconds(-1); this.services.loginSuccess(request, response, new TestingAuthenticationToken("someone", "password", "ROLE_ABC")); - Cookie cookie = response.getCookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); + Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY); assertThat(cookie).isNotNull(); // Check the expiry time is within 50ms of two weeks from current time assertThat(determineExpiryTimeFromBased64EncodedToken(cookie.getValue()) - - System.currentTimeMillis() > TWO_WEEKS_S - 50).isTrue(); + - System.currentTimeMillis() > AbstractRememberMeServices.TWO_WEEKS_S - 50).isTrue(); assertThat(cookie.getMaxAge()).isEqualTo(-1); assertThat(Base64.isArrayByteBase64(cookie.getValue().getBytes())).isTrue(); } diff --git a/web/src/test/java/org/springframework/security/web/authentication/ui/DefaultLogoutPageGeneratingFilterTests.java b/web/src/test/java/org/springframework/security/web/authentication/ui/DefaultLogoutPageGeneratingFilterTests.java index 0036813bd4..ea25312591 100644 --- a/web/src/test/java/org/springframework/security/web/authentication/ui/DefaultLogoutPageGeneratingFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/authentication/ui/DefaultLogoutPageGeneratingFilterTests.java @@ -23,7 +23,7 @@ import org.junit.Test; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import static org.hamcrest.core.StringContains.containsString; +import static org.hamcrest.CoreMatchers.containsString; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; diff --git a/web/src/test/java/org/springframework/security/web/context/AbstractSecurityWebApplicationInitializerTests.java b/web/src/test/java/org/springframework/security/web/context/AbstractSecurityWebApplicationInitializerTests.java index fdaa0cca8d..087653ce2e 100644 --- a/web/src/test/java/org/springframework/security/web/context/AbstractSecurityWebApplicationInitializerTests.java +++ b/web/src/test/java/org/springframework/security/web/context/AbstractSecurityWebApplicationInitializerTests.java @@ -40,11 +40,11 @@ import static org.assertj.core.api.Assertions.assertThatCode; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doNothing; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willDoNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.powermock.api.mockito.PowerMockito.when; /** * @author Rob Winch @@ -61,7 +61,7 @@ public class AbstractSecurityWebApplicationInitializerTests { FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); ArgumentCaptor proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); - when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration); + given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); new AbstractSecurityWebApplicationInitializer() { }.onStartup(context); @@ -80,7 +80,7 @@ public class AbstractSecurityWebApplicationInitializerTests { ArgumentCaptor proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); - when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration); + given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); new AbstractSecurityWebApplicationInitializer(MyRootConfiguration.class) { }.onStartup(context); @@ -99,7 +99,7 @@ public class AbstractSecurityWebApplicationInitializerTests { ArgumentCaptor proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); - when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration); + given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); new AbstractSecurityWebApplicationInitializer() { @Override @@ -122,7 +122,7 @@ public class AbstractSecurityWebApplicationInitializerTests { ArgumentCaptor proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); - when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration); + given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); new AbstractSecurityWebApplicationInitializer() { @Override @@ -146,7 +146,7 @@ public class AbstractSecurityWebApplicationInitializerTests { ArgumentCaptor proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); - when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration); + given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); new AbstractSecurityWebApplicationInitializer() { @Override @@ -184,9 +184,9 @@ public class AbstractSecurityWebApplicationInitializerTests { ArgumentCaptor proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); - when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration); - when(context.addFilter(anyString(), eq(filter1))).thenReturn(registration); - when(context.addFilter(anyString(), eq(filter2))).thenReturn(registration); + given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); + given(context.addFilter(anyString(), eq(filter1))).willReturn(registration); + given(context.addFilter(anyString(), eq(filter2))).willReturn(registration); new AbstractSecurityWebApplicationInitializer() { @Override @@ -212,7 +212,7 @@ public class AbstractSecurityWebApplicationInitializerTests { ArgumentCaptor proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); - when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration); + given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() { @Override @@ -235,7 +235,7 @@ public class AbstractSecurityWebApplicationInitializerTests { ArgumentCaptor proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); - when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration); + given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() { @Override @@ -256,8 +256,8 @@ public class AbstractSecurityWebApplicationInitializerTests { ArgumentCaptor proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); - when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration); - when(context.addFilter(anyString(), eq(filter))).thenReturn(registration); + given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); + given(context.addFilter(anyString(), eq(filter))).willReturn(registration); assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() { @Override @@ -279,9 +279,9 @@ public class AbstractSecurityWebApplicationInitializerTests { ArgumentCaptor proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); - when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration); - when(context.addFilter(anyString(), eq(filter1))).thenReturn(registration); - when(context.addFilter(anyString(), eq(filter2))).thenReturn(registration); + given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); + given(context.addFilter(anyString(), eq(filter1))).willReturn(registration); + given(context.addFilter(anyString(), eq(filter2))).willReturn(registration); new AbstractSecurityWebApplicationInitializer() { @Override @@ -305,7 +305,7 @@ public class AbstractSecurityWebApplicationInitializerTests { ArgumentCaptor proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); - when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration); + given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() { @Override @@ -328,7 +328,7 @@ public class AbstractSecurityWebApplicationInitializerTests { ArgumentCaptor proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); - when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration); + given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() { @Override @@ -349,8 +349,8 @@ public class AbstractSecurityWebApplicationInitializerTests { ArgumentCaptor proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); - when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration); - when(context.addFilter(anyString(), eq(filter))).thenReturn(registration); + given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); + given(context.addFilter(anyString(), eq(filter))).willReturn(registration); assertThatCode(() -> new AbstractSecurityWebApplicationInitializer() { @Override @@ -369,12 +369,12 @@ public class AbstractSecurityWebApplicationInitializerTests { FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); ArgumentCaptor proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); - when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration); + given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); ArgumentCaptor> modesCaptor = ArgumentCaptor .forClass(new HashSet() { }.getClass()); - doNothing().when(context).setSessionTrackingModes(modesCaptor.capture()); + willDoNothing().given(context).setSessionTrackingModes(modesCaptor.capture()); new AbstractSecurityWebApplicationInitializer() { }.onStartup(context); @@ -392,12 +392,12 @@ public class AbstractSecurityWebApplicationInitializerTests { FilterRegistration.Dynamic registration = mock(FilterRegistration.Dynamic.class); ArgumentCaptor proxyCaptor = ArgumentCaptor.forClass(DelegatingFilterProxy.class); - when(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).thenReturn(registration); + given(context.addFilter(eq("springSecurityFilterChain"), proxyCaptor.capture())).willReturn(registration); ArgumentCaptor> modesCaptor = ArgumentCaptor .forClass(new HashSet() { }.getClass()); - doNothing().when(context).setSessionTrackingModes(modesCaptor.capture()); + willDoNothing().given(context).setSessionTrackingModes(modesCaptor.capture()); new AbstractSecurityWebApplicationInitializer() { @Override diff --git a/web/src/test/java/org/springframework/security/web/context/HttpSessionSecurityContextRepositoryTests.java b/web/src/test/java/org/springframework/security/web/context/HttpSessionSecurityContextRepositoryTests.java index 4d0927b4e2..f8e06e9c5e 100644 --- a/web/src/test/java/org/springframework/security/web/context/HttpSessionSecurityContextRepositoryTests.java +++ b/web/src/test/java/org/springframework/security/web/context/HttpSessionSecurityContextRepositoryTests.java @@ -45,12 +45,11 @@ import org.springframework.security.core.context.SecurityContextHolder; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.when; -import static org.springframework.security.web.context.HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY; /** * @author Luke Taylor @@ -153,7 +152,7 @@ public class HttpSessionSecurityContextRepositoryTests { SecurityContext ctx = SecurityContextHolder.getContext(); ctx.setAuthentication(this.testToken); HttpSession session = mock(HttpSession.class); - when(session.getAttribute(SPRING_SECURITY_CONTEXT_KEY)).thenReturn(ctx); + given(session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)).willReturn(ctx); request.setSession(session); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse()); assertThat(repo.loadContext(holder)).isSameAs(ctx); @@ -164,7 +163,7 @@ public class HttpSessionSecurityContextRepositoryTests { repo.saveContext(ctx, holder.getRequest(), holder.getResponse()); // Must be called even though the value in the local VM is already the same - verify(session).setAttribute(SPRING_SECURITY_CONTEXT_KEY, ctx); + verify(session).setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, ctx); } @Test @@ -172,7 +171,8 @@ public class HttpSessionSecurityContextRepositoryTests { HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); SecurityContextHolder.getContext().setAuthentication(this.testToken); - request.getSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY, "NotASecurityContextInstance"); + request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, + "NotASecurityContextInstance"); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContext context = repo.loadContext(holder); @@ -192,7 +192,8 @@ public class HttpSessionSecurityContextRepositoryTests { context.setAuthentication(this.testToken); repo.saveContext(context, holder.getRequest(), holder.getResponse()); assertThat(request.getSession(false)).isNotNull(); - assertThat(request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isEqualTo(context); + assertThat(request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)) + .isEqualTo(context); } @Test @@ -328,7 +329,7 @@ public class HttpSessionSecurityContextRepositoryTests { MockHttpServletRequest request = new MockHttpServletRequest(); HttpServletResponse response = mock(HttpServletResponse.class); ServletOutputStream outputstream = mock(ServletOutputStream.class); - when(response.getOutputStream()).thenReturn(outputstream); + given(response.getOutputStream()).willReturn(outputstream); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContextHolder.setContext(repo.loadContext(holder)); SecurityContextHolder.getContext().setAuthentication(this.testToken); @@ -344,7 +345,7 @@ public class HttpSessionSecurityContextRepositoryTests { MockHttpServletRequest request = new MockHttpServletRequest(); HttpServletResponse response = mock(HttpServletResponse.class); ServletOutputStream outputstream = mock(ServletOutputStream.class); - when(response.getOutputStream()).thenReturn(outputstream); + given(response.getOutputStream()).willReturn(outputstream); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContextHolder.setContext(repo.loadContext(holder)); SecurityContextHolder.getContext().setAuthentication(this.testToken); @@ -387,13 +388,15 @@ public class HttpSessionSecurityContextRepositoryTests { MockHttpServletRequest request = new MockHttpServletRequest(); SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext(); ctxInSession.setAuthentication(this.testToken); - request.getSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY, ctxInSession); + request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, + ctxInSession); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse()); repo.loadContext(holder); SecurityContextHolder.getContext() .setAuthentication(new AnonymousAuthenticationToken("x", "x", this.testToken.getAuthorities())); repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); - assertThat(request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isNull(); + assertThat(request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)) + .isNull(); } @Test @@ -420,11 +423,13 @@ public class HttpSessionSecurityContextRepositoryTests { repo.loadContext(holder); SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext(); ctxInSession.setAuthentication(this.testToken); - request.getSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY, ctxInSession); + request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, + ctxInSession); SecurityContextHolder.getContext().setAuthentication( new AnonymousAuthenticationToken("x", "x", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"))); repo.saveContext(SecurityContextHolder.getContext(), holder.getRequest(), holder.getResponse()); - assertThat(ctxInSession).isSameAs(request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)); + assertThat(ctxInSession).isSameAs( + request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)); } // SEC-3070 @@ -434,7 +439,8 @@ public class HttpSessionSecurityContextRepositoryTests { MockHttpServletRequest request = new MockHttpServletRequest(); SecurityContext ctxInSession = SecurityContextHolder.createEmptyContext(); ctxInSession.setAuthentication(this.testToken); - request.getSession().setAttribute(SPRING_SECURITY_CONTEXT_KEY, ctxInSession); + request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, + ctxInSession); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, new MockHttpServletResponse()); repo.loadContext(holder); @@ -442,7 +448,8 @@ public class HttpSessionSecurityContextRepositoryTests { ctxInSession.setAuthentication(null); repo.saveContext(ctxInSession, holder.getRequest(), holder.getResponse()); - assertThat(request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isNull(); + assertThat(request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)) + .isNull(); } @Test @@ -527,7 +534,8 @@ public class HttpSessionSecurityContextRepositoryTests { new HttpServletResponseWrapper(holder.getResponse())); assertThat(request.getSession(false)).isNotNull(); - assertThat(request.getSession().getAttribute(SPRING_SECURITY_CONTEXT_KEY)).isEqualTo(context); + assertThat(request.getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY)) + .isEqualTo(context); } @Test(expected = IllegalStateException.class) diff --git a/web/src/test/java/org/springframework/security/web/header/writers/ClearSiteDataHeaderWriterTests.java b/web/src/test/java/org/springframework/security/web/header/writers/ClearSiteDataHeaderWriterTests.java index 46be30a595..4b9b83589b 100644 --- a/web/src/test/java/org/springframework/security/web/header/writers/ClearSiteDataHeaderWriterTests.java +++ b/web/src/test/java/org/springframework/security/web/header/writers/ClearSiteDataHeaderWriterTests.java @@ -23,12 +23,9 @@ import org.junit.rules.ExpectedException; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.CACHE; -import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.COOKIES; -import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.EXECUTION_CONTEXTS; -import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.STORAGE; /** * @author Rafiullah Hamedy @@ -64,7 +61,7 @@ public class ClearSiteDataHeaderWriterTests { @Test public void writeHeaderWhenRequestNotSecureThenHeaderIsNotPresent() { this.request.setSecure(false); - ClearSiteDataHeaderWriter headerWriter = new ClearSiteDataHeaderWriter(CACHE); + ClearSiteDataHeaderWriter headerWriter = new ClearSiteDataHeaderWriter(Directive.CACHE); headerWriter.writeHeaders(this.request, this.response); assertThat(this.response.getHeader(HEADER_NAME)).isNull(); @@ -72,7 +69,7 @@ public class ClearSiteDataHeaderWriterTests { @Test public void writeHeaderWhenRequestIsSecureThenHeaderValueMatchesPassedSource() { - ClearSiteDataHeaderWriter headerWriter = new ClearSiteDataHeaderWriter(STORAGE); + ClearSiteDataHeaderWriter headerWriter = new ClearSiteDataHeaderWriter(Directive.STORAGE); headerWriter.writeHeaders(this.request, this.response); assertThat(this.response.getHeader(HEADER_NAME)).isEqualTo("\"storage\""); @@ -80,8 +77,8 @@ public class ClearSiteDataHeaderWriterTests { @Test public void writeHeaderWhenRequestIsSecureThenHeaderValueMatchesPassedSources() { - ClearSiteDataHeaderWriter headerWriter = new ClearSiteDataHeaderWriter(CACHE, COOKIES, STORAGE, - EXECUTION_CONTEXTS); + ClearSiteDataHeaderWriter headerWriter = new ClearSiteDataHeaderWriter(Directive.CACHE, Directive.COOKIES, + Directive.STORAGE, Directive.EXECUTION_CONTEXTS); headerWriter.writeHeaders(this.request, this.response); assertThat(this.response.getHeader(HEADER_NAME)) diff --git a/web/src/test/java/org/springframework/security/web/method/ResolvableMethod.java b/web/src/test/java/org/springframework/security/web/method/ResolvableMethod.java index 37fe725548..eebbc02be4 100644 --- a/web/src/test/java/org/springframework/security/web/method/ResolvableMethod.java +++ b/web/src/test/java/org/springframework/security/web/method/ResolvableMethod.java @@ -27,6 +27,7 @@ import java.util.Set; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.Supplier; +import java.util.stream.Collectors; import org.aopalliance.intercept.MethodInterceptor; import org.apache.commons.logging.Log; @@ -54,8 +55,6 @@ import org.springframework.util.ObjectUtils; import org.springframework.util.ReflectionUtils; import org.springframework.web.bind.annotation.ValueConstants; -import static java.util.stream.Collectors.joining; - /** * Convenience class to resolve method parameters from hints. * @@ -211,13 +210,14 @@ public final class ResolvableMethod { private String formatMethod() { return this.method().getName() + Arrays.stream(this.method.getParameters()).map(this::formatParameter) - .collect(joining(",\n\t", "(\n\t", "\n)")); + .collect(Collectors.joining(",\n\t", "(\n\t", "\n)")); } private String formatParameter(Parameter param) { Annotation[] annot = param.getAnnotations(); return annot.length > 0 - ? Arrays.stream(annot).map(this::formatAnnotation).collect(joining(",", "[", "]")) + " " + param + ? Arrays.stream(annot).map(this::formatAnnotation).collect(Collectors.joining(",", "[", "]")) + " " + + param : param.toString(); } @@ -413,8 +413,8 @@ public final class ResolvableMethod { } private String formatMethods(Set methods) { - return "\nMatched:\n" - + methods.stream().map(Method::toGenericString).collect(joining(",\n\t", "[\n\t", "\n]")); + return "\nMatched:\n" + methods.stream().map(Method::toGenericString) + .collect(Collectors.joining(",\n\t", "[\n\t", "\n]")); } public ResolvableMethod mockCall(Consumer invoker) { @@ -490,7 +490,8 @@ public final class ResolvableMethod { } private String formatFilters() { - return this.filters.stream().map(Object::toString).collect(joining(",\n\t\t", "[\n\t\t", "\n\t]")); + return this.filters.stream().map(Object::toString) + .collect(Collectors.joining(",\n\t\t", "[\n\t\t", "\n\t]")); } } diff --git a/web/src/test/java/org/springframework/security/web/reactive/result/view/CsrfRequestDataValueProcessorTests.java b/web/src/test/java/org/springframework/security/web/reactive/result/view/CsrfRequestDataValueProcessorTests.java index 439292d034..fbaf87fa7f 100644 --- a/web/src/test/java/org/springframework/security/web/reactive/result/view/CsrfRequestDataValueProcessorTests.java +++ b/web/src/test/java/org/springframework/security/web/reactive/result/view/CsrfRequestDataValueProcessorTests.java @@ -31,7 +31,6 @@ import org.springframework.security.web.server.csrf.DefaultCsrfToken; import org.springframework.util.ReflectionUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.security.web.reactive.result.view.CsrfRequestDataValueProcessor.DEFAULT_CSRF_ATTR_NAME; /** * @author Rob Winch @@ -50,7 +49,7 @@ public class CsrfRequestDataValueProcessorTests { @Before public void setup() { this.expected.put(this.token.getParameterName(), this.token.getToken()); - this.exchange.getAttributes().put(DEFAULT_CSRF_ATTR_NAME, this.token); + this.exchange.getAttributes().put(CsrfRequestDataValueProcessor.DEFAULT_CSRF_ATTR_NAME, this.token); } @Test @@ -120,7 +119,7 @@ public class CsrfRequestDataValueProcessorTests { @Test public void createGetExtraHiddenFieldsHasCsrfToken() { CsrfToken token = new DefaultCsrfToken("1", "a", "b"); - this.exchange.getAttributes().put(DEFAULT_CSRF_ATTR_NAME, token); + this.exchange.getAttributes().put(CsrfRequestDataValueProcessor.DEFAULT_CSRF_ATTR_NAME, token); Map expected = new HashMap<>(); expected.put(token.getParameterName(), token.getToken()); diff --git a/web/src/test/java/org/springframework/security/web/server/authentication/SwitchUserWebFilterTests.java b/web/src/test/java/org/springframework/security/web/server/authentication/SwitchUserWebFilterTests.java index aad5b64049..7a4325920d 100644 --- a/web/src/test/java/org/springframework/security/web/server/authentication/SwitchUserWebFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/server/authentication/SwitchUserWebFilterTests.java @@ -39,6 +39,7 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.security.core.userdetails.ReactiveUserDetailsService; @@ -61,8 +62,6 @@ 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.springframework.security.core.context.ReactiveSecurityContextHolder.withSecurityContext; -import static org.springframework.security.web.server.authentication.SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR; /** * @author Artur Otrzonsek @@ -136,7 +135,8 @@ public class SwitchUserWebFilterTests { // when this.switchUserWebFilter.filter(exchange, chain) - .subscriberContext(withSecurityContext(Mono.just(securityContext))).block(); + .subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))) + .block(); // then verifyNoInteractions(chain); @@ -156,7 +156,7 @@ public class SwitchUserWebFilterTests { assertThat(switchUserAuthentication.getName()).isEqualTo(targetUsername); assertThat(switchUserAuthentication.getAuthorities()).anyMatch(SwitchUserGrantedAuthority.class::isInstance); assertThat(switchUserAuthentication.getAuthorities()) - .anyMatch((a) -> a.getAuthority().contains(ROLE_PREVIOUS_ADMINISTRATOR)); + .anyMatch((a) -> a.getAuthority().contains(SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR)); assertThat( switchUserAuthentication.getAuthorities().stream().filter(a -> a instanceof SwitchUserGrantedAuthority) .map(a -> ((SwitchUserGrantedAuthority) a).getSource()).map(Principal::getName)) @@ -169,8 +169,8 @@ public class SwitchUserWebFilterTests { final Authentication originalAuthentication = new UsernamePasswordAuthenticationToken("origPrincipal", "origCredentials"); - final GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority(ROLE_PREVIOUS_ADMINISTRATOR, - originalAuthentication); + final GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority( + SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR, originalAuthentication); final Authentication switchUserAuthentication = new UsernamePasswordAuthenticationToken("switchPrincipal", "switchCredentials", Collections.singleton(switchAuthority)); @@ -191,7 +191,8 @@ public class SwitchUserWebFilterTests { // when this.switchUserWebFilter.filter(exchange, chain) - .subscriberContext(withSecurityContext(Mono.just(securityContext))).block(); + .subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))) + .block(); // then final ArgumentCaptor authenticationCaptor = ArgumentCaptor.forClass(Authentication.class); @@ -221,7 +222,8 @@ public class SwitchUserWebFilterTests { // when this.switchUserWebFilter.filter(exchange, chain) - .subscriberContext(withSecurityContext(Mono.just(securityContext))).block(); + .subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))) + .block(); verifyNoInteractions(chain); } @@ -241,7 +243,8 @@ public class SwitchUserWebFilterTests { // when this.switchUserWebFilter.filter(exchange, chain) - .subscriberContext(withSecurityContext(Mono.just(securityContext))).block(); + .subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))) + .block(); verify(this.failureHandler).onAuthenticationFailure(any(WebFilterExchange.class), any(DisabledException.class)); verifyNoInteractions(chain); @@ -266,7 +269,8 @@ public class SwitchUserWebFilterTests { // when then this.switchUserWebFilter.filter(exchange, chain) - .subscriberContext(withSecurityContext(Mono.just(securityContext))).block(); + .subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))) + .block(); verifyNoInteractions(chain); } @@ -279,8 +283,8 @@ public class SwitchUserWebFilterTests { final Authentication originalAuthentication = new UsernamePasswordAuthenticationToken("origPrincipal", "origCredentials"); - final GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority(ROLE_PREVIOUS_ADMINISTRATOR, - originalAuthentication); + final GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority( + SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR, originalAuthentication); final Authentication switchUserAuthentication = new UsernamePasswordAuthenticationToken("switchPrincipal", "switchCredentials", Collections.singleton(switchAuthority)); @@ -294,7 +298,8 @@ public class SwitchUserWebFilterTests { // when this.switchUserWebFilter.filter(exchange, chain) - .subscriberContext(withSecurityContext(Mono.just(securityContext))).block(); + .subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))) + .block(); // then final ArgumentCaptor securityContextCaptor = ArgumentCaptor.forClass(SecurityContext.class); @@ -329,7 +334,8 @@ public class SwitchUserWebFilterTests { // when then this.switchUserWebFilter.filter(exchange, chain) - .subscriberContext(withSecurityContext(Mono.just(securityContext))).block(); + .subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))) + .block(); verifyNoInteractions(chain); } diff --git a/web/src/test/java/org/springframework/security/web/server/authorization/ServerWebExchangeDelegatingServerAccessDeniedHandlerTests.java b/web/src/test/java/org/springframework/security/web/server/authorization/ServerWebExchangeDelegatingServerAccessDeniedHandlerTests.java index da71f648a6..0467943bf2 100644 --- a/web/src/test/java/org/springframework/security/web/server/authorization/ServerWebExchangeDelegatingServerAccessDeniedHandlerTests.java +++ b/web/src/test/java/org/springframework/security/web/server/authorization/ServerWebExchangeDelegatingServerAccessDeniedHandlerTests.java @@ -25,14 +25,13 @@ import reactor.core.publisher.Mono; import org.springframework.security.web.server.authorization.ServerWebExchangeDelegatingServerAccessDeniedHandler.DelegateEntry; import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher; +import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult; import org.springframework.web.server.ServerWebExchange; 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.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult.match; -import static org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult.notMatch; public class ServerWebExchangeDelegatingServerAccessDeniedHandlerTests { @@ -55,7 +54,7 @@ public class ServerWebExchangeDelegatingServerAccessDeniedHandlerTests { public void handleWhenNothingMatchesThenOnlyDefaultHandlerInvoked() { ServerAccessDeniedHandler handler = mock(ServerAccessDeniedHandler.class); ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class); - given(matcher.matches(this.exchange)).willReturn(notMatch()); + given(matcher.matches(this.exchange)).willReturn(MatchResult.notMatch()); given(handler.handle(this.exchange, null)).willReturn(Mono.empty()); given(this.accessDeniedHandler.handle(this.exchange, null)).willReturn(Mono.empty()); @@ -75,7 +74,7 @@ public class ServerWebExchangeDelegatingServerAccessDeniedHandlerTests { ServerWebExchangeMatcher firstMatcher = mock(ServerWebExchangeMatcher.class); ServerAccessDeniedHandler secondHandler = mock(ServerAccessDeniedHandler.class); ServerWebExchangeMatcher secondMatcher = mock(ServerWebExchangeMatcher.class); - given(firstMatcher.matches(this.exchange)).willReturn(match()); + given(firstMatcher.matches(this.exchange)).willReturn(MatchResult.match()); given(firstHandler.handle(this.exchange, null)).willReturn(Mono.empty()); given(secondHandler.handle(this.exchange, null)).willReturn(Mono.empty()); @@ -98,8 +97,8 @@ public class ServerWebExchangeDelegatingServerAccessDeniedHandlerTests { ServerWebExchangeMatcher firstMatcher = mock(ServerWebExchangeMatcher.class); ServerAccessDeniedHandler secondHandler = mock(ServerAccessDeniedHandler.class); ServerWebExchangeMatcher secondMatcher = mock(ServerWebExchangeMatcher.class); - given(firstMatcher.matches(this.exchange)).willReturn(notMatch()); - given(secondMatcher.matches(this.exchange)).willReturn(match()); + given(firstMatcher.matches(this.exchange)).willReturn(MatchResult.notMatch()); + given(secondMatcher.matches(this.exchange)).willReturn(MatchResult.match()); given(firstHandler.handle(this.exchange, null)).willReturn(Mono.empty()); given(secondHandler.handle(this.exchange, null)).willReturn(Mono.empty()); diff --git a/web/src/test/java/org/springframework/security/web/server/csrf/CsrfWebFilterTests.java b/web/src/test/java/org/springframework/security/web/server/csrf/CsrfWebFilterTests.java index d301f227e2..564a3d2e62 100644 --- a/web/src/test/java/org/springframework/security/web/server/csrf/CsrfWebFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/server/csrf/CsrfWebFilterTests.java @@ -33,18 +33,16 @@ import org.springframework.security.web.server.util.matcher.ServerWebExchangeMat import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilterChain; import org.springframework.web.server.WebSession; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyZeroInteractions; -import static org.springframework.mock.web.server.MockServerWebExchange.from; -import static org.springframework.web.reactive.function.BodyInserters.fromMultipartData; /** * @author Rob Winch @@ -64,9 +62,9 @@ public class CsrfWebFilterTests { private CsrfWebFilter csrfFilter = new CsrfWebFilter(); - private MockServerWebExchange get = from(MockServerHttpRequest.get("/")); + private MockServerWebExchange get = MockServerWebExchange.from(MockServerHttpRequest.get("/")); - private ServerWebExchange post = from(MockServerHttpRequest.post("/")); + private ServerWebExchange post = MockServerWebExchange.from(MockServerHttpRequest.post("/")); @Test public void filterWhenGetThenSessionNotCreatedAndChainContinues() { @@ -108,7 +106,7 @@ public class CsrfWebFilterTests { public void filterWhenPostAndEstablishedCsrfTokenAndRequestParamInvalidTokenThenCsrfException() { this.csrfFilter.setCsrfTokenRepository(this.repository); given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); - this.post = from(MockServerHttpRequest.post("/") + this.post = MockServerWebExchange.from(MockServerHttpRequest.post("/") .body(this.token.getParameterName() + "=" + this.token.getToken() + "INVALID")); Mono result = this.csrfFilter.filter(this.post, this.chain); @@ -126,8 +124,9 @@ public class CsrfWebFilterTests { this.csrfFilter.setCsrfTokenRepository(this.repository); given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); given(this.repository.generateToken(any())).willReturn(Mono.just(this.token)); - this.post = from(MockServerHttpRequest.post("/").contentType(MediaType.APPLICATION_FORM_URLENCODED) - .body(this.token.getParameterName() + "=" + this.token.getToken())); + this.post = MockServerWebExchange + .from(MockServerHttpRequest.post("/").contentType(MediaType.APPLICATION_FORM_URLENCODED) + .body(this.token.getParameterName() + "=" + this.token.getToken())); Mono result = this.csrfFilter.filter(this.post, this.chain); @@ -140,7 +139,7 @@ public class CsrfWebFilterTests { public void filterWhenPostAndEstablishedCsrfTokenAndHeaderInvalidTokenThenCsrfException() { this.csrfFilter.setCsrfTokenRepository(this.repository); given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); - this.post = from( + this.post = MockServerWebExchange.from( MockServerHttpRequest.post("/").header(this.token.getHeaderName(), this.token.getToken() + "INVALID")); Mono result = this.csrfFilter.filter(this.post, this.chain); @@ -158,7 +157,8 @@ public class CsrfWebFilterTests { this.csrfFilter.setCsrfTokenRepository(this.repository); given(this.repository.loadToken(any())).willReturn(Mono.just(this.token)); given(this.repository.generateToken(any())).willReturn(Mono.just(this.token)); - this.post = from(MockServerHttpRequest.post("/").header(this.token.getHeaderName(), this.token.getToken())); + this.post = MockServerWebExchange + .from(MockServerHttpRequest.post("/").header(this.token.getHeaderName(), this.token.getToken())); Mono result = this.csrfFilter.filter(this.post, this.chain); @@ -170,8 +170,8 @@ public class CsrfWebFilterTests { @Test // gh-8452 public void matchesRequireCsrfProtectionWhenNonStandardHTTPMethodIsUsed() { - MockServerWebExchange nonStandardHttpExchange = from( - MockServerHttpRequest.method("non-standard-http-method", "/")); + MockServerWebExchange nonStandardHttpExchange = MockServerWebExchange + .from(MockServerHttpRequest.method("non-standard-http-method", "/")); ServerWebExchangeMatcher serverWebExchangeMatcher = CsrfWebFilter.DEFAULT_CSRF_MATCHER; assertThat(serverWebExchangeMatcher.matches(nonStandardHttpExchange).map(MatchResult::isMatch).block()) @@ -186,7 +186,7 @@ public class CsrfWebFilterTests { ServerWebExchangeMatcher matcher = mock(ServerWebExchangeMatcher.class); this.csrfFilter.setRequireCsrfProtectionMatcher(matcher); - MockServerWebExchange exchange = from(MockServerHttpRequest.post("/post").build()); + MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/post").build()); CsrfWebFilter.skipExchange(exchange); this.csrfFilter.filter(exchange, this.chain).block(); @@ -201,8 +201,8 @@ public class CsrfWebFilterTests { WebTestClient client = WebTestClient.bindToController(new OkController()).webFilter(this.csrfFilter).build(); client.post().uri("/").contentType(MediaType.MULTIPART_FORM_DATA) - .body(fromMultipartData(this.token.getParameterName(), this.token.getToken())).exchange().expectStatus() - .isForbidden(); + .body(BodyInserters.fromMultipartData(this.token.getParameterName(), this.token.getToken())).exchange() + .expectStatus().isForbidden(); } @Test @@ -215,8 +215,8 @@ public class CsrfWebFilterTests { WebTestClient client = WebTestClient.bindToController(new OkController()).webFilter(this.csrfFilter).build(); client.post().uri("/").contentType(MediaType.MULTIPART_FORM_DATA) - .body(fromMultipartData(this.token.getParameterName(), this.token.getToken())).exchange().expectStatus() - .is2xxSuccessful(); + .body(BodyInserters.fromMultipartData(this.token.getParameterName(), this.token.getToken())).exchange() + .expectStatus().is2xxSuccessful(); } @Test diff --git a/web/src/test/java/org/springframework/security/web/server/util/matcher/ServerWebExchangeMatchersTests.java b/web/src/test/java/org/springframework/security/web/server/util/matcher/ServerWebExchangeMatchersTests.java index 938af60bfd..80f9430b94 100644 --- a/web/src/test/java/org/springframework/security/web/server/util/matcher/ServerWebExchangeMatchersTests.java +++ b/web/src/test/java/org/springframework/security/web/server/util/matcher/ServerWebExchangeMatchersTests.java @@ -26,8 +26,6 @@ import org.springframework.web.server.ServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyZeroInteractions; -import static org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers.anyExchange; -import static org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers.pathMatchers; /** * @author Rob Winch @@ -39,7 +37,7 @@ public class ServerWebExchangeMatchersTests { @Test public void pathMatchersWhenSingleAndSamePatternThenMatches() { - assertThat(pathMatchers("/").matches(this.exchange).block().isMatch()).isTrue(); + assertThat(ServerWebExchangeMatchers.pathMatchers("/").matches(this.exchange).block().isMatch()).isTrue(); } @Test @@ -57,19 +55,21 @@ public class ServerWebExchangeMatchersTests { @Test public void pathMatchersWhenSingleAndDifferentPatternThenDoesNotMatch() { - assertThat(pathMatchers("/foobar").matches(this.exchange).block().isMatch()).isFalse(); + assertThat(ServerWebExchangeMatchers.pathMatchers("/foobar").matches(this.exchange).block().isMatch()) + .isFalse(); } @Test public void pathMatchersWhenMultiThenMatches() { - assertThat(pathMatchers("/foobar", "/").matches(this.exchange).block().isMatch()).isTrue(); + assertThat(ServerWebExchangeMatchers.pathMatchers("/foobar", "/").matches(this.exchange).block().isMatch()) + .isTrue(); } @Test public void anyExchangeWhenMockThenMatches() { ServerWebExchange mockExchange = mock(ServerWebExchange.class); - assertThat(anyExchange().matches(mockExchange).block().isMatch()).isTrue(); + assertThat(ServerWebExchangeMatchers.anyExchange().matches(mockExchange).block().isMatch()).isTrue(); verifyZeroInteractions(mockExchange); } @@ -83,7 +83,7 @@ public class ServerWebExchangeMatchersTests { */ @Test public void anyExchangeWhenTwoCreatedThenDifferentToPreventIssuesInMap() { - assertThat(anyExchange()).isNotEqualTo(anyExchange()); + assertThat(ServerWebExchangeMatchers.anyExchange()).isNotEqualTo(ServerWebExchangeMatchers.anyExchange()); } } diff --git a/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilterTests.java b/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilterTests.java index c491112085..8721b35d2e 100644 --- a/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilterTests.java +++ b/web/src/test/java/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilterTests.java @@ -55,12 +55,12 @@ import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.powermock.api.mockito.PowerMockito.doThrow; -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.verifyZeroInteractions; -import static org.powermock.api.mockito.PowerMockito.when; +import static org.mockito.Mockito.verifyZeroInteractions; /** * Tests {@link SecurityContextHolderAwareRequestFilter}. @@ -159,7 +159,7 @@ public class SecurityContextHolderAwareRequestFilterTests { @Test public void authenticateNullEntryPointTrue() throws Exception { - when(this.request.authenticate(this.response)).thenReturn(true); + given(this.request.authenticate(this.response)).willReturn(true); this.filter.setAuthenticationEntryPoint(null); this.filter.afterPropertiesSet(); @@ -171,8 +171,8 @@ public class SecurityContextHolderAwareRequestFilterTests { @Test public void login() throws Exception { TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password", "ROLE_USER"); - when(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class))) - .thenReturn(expectedAuth); + given(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class))) + .willReturn(expectedAuth); wrappedRequest().login(expectedAuth.getName(), String.valueOf(expectedAuth.getCredentials())); @@ -185,8 +185,8 @@ public class SecurityContextHolderAwareRequestFilterTests { @Test public void loginWithExistingUser() throws Exception { TestingAuthenticationToken expectedAuth = new TestingAuthenticationToken("user", "password", "ROLE_USER"); - when(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class))) - .thenReturn(new TestingAuthenticationToken("newuser", "not be found", "ROLE_USER")); + given(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class))) + .willReturn(new TestingAuthenticationToken("newuser", "not be found", "ROLE_USER")); SecurityContextHolder.getContext().setAuthentication(expectedAuth); try { @@ -203,8 +203,8 @@ public class SecurityContextHolderAwareRequestFilterTests { @Test public void loginFail() throws Exception { AuthenticationException authException = new BadCredentialsException("Invalid"); - when(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class))) - .thenThrow(authException); + given(this.authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class))) + .willThrow(authException); try { wrappedRequest().login("invalid", "credentials"); @@ -241,7 +241,7 @@ public class SecurityContextHolderAwareRequestFilterTests { String username = "username"; String password = "password"; ServletException authException = new ServletException("Failed Login"); - doThrow(authException).when(this.request).login(username, password); + willThrow(authException).given(this.request).login(username, password); try { wrappedRequest().login(username, password); @@ -292,7 +292,7 @@ public class SecurityContextHolderAwareRequestFilterTests { context.setAuthentication(expectedAuth); SecurityContextHolder.setContext(context); AsyncContext asyncContext = mock(AsyncContext.class); - when(this.request.getAsyncContext()).thenReturn(asyncContext); + given(this.request.getAsyncContext()).willReturn(asyncContext); Runnable runnable = () -> { }; @@ -314,7 +314,7 @@ public class SecurityContextHolderAwareRequestFilterTests { context.setAuthentication(expectedAuth); SecurityContextHolder.setContext(context); AsyncContext asyncContext = mock(AsyncContext.class); - when(this.request.startAsync()).thenReturn(asyncContext); + given(this.request.startAsync()).willReturn(asyncContext); Runnable runnable = () -> { }; @@ -336,7 +336,7 @@ public class SecurityContextHolderAwareRequestFilterTests { context.setAuthentication(expectedAuth); SecurityContextHolder.setContext(context); AsyncContext asyncContext = mock(AsyncContext.class); - when(this.request.startAsync(this.request, this.response)).thenReturn(asyncContext); + given(this.request.startAsync(this.request, this.response)).willReturn(asyncContext); Runnable runnable = () -> { };