refactor: AssertJ best practices

Use this link to re-run the recipe: https://app.moderne.io/recipes/builder/bGVuS?organizationId=RGVmYXVsdA%3D%3D

Co-authored-by: Moderne <team@moderne.io>
This commit is contained in:
Tim te Beek 2023-08-06 19:29:47 +00:00 committed by Josh Cummings
parent 36a488a360
commit 9df9cb5aed
69 changed files with 336 additions and 335 deletions

View File

@ -112,7 +112,7 @@ public class JdbcAclServiceTests {
given(this.jdbcOperations.query(anyString(), eq(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); ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockLongIdDomainObject.class, 1L);
List<ObjectIdentity> objectIdentities = this.aclService.findChildren(objectIdentity); List<ObjectIdentity> objectIdentities = this.aclService.findChildren(objectIdentity);
assertThat(objectIdentities.size()).isEqualTo(1); assertThat(objectIdentities).hasSize(1);
assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo("5577"); assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo("5577");
} }
@ -127,7 +127,7 @@ public class JdbcAclServiceTests {
public void findChildrenWithoutIdType() { public void findChildrenWithoutIdType() {
ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockLongIdDomainObject.class, 4711L); ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockLongIdDomainObject.class, 4711L);
List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity); List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity);
assertThat(objectIdentities.size()).isEqualTo(1); assertThat(objectIdentities).hasSize(1);
assertThat(objectIdentities.get(0).getType()).isEqualTo(MockUntypedIdDomainObject.class.getName()); assertThat(objectIdentities.get(0).getType()).isEqualTo(MockUntypedIdDomainObject.class.getName());
assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo(5000L); assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo(5000L);
} }
@ -143,7 +143,7 @@ public class JdbcAclServiceTests {
public void findChildrenOfIdTypeLong() { public void findChildrenOfIdTypeLong() {
ObjectIdentity objectIdentity = new ObjectIdentityImpl("location", "US-PAL"); ObjectIdentity objectIdentity = new ObjectIdentityImpl("location", "US-PAL");
List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity); List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity);
assertThat(objectIdentities.size()).isEqualTo(2); assertThat(objectIdentities).hasSize(2);
assertThat(objectIdentities.get(0).getType()).isEqualTo(MockLongIdDomainObject.class.getName()); assertThat(objectIdentities.get(0).getType()).isEqualTo(MockLongIdDomainObject.class.getName());
assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo(4711L); assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo(4711L);
assertThat(objectIdentities.get(1).getType()).isEqualTo(MockLongIdDomainObject.class.getName()); assertThat(objectIdentities.get(1).getType()).isEqualTo(MockLongIdDomainObject.class.getName());
@ -155,7 +155,7 @@ public class JdbcAclServiceTests {
ObjectIdentity objectIdentity = new ObjectIdentityImpl("location", "US"); ObjectIdentity objectIdentity = new ObjectIdentityImpl("location", "US");
this.aclServiceIntegration.setAclClassIdSupported(true); this.aclServiceIntegration.setAclClassIdSupported(true);
List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity); List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity);
assertThat(objectIdentities.size()).isEqualTo(1); assertThat(objectIdentities).hasSize(1);
assertThat(objectIdentities.get(0).getType()).isEqualTo("location"); assertThat(objectIdentities.get(0).getType()).isEqualTo("location");
assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo("US-PAL"); assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo("US-PAL");
} }
@ -165,7 +165,7 @@ public class JdbcAclServiceTests {
ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockUntypedIdDomainObject.class, 5000L); ObjectIdentity objectIdentity = new ObjectIdentityImpl(MockUntypedIdDomainObject.class, 5000L);
this.aclServiceIntegration.setAclClassIdSupported(true); this.aclServiceIntegration.setAclClassIdSupported(true);
List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity); List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity);
assertThat(objectIdentities.size()).isEqualTo(1); assertThat(objectIdentities).hasSize(1);
assertThat(objectIdentities.get(0).getType()).isEqualTo("costcenter"); assertThat(objectIdentities.get(0).getType()).isEqualTo("costcenter");
assertThat(objectIdentities.get(0).getIdentifier()) assertThat(objectIdentities.get(0).getIdentifier())
.isEqualTo(UUID.fromString("25d93b3f-c3aa-4814-9d5e-c7c96ced7762")); .isEqualTo(UUID.fromString("25d93b3f-c3aa-4814-9d5e-c7c96ced7762"));
@ -186,7 +186,7 @@ public class JdbcAclServiceTests {
ObjectIdentity objectIdentity = new ObjectIdentityImpl("location", "US"); ObjectIdentity objectIdentity = new ObjectIdentityImpl("location", "US");
this.aclServiceIntegration.setAclClassIdSupported(true); this.aclServiceIntegration.setAclClassIdSupported(true);
List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity); List<ObjectIdentity> objectIdentities = this.aclServiceIntegration.findChildren(objectIdentity);
assertThat(objectIdentities.size()).isEqualTo(1); assertThat(objectIdentities).hasSize(1);
assertThat(objectIdentities.get(0).getType()).isEqualTo("location"); assertThat(objectIdentities.get(0).getType()).isEqualTo("location");
assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo("prefix:US-PAL"); assertThat(objectIdentities.get(0).getIdentifier()).isEqualTo("prefix:US-PAL");
} }

View File

@ -120,9 +120,9 @@ public class SidTests {
PrincipalSid principalSid = new PrincipalSid(authentication); PrincipalSid principalSid = new PrincipalSid(authentication);
GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_TEST"); GrantedAuthority ga = new SimpleGrantedAuthority("ROLE_TEST");
GrantedAuthoritySid gaSid = new GrantedAuthoritySid(ga); GrantedAuthoritySid gaSid = new GrantedAuthoritySid(ga);
assertThat("johndoe".equals(principalSid.getPrincipal())).isTrue(); assertThat("johndoe").isEqualTo(principalSid.getPrincipal());
assertThat("scott".equals(principalSid.getPrincipal())).isFalse(); assertThat("scott".equals(principalSid.getPrincipal())).isFalse();
assertThat("ROLE_TEST".equals(gaSid.getGrantedAuthority())).isTrue(); assertThat("ROLE_TEST").isEqualTo(gaSid.getGrantedAuthority());
assertThat("ROLE_TEST2".equals(gaSid.getGrantedAuthority())).isFalse(); assertThat("ROLE_TEST2".equals(gaSid.getGrantedAuthority())).isFalse();
} }

View File

@ -143,8 +143,8 @@ public class AnnotationSecurityAspectTests {
SecurityContextHolder.getContext().setAuthentication(this.anne); SecurityContextHolder.getContext().setAuthentication(this.anne);
List<String> objects = this.prePostSecured.postFilterMethod(); List<String> objects = this.prePostSecured.postFilterMethod();
assertThat(objects).hasSize(2); assertThat(objects).hasSize(2);
assertThat(objects.contains("apple")).isTrue(); assertThat(objects).contains("apple");
assertThat(objects.contains("aubergine")).isTrue(); assertThat(objects).contains("aubergine");
} }
private void configureForElAnnotations() { private void configureForElAnnotations() {

View File

@ -87,7 +87,7 @@ public class LdapUserServiceBeanDefinitionParserTests {
Set<String> authorities = AuthorityUtils.authorityListToSet(ben.getAuthorities()); Set<String> authorities = AuthorityUtils.authorityListToSet(ben.getAuthorities());
assertThat(authorities).hasSize(3); assertThat(authorities).hasSize(3);
assertThat(authorities.contains("ROLE_DEVELOPERS")).isTrue(); assertThat(authorities).contains("ROLE_DEVELOPERS");
} }
@Test @Test
@ -128,7 +128,7 @@ public class LdapUserServiceBeanDefinitionParserTests {
Set<String> authorities = AuthorityUtils.authorityListToSet(ben.getAuthorities()); Set<String> authorities = AuthorityUtils.authorityListToSet(ben.getAuthorities());
assertThat(authorities).hasSize(3); assertThat(authorities).hasSize(3);
assertThat(authorities.contains("ROLE_DEVELOPER")).isTrue(); assertThat(authorities).contains("ROLE_DEVELOPER");
} }

View File

@ -17,11 +17,13 @@
package org.springframework.security.config.annotation.authentication.configurers.provisioning; package org.springframework.security.config.annotation.authentication.configurers.provisioning;
import java.util.Arrays; import java.util.Arrays;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@ -73,7 +75,7 @@ public class UserDetailsManagerConfigurerTests {
.authorities(authority) .authorities(authority)
.build(); .build();
// @formatter:on // @formatter:on
assertThat(userDetails.getAuthorities().stream().findFirst().get()).isEqualTo(authority); assertThat((Optional<GrantedAuthority>) userDetails.getAuthorities().stream().findFirst()).contains(authority);
} }
@Test @Test
@ -99,7 +101,7 @@ public class UserDetailsManagerConfigurerTests {
.authorities(Arrays.asList(authority)) .authorities(Arrays.asList(authority))
.build(); .build();
// @formatter:on // @formatter:on
assertThat(userDetails.getAuthorities().stream().findFirst().get()).isEqualTo(authority); assertThat((Optional<GrantedAuthority>) userDetails.getAuthorities().stream().findFirst()).contains(authority);
} }
private UserDetailsManagerConfigurer<AuthenticationManagerBuilder, InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder>> configurer() { private UserDetailsManagerConfigurer<AuthenticationManagerBuilder, InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder>> configurer() {

View File

@ -47,7 +47,7 @@ public class AbstractRequestMatcherRegistryNoMvcTests {
public void requestMatchersWhenPatternAndMvcNotPresentThenReturnAntPathRequestMatcherType() { public void requestMatchersWhenPatternAndMvcNotPresentThenReturnAntPathRequestMatcherType() {
List<RequestMatcher> requestMatchers = this.matcherRegistry.requestMatchers("/path"); List<RequestMatcher> requestMatchers = this.matcherRegistry.requestMatchers("/path");
assertThat(requestMatchers).isNotEmpty(); assertThat(requestMatchers).isNotEmpty();
assertThat(requestMatchers.size()).isEqualTo(1); assertThat(requestMatchers).hasSize(1);
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(AntPathRequestMatcher.class); assertThat(requestMatchers.get(0)).isExactlyInstanceOf(AntPathRequestMatcher.class);
} }
@ -55,7 +55,7 @@ public class AbstractRequestMatcherRegistryNoMvcTests {
public void requestMatchersWhenHttpMethodAndPatternAndMvcNotPresentThenReturnAntPathRequestMatcherType() { public void requestMatchersWhenHttpMethodAndPatternAndMvcNotPresentThenReturnAntPathRequestMatcherType() {
List<RequestMatcher> requestMatchers = this.matcherRegistry.requestMatchers(HttpMethod.GET, "/path"); List<RequestMatcher> requestMatchers = this.matcherRegistry.requestMatchers(HttpMethod.GET, "/path");
assertThat(requestMatchers).isNotEmpty(); assertThat(requestMatchers).isNotEmpty();
assertThat(requestMatchers.size()).isEqualTo(1); assertThat(requestMatchers).hasSize(1);
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(AntPathRequestMatcher.class); assertThat(requestMatchers.get(0)).isExactlyInstanceOf(AntPathRequestMatcher.class);
} }
@ -63,7 +63,7 @@ public class AbstractRequestMatcherRegistryNoMvcTests {
public void requestMatchersWhenHttpMethodAndMvcNotPresentThenReturnAntPathMatcherType() { public void requestMatchersWhenHttpMethodAndMvcNotPresentThenReturnAntPathMatcherType() {
List<RequestMatcher> requestMatchers = this.matcherRegistry.requestMatchers(HttpMethod.GET); List<RequestMatcher> requestMatchers = this.matcherRegistry.requestMatchers(HttpMethod.GET);
assertThat(requestMatchers).isNotEmpty(); assertThat(requestMatchers).isNotEmpty();
assertThat(requestMatchers.size()).isEqualTo(1); assertThat(requestMatchers).hasSize(1);
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(AntPathRequestMatcher.class); assertThat(requestMatchers.get(0)).isExactlyInstanceOf(AntPathRequestMatcher.class);
} }

View File

@ -75,7 +75,7 @@ public class AbstractRequestMatcherRegistryTests {
List<RequestMatcher> requestMatchers = this.matcherRegistry List<RequestMatcher> requestMatchers = this.matcherRegistry
.requestMatchers(new RegexRequestMatcher("/a.*", HttpMethod.GET.name())); .requestMatchers(new RegexRequestMatcher("/a.*", HttpMethod.GET.name()));
assertThat(requestMatchers).isNotEmpty(); assertThat(requestMatchers).isNotEmpty();
assertThat(requestMatchers.size()).isEqualTo(1); assertThat(requestMatchers).hasSize(1);
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(RegexRequestMatcher.class); assertThat(requestMatchers.get(0)).isExactlyInstanceOf(RegexRequestMatcher.class);
} }
@ -84,7 +84,7 @@ public class AbstractRequestMatcherRegistryTests {
List<RequestMatcher> requestMatchers = this.matcherRegistry List<RequestMatcher> requestMatchers = this.matcherRegistry
.requestMatchers(new RegexRequestMatcher("/a.*", null)); .requestMatchers(new RegexRequestMatcher("/a.*", null));
assertThat(requestMatchers).isNotEmpty(); assertThat(requestMatchers).isNotEmpty();
assertThat(requestMatchers.size()).isEqualTo(1); assertThat(requestMatchers).hasSize(1);
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(RegexRequestMatcher.class); assertThat(requestMatchers.get(0)).isExactlyInstanceOf(RegexRequestMatcher.class);
} }
@ -93,7 +93,7 @@ public class AbstractRequestMatcherRegistryTests {
List<RequestMatcher> requestMatchers = this.matcherRegistry List<RequestMatcher> requestMatchers = this.matcherRegistry
.requestMatchers(new AntPathRequestMatcher("/a.*", HttpMethod.GET.name())); .requestMatchers(new AntPathRequestMatcher("/a.*", HttpMethod.GET.name()));
assertThat(requestMatchers).isNotEmpty(); assertThat(requestMatchers).isNotEmpty();
assertThat(requestMatchers.size()).isEqualTo(1); assertThat(requestMatchers).hasSize(1);
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(AntPathRequestMatcher.class); assertThat(requestMatchers.get(0)).isExactlyInstanceOf(AntPathRequestMatcher.class);
} }
@ -101,7 +101,7 @@ public class AbstractRequestMatcherRegistryTests {
public void antMatchersWhenPatternParamThenReturnAntPathRequestMatcherType() { public void antMatchersWhenPatternParamThenReturnAntPathRequestMatcherType() {
List<RequestMatcher> requestMatchers = this.matcherRegistry.requestMatchers(new AntPathRequestMatcher("/a.*")); List<RequestMatcher> requestMatchers = this.matcherRegistry.requestMatchers(new AntPathRequestMatcher("/a.*"));
assertThat(requestMatchers).isNotEmpty(); assertThat(requestMatchers).isNotEmpty();
assertThat(requestMatchers.size()).isEqualTo(1); assertThat(requestMatchers).hasSize(1);
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(AntPathRequestMatcher.class); assertThat(requestMatchers.get(0)).isExactlyInstanceOf(AntPathRequestMatcher.class);
} }
@ -110,7 +110,7 @@ public class AbstractRequestMatcherRegistryTests {
List<RequestMatcher> requestMatchers = this.matcherRegistry.dispatcherTypeMatchers(HttpMethod.GET, List<RequestMatcher> requestMatchers = this.matcherRegistry.dispatcherTypeMatchers(HttpMethod.GET,
DispatcherType.ASYNC); DispatcherType.ASYNC);
assertThat(requestMatchers).isNotEmpty(); assertThat(requestMatchers).isNotEmpty();
assertThat(requestMatchers.size()).isEqualTo(1); assertThat(requestMatchers).hasSize(1);
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(DispatcherTypeRequestMatcher.class); assertThat(requestMatchers.get(0)).isExactlyInstanceOf(DispatcherTypeRequestMatcher.class);
} }
@ -118,7 +118,7 @@ public class AbstractRequestMatcherRegistryTests {
public void dispatcherMatchersWhenPatternParamThenReturnAntPathRequestMatcherType() { public void dispatcherMatchersWhenPatternParamThenReturnAntPathRequestMatcherType() {
List<RequestMatcher> requestMatchers = this.matcherRegistry.dispatcherTypeMatchers(DispatcherType.INCLUDE); List<RequestMatcher> requestMatchers = this.matcherRegistry.dispatcherTypeMatchers(DispatcherType.INCLUDE);
assertThat(requestMatchers).isNotEmpty(); assertThat(requestMatchers).isNotEmpty();
assertThat(requestMatchers.size()).isEqualTo(1); assertThat(requestMatchers).hasSize(1);
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(DispatcherTypeRequestMatcher.class); assertThat(requestMatchers.get(0)).isExactlyInstanceOf(DispatcherTypeRequestMatcher.class);
} }
@ -126,7 +126,7 @@ public class AbstractRequestMatcherRegistryTests {
public void requestMatchersWhenPatternAndMvcPresentThenReturnMvcRequestMatcherType() { public void requestMatchersWhenPatternAndMvcPresentThenReturnMvcRequestMatcherType() {
List<RequestMatcher> requestMatchers = this.matcherRegistry.requestMatchers("/path"); List<RequestMatcher> requestMatchers = this.matcherRegistry.requestMatchers("/path");
assertThat(requestMatchers).isNotEmpty(); assertThat(requestMatchers).isNotEmpty();
assertThat(requestMatchers.size()).isEqualTo(1); assertThat(requestMatchers).hasSize(1);
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(MvcRequestMatcher.class); assertThat(requestMatchers.get(0)).isExactlyInstanceOf(MvcRequestMatcher.class);
} }
@ -134,7 +134,7 @@ public class AbstractRequestMatcherRegistryTests {
public void requestMatchersWhenHttpMethodAndPatternAndMvcPresentThenReturnMvcRequestMatcherType() { public void requestMatchersWhenHttpMethodAndPatternAndMvcPresentThenReturnMvcRequestMatcherType() {
List<RequestMatcher> requestMatchers = this.matcherRegistry.requestMatchers(HttpMethod.GET, "/path"); List<RequestMatcher> requestMatchers = this.matcherRegistry.requestMatchers(HttpMethod.GET, "/path");
assertThat(requestMatchers).isNotEmpty(); assertThat(requestMatchers).isNotEmpty();
assertThat(requestMatchers.size()).isEqualTo(1); assertThat(requestMatchers).hasSize(1);
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(MvcRequestMatcher.class); assertThat(requestMatchers.get(0)).isExactlyInstanceOf(MvcRequestMatcher.class);
} }
@ -142,7 +142,7 @@ public class AbstractRequestMatcherRegistryTests {
public void requestMatchersWhenHttpMethodAndMvcPresentThenReturnMvcRequestMatcherType() { public void requestMatchersWhenHttpMethodAndMvcPresentThenReturnMvcRequestMatcherType() {
List<RequestMatcher> requestMatchers = this.matcherRegistry.requestMatchers(HttpMethod.GET); List<RequestMatcher> requestMatchers = this.matcherRegistry.requestMatchers(HttpMethod.GET);
assertThat(requestMatchers).isNotEmpty(); assertThat(requestMatchers).isNotEmpty();
assertThat(requestMatchers.size()).isEqualTo(1); assertThat(requestMatchers).hasSize(1);
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(MvcRequestMatcher.class); assertThat(requestMatchers.get(0)).isExactlyInstanceOf(MvcRequestMatcher.class);
} }

View File

@ -84,10 +84,10 @@ public class DefaultFiltersTests {
this.spring.register(NullWebInvocationPrivilegeEvaluatorConfig.class, UserDetailsServiceConfig.class); this.spring.register(NullWebInvocationPrivilegeEvaluatorConfig.class, UserDetailsServiceConfig.class);
List<SecurityFilterChain> filterChains = this.spring.getContext().getBean(FilterChainProxy.class) List<SecurityFilterChain> filterChains = this.spring.getContext().getBean(FilterChainProxy.class)
.getFilterChains(); .getFilterChains();
assertThat(filterChains.size()).isEqualTo(1); assertThat(filterChains).hasSize(1);
DefaultSecurityFilterChain filterChain = (DefaultSecurityFilterChain) filterChains.get(0); DefaultSecurityFilterChain filterChain = (DefaultSecurityFilterChain) filterChains.get(0);
assertThat(filterChain.getRequestMatcher()).isInstanceOf(AnyRequestMatcher.class); assertThat(filterChain.getRequestMatcher()).isInstanceOf(AnyRequestMatcher.class);
assertThat(filterChain.getFilters().size()).isEqualTo(1); assertThat(filterChain.getFilters()).hasSize(1);
long filter = filterChain.getFilters().stream() long filter = filterChain.getFilters().stream()
.filter((it) -> it instanceof UsernamePasswordAuthenticationFilter).count(); .filter((it) -> it instanceof UsernamePasswordAuthenticationFilter).count();
assertThat(filter).isEqualTo(1); assertThat(filter).isEqualTo(1);
@ -98,23 +98,23 @@ public class DefaultFiltersTests {
this.spring.register(FilterChainProxyBuilderIgnoringConfig.class, UserDetailsServiceConfig.class); this.spring.register(FilterChainProxyBuilderIgnoringConfig.class, UserDetailsServiceConfig.class);
List<SecurityFilterChain> filterChains = this.spring.getContext().getBean(FilterChainProxy.class) List<SecurityFilterChain> filterChains = this.spring.getContext().getBean(FilterChainProxy.class)
.getFilterChains(); .getFilterChains();
assertThat(filterChains.size()).isEqualTo(2); assertThat(filterChains).hasSize(2);
DefaultSecurityFilterChain firstFilter = (DefaultSecurityFilterChain) filterChains.get(0); DefaultSecurityFilterChain firstFilter = (DefaultSecurityFilterChain) filterChains.get(0);
DefaultSecurityFilterChain secondFilter = (DefaultSecurityFilterChain) filterChains.get(1); DefaultSecurityFilterChain secondFilter = (DefaultSecurityFilterChain) filterChains.get(1);
assertThat(firstFilter.getFilters().isEmpty()).isEqualTo(true); assertThat(firstFilter.getFilters().isEmpty()).isEqualTo(true);
assertThat(secondFilter.getRequestMatcher()).isInstanceOf(AnyRequestMatcher.class); assertThat(secondFilter.getRequestMatcher()).isInstanceOf(AnyRequestMatcher.class);
List<? extends Class<? extends Filter>> classes = secondFilter.getFilters().stream().map(Filter::getClass) List<Class<? extends Filter>> classes = secondFilter.getFilters().stream().map(Filter::getClass)
.collect(Collectors.toList()); .collect(Collectors.toList());
assertThat(classes.contains(WebAsyncManagerIntegrationFilter.class)).isTrue(); assertThat(classes).contains(WebAsyncManagerIntegrationFilter.class);
assertThat(classes.contains(SecurityContextHolderFilter.class)).isTrue(); assertThat(classes).contains(SecurityContextHolderFilter.class);
assertThat(classes.contains(HeaderWriterFilter.class)).isTrue(); assertThat(classes).contains(HeaderWriterFilter.class);
assertThat(classes.contains(LogoutFilter.class)).isTrue(); assertThat(classes).contains(LogoutFilter.class);
assertThat(classes.contains(CsrfFilter.class)).isTrue(); assertThat(classes).contains(CsrfFilter.class);
assertThat(classes.contains(RequestCacheAwareFilter.class)).isTrue(); assertThat(classes).contains(RequestCacheAwareFilter.class);
assertThat(classes.contains(SecurityContextHolderAwareRequestFilter.class)).isTrue(); assertThat(classes).contains(SecurityContextHolderAwareRequestFilter.class);
assertThat(classes.contains(AnonymousAuthenticationFilter.class)).isTrue(); assertThat(classes).contains(AnonymousAuthenticationFilter.class);
assertThat(classes.contains(ExceptionTranslationFilter.class)).isTrue(); assertThat(classes).contains(ExceptionTranslationFilter.class);
assertThat(classes.contains(FilterSecurityInterceptor.class)).isTrue(); assertThat(classes).contains(FilterSecurityInterceptor.class);
} }
@Test @Test

View File

@ -27,7 +27,6 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import net.shibboleth.utilities.java.support.xml.SerializeSupport; import net.shibboleth.utilities.java.support.xml.SerializeSupport;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -412,7 +411,7 @@ public class Saml2LoginConfigurerTests {
// assertions // assertions
Authentication authentication = this.securityContextRepository Authentication authentication = this.securityContextRepository
.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication(); .loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
Assertions.assertNotNull(authentication, "Expected a valid authentication object."); assertThat(authentication).as("Expected a valid authentication object.").isNotNull();
assertThat(authentication.getAuthorities()).hasSize(1); assertThat(authentication.getAuthorities()).hasSize(1);
assertThat(authentication.getAuthorities()).first().isInstanceOf(SimpleGrantedAuthority.class) assertThat(authentication.getAuthorities()).first().isInstanceOf(SimpleGrantedAuthority.class)
.hasToString(expected); .hasToString(expected);

View File

@ -286,8 +286,8 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
private void assertHandshake(HttpServletRequest request) { private void assertHandshake(HttpServletRequest request) {
TestHandshakeHandler handshakeHandler = this.context.getBean(TestHandshakeHandler.class); TestHandshakeHandler handshakeHandler = this.context.getBean(TestHandshakeHandler.class);
assertThatCsrfToken(handshakeHandler.attributes.get(CsrfToken.class.getName())).isEqualTo(this.token); assertThatCsrfToken(handshakeHandler.attributes.get(CsrfToken.class.getName())).isEqualTo(this.token);
assertThat(handshakeHandler.attributes.get(this.sessionAttr)) assertThat(handshakeHandler.attributes).containsEntry(this.sessionAttr,
.isEqualTo(request.getSession().getAttribute(this.sessionAttr)); request.getSession().getAttribute(this.sessionAttr));
} }
private HttpRequestHandler handler(HttpServletRequest request) throws Exception { private HttpRequestHandler handler(HttpServletRequest request) throws Exception {

View File

@ -371,8 +371,8 @@ public class WebSocketMessageBrokerSecurityConfigurationTests {
private void assertHandshake(HttpServletRequest request) { private void assertHandshake(HttpServletRequest request) {
TestHandshakeHandler handshakeHandler = this.context.getBean(TestHandshakeHandler.class); TestHandshakeHandler handshakeHandler = this.context.getBean(TestHandshakeHandler.class);
assertThatCsrfToken(handshakeHandler.attributes.get(CsrfToken.class.getName())).isEqualTo(this.token); assertThatCsrfToken(handshakeHandler.attributes.get(CsrfToken.class.getName())).isEqualTo(this.token);
assertThat(handshakeHandler.attributes.get(this.sessionAttr)) assertThat(handshakeHandler.attributes).containsEntry(this.sessionAttr,
.isEqualTo(request.getSession().getAttribute(this.sessionAttr)); request.getSession().getAttribute(this.sessionAttr));
} }
private HttpRequestHandler handler(HttpServletRequest request) throws Exception { private HttpRequestHandler handler(HttpServletRequest request) throws Exception {

View File

@ -418,7 +418,7 @@ public class MiscHttpConfigTests {
this.spring.configLocations(xml("DeleteCookies")).autowire(); this.spring.configLocations(xml("DeleteCookies")).autowire();
MvcResult result = this.mvc.perform(post("/logout").with(csrf())).andReturn(); MvcResult result = this.mvc.perform(post("/logout").with(csrf())).andReturn();
List<String> values = result.getResponse().getHeaders("Set-Cookie"); List<String> values = result.getResponse().getHeaders("Set-Cookie");
assertThat(values.size()).isEqualTo(2); assertThat(values).hasSize(2);
assertThat(values).extracting((value) -> value.split("=")[0]).contains("JSESSIONID", "mycookie"); assertThat(values).extracting((value) -> value.split("=")[0]).contains("JSESSIONID", "mycookie");
} }

View File

@ -16,7 +16,6 @@
package org.springframework.security.access.intercept; package org.springframework.security.access.intercept;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
@ -50,7 +49,7 @@ public class RunAsImplAuthenticationProviderTests {
RunAsImplAuthenticationProvider provider = new RunAsImplAuthenticationProvider(); RunAsImplAuthenticationProvider provider = new RunAsImplAuthenticationProvider();
provider.setKey("my_password"); provider.setKey("my_password");
Authentication result = provider.authenticate(token); Authentication result = provider.authenticate(token);
Assertions.assertTrue(result instanceof RunAsUserToken, "Should have returned RunAsUserToken"); assertThat(result instanceof RunAsUserToken).as("Should have returned RunAsUserToken").isTrue();
RunAsUserToken resultCast = (RunAsUserToken) result; RunAsUserToken resultCast = (RunAsUserToken) result;
assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode()); assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode());
} }

View File

@ -66,9 +66,9 @@ public class RunAsManagerImplTests {
assertThat(result.getPrincipal()).isEqualTo(inputToken.getPrincipal()); assertThat(result.getPrincipal()).isEqualTo(inputToken.getPrincipal());
assertThat(result.getCredentials()).isEqualTo(inputToken.getCredentials()); assertThat(result.getCredentials()).isEqualTo(inputToken.getCredentials());
Set<String> authorities = AuthorityUtils.authorityListToSet(result.getAuthorities()); Set<String> authorities = AuthorityUtils.authorityListToSet(result.getAuthorities());
assertThat(authorities.contains("FOOBAR_RUN_AS_SOMETHING")).isTrue(); assertThat(authorities).contains("FOOBAR_RUN_AS_SOMETHING");
assertThat(authorities.contains("ONE")).isTrue(); assertThat(authorities).contains("ONE");
assertThat(authorities.contains("TWO")).isTrue(); assertThat(authorities).contains("TWO");
RunAsUserToken resultCast = (RunAsUserToken) result; RunAsUserToken resultCast = (RunAsUserToken) result;
assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode()); assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode());
} }
@ -87,9 +87,9 @@ public class RunAsManagerImplTests {
assertThat(result.getPrincipal()).isEqualTo(inputToken.getPrincipal()); assertThat(result.getPrincipal()).isEqualTo(inputToken.getPrincipal());
assertThat(result.getCredentials()).isEqualTo(inputToken.getCredentials()); assertThat(result.getCredentials()).isEqualTo(inputToken.getCredentials());
Set<String> authorities = AuthorityUtils.authorityListToSet(result.getAuthorities()); Set<String> authorities = AuthorityUtils.authorityListToSet(result.getAuthorities());
assertThat(authorities.contains("ROLE_RUN_AS_SOMETHING")).isTrue(); assertThat(authorities).contains("ROLE_RUN_AS_SOMETHING");
assertThat(authorities.contains("ROLE_ONE")).isTrue(); assertThat(authorities).contains("ROLE_ONE");
assertThat(authorities.contains("ROLE_TWO")).isTrue(); assertThat(authorities).contains("ROLE_TWO");
RunAsUserToken resultCast = (RunAsUserToken) result; RunAsUserToken resultCast = (RunAsUserToken) result;
assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode()); assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode());
} }

View File

@ -50,7 +50,7 @@ public class DelegatingMethodSecurityMetadataSourceTests {
sources.add(delegate); sources.add(delegate);
this.mds = new DelegatingMethodSecurityMetadataSource(sources); this.mds = new DelegatingMethodSecurityMetadataSource(sources);
assertThat(this.mds.getMethodSecurityMetadataSources()).isSameAs(sources); assertThat(this.mds.getMethodSecurityMetadataSources()).isSameAs(sources);
assertThat(this.mds.getAllConfigAttributes().isEmpty()).isTrue(); assertThat(this.mds.getAllConfigAttributes()).isEmpty();
MethodInvocation mi = new SimpleMethodInvocation(null, String.class.getMethod("toString")); MethodInvocation mi = new SimpleMethodInvocation(null, String.class.getMethod("toString"));
assertThat(this.mds.getAttributes(mi)).isEqualTo(Collections.emptyList()); assertThat(this.mds.getAttributes(mi)).isEqualTo(Collections.emptyList());
// Exercise the cached case // Exercise the cached case
@ -68,7 +68,7 @@ public class DelegatingMethodSecurityMetadataSourceTests {
sources.add(delegate); sources.add(delegate);
this.mds = new DelegatingMethodSecurityMetadataSource(sources); this.mds = new DelegatingMethodSecurityMetadataSource(sources);
assertThat(this.mds.getMethodSecurityMetadataSources()).isSameAs(sources); assertThat(this.mds.getMethodSecurityMetadataSources()).isSameAs(sources);
assertThat(this.mds.getAllConfigAttributes().isEmpty()).isTrue(); assertThat(this.mds.getAllConfigAttributes()).isEmpty();
MethodInvocation mi = new SimpleMethodInvocation("", toString); MethodInvocation mi = new SimpleMethodInvocation("", toString);
assertThat(this.mds.getAttributes(mi)).isSameAs(attributes); assertThat(this.mds.getAttributes(mi)).isSameAs(attributes);
// Exercise the cached case // Exercise the cached case

View File

@ -89,7 +89,7 @@ public class InMemoryConfigurationTests {
public void mappedNonnullDefault() { public void mappedNonnullDefault() {
InMemoryConfiguration configuration = new InMemoryConfiguration(this.mappedEntries, this.defaultEntries); InMemoryConfiguration configuration = new InMemoryConfiguration(this.mappedEntries, this.defaultEntries);
assertThat(this.defaultEntries).isEqualTo(configuration.getAppConfigurationEntry("missing")); assertThat(this.defaultEntries).isEqualTo(configuration.getAppConfigurationEntry("missing"));
assertThat(this.mappedEntries.get("name")).isEqualTo(configuration.getAppConfigurationEntry("name")); assertThat(this.mappedEntries).containsEntry("name", configuration.getAppConfigurationEntry("name"));
} }
@Test @Test

View File

@ -37,11 +37,11 @@ public class AuthorityUtilsTests {
List<GrantedAuthority> authorityArray = AuthorityUtils List<GrantedAuthority> authorityArray = AuthorityUtils
.commaSeparatedStringToAuthorityList(" ROLE_A, B, C, ROLE_D\n,\n E "); .commaSeparatedStringToAuthorityList(" ROLE_A, B, C, ROLE_D\n,\n E ");
Set<String> authorities = AuthorityUtils.authorityListToSet(authorityArray); Set<String> authorities = AuthorityUtils.authorityListToSet(authorityArray);
assertThat(authorities.contains("B")).isTrue(); assertThat(authorities).contains("B");
assertThat(authorities.contains("C")).isTrue(); assertThat(authorities).contains("C");
assertThat(authorities.contains("E")).isTrue(); assertThat(authorities).contains("E");
assertThat(authorities.contains("ROLE_A")).isTrue(); assertThat(authorities).contains("ROLE_A");
assertThat(authorities.contains("ROLE_D")).isTrue(); assertThat(authorities).contains("ROLE_D");
} }
@Test @Test

View File

@ -45,8 +45,8 @@ public class SimpleAuthoritiesMapperTests {
SimpleAuthorityMapper mapper = new SimpleAuthorityMapper(); SimpleAuthorityMapper mapper = new SimpleAuthorityMapper();
Set<String> mapped = AuthorityUtils Set<String> mapped = AuthorityUtils
.authorityListToSet(mapper.mapAuthorities(AuthorityUtils.createAuthorityList("AaA", "ROLE_bbb"))); .authorityListToSet(mapper.mapAuthorities(AuthorityUtils.createAuthorityList("AaA", "ROLE_bbb")));
assertThat(mapped.contains("ROLE_AaA")).isTrue(); assertThat(mapped).contains("ROLE_AaA");
assertThat(mapped.contains("ROLE_bbb")).isTrue(); assertThat(mapped).contains("ROLE_bbb");
} }
@Test @Test
@ -56,19 +56,19 @@ public class SimpleAuthoritiesMapperTests {
List<GrantedAuthority> toMap = AuthorityUtils.createAuthorityList("AaA", "Bbb"); List<GrantedAuthority> toMap = AuthorityUtils.createAuthorityList("AaA", "Bbb");
Set<String> mapped = AuthorityUtils.authorityListToSet(mapper.mapAuthorities(toMap)); Set<String> mapped = AuthorityUtils.authorityListToSet(mapper.mapAuthorities(toMap));
assertThat(mapped).hasSize(2); assertThat(mapped).hasSize(2);
assertThat(mapped.contains("AaA")).isTrue(); assertThat(mapped).contains("AaA");
assertThat(mapped.contains("Bbb")).isTrue(); assertThat(mapped).contains("Bbb");
mapper.setConvertToLowerCase(true); mapper.setConvertToLowerCase(true);
mapped = AuthorityUtils.authorityListToSet(mapper.mapAuthorities(toMap)); mapped = AuthorityUtils.authorityListToSet(mapper.mapAuthorities(toMap));
assertThat(mapped).hasSize(2); assertThat(mapped).hasSize(2);
assertThat(mapped.contains("aaa")).isTrue(); assertThat(mapped).contains("aaa");
assertThat(mapped.contains("bbb")).isTrue(); assertThat(mapped).contains("bbb");
mapper.setConvertToLowerCase(false); mapper.setConvertToLowerCase(false);
mapper.setConvertToUpperCase(true); mapper.setConvertToUpperCase(true);
mapped = AuthorityUtils.authorityListToSet(mapper.mapAuthorities(toMap)); mapped = AuthorityUtils.authorityListToSet(mapper.mapAuthorities(toMap));
assertThat(mapped).hasSize(2); assertThat(mapped).hasSize(2);
assertThat(mapped.contains("AAA")).isTrue(); assertThat(mapped).contains("AAA");
assertThat(mapped.contains("BBB")).isTrue(); assertThat(mapped).contains("BBB");
} }
@Test @Test
@ -86,7 +86,7 @@ public class SimpleAuthoritiesMapperTests {
mapper.setDefaultAuthority("ROLE_USER"); mapper.setDefaultAuthority("ROLE_USER");
Set<String> mapped = AuthorityUtils.authorityListToSet(mapper.mapAuthorities(AuthorityUtils.NO_AUTHORITIES)); Set<String> mapped = AuthorityUtils.authorityListToSet(mapper.mapAuthorities(AuthorityUtils.NO_AUTHORITIES));
assertThat(mapped).hasSize(1); assertThat(mapped).hasSize(1);
assertThat(mapped.contains("ROLE_USER")).isTrue(); assertThat(mapped).contains("ROLE_USER");
} }
} }

View File

@ -97,8 +97,8 @@ public class SessionRegistryImplTests {
this.sessionRegistry.registerNewSession(sessionId2, principal1); this.sessionRegistry.registerNewSession(sessionId2, principal1);
this.sessionRegistry.registerNewSession(sessionId3, principal2); this.sessionRegistry.registerNewSession(sessionId3, principal2);
assertThat(this.sessionRegistry.getAllPrincipals()).hasSize(2); assertThat(this.sessionRegistry.getAllPrincipals()).hasSize(2);
assertThat(this.sessionRegistry.getAllPrincipals().contains(principal1)).isTrue(); assertThat(this.sessionRegistry.getAllPrincipals()).contains(principal1);
assertThat(this.sessionRegistry.getAllPrincipals().contains(principal2)).isTrue(); assertThat(this.sessionRegistry.getAllPrincipals()).contains(principal2);
} }
@Test @Test

View File

@ -189,7 +189,7 @@ public class JdbcUserDetailsManagerTests {
public void userExistsReturnsTrueForExistingUsername() { public void userExistsReturnsTrueForExistingUsername() {
insertJoe(); insertJoe();
assertThat(this.manager.userExists("joe")).isTrue(); assertThat(this.manager.userExists("joe")).isTrue();
assertThat(this.cache.getUserMap().containsKey("joe")).isTrue(); assertThat(this.cache.getUserMap()).containsKey("joe");
} }
@Test @Test
@ -251,7 +251,7 @@ public class JdbcUserDetailsManagerTests {
UserDetails newJoe = this.manager.loadUserByUsername("joe"); UserDetails newJoe = this.manager.loadUserByUsername("joe");
assertThat(newJoe.getPassword()).isEqualTo("password"); assertThat(newJoe.getPassword()).isEqualTo("password");
assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("password"); assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials()).isEqualTo("password");
assertThat(this.cache.getUserMap().containsKey("joe")).isTrue(); assertThat(this.cache.getUserMap()).containsKey("joe");
} }
@Test @Test

View File

@ -390,7 +390,7 @@ public class BCryptTests {
Arrays.fill(ba, (byte) 0); Arrays.fill(ba, (byte) 0);
ba[i] = (byte) b; ba[i] = (byte) b;
String s = encode_base64(ba, 3); String s = encode_base64(ba, 3);
assertThat(s.length()).isEqualTo(4); assertThat(s).hasSize(4);
byte[] decoded = BCrypt.decode_base64(s, 3); byte[] decoded = BCrypt.decode_base64(s, 3);
assertThat(decoded).isEqualTo(ba); assertThat(decoded).isEqualTo(ba);
} }

View File

@ -20,7 +20,6 @@ import java.security.SecureRandom;
import java.util.Random; import java.util.Random;
import java.util.UUID; import java.util.UUID;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -29,6 +28,8 @@ import org.springframework.security.crypto.encrypt.AesBytesEncryptor.CipherAlgor
import org.springframework.security.crypto.keygen.BytesKeyGenerator; import org.springframework.security.crypto.keygen.BytesKeyGenerator;
import org.springframework.security.crypto.keygen.KeyGenerators; import org.springframework.security.crypto.keygen.KeyGenerators;
import static org.assertj.core.api.Assertions.assertThat;
public class BouncyCastleAesBytesEncryptorEquivalencyTests { public class BouncyCastleAesBytesEncryptorEquivalencyTests {
private byte[] testData; private byte[] testData;
@ -96,11 +97,11 @@ public class BouncyCastleAesBytesEncryptorEquivalencyTests {
// and can decrypt back to the original input // and can decrypt back to the original input
byte[] leftEncrypted = left.encrypt(this.testData); byte[] leftEncrypted = left.encrypt(this.testData);
byte[] rightEncrypted = right.encrypt(this.testData); byte[] rightEncrypted = right.encrypt(this.testData);
Assertions.assertArrayEquals(leftEncrypted, rightEncrypted); assertThat(rightEncrypted).containsExactly(leftEncrypted);
byte[] leftDecrypted = left.decrypt(leftEncrypted); byte[] leftDecrypted = left.decrypt(leftEncrypted);
byte[] rightDecrypted = right.decrypt(rightEncrypted); byte[] rightDecrypted = right.decrypt(rightEncrypted);
Assertions.assertArrayEquals(this.testData, leftDecrypted); assertThat(leftDecrypted).containsExactly(this.testData);
Assertions.assertArrayEquals(this.testData, rightDecrypted); assertThat(rightDecrypted).containsExactly(this.testData);
} }
} }
@ -114,8 +115,8 @@ public class BouncyCastleAesBytesEncryptorEquivalencyTests {
byte[] rightEncrypted = right.encrypt(this.testData); byte[] rightEncrypted = right.encrypt(this.testData);
byte[] leftDecrypted = left.decrypt(rightEncrypted); byte[] leftDecrypted = left.decrypt(rightEncrypted);
byte[] rightDecrypted = right.decrypt(leftEncrypted); byte[] rightDecrypted = right.decrypt(leftEncrypted);
Assertions.assertArrayEquals(this.testData, leftDecrypted); assertThat(leftDecrypted).containsExactly(this.testData);
Assertions.assertArrayEquals(this.testData, rightDecrypted); assertThat(rightDecrypted).containsExactly(this.testData);
} }
} }

View File

@ -20,13 +20,13 @@ import java.security.SecureRandom;
import java.util.UUID; import java.util.UUID;
import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Arrays;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.security.crypto.codec.Hex; import org.springframework.security.crypto.codec.Hex;
import org.springframework.security.crypto.keygen.KeyGenerators; import org.springframework.security.crypto.keygen.KeyGenerators;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
public class BouncyCastleAesBytesEncryptorTests { public class BouncyCastleAesBytesEncryptorTests {
@ -64,11 +64,11 @@ public class BouncyCastleAesBytesEncryptorTests {
private void generatesDifferentCipherTexts(BytesEncryptor bcEncryptor) { private void generatesDifferentCipherTexts(BytesEncryptor bcEncryptor) {
byte[] encrypted1 = bcEncryptor.encrypt(this.testData); byte[] encrypted1 = bcEncryptor.encrypt(this.testData);
byte[] encrypted2 = bcEncryptor.encrypt(this.testData); byte[] encrypted2 = bcEncryptor.encrypt(this.testData);
Assertions.assertFalse(Arrays.areEqual(encrypted1, encrypted2)); assertThat(Arrays.areEqual(encrypted1, encrypted2)).isFalse();
byte[] decrypted1 = bcEncryptor.decrypt(encrypted1); byte[] decrypted1 = bcEncryptor.decrypt(encrypted1);
byte[] decrypted2 = bcEncryptor.decrypt(encrypted2); byte[] decrypted2 = bcEncryptor.decrypt(encrypted2);
Assertions.assertArrayEquals(this.testData, decrypted1); assertThat(decrypted1).containsExactly(this.testData);
Assertions.assertArrayEquals(this.testData, decrypted2); assertThat(decrypted2).containsExactly(this.testData);
} }
@Test @Test

View File

@ -60,7 +60,7 @@ public class KeyGeneratorsTests {
public void string() { public void string() {
StringKeyGenerator keyGenerator = KeyGenerators.string(); StringKeyGenerator keyGenerator = KeyGenerators.string();
String hexStringKey = keyGenerator.generateKey(); String hexStringKey = keyGenerator.generateKey();
assertThat(hexStringKey.length()).isEqualTo(16); assertThat(hexStringKey).hasSize(16);
assertThat(Hex.decode(hexStringKey)).hasSize(8); assertThat(Hex.decode(hexStringKey)).hasSize(8);
String hexStringKey2 = keyGenerator.generateKey(); String hexStringKey2 = keyGenerator.generateKey();
assertThat(hexStringKey.equals(hexStringKey2)).isFalse(); assertThat(hexStringKey.equals(hexStringKey2)).isFalse();

View File

@ -39,8 +39,8 @@ public class Pbkdf2PasswordEncoderTests {
// encode output is an hex coded String so with 2 chars per encoding result byte // encode output is an hex coded String so with 2 chars per encoding result byte
// (ie. 1 char for 4 bits). // (ie. 1 char for 4 bits).
// The encoding result size is : (saltLength * 8) bits + hashWith bits. // The encoding result size is : (saltLength * 8) bits + hashWith bits.
assertThat(this.encoder.encode("password").length()).isEqualTo((8 * 8 + 256) / 4); assertThat(this.encoder.encode("password")).hasSize((8 * 8 + 256) / 4);
assertThat(this.encoderSalt16.encode("password").length()).isEqualTo((16 * 8 + 256) / 4); assertThat(this.encoderSalt16.encode("password")).hasSize((16 * 8 + 256) / 4);
} }
@Test @Test

View File

@ -104,9 +104,9 @@ public class SpringSecurityLdapTemplateITests {
new String[] { param }, "ou"); new String[] { param }, "ou");
assertThat(values).as("Expected 3 results from search").hasSize(3); assertThat(values).as("Expected 3 results from search").hasSize(3);
assertThat(values.contains("developer")).isTrue(); assertThat(values).contains("developer");
assertThat(values.contains("manager")).isTrue(); assertThat(values).contains("manager");
assertThat(values.contains("submanager")).isTrue(); assertThat(values).contains("submanager");
} }
@Test @Test
@ -149,7 +149,7 @@ public class SpringSecurityLdapTemplateITests {
} }
protected void assertAttributeValue(Map<String, List<String>> record, String attributeName, String... values) { protected void assertAttributeValue(Map<String, List<String>> record, String attributeName, String... values) {
assertThat(record.containsKey(attributeName)).isTrue(); assertThat(record).containsKey(attributeName);
assertThat(record.get(attributeName)).hasSize(values.length); assertThat(record.get(attributeName)).hasSize(values.length);
for (int i = 0; i < values.length; i++) { for (int i = 0; i < values.length; i++) {
assertThat(record.get(attributeName).get(i)).isEqualTo(values[i]); assertThat(record.get(attributeName).get(i)).isEqualTo(values[i]);

View File

@ -72,8 +72,8 @@ public class DefaultLdapAuthoritiesPopulatorGetGrantedAuthoritiesTests {
assertThat(authorities).as("Should have 1 role").hasSize(2); assertThat(authorities).as("Should have 1 role").hasSize(2);
assertThat(authorities.contains("ROLE_DEVELOPER")).isTrue(); assertThat(authorities).contains("ROLE_DEVELOPER");
assertThat(authorities.contains("ROLE_")).isTrue(); assertThat(authorities).contains("ROLE_");
} }
@Configuration @Configuration

View File

@ -68,7 +68,7 @@ public class DefaultLdapAuthoritiesPopulatorTests {
Collection<GrantedAuthority> authorities = this.populator.getGrantedAuthorities(ctx, "notfound"); Collection<GrantedAuthority> authorities = this.populator.getGrantedAuthorities(ctx, "notfound");
assertThat(authorities).hasSize(1); assertThat(authorities).hasSize(1);
assertThat(AuthorityUtils.authorityListToSet(authorities).contains("ROLE_USER")).isTrue(); assertThat(AuthorityUtils.authorityListToSet(authorities)).contains("ROLE_USER");
} }
@Test @Test
@ -79,7 +79,7 @@ public class DefaultLdapAuthoritiesPopulatorTests {
Collection<GrantedAuthority> authorities = this.populator Collection<GrantedAuthority> authorities = this.populator
.getGrantedAuthorities(new DirContextAdapter(new DistinguishedName("cn=notused")), "notused"); .getGrantedAuthorities(new DirContextAdapter(new DistinguishedName("cn=notused")), "notused");
assertThat(authorities).hasSize(1); assertThat(authorities).hasSize(1);
assertThat(AuthorityUtils.authorityListToSet(authorities).contains("ROLE_USER")).isTrue(); assertThat(AuthorityUtils.authorityListToSet(authorities)).contains("ROLE_USER");
} }
@Test @Test
@ -98,8 +98,8 @@ public class DefaultLdapAuthoritiesPopulatorTests {
assertThat(authorities).as("Should have 2 roles").hasSize(2); assertThat(authorities).as("Should have 2 roles").hasSize(2);
assertThat(authorities.contains("ROLE_DEVELOPER")).isTrue(); assertThat(authorities).contains("ROLE_DEVELOPER");
assertThat(authorities.contains("ROLE_MANAGER")).isTrue(); assertThat(authorities).contains("ROLE_MANAGER");
} }
@Test @Test
@ -115,7 +115,7 @@ public class DefaultLdapAuthoritiesPopulatorTests {
.authorityListToSet(this.populator.getGrantedAuthorities(ctx, "manager")); .authorityListToSet(this.populator.getGrantedAuthorities(ctx, "manager"));
assertThat(authorities).as("Should have 1 role").hasSize(1); assertThat(authorities).as("Should have 1 role").hasSize(1);
assertThat(authorities.contains("ROLE_MANAGER")).isTrue(); assertThat(authorities).contains("ROLE_MANAGER");
} }
@Test @Test
@ -130,8 +130,8 @@ public class DefaultLdapAuthoritiesPopulatorTests {
.authorityListToSet(this.populator.getGrantedAuthorities(ctx, "manager")); .authorityListToSet(this.populator.getGrantedAuthorities(ctx, "manager"));
assertThat(authorities).as("Should have 2 roles").hasSize(2); assertThat(authorities).as("Should have 2 roles").hasSize(2);
assertThat(authorities.contains("ROLE_MANAGER")).isTrue(); assertThat(authorities).contains("ROLE_MANAGER");
assertThat(authorities.contains("ROLE_DEVELOPER")).isTrue(); assertThat(authorities).contains("ROLE_DEVELOPER");
} }
@Test @Test
@ -147,9 +147,9 @@ public class DefaultLdapAuthoritiesPopulatorTests {
.authorityListToSet(this.populator.getGrantedAuthorities(ctx, "manager")); .authorityListToSet(this.populator.getGrantedAuthorities(ctx, "manager"));
assertThat(authorities).as("Should have 3 roles").hasSize(3); assertThat(authorities).as("Should have 3 roles").hasSize(3);
assertThat(authorities.contains("ROLE_MANAGER")).isTrue(); assertThat(authorities).contains("ROLE_MANAGER");
assertThat(authorities.contains("ROLE_SUBMANAGER")).isTrue(); assertThat(authorities).contains("ROLE_SUBMANAGER");
assertThat(authorities.contains("ROLE_DEVELOPER")).isTrue(); assertThat(authorities).contains("ROLE_DEVELOPER");
} }
@Test @Test
@ -164,7 +164,7 @@ public class DefaultLdapAuthoritiesPopulatorTests {
Collection<GrantedAuthority> authorities = this.populator Collection<GrantedAuthority> authorities = this.populator
.getGrantedAuthorities(new DirContextAdapter(new DistinguishedName("cn=notused")), "notused"); .getGrantedAuthorities(new DirContextAdapter(new DistinguishedName("cn=notused")), "notused");
assertThat(authorities).hasSize(1); assertThat(authorities).hasSize(1);
assertThat(AuthorityUtils.authorityListToSet(authorities).contains("ROLE_EXTRA")).isTrue(); assertThat(AuthorityUtils.authorityListToSet(authorities)).contains("ROLE_EXTRA");
} }
@Test @Test
@ -180,7 +180,7 @@ public class DefaultLdapAuthoritiesPopulatorTests {
.authorityListToSet(this.populator.getGrantedAuthorities(ctx, "notused")); .authorityListToSet(this.populator.getGrantedAuthorities(ctx, "notused"));
assertThat(authorities).as("Should have 1 role").hasSize(1); assertThat(authorities).as("Should have 1 role").hasSize(1);
assertThat(authorities.contains("ROLE_MANAGER")).isTrue(); assertThat(authorities).contains("ROLE_MANAGER");
} }
@Test @Test

View File

@ -128,14 +128,14 @@ public class NestedLdapAuthoritiesPopulatorTests {
LdapAuthority[] ldapAuthorities = authorities.toArray(new LdapAuthority[0]); LdapAuthority[] ldapAuthorities = authorities.toArray(new LdapAuthority[0]);
assertThat(ldapAuthorities).hasSize(5); assertThat(ldapAuthorities).hasSize(5);
// groovy-developers group // groovy-developers group
assertThat(ldapAuthorities[0].getAttributes().containsKey("member")).isTrue(); assertThat(ldapAuthorities[0].getAttributes()).containsKey("member");
assertThat(ldapAuthorities[0].getAttributes().get("member")).isNotNull(); assertThat(ldapAuthorities[0].getAttributes().get("member")).isNotNull();
assertThat(ldapAuthorities[0].getAttributes().get("member")).hasSize(3); assertThat(ldapAuthorities[0].getAttributes().get("member")).hasSize(3);
assertThat(ldapAuthorities[0].getFirstAttributeValue("member")) assertThat(ldapAuthorities[0].getFirstAttributeValue("member"))
.isEqualTo("cn=groovy-developers,ou=jdeveloper,dc=springframework,dc=org"); .isEqualTo("cn=groovy-developers,ou=jdeveloper,dc=springframework,dc=org");
// java group // java group
assertThat(ldapAuthorities[1].getAttributes().containsKey("member")).isTrue(); assertThat(ldapAuthorities[1].getAttributes()).containsKey("member");
assertThat(ldapAuthorities[1].getAttributes().get("member")).isNotNull(); assertThat(ldapAuthorities[1].getAttributes().get("member")).isNotNull();
assertThat(ldapAuthorities[1].getAttributes().get("member")).hasSize(3); assertThat(ldapAuthorities[1].getAttributes().get("member")).hasSize(3);
assertThat(this.groovyDevelopers.getDn()).isEqualTo(ldapAuthorities[1].getFirstAttributeValue("member")); assertThat(this.groovyDevelopers.getDn()).isEqualTo(ldapAuthorities[1].getFirstAttributeValue("member"));

View File

@ -46,7 +46,7 @@ public class InetOrgPersonTests {
InetOrgPerson p2 = (InetOrgPerson) essence.createUserDetails(); InetOrgPerson p2 = (InetOrgPerson) essence.createUserDetails();
Set<InetOrgPerson> set = new HashSet<>(); Set<InetOrgPerson> set = new HashSet<>();
set.add(p); set.add(p);
assertThat(set.contains(p2)).isTrue(); assertThat(set).contains(p2);
} }
@Test @Test

View File

@ -60,7 +60,7 @@ public class LdapUserDetailsServiceTests {
UserDetails user = service.loadUserByUsername("doesntmatterwegetjoeanyway"); UserDetails user = service.loadUserByUsername("doesntmatterwegetjoeanyway");
Set<String> authorities = AuthorityUtils.authorityListToSet(user.getAuthorities()); Set<String> authorities = AuthorityUtils.authorityListToSet(user.getAuthorities());
assertThat(authorities).hasSize(1); assertThat(authorities).hasSize(1);
assertThat(authorities.contains("ROLE_FROM_POPULATOR")).isTrue(); assertThat(authorities).contains("ROLE_FROM_POPULATOR");
} }
@Test @Test

View File

@ -47,7 +47,7 @@ public class UserDetailsServiceLdapAuthoritiesPopulatorTests {
UserDetailsServiceLdapAuthoritiesPopulator populator = new UserDetailsServiceLdapAuthoritiesPopulator(uds); UserDetailsServiceLdapAuthoritiesPopulator populator = new UserDetailsServiceLdapAuthoritiesPopulator(uds);
Collection<? extends GrantedAuthority> auths = populator.getGrantedAuthorities(new DirContextAdapter(), "joe"); Collection<? extends GrantedAuthority> auths = populator.getGrantedAuthorities(new DirContextAdapter(), "joe");
assertThat(auths).hasSize(1); assertThat(auths).hasSize(1);
assertThat(AuthorityUtils.authorityListToSet(auths).contains("ROLE_USER")).isTrue(); assertThat(AuthorityUtils.authorityListToSet(auths)).contains("ROLE_USER");
} }
} }

View File

@ -113,7 +113,7 @@ public class SimpDestinationMessageMatcherTests {
this.matcher = new SimpDestinationMessageMatcher("/topics/{topic}/**"); this.matcher = new SimpDestinationMessageMatcher("/topics/{topic}/**");
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "/topics/someTopic/sub1"); this.messageBuilder.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "/topics/someTopic/sub1");
this.messageBuilder.setHeader(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER, SimpMessageType.MESSAGE); this.messageBuilder.setHeader(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER, SimpMessageType.MESSAGE);
assertThat(this.matcher.extractPathVariables(this.messageBuilder.build()).get("topic")).isEqualTo("someTopic"); assertThat(this.matcher.extractPathVariables(this.messageBuilder.build())).containsEntry("topic", "someTopic");
} }
@Test @Test

View File

@ -75,7 +75,7 @@ public class CsrfTokenHandshakeInterceptorTests {
CsrfToken token = new DefaultCsrfToken("header", "param", "token"); CsrfToken token = new DefaultCsrfToken("header", "param", "token");
this.httpRequest.setAttribute(DeferredCsrfToken.class.getName(), new TestDeferredCsrfToken(token)); this.httpRequest.setAttribute(DeferredCsrfToken.class.getName(), new TestDeferredCsrfToken(token));
this.interceptor.beforeHandshake(this.request, this.response, this.wsHandler, this.attributes); this.interceptor.beforeHandshake(this.request, this.response, this.wsHandler, this.attributes);
assertThat(this.attributes.keySet()).containsOnly(CsrfToken.class.getName()); assertThat(this.attributes).containsOnlyKeys(CsrfToken.class.getName());
CsrfToken csrfToken = (CsrfToken) this.attributes.get(CsrfToken.class.getName()); CsrfToken csrfToken = (CsrfToken) this.attributes.get(CsrfToken.class.getName());
assertThat(csrfToken.getHeaderName()).isEqualTo(token.getHeaderName()); assertThat(csrfToken.getHeaderName()).isEqualTo(token.getHeaderName());
assertThat(csrfToken.getParameterName()).isEqualTo(token.getParameterName()); assertThat(csrfToken.getParameterName()).isEqualTo(token.getParameterName());

View File

@ -130,7 +130,7 @@ public class DefaultAuthorizationCodeTokenResponseClientTests {
assertThat(accessTokenResponse.getAccessToken().getExpiresAt()).isBetween(expiresAtBefore, expiresAtAfter); assertThat(accessTokenResponse.getAccessToken().getExpiresAt()).isBetween(expiresAtBefore, expiresAtAfter);
assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("read", "write"); assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("read", "write");
assertThat(accessTokenResponse.getRefreshToken().getTokenValue()).isEqualTo("refresh-token-1234"); assertThat(accessTokenResponse.getRefreshToken().getTokenValue()).isEqualTo("refresh-token-1234");
assertThat(accessTokenResponse.getAdditionalParameters().size()).isEqualTo(2); assertThat(accessTokenResponse.getAdditionalParameters()).hasSize(2);
assertThat(accessTokenResponse.getAdditionalParameters()).containsEntry("custom_parameter_1", "custom-value-1"); assertThat(accessTokenResponse.getAdditionalParameters()).containsEntry("custom_parameter_1", "custom-value-1");
assertThat(accessTokenResponse.getAdditionalParameters()).containsEntry("custom_parameter_2", "custom-value-2"); assertThat(accessTokenResponse.getAdditionalParameters()).containsEntry("custom_parameter_2", "custom-value-2");
} }

View File

@ -132,7 +132,7 @@ public class DefaultClientCredentialsTokenResponseClientTests {
assertThat(accessTokenResponse.getAccessToken().getExpiresAt()).isBetween(expiresAtBefore, expiresAtAfter); assertThat(accessTokenResponse.getAccessToken().getExpiresAt()).isBetween(expiresAtBefore, expiresAtAfter);
assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("read", "write"); assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("read", "write");
assertThat(accessTokenResponse.getRefreshToken()).isNull(); assertThat(accessTokenResponse.getRefreshToken()).isNull();
assertThat(accessTokenResponse.getAdditionalParameters().size()).isEqualTo(2); assertThat(accessTokenResponse.getAdditionalParameters()).hasSize(2);
assertThat(accessTokenResponse.getAdditionalParameters()).containsEntry("custom_parameter_1", "custom-value-1"); assertThat(accessTokenResponse.getAdditionalParameters()).containsEntry("custom_parameter_1", "custom-value-1");
assertThat(accessTokenResponse.getAdditionalParameters()).containsEntry("custom_parameter_2", "custom-value-2"); assertThat(accessTokenResponse.getAdditionalParameters()).containsEntry("custom_parameter_2", "custom-value-2");
} }

View File

@ -140,8 +140,8 @@ public class NimbusJwtClientAuthenticationParametersConverterTests {
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withPublicKey(rsaJwk.toRSAPublicKey()).build(); NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withPublicKey(rsaJwk.toRSAPublicKey()).build();
Jwt jws = jwtDecoder.decode(encodedJws); Jwt jws = jwtDecoder.decode(encodedJws);
assertThat(jws.getHeaders().get(JoseHeaderNames.ALG)).isEqualTo(SignatureAlgorithm.RS256.getName()); assertThat(jws.getHeaders()).containsEntry(JoseHeaderNames.ALG, SignatureAlgorithm.RS256.getName());
assertThat(jws.getHeaders().get(JoseHeaderNames.KID)).isEqualTo(rsaJwk.getKeyID()); assertThat(jws.getHeaders()).containsEntry(JoseHeaderNames.KID, rsaJwk.getKeyID());
assertThat(jws.<String>getClaim(JwtClaimNames.ISS)).isEqualTo(clientRegistration.getClientId()); assertThat(jws.<String>getClaim(JwtClaimNames.ISS)).isEqualTo(clientRegistration.getClientId());
assertThat(jws.getSubject()).isEqualTo(clientRegistration.getClientId()); assertThat(jws.getSubject()).isEqualTo(clientRegistration.getClientId());
assertThat(jws.getAudience()) assertThat(jws.getAudience())
@ -174,8 +174,8 @@ public class NimbusJwtClientAuthenticationParametersConverterTests {
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withSecretKey(secretJwk.toSecretKey()).build(); NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withSecretKey(secretJwk.toSecretKey()).build();
Jwt jws = jwtDecoder.decode(encodedJws); Jwt jws = jwtDecoder.decode(encodedJws);
assertThat(jws.getHeaders().get(JoseHeaderNames.ALG)).isEqualTo(MacAlgorithm.HS256.getName()); assertThat(jws.getHeaders()).containsEntry(JoseHeaderNames.ALG, MacAlgorithm.HS256.getName());
assertThat(jws.getHeaders().get(JoseHeaderNames.KID)).isEqualTo(secretJwk.getKeyID()); assertThat(jws.getHeaders()).containsEntry(JoseHeaderNames.KID, secretJwk.getKeyID());
assertThat(jws.<String>getClaim(JwtClaimNames.ISS)).isEqualTo(clientRegistration.getClientId()); assertThat(jws.<String>getClaim(JwtClaimNames.ISS)).isEqualTo(clientRegistration.getClientId());
assertThat(jws.getSubject()).isEqualTo(clientRegistration.getClientId()); assertThat(jws.getSubject()).isEqualTo(clientRegistration.getClientId());
assertThat(jws.getAudience()) assertThat(jws.getAudience())
@ -217,9 +217,9 @@ public class NimbusJwtClientAuthenticationParametersConverterTests {
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withSecretKey(secretJwk.toSecretKey()).build(); NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withSecretKey(secretJwk.toSecretKey()).build();
Jwt jws = jwtDecoder.decode(encodedJws); Jwt jws = jwtDecoder.decode(encodedJws);
assertThat(jws.getHeaders().get(JoseHeaderNames.ALG)).isEqualTo(MacAlgorithm.HS256.getName()); assertThat(jws.getHeaders()).containsEntry(JoseHeaderNames.ALG, MacAlgorithm.HS256.getName());
assertThat(jws.getHeaders().get(JoseHeaderNames.KID)).isEqualTo(secretJwk.getKeyID()); assertThat(jws.getHeaders()).containsEntry(JoseHeaderNames.KID, secretJwk.getKeyID());
assertThat(jws.getHeaders().get(headerName)).isEqualTo(headerValue); assertThat(jws.getHeaders()).containsEntry(headerName, headerValue);
assertThat(jws.<String>getClaim(JwtClaimNames.ISS)).isEqualTo(clientRegistration.getClientId()); assertThat(jws.<String>getClaim(JwtClaimNames.ISS)).isEqualTo(clientRegistration.getClientId());
assertThat(jws.getSubject()).isEqualTo(clientRegistration.getClientId()); assertThat(jws.getSubject()).isEqualTo(clientRegistration.getClientId());
assertThat(jws.getAudience()) assertThat(jws.getAudience())

View File

@ -117,7 +117,7 @@ public class WebClientReactiveAuthorizationCodeTokenResponseClientTests {
assertThat(accessTokenResponse.getAccessToken().getExpiresAt()).isBetween(expiresAtBefore, expiresAtAfter); assertThat(accessTokenResponse.getAccessToken().getExpiresAt()).isBetween(expiresAtBefore, expiresAtAfter);
assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("openid", "profile"); assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("openid", "profile");
assertThat(accessTokenResponse.getRefreshToken().getTokenValue()).isEqualTo("refresh-token-1234"); assertThat(accessTokenResponse.getRefreshToken().getTokenValue()).isEqualTo("refresh-token-1234");
assertThat(accessTokenResponse.getAdditionalParameters().size()).isEqualTo(2); assertThat(accessTokenResponse.getAdditionalParameters()).hasSize(2);
assertThat(accessTokenResponse.getAdditionalParameters()).containsEntry("custom_parameter_1", "custom-value-1"); assertThat(accessTokenResponse.getAdditionalParameters()).containsEntry("custom_parameter_1", "custom-value-1");
assertThat(accessTokenResponse.getAdditionalParameters()).containsEntry("custom_parameter_2", "custom-value-2"); assertThat(accessTokenResponse.getAdditionalParameters()).containsEntry("custom_parameter_2", "custom-value-2");
} }

View File

@ -234,7 +234,7 @@ public class OidcUserServiceTests {
.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken)); .loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken));
assertThat(user.getIdToken()).isNotNull(); assertThat(user.getIdToken()).isNotNull();
assertThat(user.getUserInfo()).isNotNull(); assertThat(user.getUserInfo()).isNotNull();
assertThat(user.getUserInfo().getClaims().size()).isEqualTo(6); assertThat(user.getUserInfo().getClaims()).hasSize(6);
assertThat(user.getIdToken()).isEqualTo(this.idToken); assertThat(user.getIdToken()).isEqualTo(this.idToken);
assertThat(user.getName()).isEqualTo("subject1"); assertThat(user.getName()).isEqualTo("subject1");
assertThat(user.getUserInfo().getSubject()).isEqualTo("subject1"); assertThat(user.getUserInfo().getSubject()).isEqualTo("subject1");
@ -243,7 +243,7 @@ public class OidcUserServiceTests {
assertThat(user.getUserInfo().getFamilyName()).isEqualTo("last"); assertThat(user.getUserInfo().getFamilyName()).isEqualTo("last");
assertThat(user.getUserInfo().getPreferredUsername()).isEqualTo("user1"); assertThat(user.getUserInfo().getPreferredUsername()).isEqualTo("user1");
assertThat(user.getUserInfo().getEmail()).isEqualTo("user1@example.com"); assertThat(user.getUserInfo().getEmail()).isEqualTo("user1@example.com");
assertThat(user.getAuthorities().size()).isEqualTo(3); assertThat(user.getAuthorities()).hasSize(3);
assertThat(user.getAuthorities().iterator().next()).isInstanceOf(OidcUserAuthority.class); assertThat(user.getAuthorities().iterator().next()).isInstanceOf(OidcUserAuthority.class);
OidcUserAuthority userAuthority = (OidcUserAuthority) user.getAuthorities().iterator().next(); OidcUserAuthority userAuthority = (OidcUserAuthority) user.getAuthorities().iterator().next();
assertThat(userAuthority.getAuthority()).isEqualTo("OIDC_USER"); assertThat(userAuthority.getAuthority()).isEqualTo("OIDC_USER");

View File

@ -144,14 +144,14 @@ public class DefaultOAuth2UserServiceTests {
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build(); .userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
OAuth2User user = this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)); OAuth2User user = this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken));
assertThat(user.getName()).isEqualTo("user1"); assertThat(user.getName()).isEqualTo("user1");
assertThat(user.getAttributes().size()).isEqualTo(6); assertThat(user.getAttributes()).hasSize(6);
assertThat((String) user.getAttribute("user-name")).isEqualTo("user1"); assertThat((String) user.getAttribute("user-name")).isEqualTo("user1");
assertThat((String) user.getAttribute("first-name")).isEqualTo("first"); assertThat((String) user.getAttribute("first-name")).isEqualTo("first");
assertThat((String) user.getAttribute("last-name")).isEqualTo("last"); assertThat((String) user.getAttribute("last-name")).isEqualTo("last");
assertThat((String) user.getAttribute("middle-name")).isEqualTo("middle"); assertThat((String) user.getAttribute("middle-name")).isEqualTo("middle");
assertThat((String) user.getAttribute("address")).isEqualTo("address"); assertThat((String) user.getAttribute("address")).isEqualTo("address");
assertThat((String) user.getAttribute("email")).isEqualTo("user1@example.com"); assertThat((String) user.getAttribute("email")).isEqualTo("user1@example.com");
assertThat(user.getAuthorities().size()).isEqualTo(1); assertThat(user.getAuthorities()).hasSize(1);
assertThat(user.getAuthorities().iterator().next()).isInstanceOf(OAuth2UserAuthority.class); assertThat(user.getAuthorities().iterator().next()).isInstanceOf(OAuth2UserAuthority.class);
OAuth2UserAuthority userAuthority = (OAuth2UserAuthority) user.getAuthorities().iterator().next(); OAuth2UserAuthority userAuthority = (OAuth2UserAuthority) user.getAuthorities().iterator().next();
assertThat(userAuthority.getAuthority()).isEqualTo("OAUTH2_USER"); assertThat(userAuthority.getAuthority()).isEqualTo("OAUTH2_USER");

View File

@ -131,14 +131,14 @@ public class DefaultReactiveOAuth2UserServiceTests {
enqueueApplicationJsonBody(userInfoResponse); enqueueApplicationJsonBody(userInfoResponse);
OAuth2User user = this.userService.loadUser(oauth2UserRequest()).block(); OAuth2User user = this.userService.loadUser(oauth2UserRequest()).block();
assertThat(user.getName()).isEqualTo("user1"); assertThat(user.getName()).isEqualTo("user1");
assertThat(user.getAttributes().size()).isEqualTo(6); assertThat(user.getAttributes()).hasSize(6);
assertThat((String) user.getAttribute("id")).isEqualTo("user1"); assertThat((String) user.getAttribute("id")).isEqualTo("user1");
assertThat((String) user.getAttribute("first-name")).isEqualTo("first"); assertThat((String) user.getAttribute("first-name")).isEqualTo("first");
assertThat((String) user.getAttribute("last-name")).isEqualTo("last"); assertThat((String) user.getAttribute("last-name")).isEqualTo("last");
assertThat((String) user.getAttribute("middle-name")).isEqualTo("middle"); assertThat((String) user.getAttribute("middle-name")).isEqualTo("middle");
assertThat((String) user.getAttribute("address")).isEqualTo("address"); assertThat((String) user.getAttribute("address")).isEqualTo("address");
assertThat((String) user.getAttribute("email")).isEqualTo("user1@example.com"); assertThat((String) user.getAttribute("email")).isEqualTo("user1@example.com");
assertThat(user.getAuthorities().size()).isEqualTo(1); assertThat(user.getAuthorities()).hasSize(1);
assertThat(user.getAuthorities().iterator().next()).isInstanceOf(OAuth2UserAuthority.class); assertThat(user.getAuthorities().iterator().next()).isInstanceOf(OAuth2UserAuthority.class);
OAuth2UserAuthority userAuthority = (OAuth2UserAuthority) user.getAuthorities().iterator().next(); OAuth2UserAuthority userAuthority = (OAuth2UserAuthority) user.getAuthorities().iterator().next();
assertThat(userAuthority.getAuthority()).isEqualTo("OAUTH2_USER"); assertThat(userAuthority.getAuthority()).isEqualTo("OAUTH2_USER");

View File

@ -139,15 +139,15 @@ public class ClaimTypeConverterTests {
claims.put(JSON_ARRAY_CLAIM, jsonArray); claims.put(JSON_ARRAY_CLAIM, jsonArray);
claims.put(JSON_OBJECT_CLAIM, jsonObject); claims.put(JSON_OBJECT_CLAIM, jsonObject);
claims = this.claimTypeConverter.convert(claims); claims = this.claimTypeConverter.convert(claims);
assertThat(claims.get(STRING_CLAIM)).isEqualTo("true"); assertThat(claims).containsEntry(STRING_CLAIM, "true");
assertThat(claims.get(BOOLEAN_CLAIM)).isEqualTo(Boolean.TRUE); assertThat(claims).containsEntry(BOOLEAN_CLAIM, Boolean.TRUE);
assertThat(claims.get(INSTANT_CLAIM)).isEqualTo(instant); assertThat(claims).containsEntry(INSTANT_CLAIM, instant);
assertThat(claims.get(URL_CLAIM)).isEqualTo(url); assertThat(claims).containsEntry(URL_CLAIM, url);
assertThat(claims.get(COLLECTION_STRING_CLAIM)).isEqualTo(listString); assertThat(claims).containsEntry(COLLECTION_STRING_CLAIM, listString);
assertThat(claims.get(LIST_STRING_CLAIM)).isEqualTo(listString); assertThat(claims).containsEntry(LIST_STRING_CLAIM, listString);
assertThat(claims.get(MAP_STRING_OBJECT_CLAIM)).isEqualTo(mapStringObject); assertThat(claims).containsEntry(MAP_STRING_OBJECT_CLAIM, mapStringObject);
assertThat(claims.get(JSON_ARRAY_CLAIM)).isEqualTo(jsonArrayListString); assertThat(claims).containsEntry(JSON_ARRAY_CLAIM, jsonArrayListString);
assertThat(claims.get(JSON_OBJECT_CLAIM)).isEqualTo(jsonObjectMap); assertThat(claims).containsEntry(JSON_OBJECT_CLAIM, jsonObjectMap);
} }
@Test @Test

View File

@ -22,7 +22,6 @@ import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -30,6 +29,8 @@ import org.springframework.core.convert.converter.Converter;
import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2RefreshToken; import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Tests for {@link DefaultMapOAuth2AccessTokenResponseConverter}. * Tests for {@link DefaultMapOAuth2AccessTokenResponseConverter}.
* *
@ -56,24 +57,24 @@ public class DefaultMapOAuth2AccessTokenResponseConverterTests {
map.put("custom_parameter_2", "custom-value-2"); map.put("custom_parameter_2", "custom-value-2");
OAuth2AccessTokenResponse converted = this.messageConverter.convert(map); OAuth2AccessTokenResponse converted = this.messageConverter.convert(map);
OAuth2AccessToken accessToken = converted.getAccessToken(); OAuth2AccessToken accessToken = converted.getAccessToken();
Assertions.assertNotNull(accessToken); assertThat(accessToken).isNotNull();
Assertions.assertEquals("access-token-1234", accessToken.getTokenValue()); assertThat(accessToken.getTokenValue()).isEqualTo("access-token-1234");
Assertions.assertEquals(OAuth2AccessToken.TokenType.BEARER, accessToken.getTokenType()); assertThat(accessToken.getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER);
Set<String> scopes = accessToken.getScopes(); Set<String> scopes = accessToken.getScopes();
Assertions.assertNotNull(scopes); assertThat(scopes).isNotNull();
Assertions.assertEquals(2, scopes.size()); assertThat(scopes).hasSize(2);
Assertions.assertTrue(scopes.contains("read")); assertThat(scopes).contains("read");
Assertions.assertTrue(scopes.contains("write")); assertThat(scopes).contains("write");
Assertions.assertEquals(3600, assertThat(Duration.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()).getSeconds())
Duration.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()).getSeconds()); .isEqualTo(3600);
OAuth2RefreshToken refreshToken = converted.getRefreshToken(); OAuth2RefreshToken refreshToken = converted.getRefreshToken();
Assertions.assertNotNull(refreshToken); assertThat(refreshToken).isNotNull();
Assertions.assertEquals("refresh-token-1234", refreshToken.getTokenValue()); assertThat(refreshToken.getTokenValue()).isEqualTo("refresh-token-1234");
Map<String, Object> additionalParameters = converted.getAdditionalParameters(); Map<String, Object> additionalParameters = converted.getAdditionalParameters();
Assertions.assertNotNull(additionalParameters); assertThat(additionalParameters).isNotNull();
Assertions.assertEquals(2, additionalParameters.size()); assertThat(additionalParameters).hasSize(2);
Assertions.assertEquals("custom-value-1", additionalParameters.get("custom_parameter_1")); assertThat(additionalParameters).containsEntry("custom_parameter_1", "custom-value-1");
Assertions.assertEquals("custom-value-2", additionalParameters.get("custom_parameter_2")); assertThat(additionalParameters).containsEntry("custom_parameter_2", "custom-value-2");
} }
@Test @Test
@ -83,19 +84,18 @@ public class DefaultMapOAuth2AccessTokenResponseConverterTests {
map.put("token_type", "bearer"); map.put("token_type", "bearer");
OAuth2AccessTokenResponse converted = this.messageConverter.convert(map); OAuth2AccessTokenResponse converted = this.messageConverter.convert(map);
OAuth2AccessToken accessToken = converted.getAccessToken(); OAuth2AccessToken accessToken = converted.getAccessToken();
Assertions.assertNotNull(accessToken); assertThat(accessToken).isNotNull();
Assertions.assertEquals("access-token-1234", accessToken.getTokenValue()); assertThat(accessToken.getTokenValue()).isEqualTo("access-token-1234");
Assertions.assertEquals(OAuth2AccessToken.TokenType.BEARER, accessToken.getTokenType()); assertThat(accessToken.getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER);
Set<String> scopes = accessToken.getScopes(); Set<String> scopes = accessToken.getScopes();
Assertions.assertNotNull(scopes); assertThat(scopes).isNotNull();
Assertions.assertEquals(0, scopes.size()); assertThat(scopes).isEmpty();
Assertions.assertEquals(1, assertThat(Duration.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()).getSeconds()).isEqualTo(1);
Duration.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()).getSeconds());
OAuth2RefreshToken refreshToken = converted.getRefreshToken(); OAuth2RefreshToken refreshToken = converted.getRefreshToken();
Assertions.assertNull(refreshToken); assertThat(refreshToken).isNull();
Map<String, Object> additionalParameters = converted.getAdditionalParameters(); Map<String, Object> additionalParameters = converted.getAdditionalParameters();
Assertions.assertNotNull(additionalParameters); assertThat(additionalParameters).isNotNull();
Assertions.assertEquals(0, additionalParameters.size()); assertThat(additionalParameters).isEmpty();
} }
@Test @Test
@ -106,19 +106,18 @@ public class DefaultMapOAuth2AccessTokenResponseConverterTests {
map.put("expires_in", "2100-01-01-abc"); map.put("expires_in", "2100-01-01-abc");
OAuth2AccessTokenResponse converted = this.messageConverter.convert(map); OAuth2AccessTokenResponse converted = this.messageConverter.convert(map);
OAuth2AccessToken accessToken = converted.getAccessToken(); OAuth2AccessToken accessToken = converted.getAccessToken();
Assertions.assertNotNull(accessToken); assertThat(accessToken).isNotNull();
Assertions.assertEquals("access-token-1234", accessToken.getTokenValue()); assertThat(accessToken.getTokenValue()).isEqualTo("access-token-1234");
Assertions.assertEquals(OAuth2AccessToken.TokenType.BEARER, accessToken.getTokenType()); assertThat(accessToken.getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER);
Set<String> scopes = accessToken.getScopes(); Set<String> scopes = accessToken.getScopes();
Assertions.assertNotNull(scopes); assertThat(scopes).isNotNull();
Assertions.assertEquals(0, scopes.size()); assertThat(scopes).isEmpty();
Assertions.assertEquals(1, assertThat(Duration.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()).getSeconds()).isEqualTo(1);
Duration.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()).getSeconds());
OAuth2RefreshToken refreshToken = converted.getRefreshToken(); OAuth2RefreshToken refreshToken = converted.getRefreshToken();
Assertions.assertNull(refreshToken); assertThat(refreshToken).isNull();
Map<String, Object> additionalParameters = converted.getAdditionalParameters(); Map<String, Object> additionalParameters = converted.getAdditionalParameters();
Assertions.assertNotNull(additionalParameters); assertThat(additionalParameters).isNotNull();
Assertions.assertEquals(0, additionalParameters.size()); assertThat(additionalParameters).isEmpty();
} }
// gh-9685 // gh-9685
@ -130,11 +129,11 @@ public class DefaultMapOAuth2AccessTokenResponseConverterTests {
map.put("expires_in", 3600); map.put("expires_in", 3600);
OAuth2AccessTokenResponse converted = this.messageConverter.convert(map); OAuth2AccessTokenResponse converted = this.messageConverter.convert(map);
OAuth2AccessToken accessToken = converted.getAccessToken(); OAuth2AccessToken accessToken = converted.getAccessToken();
Assertions.assertNotNull(accessToken); assertThat(accessToken).isNotNull();
Assertions.assertEquals("access-token-1234", accessToken.getTokenValue()); assertThat(accessToken.getTokenValue()).isEqualTo("access-token-1234");
Assertions.assertEquals(OAuth2AccessToken.TokenType.BEARER, accessToken.getTokenType()); assertThat(accessToken.getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER);
Assertions.assertEquals(3600, assertThat(Duration.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()).getSeconds())
Duration.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()).getSeconds()); .isEqualTo(3600);
} }
// gh-9685 // gh-9685
@ -153,24 +152,24 @@ public class DefaultMapOAuth2AccessTokenResponseConverterTests {
map.put("custom_parameter_2", "custom-value-2"); map.put("custom_parameter_2", "custom-value-2");
OAuth2AccessTokenResponse converted = this.messageConverter.convert(map); OAuth2AccessTokenResponse converted = this.messageConverter.convert(map);
OAuth2AccessToken accessToken = converted.getAccessToken(); OAuth2AccessToken accessToken = converted.getAccessToken();
Assertions.assertNotNull(accessToken); assertThat(accessToken).isNotNull();
Assertions.assertEquals("access-token-1234", accessToken.getTokenValue()); assertThat(accessToken.getTokenValue()).isEqualTo("access-token-1234");
Assertions.assertEquals(OAuth2AccessToken.TokenType.BEARER, accessToken.getTokenType()); assertThat(accessToken.getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER);
Set<String> scopes = accessToken.getScopes(); Set<String> scopes = accessToken.getScopes();
Assertions.assertNotNull(scopes); assertThat(scopes).isNotNull();
Assertions.assertEquals(2, scopes.size()); assertThat(scopes).hasSize(2);
Assertions.assertTrue(scopes.contains("read")); assertThat(scopes).contains("read");
Assertions.assertTrue(scopes.contains("write")); assertThat(scopes).contains("write");
Assertions.assertEquals(3600, assertThat(Duration.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()).getSeconds())
Duration.between(accessToken.getIssuedAt(), accessToken.getExpiresAt()).getSeconds()); .isEqualTo(3600);
OAuth2RefreshToken refreshToken = converted.getRefreshToken(); OAuth2RefreshToken refreshToken = converted.getRefreshToken();
Assertions.assertNotNull(refreshToken); assertThat(refreshToken).isNotNull();
Assertions.assertEquals("refresh-token-1234", refreshToken.getTokenValue()); assertThat(refreshToken.getTokenValue()).isEqualTo("refresh-token-1234");
Map<String, Object> additionalParameters = converted.getAdditionalParameters(); Map<String, Object> additionalParameters = converted.getAdditionalParameters();
Assertions.assertNotNull(additionalParameters); assertThat(additionalParameters).isNotNull();
Assertions.assertEquals(2, additionalParameters.size()); assertThat(additionalParameters).hasSize(2);
Assertions.assertEquals(nestedObject, additionalParameters.get("custom_parameter_1")); assertThat(additionalParameters).containsEntry("custom_parameter_1", nestedObject);
Assertions.assertEquals("custom-value-2", additionalParameters.get("custom_parameter_2")); assertThat(additionalParameters).containsEntry("custom_parameter_2", "custom-value-2");
} }
} }

View File

@ -22,13 +22,14 @@ import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.Converter;
import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.OAuth2AccessToken;
import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Tests for {@link DefaultOAuth2AccessTokenResponseMapConverter}. * Tests for {@link DefaultOAuth2AccessTokenResponseMapConverter}.
* *
@ -61,14 +62,14 @@ public class DefaultOAuth2AccessTokenResponseMapConverterTests {
.build(); .build();
// @formatter:on // @formatter:on
Map<String, Object> result = this.messageConverter.convert(build); Map<String, Object> result = this.messageConverter.convert(build);
Assertions.assertEquals(7, result.size()); assertThat(result).hasSize(7);
Assertions.assertEquals("access-token-value-1234", result.get("access_token")); assertThat(result).containsEntry("access_token", "access-token-value-1234");
Assertions.assertEquals("refresh-token-value-1234", result.get("refresh_token")); assertThat(result).containsEntry("refresh_token", "refresh-token-value-1234");
Assertions.assertEquals("read write", result.get("scope")); assertThat(result).containsEntry("scope", "read write");
Assertions.assertEquals("Bearer", result.get("token_type")); assertThat(result).containsEntry("token_type", "Bearer");
Assertions.assertNotNull(result.get("expires_in")); assertThat(result.get("expires_in")).isNotNull();
Assertions.assertEquals("custom-value-1", result.get("custom_parameter_1")); assertThat(result).containsEntry("custom_parameter_1", "custom-value-1");
Assertions.assertEquals("custom-value-2", result.get("custom_parameter_2")); assertThat(result).containsEntry("custom_parameter_2", "custom-value-2");
} }
@Test @Test
@ -79,10 +80,10 @@ public class DefaultOAuth2AccessTokenResponseMapConverterTests {
.build(); .build();
// @formatter:on // @formatter:on
Map<String, Object> result = this.messageConverter.convert(build); Map<String, Object> result = this.messageConverter.convert(build);
Assertions.assertEquals(3, result.size()); assertThat(result).hasSize(3);
Assertions.assertEquals("access-token-value-1234", result.get("access_token")); assertThat(result).containsEntry("access_token", "access-token-value-1234");
Assertions.assertEquals("Bearer", result.get("token_type")); assertThat(result).containsEntry("token_type", "Bearer");
Assertions.assertNotNull(result.get("expires_in")); assertThat(result.get("expires_in")).isNotNull();
} }
// gh-9685 // gh-9685
@ -107,14 +108,14 @@ public class DefaultOAuth2AccessTokenResponseMapConverterTests {
.build(); .build();
// @formatter:on // @formatter:on
Map<String, Object> result = this.messageConverter.convert(build); Map<String, Object> result = this.messageConverter.convert(build);
Assertions.assertEquals(7, result.size()); assertThat(result).hasSize(7);
Assertions.assertEquals("access-token-value-1234", result.get("access_token")); assertThat(result).containsEntry("access_token", "access-token-value-1234");
Assertions.assertEquals("refresh-token-value-1234", result.get("refresh_token")); assertThat(result).containsEntry("refresh_token", "refresh-token-value-1234");
Assertions.assertEquals("read write", result.get("scope")); assertThat(result).containsEntry("scope", "read write");
Assertions.assertEquals("Bearer", result.get("token_type")); assertThat(result).containsEntry("token_type", "Bearer");
Assertions.assertNotNull(result.get("expires_in")); assertThat(result.get("expires_in")).isNotNull();
Assertions.assertEquals(nestedObject, result.get("custom_parameter_1")); assertThat(result).containsEntry("custom_parameter_1", nestedObject);
Assertions.assertEquals("custom-value-2", result.get("custom_parameter_2")); assertThat(result).containsEntry("custom_parameter_2", "custom-value-2");
} }
} }

View File

@ -41,11 +41,11 @@ public class OidcIdTokenBuilderTests {
.build(); .build();
// @formatter:on // @formatter:on
assertThat(first.getClaims()).hasSize(1); assertThat(first.getClaims()).hasSize(1);
assertThat(first.getClaims().get("TEST_CLAIM_1")).isEqualTo("C1"); assertThat(first.getClaims()).containsEntry("TEST_CLAIM_1", "C1");
assertThat(first.getTokenValue()).isEqualTo("V1"); assertThat(first.getTokenValue()).isEqualTo("V1");
assertThat(second.getClaims()).hasSize(2); assertThat(second.getClaims()).hasSize(2);
assertThat(second.getClaims().get("TEST_CLAIM_1")).isEqualTo("C2"); assertThat(second.getClaims()).containsEntry("TEST_CLAIM_1", "C2");
assertThat(second.getClaims().get("TEST_CLAIM_2")).isEqualTo("C3"); assertThat(second.getClaims()).containsEntry("TEST_CLAIM_2", "C3");
assertThat(second.getTokenValue()).isEqualTo("V2"); assertThat(second.getTokenValue()).isEqualTo("V2");
} }

View File

@ -38,10 +38,10 @@ public class OidcUserInfoBuilderTests {
.build(); .build();
// @formatter:on // @formatter:on
assertThat(first.getClaims()).hasSize(1); assertThat(first.getClaims()).hasSize(1);
assertThat(first.getClaims().get("TEST_CLAIM_1")).isEqualTo("C1"); assertThat(first.getClaims()).containsEntry("TEST_CLAIM_1", "C1");
assertThat(second.getClaims()).hasSize(2); assertThat(second.getClaims()).hasSize(2);
assertThat(second.getClaims().get("TEST_CLAIM_1")).isEqualTo("C2"); assertThat(second.getClaims()).containsEntry("TEST_CLAIM_1", "C2");
assertThat(second.getClaims().get("TEST_CLAIM_2")).isEqualTo("C3"); assertThat(second.getClaims()).containsEntry("TEST_CLAIM_2", "C3");
} }
@Test @Test

View File

@ -47,16 +47,16 @@ public class JwtBuilderTests {
.build(); .build();
// @formatter:on // @formatter:on
assertThat(first.getHeaders()).hasSize(1); assertThat(first.getHeaders()).hasSize(1);
assertThat(first.getHeaders().get("TEST_HEADER_1")).isEqualTo("H1"); assertThat(first.getHeaders()).containsEntry("TEST_HEADER_1", "H1");
assertThat(first.getClaims()).hasSize(1); assertThat(first.getClaims()).hasSize(1);
assertThat(first.getClaims().get("TEST_CLAIM_1")).isEqualTo("C1"); assertThat(first.getClaims()).containsEntry("TEST_CLAIM_1", "C1");
assertThat(first.getTokenValue()).isEqualTo("V1"); assertThat(first.getTokenValue()).isEqualTo("V1");
assertThat(second.getHeaders()).hasSize(2); assertThat(second.getHeaders()).hasSize(2);
assertThat(second.getHeaders().get("TEST_HEADER_1")).isEqualTo("H2"); assertThat(second.getHeaders()).containsEntry("TEST_HEADER_1", "H2");
assertThat(second.getHeaders().get("TEST_HEADER_2")).isEqualTo("H3"); assertThat(second.getHeaders()).containsEntry("TEST_HEADER_2", "H3");
assertThat(second.getClaims()).hasSize(2); assertThat(second.getClaims()).hasSize(2);
assertThat(second.getClaims().get("TEST_CLAIM_1")).isEqualTo("C2"); assertThat(second.getClaims()).containsEntry("TEST_CLAIM_1", "C2");
assertThat(second.getClaims().get("TEST_CLAIM_2")).isEqualTo("C3"); assertThat(second.getClaims()).containsEntry("TEST_CLAIM_2", "C3");
assertThat(second.getTokenValue()).isEqualTo("V2"); assertThat(second.getTokenValue()).isEqualTo("V2");
} }

View File

@ -50,7 +50,7 @@ public class JwtClaimValidatorTests {
public void validateWhenClaimFailsTheTestThenReturnsFailure() { public void validateWhenClaimFailsTheTestThenReturnsFailure() {
Jwt jwt = TestJwts.jwt().claim(JwtClaimNames.ISS, "http://abc").build(); Jwt jwt = TestJwts.jwt().claim(JwtClaimNames.ISS, "http://abc").build();
Collection<OAuth2Error> details = this.validator.validate(jwt).getErrors(); Collection<OAuth2Error> details = this.validator.validate(jwt).getErrors();
assertThat(this.validator.validate(jwt).getErrors().isEmpty()).isFalse(); assertThat(this.validator.validate(jwt).getErrors()).isNotEmpty();
assertThat(details).allMatch((error) -> Objects.equals(error.getErrorCode(), OAuth2ErrorCodes.INVALID_TOKEN)); assertThat(details).allMatch((error) -> Objects.equals(error.getErrorCode(), OAuth2ErrorCodes.INVALID_TOKEN));
} }

View File

@ -53,7 +53,7 @@ public class MappedJwtClaimSetConverterTests {
.withDefaults(Collections.singletonMap(JwtClaimNames.EXP, expiresAtConverter)); .withDefaults(Collections.singletonMap(JwtClaimNames.EXP, expiresAtConverter));
Map<String, Object> source = new HashMap<>(); Map<String, Object> source = new HashMap<>();
Map<String, Object> target = converter.convert(source); Map<String, Object> target = converter.convert(source);
assertThat(target.get(JwtClaimNames.IAT)).isEqualTo(Instant.ofEpochMilli(at.toEpochMilli()).minusSeconds(1)); assertThat(target).containsEntry(JwtClaimNames.IAT, Instant.ofEpochMilli(at.toEpochMilli()).minusSeconds(1));
} }
@Test @Test
@ -61,8 +61,8 @@ public class MappedJwtClaimSetConverterTests {
MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap()); MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap());
Map<String, Object> source = Collections.singletonMap(JwtClaimNames.EXP, 1000000000L); Map<String, Object> source = Collections.singletonMap(JwtClaimNames.EXP, 1000000000L);
Map<String, Object> target = converter.convert(source); Map<String, Object> target = converter.convert(source);
assertThat(target.get(JwtClaimNames.EXP)).isEqualTo(Instant.ofEpochSecond(1000000000L)); assertThat(target).containsEntry(JwtClaimNames.EXP, Instant.ofEpochSecond(1000000000L));
assertThat(target.get(JwtClaimNames.IAT)).isEqualTo(Instant.ofEpochSecond(1000000000L).minusSeconds(1)); assertThat(target).containsEntry(JwtClaimNames.IAT, Instant.ofEpochSecond(1000000000L).minusSeconds(1));
} }
@Test @Test
@ -71,11 +71,11 @@ public class MappedJwtClaimSetConverterTests {
Map<String, Object> source = Collections.singletonMap(JwtClaimNames.AUD, "audience"); Map<String, Object> source = Collections.singletonMap(JwtClaimNames.AUD, "audience");
Map<String, Object> target = converter.convert(source); Map<String, Object> target = converter.convert(source);
assertThat(target.get(JwtClaimNames.AUD)).isInstanceOf(Collection.class); assertThat(target.get(JwtClaimNames.AUD)).isInstanceOf(Collection.class);
assertThat(target.get(JwtClaimNames.AUD)).isEqualTo(Arrays.asList("audience")); assertThat(target).containsEntry(JwtClaimNames.AUD, Arrays.asList("audience"));
source = Collections.singletonMap(JwtClaimNames.AUD, Arrays.asList("one", "two")); source = Collections.singletonMap(JwtClaimNames.AUD, Arrays.asList("one", "two"));
target = converter.convert(source); target = converter.convert(source);
assertThat(target.get(JwtClaimNames.AUD)).isInstanceOf(Collection.class); assertThat(target.get(JwtClaimNames.AUD)).isInstanceOf(Collection.class);
assertThat(target.get(JwtClaimNames.AUD)).isEqualTo(Arrays.asList("one", "two")); assertThat(target).containsEntry(JwtClaimNames.AUD, Arrays.asList("one", "two"));
} }
@Test @Test
@ -90,13 +90,13 @@ public class MappedJwtClaimSetConverterTests {
source.put(JwtClaimNames.NBF, 1000000000); source.put(JwtClaimNames.NBF, 1000000000);
source.put(JwtClaimNames.SUB, 1234); source.put(JwtClaimNames.SUB, 1234);
Map<String, Object> target = converter.convert(source); Map<String, Object> target = converter.convert(source);
assertThat(target.get(JwtClaimNames.JTI)).isEqualTo("1"); assertThat(target).containsEntry(JwtClaimNames.JTI, "1");
assertThat(target.get(JwtClaimNames.AUD)).isEqualTo(Arrays.asList("audience")); assertThat(target).containsEntry(JwtClaimNames.AUD, Arrays.asList("audience"));
assertThat(target.get(JwtClaimNames.EXP)).isEqualTo(Instant.ofEpochSecond(2000000000L)); assertThat(target).containsEntry(JwtClaimNames.EXP, Instant.ofEpochSecond(2000000000L));
assertThat(target.get(JwtClaimNames.IAT)).isEqualTo(Instant.ofEpochSecond(1000000000L)); assertThat(target).containsEntry(JwtClaimNames.IAT, Instant.ofEpochSecond(1000000000L));
assertThat(target.get(JwtClaimNames.ISS)).isEqualTo("https://any.url"); assertThat(target).containsEntry(JwtClaimNames.ISS, "https://any.url");
assertThat(target.get(JwtClaimNames.NBF)).isEqualTo(Instant.ofEpochSecond(1000000000L)); assertThat(target).containsEntry(JwtClaimNames.NBF, Instant.ofEpochSecond(1000000000L));
assertThat(target.get(JwtClaimNames.SUB)).isEqualTo("1234"); assertThat(target).containsEntry(JwtClaimNames.SUB, "1234");
} }
@Test @Test
@ -114,13 +114,13 @@ public class MappedJwtClaimSetConverterTests {
source.put(JwtClaimNames.NBF, "1000000000"); source.put(JwtClaimNames.NBF, "1000000000");
source.put(JwtClaimNames.SUB, 2345); source.put(JwtClaimNames.SUB, 2345);
Map<String, Object> target = converter.convert(source); Map<String, Object> target = converter.convert(source);
assertThat(target.get(JwtClaimNames.JTI)).isEqualTo("1"); assertThat(target).containsEntry(JwtClaimNames.JTI, "1");
assertThat(target.get(JwtClaimNames.AUD)).isEqualTo(Arrays.asList("audience")); assertThat(target).containsEntry(JwtClaimNames.AUD, Arrays.asList("audience"));
assertThat(target.get(JwtClaimNames.EXP)).isEqualTo(Instant.ofEpochSecond(2000000000L)); assertThat(target).containsEntry(JwtClaimNames.EXP, Instant.ofEpochSecond(2000000000L));
assertThat(target.get(JwtClaimNames.IAT)).isEqualTo(Instant.ofEpochSecond(1000000000L)); assertThat(target).containsEntry(JwtClaimNames.IAT, Instant.ofEpochSecond(1000000000L));
assertThat(target.get(JwtClaimNames.ISS)).isEqualTo("https://any.url"); assertThat(target).containsEntry(JwtClaimNames.ISS, "https://any.url");
assertThat(target.get(JwtClaimNames.NBF)).isEqualTo(Instant.ofEpochSecond(1000000000L)); assertThat(target).containsEntry(JwtClaimNames.NBF, Instant.ofEpochSecond(1000000000L));
assertThat(target.get(JwtClaimNames.SUB)).isEqualTo("1234"); assertThat(target).containsEntry(JwtClaimNames.SUB, "1234");
} }
// gh-10135 // gh-10135
@ -149,7 +149,7 @@ public class MappedJwtClaimSetConverterTests {
given(claimConverter.convert(any())).willReturn("custom-value"); given(claimConverter.convert(any())).willReturn("custom-value");
Map<String, Object> source = new HashMap<>(); Map<String, Object> source = new HashMap<>();
Map<String, Object> target = converter.convert(source); Map<String, Object> target = converter.convert(source);
assertThat(target.get("custom-claim")).isEqualTo("custom-value"); assertThat(target).containsEntry("custom-claim", "custom-value");
} }
@Test @Test
@ -167,13 +167,13 @@ public class MappedJwtClaimSetConverterTests {
source.put(JwtClaimNames.NBF, new Object()); source.put(JwtClaimNames.NBF, new Object());
source.put(JwtClaimNames.SUB, new Object()); source.put(JwtClaimNames.SUB, new Object());
Map<String, Object> target = converter.convert(source); Map<String, Object> target = converter.convert(source);
assertThat(target.get(JwtClaimNames.JTI)).isEqualTo(source.get(JwtClaimNames.JTI)); assertThat(target).containsEntry(JwtClaimNames.JTI, source.get(JwtClaimNames.JTI));
assertThat(target.get(JwtClaimNames.AUD)).isEqualTo(source.get(JwtClaimNames.AUD)); assertThat(target).containsEntry(JwtClaimNames.AUD, source.get(JwtClaimNames.AUD));
assertThat(target.get(JwtClaimNames.EXP)).isEqualTo(source.get(JwtClaimNames.EXP)); assertThat(target).containsEntry(JwtClaimNames.EXP, source.get(JwtClaimNames.EXP));
assertThat(target.get(JwtClaimNames.IAT)).isEqualTo(source.get(JwtClaimNames.IAT)); assertThat(target).containsEntry(JwtClaimNames.IAT, source.get(JwtClaimNames.IAT));
assertThat(target.get(JwtClaimNames.ISS)).isEqualTo(source.get(JwtClaimNames.ISS)); assertThat(target).containsEntry(JwtClaimNames.ISS, source.get(JwtClaimNames.ISS));
assertThat(target.get(JwtClaimNames.NBF)).isEqualTo(source.get(JwtClaimNames.NBF)); assertThat(target).containsEntry(JwtClaimNames.NBF, source.get(JwtClaimNames.NBF));
assertThat(target.get(JwtClaimNames.SUB)).isEqualTo("1234"); assertThat(target).containsEntry(JwtClaimNames.SUB, "1234");
} }
@Test @Test
@ -195,7 +195,7 @@ public class MappedJwtClaimSetConverterTests {
MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap()); MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap());
Map<String, Object> nonUriIssuer = Collections.singletonMap(JwtClaimNames.ISS, "issuer"); Map<String, Object> nonUriIssuer = Collections.singletonMap(JwtClaimNames.ISS, "issuer");
Map<String, Object> target = converter.convert(nonUriIssuer); Map<String, Object> target = converter.convert(nonUriIssuer);
assertThat(target.get(JwtClaimNames.ISS)).isEqualTo("issuer"); assertThat(target).containsEntry(JwtClaimNames.ISS, "issuer");
} }
// gh-6073 // gh-6073
@ -204,7 +204,7 @@ public class MappedJwtClaimSetConverterTests {
MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap()); MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap());
Map<String, Object> issuer = Collections.singletonMap(JwtClaimNames.ISS, new URL("https://issuer")); Map<String, Object> issuer = Collections.singletonMap(JwtClaimNames.ISS, new URL("https://issuer"));
Map<String, Object> target = converter.convert(issuer); Map<String, Object> target = converter.convert(issuer);
assertThat(target.get(JwtClaimNames.ISS)).isEqualTo("https://issuer"); assertThat(target).containsEntry(JwtClaimNames.ISS, "https://issuer");
} }
@Test @Test

View File

@ -100,11 +100,11 @@ public class NimbusJweEncoderTests {
// @formatter:on // @formatter:on
Jwt encodedJwe = this.jweEncoder.encode(JwtEncoderParameters.from(jwtClaimsSet)); Jwt encodedJwe = this.jweEncoder.encode(JwtEncoderParameters.from(jwtClaimsSet));
assertThat(encodedJwe.getHeaders().get(JoseHeaderNames.ALG)).isEqualTo(DEFAULT_JWE_HEADER.getAlgorithm()); assertThat(encodedJwe.getHeaders()).containsEntry(JoseHeaderNames.ALG, DEFAULT_JWE_HEADER.getAlgorithm());
assertThat(encodedJwe.getHeaders().get("enc")).isEqualTo(DEFAULT_JWE_HEADER.<String>getHeader("enc")); assertThat(encodedJwe.getHeaders()).containsEntry("enc", DEFAULT_JWE_HEADER.<String>getHeader("enc"));
assertThat(encodedJwe.getHeaders().get(JoseHeaderNames.JKU)).isNull(); assertThat(encodedJwe.getHeaders().get(JoseHeaderNames.JKU)).isNull();
assertThat(encodedJwe.getHeaders().get(JoseHeaderNames.JWK)).isNull(); assertThat(encodedJwe.getHeaders().get(JoseHeaderNames.JWK)).isNull();
assertThat(encodedJwe.getHeaders().get(JoseHeaderNames.KID)).isEqualTo(rsaJwk.getKeyID()); assertThat(encodedJwe.getHeaders()).containsEntry(JoseHeaderNames.KID, rsaJwk.getKeyID());
assertThat(encodedJwe.getHeaders().get(JoseHeaderNames.X5U)).isNull(); assertThat(encodedJwe.getHeaders().get(JoseHeaderNames.X5U)).isNull();
assertThat(encodedJwe.getHeaders().get(JoseHeaderNames.X5C)).isNull(); assertThat(encodedJwe.getHeaders().get(JoseHeaderNames.X5C)).isNull();
assertThat(encodedJwe.getHeaders().get(JoseHeaderNames.X5T)).isNull(); assertThat(encodedJwe.getHeaders().get(JoseHeaderNames.X5T)).isNull();
@ -144,18 +144,18 @@ public class NimbusJweEncoderTests {
// @formatter:on // @formatter:on
Jwt encodedJweNestedJws = this.jweEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet)); Jwt encodedJweNestedJws = this.jweEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet));
assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.ALG)) assertThat(encodedJweNestedJws.getHeaders()).containsEntry(JoseHeaderNames.ALG,
.isEqualTo(DEFAULT_JWE_HEADER.getAlgorithm()); DEFAULT_JWE_HEADER.getAlgorithm());
assertThat(encodedJweNestedJws.getHeaders().get("enc")).isEqualTo(DEFAULT_JWE_HEADER.<String>getHeader("enc")); assertThat(encodedJweNestedJws.getHeaders()).containsEntry("enc", DEFAULT_JWE_HEADER.<String>getHeader("enc"));
assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.JKU)).isNull(); assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.JKU)).isNull();
assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.JWK)).isNull(); assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.JWK)).isNull();
assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.KID)).isEqualTo(rsaJwk.getKeyID()); assertThat(encodedJweNestedJws.getHeaders()).containsEntry(JoseHeaderNames.KID, rsaJwk.getKeyID());
assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.X5U)).isNull(); assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.X5U)).isNull();
assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.X5C)).isNull(); assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.X5C)).isNull();
assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.X5T)).isNull(); assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.X5T)).isNull();
assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.X5T_S256)).isNull(); assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.X5T_S256)).isNull();
assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.TYP)).isNull(); assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.TYP)).isNull();
assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.CTY)).isEqualTo("JWT"); assertThat(encodedJweNestedJws.getHeaders()).containsEntry(JoseHeaderNames.CTY, "JWT");
assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.CRIT)).isNull(); assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.CRIT)).isNull();
assertThat(encodedJweNestedJws.getIssuer()).isEqualTo(jwtClaimsSet.getIssuer()); assertThat(encodedJweNestedJws.getIssuer()).isEqualTo(jwtClaimsSet.getIssuer());

View File

@ -248,8 +248,8 @@ public class NimbusJwtDecoderTests {
given(claimSetConverter.convert(any(Map.class))).willReturn(Collections.singletonMap("custom", "value")); given(claimSetConverter.convert(any(Map.class))).willReturn(Collections.singletonMap("custom", "value"));
this.jwtDecoder.setClaimSetConverter(claimSetConverter); this.jwtDecoder.setClaimSetConverter(claimSetConverter);
Jwt jwt = this.jwtDecoder.decode(SIGNED_JWT); Jwt jwt = this.jwtDecoder.decode(SIGNED_JWT);
assertThat(jwt.getClaims().size()).isEqualTo(1); assertThat(jwt.getClaims()).hasSize(1);
assertThat(jwt.getClaims().get("custom")).isEqualTo("value"); assertThat(jwt.getClaims()).containsEntry("custom", "value");
} }
// gh-7885 // gh-7885

View File

@ -144,7 +144,7 @@ public class NimbusJwtEncoderTests {
Jwt encodedJws = this.jwtEncoder.encode(JwtEncoderParameters.from(jwtClaimsSet)); Jwt encodedJws = this.jwtEncoder.encode(JwtEncoderParameters.from(jwtClaimsSet));
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.ALG)).isEqualTo(SignatureAlgorithm.RS256); assertThat(encodedJws.getHeaders()).containsEntry(JoseHeaderNames.ALG, SignatureAlgorithm.RS256);
} }
@Test @Test
@ -165,7 +165,7 @@ public class NimbusJwtEncoderTests {
Jwt encodedJws = this.jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet)); Jwt encodedJws = this.jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet));
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.KID)).isEqualTo(rsaJwk2.getKeyID()); assertThat(encodedJws.getHeaders()).containsEntry(JoseHeaderNames.KID, rsaJwk2.getKeyID());
} }
@Test @Test
@ -189,8 +189,8 @@ public class NimbusJwtEncoderTests {
Jwt encodedJws = this.jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet)); Jwt encodedJws = this.jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet));
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.X5T_S256)) assertThat(encodedJws.getHeaders()).containsEntry(JoseHeaderNames.X5T_S256,
.isEqualTo(rsaJwk1.getX509CertSHA256Thumbprint().toString()); rsaJwk1.getX509CertSHA256Thumbprint().toString());
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.KID)).isNull(); assertThat(encodedJws.getHeaders().get(JoseHeaderNames.KID)).isNull();
} }
@ -230,15 +230,15 @@ public class NimbusJwtEncoderTests {
Jwt encodedJws = this.jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet)); Jwt encodedJws = this.jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet));
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.ALG)).isEqualTo(jwsHeader.getAlgorithm()); assertThat(encodedJws.getHeaders()).containsEntry(JoseHeaderNames.ALG, jwsHeader.getAlgorithm());
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.JKU)).isNull(); assertThat(encodedJws.getHeaders().get(JoseHeaderNames.JKU)).isNull();
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.JWK)).isNull(); assertThat(encodedJws.getHeaders().get(JoseHeaderNames.JWK)).isNull();
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.KID)).isEqualTo(rsaJwk.getKeyID()); assertThat(encodedJws.getHeaders()).containsEntry(JoseHeaderNames.KID, rsaJwk.getKeyID());
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.X5U)).isNull(); assertThat(encodedJws.getHeaders().get(JoseHeaderNames.X5U)).isNull();
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.X5C)).isNull(); assertThat(encodedJws.getHeaders().get(JoseHeaderNames.X5C)).isNull();
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.X5T)).isNull(); assertThat(encodedJws.getHeaders().get(JoseHeaderNames.X5T)).isNull();
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.X5T_S256)) assertThat(encodedJws.getHeaders()).containsEntry(JoseHeaderNames.X5T_S256,
.isEqualTo(rsaJwk.getX509CertSHA256Thumbprint().toString()); rsaJwk.getX509CertSHA256Thumbprint().toString());
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.TYP)).isNull(); assertThat(encodedJws.getHeaders().get(JoseHeaderNames.TYP)).isNull();
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.CTY)).isNull(); assertThat(encodedJws.getHeaders().get(JoseHeaderNames.CTY)).isNull();
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.CRIT)).isNull(); assertThat(encodedJws.getHeaders().get(JoseHeaderNames.CRIT)).isNull();

View File

@ -149,7 +149,7 @@ public class NimbusReactiveJwtDecoderTests {
@Test @Test
public void decodeWhenMessageReadScopeThenSuccess() { public void decodeWhenMessageReadScopeThenSuccess() {
Jwt jwt = this.decoder.decode(this.messageReadToken).block(); Jwt jwt = this.decoder.decode(this.messageReadToken).block();
assertThat(jwt.getClaims().get("scope")).isEqualTo("message:read"); assertThat(jwt.getClaims()).containsEntry("scope", "message:read");
} }
@Test @Test
@ -167,7 +167,7 @@ public class NimbusReactiveJwtDecoderTests {
public void decodeWhenIssuedAtThenSuccess() { public void decodeWhenIssuedAtThenSuccess() {
String withIssuedAt = "eyJraWQiOiJrZXktaWQtMSIsImFsZyI6IlJTMjU2In0.eyJzY29wZSI6IiIsImV4cCI6OTIyMzM3MjAwNjA5NjM3NSwiaWF0IjoxNTI5OTQyNDQ4fQ.LBzAJO-FR-uJDHST61oX4kimuQjz6QMJPW_mvEXRB6A-fMQWpfTQ089eboipAqsb33XnwWth9ELju9HMWLk0FjlWVVzwObh9FcoKelmPNR8mZIlFG-pAYGgSwi8HufyLabXHntFavBiFtqwp_z9clSOFK1RxWvt3lywEbGgtCKve0BXOjfKWiH1qe4QKGixH-NFxidvz8Qd5WbJwyb9tChC6ZKoKPv7Jp-N5KpxkY-O2iUtINvn4xOSactUsvKHgF8ZzZjvJGzG57r606OZXaNtoElQzjAPU5xDGg5liuEJzfBhvqiWCLRmSuZ33qwp3aoBnFgEw0B85gsNe3ggABg"; String withIssuedAt = "eyJraWQiOiJrZXktaWQtMSIsImFsZyI6IlJTMjU2In0.eyJzY29wZSI6IiIsImV4cCI6OTIyMzM3MjAwNjA5NjM3NSwiaWF0IjoxNTI5OTQyNDQ4fQ.LBzAJO-FR-uJDHST61oX4kimuQjz6QMJPW_mvEXRB6A-fMQWpfTQ089eboipAqsb33XnwWth9ELju9HMWLk0FjlWVVzwObh9FcoKelmPNR8mZIlFG-pAYGgSwi8HufyLabXHntFavBiFtqwp_z9clSOFK1RxWvt3lywEbGgtCKve0BXOjfKWiH1qe4QKGixH-NFxidvz8Qd5WbJwyb9tChC6ZKoKPv7Jp-N5KpxkY-O2iUtINvn4xOSactUsvKHgF8ZzZjvJGzG57r606OZXaNtoElQzjAPU5xDGg5liuEJzfBhvqiWCLRmSuZ33qwp3aoBnFgEw0B85gsNe3ggABg";
Jwt jwt = this.decoder.decode(withIssuedAt).block(); Jwt jwt = this.decoder.decode(withIssuedAt).block();
assertThat(jwt.getClaims().get(JwtClaimNames.IAT)).isEqualTo(Instant.ofEpochSecond(1529942448L)); assertThat(jwt.getClaims()).containsEntry(JwtClaimNames.IAT, Instant.ofEpochSecond(1529942448L));
} }
@Test @Test
@ -267,8 +267,8 @@ public class NimbusReactiveJwtDecoderTests {
this.decoder.setClaimSetConverter(claimSetConverter); this.decoder.setClaimSetConverter(claimSetConverter);
given(claimSetConverter.convert(any(Map.class))).willReturn(Collections.singletonMap("custom", "value")); given(claimSetConverter.convert(any(Map.class))).willReturn(Collections.singletonMap("custom", "value"));
Jwt jwt = this.decoder.decode(this.messageReadToken).block(); Jwt jwt = this.decoder.decode(this.messageReadToken).block();
assertThat(jwt.getClaims().size()).isEqualTo(1); assertThat(jwt.getClaims()).hasSize(1);
assertThat(jwt.getClaims().get("custom")).isEqualTo("value"); assertThat(jwt.getClaims()).containsEntry("custom", "value");
verify(claimSetConverter).convert(any(Map.class)); verify(claimSetConverter).convert(any(Map.class));
} }

View File

@ -248,7 +248,7 @@ public class RelyingPartyRegistrationsTests {
public void collectionFromMetadataLocationCanHandleFederationMetadata() { public void collectionFromMetadataLocationCanHandleFederationMetadata() {
Collection<RelyingPartyRegistration.Builder> federationMetadataWithSkippedSPEntries = RelyingPartyRegistrations Collection<RelyingPartyRegistration.Builder> federationMetadataWithSkippedSPEntries = RelyingPartyRegistrations
.collectionFromMetadataLocation("classpath:test-federated-metadata.xml"); .collectionFromMetadataLocation("classpath:test-federated-metadata.xml");
assertThat(federationMetadataWithSkippedSPEntries.size()).isEqualTo(1); assertThat(federationMetadataWithSkippedSPEntries).hasSize(1);
} }
@Test @Test

View File

@ -17,7 +17,6 @@
package org.springframework.security.saml2.provider.service.web.authentication; package org.springframework.security.saml2.provider.service.web.authentication;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -45,6 +44,7 @@ import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatNoException; import static org.assertj.core.api.Assertions.assertThatNoException;
@ -92,7 +92,7 @@ public class Saml2WebSsoAuthenticationFilterTests {
@Test @Test
public void requiresAuthenticationWhenHappyPathThenReturnsTrue() { public void requiresAuthenticationWhenHappyPathThenReturnsTrue() {
Assertions.assertTrue(this.filter.requiresAuthentication(this.request, this.response)); assertThat(this.filter.requiresAuthentication(this.request, this.response)).isTrue();
} }
@Test @Test
@ -100,7 +100,7 @@ public class Saml2WebSsoAuthenticationFilterTests {
this.filter = new Saml2WebSsoAuthenticationFilter(this.repository, "/some/other/path/{registrationId}"); this.filter = new Saml2WebSsoAuthenticationFilter(this.repository, "/some/other/path/{registrationId}");
this.request.setPathInfo("/some/other/path/idp-registration-id"); this.request.setPathInfo("/some/other/path/idp-registration-id");
this.request.setParameter(Saml2ParameterNames.SAML_RESPONSE, "xml-data-goes-here"); this.request.setParameter(Saml2ParameterNames.SAML_RESPONSE, "xml-data-goes-here");
Assertions.assertTrue(this.filter.requiresAuthentication(this.request, this.response)); assertThat(this.filter.requiresAuthentication(this.request, this.response)).isTrue();
} }
@Test @Test
@ -141,7 +141,7 @@ public class Saml2WebSsoAuthenticationFilterTests {
this.filter.setAuthenticationDetailsSource(authenticationDetailsSource); this.filter.setAuthenticationDetailsSource(authenticationDetailsSource);
this.request.setPathInfo("/some/other/path/idp-registration-id"); this.request.setPathInfo("/some/other/path/idp-registration-id");
this.filter.attemptAuthentication(this.request, this.response); this.filter.attemptAuthentication(this.request, this.response);
Assertions.assertEquals(details, token.getDetails()); assertThat(token.getDetails()).isEqualTo(details);
} }
@Test @Test

View File

@ -64,7 +64,7 @@ public class SecurityMockServerConfigurerOpaqueTokenTests extends AbstractMockSe
BearerTokenAuthentication token = (BearerTokenAuthentication) context.getAuthentication(); BearerTokenAuthentication token = (BearerTokenAuthentication) context.getAuthentication();
assertThat(token.getAuthorities()).isNotEmpty(); assertThat(token.getAuthorities()).isNotEmpty();
assertThat(token.getToken()).isNotNull(); assertThat(token.getToken()).isNotNull();
assertThat(token.getTokenAttributes().get(OAuth2TokenIntrospectionClaimNames.SUB)).isEqualTo("user"); assertThat(token.getTokenAttributes()).containsEntry(OAuth2TokenIntrospectionClaimNames.SUB, "user");
} }
@Test @Test

View File

@ -63,7 +63,7 @@ public class SecurityMockServerConfigurersJwtTests extends AbstractMockServerCon
assertThat(token.getAuthorities()).isNotEmpty(); assertThat(token.getAuthorities()).isNotEmpty();
assertThat(token.getToken()).isNotNull(); assertThat(token.getToken()).isNotNull();
assertThat(token.getToken().getSubject()).isEqualTo("user"); assertThat(token.getToken().getSubject()).isEqualTo("user");
assertThat(token.getToken().getHeaders().get("alg")).isEqualTo("none"); assertThat(token.getToken().getHeaders()).containsEntry("alg", "none");
} }
@Test @Test
@ -119,7 +119,7 @@ public class SecurityMockServerConfigurersJwtTests extends AbstractMockServerCon
JwtAuthenticationToken retrievedToken = (JwtAuthenticationToken) context.getAuthentication(); JwtAuthenticationToken retrievedToken = (JwtAuthenticationToken) context.getAuthentication();
assertThat(retrievedToken.getToken().getSubject()).isEqualTo("some_user"); assertThat(retrievedToken.getToken().getSubject()).isEqualTo("some_user");
assertThat(retrievedToken.getToken().getTokenValue()).isEqualTo("token"); assertThat(retrievedToken.getToken().getTokenValue()).isEqualTo("token");
assertThat(retrievedToken.getToken().getHeaders().get("header1")).isEqualTo("value1"); assertThat(retrievedToken.getToken().getHeaders()).containsEntry("header1", "value1");
} }
} }

View File

@ -102,7 +102,7 @@ public class SecurityMockMvcRequestPostProcessorsJwtTests {
assertThat(token.getAuthorities()).isNotEmpty(); assertThat(token.getAuthorities()).isNotEmpty();
assertThat(token.getToken()).isNotNull(); assertThat(token.getToken()).isNotNull();
assertThat(token.getToken().getSubject()).isEqualTo("user"); assertThat(token.getToken().getSubject()).isEqualTo("user");
assertThat(token.getToken().getHeaders().get("alg")).isEqualTo("none"); assertThat(token.getToken().getHeaders()).containsEntry("alg", "none");
} }
@Test @Test
@ -158,7 +158,7 @@ public class SecurityMockMvcRequestPostProcessorsJwtTests {
JwtAuthenticationToken retrievedToken = (JwtAuthenticationToken) context.getAuthentication(); JwtAuthenticationToken retrievedToken = (JwtAuthenticationToken) context.getAuthentication();
assertThat(retrievedToken.getToken().getSubject()).isEqualTo("some_user"); assertThat(retrievedToken.getToken().getSubject()).isEqualTo("some_user");
assertThat(retrievedToken.getToken().getTokenValue()).isEqualTo("token"); assertThat(retrievedToken.getToken().getTokenValue()).isEqualTo("token");
assertThat(retrievedToken.getToken().getHeaders().get("header1")).isEqualTo("value1"); assertThat(retrievedToken.getToken().getHeaders()).containsEntry("header1", "value1");
} }
} }

View File

@ -42,7 +42,7 @@ public class PreAuthenticatedAuthenticationTokenTests {
assertThat(token.getPrincipal()).isEqualTo(principal); assertThat(token.getPrincipal()).isEqualTo(principal);
assertThat(token.getCredentials()).isEqualTo(credentials); assertThat(token.getCredentials()).isEqualTo(credentials);
assertThat(token.getDetails()).isEqualTo(details); assertThat(token.getDetails()).isEqualTo(details);
assertThat(token.getAuthorities().isEmpty()).isTrue(); assertThat(token.getAuthorities()).isEmpty();
} }
@Test @Test
@ -53,7 +53,7 @@ public class PreAuthenticatedAuthenticationTokenTests {
assertThat(token.getPrincipal()).isEqualTo(principal); assertThat(token.getPrincipal()).isEqualTo(principal);
assertThat(token.getCredentials()).isEqualTo(credentials); assertThat(token.getCredentials()).isEqualTo(credentials);
assertThat(token.getDetails()).isNull(); assertThat(token.getDetails()).isNull();
assertThat(token.getAuthorities().isEmpty()).isTrue(); assertThat(token.getAuthorities()).isEmpty();
} }
@Test @Test

View File

@ -95,10 +95,10 @@ public class JdbcTokenRepositoryImplTests {
PersistentRememberMeToken token = new PersistentRememberMeToken("joeuser", "joesseries", "atoken", currentDate); PersistentRememberMeToken token = new PersistentRememberMeToken("joeuser", "joesseries", "atoken", currentDate);
this.repo.createNewToken(token); this.repo.createNewToken(token);
Map<String, Object> results = this.template.queryForMap("select * from persistent_logins"); Map<String, Object> results = this.template.queryForMap("select * from persistent_logins");
assertThat(results.get("last_used")).isEqualTo(currentDate); assertThat(results).containsEntry("last_used", currentDate);
assertThat(results.get("username")).isEqualTo("joeuser"); assertThat(results).containsEntry("username", "joeuser");
assertThat(results.get("series")).isEqualTo("joesseries"); assertThat(results).containsEntry("series", "joesseries");
assertThat(results.get("token")).isEqualTo("atoken"); assertThat(results).containsEntry("token", "atoken");
} }
@Test @Test
@ -157,9 +157,9 @@ public class JdbcTokenRepositoryImplTests {
this.repo.updateToken("joesseries", "newtoken", new Date()); this.repo.updateToken("joesseries", "newtoken", new Date());
Map<String, Object> results = this.template Map<String, Object> results = this.template
.queryForMap("select * from persistent_logins where series = 'joesseries'"); .queryForMap("select * from persistent_logins where series = 'joesseries'");
assertThat(results.get("username")).isEqualTo("joeuser"); assertThat(results).containsEntry("username", "joeuser");
assertThat(results.get("series")).isEqualTo("joesseries"); assertThat(results).containsEntry("series", "joesseries");
assertThat(results.get("token")).isEqualTo("newtoken"); assertThat(results).containsEntry("token", "newtoken");
Date lastUsed = (Date) results.get("last_used"); Date lastUsed = (Date) results.get("last_used");
assertThat(lastUsed.getTime() > ts.getTime()).isTrue(); assertThat(lastUsed.getTime() > ts.getTime()).isTrue();
} }

View File

@ -93,7 +93,7 @@ public class PersistentTokenBasedRememberMeServicesTests {
this.services.processAutoLoginCookie(new String[] { "series", "token" }, new MockHttpServletRequest(), this.services.processAutoLoginCookie(new String[] { "series", "token" }, new MockHttpServletRequest(),
response); response);
assertThat(this.repo.getStoredToken().getSeries()).isEqualTo("series"); assertThat(this.repo.getStoredToken().getSeries()).isEqualTo("series");
assertThat(this.repo.getStoredToken().getTokenValue().length()).isEqualTo(16); assertThat(this.repo.getStoredToken().getTokenValue()).hasSize(16);
String[] cookie = this.services.decodeCookie(response.getCookie("mycookiename").getValue()); String[] cookie = this.services.decodeCookie(response.getCookie("mycookiename").getValue());
assertThat(cookie[0]).isEqualTo("series"); assertThat(cookie[0]).isEqualTo("series");
assertThat(cookie[1]).isEqualTo(this.repo.getStoredToken().getTokenValue()); assertThat(cookie[1]).isEqualTo(this.repo.getStoredToken().getTokenValue());
@ -108,8 +108,8 @@ public class PersistentTokenBasedRememberMeServicesTests {
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
this.services.loginSuccess(new MockHttpServletRequest(), response, this.services.loginSuccess(new MockHttpServletRequest(), response,
UsernamePasswordAuthenticationToken.unauthenticated("joe", "password")); UsernamePasswordAuthenticationToken.unauthenticated("joe", "password"));
assertThat(this.repo.getStoredToken().getSeries().length()).isEqualTo(16); assertThat(this.repo.getStoredToken().getSeries()).hasSize(16);
assertThat(this.repo.getStoredToken().getTokenValue().length()).isEqualTo(16); assertThat(this.repo.getStoredToken().getTokenValue()).hasSize(16);
String[] cookie = this.services.decodeCookie(response.getCookie("mycookiename").getValue()); String[] cookie = this.services.decodeCookie(response.getCookie("mycookiename").getValue());
assertThat(cookie[0]).isEqualTo(this.repo.getStoredToken().getSeries()); assertThat(cookie[0]).isEqualTo(this.repo.getStoredToken().getSeries());
assertThat(cookie[1]).isEqualTo(this.repo.getStoredToken().getTokenValue()); assertThat(cookie[1]).isEqualTo(this.repo.getStoredToken().getTokenValue());

View File

@ -38,16 +38,16 @@ public class DigestAuthUtilsTests {
String unsplit = "username=\"rod\", invalidEntryThatHasNoEqualsSign, realm=\"Contacts Realm\", nonce=\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\", uri=\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\", response=\"38644211cf9ac3da63ab639807e2baff\", qop=auth, nc=00000004, cnonce=\"2b8d329a8571b99a\""; String unsplit = "username=\"rod\", invalidEntryThatHasNoEqualsSign, realm=\"Contacts Realm\", nonce=\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\", uri=\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\", response=\"38644211cf9ac3da63ab639807e2baff\", qop=auth, nc=00000004, cnonce=\"2b8d329a8571b99a\"";
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(unsplit); String[] headerEntries = StringUtils.commaDelimitedListToStringArray(unsplit);
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\""); Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
assertThat(headerMap.get("username")).isEqualTo("rod"); assertThat(headerMap).containsEntry("username", "rod");
assertThat(headerMap.get("realm")).isEqualTo("Contacts Realm"); assertThat(headerMap).containsEntry("realm", "Contacts Realm");
assertThat(headerMap.get("nonce")) assertThat(headerMap).containsEntry("nonce",
.isEqualTo("MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ=="); "MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==");
assertThat(headerMap.get("uri")) assertThat(headerMap).containsEntry("uri",
.isEqualTo("/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4"); "/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4");
assertThat(headerMap.get("response")).isEqualTo("38644211cf9ac3da63ab639807e2baff"); assertThat(headerMap).containsEntry("response", "38644211cf9ac3da63ab639807e2baff");
assertThat(headerMap.get("qop")).isEqualTo("auth"); assertThat(headerMap).containsEntry("qop", "auth");
assertThat(headerMap.get("nc")).isEqualTo("00000004"); assertThat(headerMap).containsEntry("nc", "00000004");
assertThat(headerMap.get("cnonce")).isEqualTo("2b8d329a8571b99a"); assertThat(headerMap).containsEntry("cnonce", "2b8d329a8571b99a");
assertThat(headerMap).hasSize(8); assertThat(headerMap).hasSize(8);
} }
@ -56,16 +56,16 @@ public class DigestAuthUtilsTests {
String unsplit = "username=\"rod\", realm=\"Contacts Realm\", nonce=\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\", uri=\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\", response=\"38644211cf9ac3da63ab639807e2baff\", qop=auth, nc=00000004, cnonce=\"2b8d329a8571b99a\""; String unsplit = "username=\"rod\", realm=\"Contacts Realm\", nonce=\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\", uri=\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\", response=\"38644211cf9ac3da63ab639807e2baff\", qop=auth, nc=00000004, cnonce=\"2b8d329a8571b99a\"";
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(unsplit); String[] headerEntries = StringUtils.commaDelimitedListToStringArray(unsplit);
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", null); Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", null);
assertThat(headerMap.get("username")).isEqualTo("\"rod\""); assertThat(headerMap).containsEntry("username", "\"rod\"");
assertThat(headerMap.get("realm")).isEqualTo("\"Contacts Realm\""); assertThat(headerMap).containsEntry("realm", "\"Contacts Realm\"");
assertThat(headerMap.get("nonce")) assertThat(headerMap).containsEntry("nonce",
.isEqualTo("\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\""); "\"MTEwOTAyMzU1MTQ4NDo1YzY3OWViYWM5NDNmZWUwM2UwY2NmMDBiNDQzMTQ0OQ==\"");
assertThat(headerMap.get("uri")) assertThat(headerMap).containsEntry("uri",
.isEqualTo("\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\""); "\"/spring-security-sample-contacts-filter/secure/adminPermission.htm?contactId=4\"");
assertThat(headerMap.get("response")).isEqualTo("\"38644211cf9ac3da63ab639807e2baff\""); assertThat(headerMap).containsEntry("response", "\"38644211cf9ac3da63ab639807e2baff\"");
assertThat(headerMap.get("qop")).isEqualTo("auth"); assertThat(headerMap).containsEntry("qop", "auth");
assertThat(headerMap.get("nc")).isEqualTo("00000004"); assertThat(headerMap).containsEntry("nc", "00000004");
assertThat(headerMap.get("cnonce")).isEqualTo("\"2b8d329a8571b99a\""); assertThat(headerMap).containsEntry("cnonce", "\"2b8d329a8571b99a\"");
assertThat(headerMap).hasSize(8); assertThat(headerMap).hasSize(8);
} }

View File

@ -93,8 +93,8 @@ public class DigestAuthenticationEntryPointTests {
String header = response.getHeader("WWW-Authenticate").toString().substring(7); String header = response.getHeader("WWW-Authenticate").toString().substring(7);
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header); String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header);
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\""); Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
assertThat(headerMap.get("realm")).isEqualTo("hello"); assertThat(headerMap).containsEntry("realm", "hello");
assertThat(headerMap.get("qop")).isEqualTo("auth"); assertThat(headerMap).containsEntry("qop", "auth");
assertThat(headerMap.get("stale")).isNull(); assertThat(headerMap.get("stale")).isNull();
checkNonceValid(headerMap.get("nonce")); checkNonceValid(headerMap.get("nonce"));
} }
@ -116,9 +116,9 @@ public class DigestAuthenticationEntryPointTests {
String header = response.getHeader("WWW-Authenticate").toString().substring(7); String header = response.getHeader("WWW-Authenticate").toString().substring(7);
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header); String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header);
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\""); Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
assertThat(headerMap.get("realm")).isEqualTo("hello"); assertThat(headerMap).containsEntry("realm", "hello");
assertThat(headerMap.get("qop")).isEqualTo("auth"); assertThat(headerMap).containsEntry("qop", "auth");
assertThat(headerMap.get("stale")).isEqualTo("true"); assertThat(headerMap).containsEntry("stale", "true");
checkNonceValid(headerMap.get("nonce")); checkNonceValid(headerMap.get("nonce"));
} }

View File

@ -149,7 +149,7 @@ public class DigestAuthenticationFilterTests {
String header = response.getHeader("WWW-Authenticate").toString().substring(7); String header = response.getHeader("WWW-Authenticate").toString().substring(7);
String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header); String[] headerEntries = StringUtils.commaDelimitedListToStringArray(header);
Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\""); Map<String, String> headerMap = DigestAuthUtils.splitEachArrayElementAndCreateMap(headerEntries, "=", "\"");
assertThat(headerMap.get("stale")).isEqualTo("true"); assertThat(headerMap).containsEntry("stale", "true");
} }
@Test @Test

View File

@ -47,7 +47,7 @@ public class CacheControlHeadersWriterTests {
@Test @Test
public void writeHeaders() { public void writeHeaders() {
this.writer.writeHeaders(this.request, this.response); this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames().size()).isEqualTo(3); assertThat(this.response.getHeaderNames()).hasSize(3);
assertThat(this.response.getHeaderValues("Cache-Control")) assertThat(this.response.getHeaderValues("Cache-Control"))
.containsOnly("no-cache, no-store, max-age=0, must-revalidate"); .containsOnly("no-cache, no-store, max-age=0, must-revalidate");
assertThat(this.response.getHeaderValues("Pragma")).containsOnly("no-cache"); assertThat(this.response.getHeaderValues("Pragma")).containsOnly("no-cache");

View File

@ -112,7 +112,7 @@ public class HstsHeaderWriterTests {
public void writeHeadersInsecureRequestDoesNotWriteHeader() { public void writeHeadersInsecureRequestDoesNotWriteHeader() {
this.request.setSecure(false); this.request.setSecure(false);
this.writer.writeHeaders(this.request, this.response); this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames().isEmpty()).isTrue(); assertThat(this.response.getHeaderNames()).isEmpty();
} }
@Test @Test

View File

@ -72,7 +72,7 @@ public class FrameOptionsHeaderWriterTests {
public void writeHeadersAllowFromReturnsNull() { public void writeHeadersAllowFromReturnsNull() {
this.writer = new XFrameOptionsHeaderWriter(this.strategy); this.writer = new XFrameOptionsHeaderWriter(this.strategy);
this.writer.writeHeaders(this.request, this.response); this.writer.writeHeaders(this.request, this.response);
assertThat(this.response.getHeaderNames().isEmpty()).isTrue(); assertThat(this.response.getHeaderNames()).isEmpty();
} }
@Test @Test

View File

@ -45,7 +45,7 @@ public class DefaultSavedRequestTests {
MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("If-None-Match", "somehashvalue"); request.addHeader("If-None-Match", "somehashvalue");
DefaultSavedRequest saved = new DefaultSavedRequest(request, new MockPortResolver(8080, 8443)); DefaultSavedRequest saved = new DefaultSavedRequest(request, new MockPortResolver(8080, 8443));
assertThat(saved.getHeaderValues("if-none-match").isEmpty()).isTrue(); assertThat(saved.getHeaderValues("if-none-match")).isEmpty();
} }
// SEC-3082 // SEC-3082

View File

@ -46,7 +46,7 @@ public class CookieServerRequestCacheTests {
.from(MockServerHttpRequest.get("/secured/").accept(MediaType.TEXT_HTML)); .from(MockServerHttpRequest.get("/secured/").accept(MediaType.TEXT_HTML));
this.cache.saveRequest(exchange).block(); this.cache.saveRequest(exchange).block();
MultiValueMap<String, ResponseCookie> cookies = exchange.getResponse().getCookies(); MultiValueMap<String, ResponseCookie> cookies = exchange.getResponse().getCookies();
assertThat(cookies.size()).isEqualTo(1); assertThat(cookies).hasSize(1);
ResponseCookie cookie = cookies.getFirst("REDIRECT_URI"); ResponseCookie cookie = cookies.getFirst("REDIRECT_URI");
assertThat(cookie).isNotNull(); assertThat(cookie).isNotNull();
String encodedRedirectUrl = Base64.getEncoder().encodeToString("/secured/".getBytes()); String encodedRedirectUrl = Base64.getEncoder().encodeToString("/secured/".getBytes());
@ -60,7 +60,7 @@ public class CookieServerRequestCacheTests {
.from(MockServerHttpRequest.get("/secured/").queryParam("key", "value").accept(MediaType.TEXT_HTML)); .from(MockServerHttpRequest.get("/secured/").queryParam("key", "value").accept(MediaType.TEXT_HTML));
this.cache.saveRequest(exchange).block(); this.cache.saveRequest(exchange).block();
MultiValueMap<String, ResponseCookie> cookies = exchange.getResponse().getCookies(); MultiValueMap<String, ResponseCookie> cookies = exchange.getResponse().getCookies();
assertThat(cookies.size()).isEqualTo(1); assertThat(cookies).hasSize(1);
ResponseCookie cookie = cookies.getFirst("REDIRECT_URI"); ResponseCookie cookie = cookies.getFirst("REDIRECT_URI");
assertThat(cookie).isNotNull(); assertThat(cookie).isNotNull();
String encodedRedirectUrl = Base64.getEncoder().encodeToString("/secured/?key=value".getBytes()); String encodedRedirectUrl = Base64.getEncoder().encodeToString("/secured/?key=value".getBytes());