Merge branch '6.1.x'
Closes gh-13884
This commit is contained in:
@@ -115,7 +115,7 @@ public class FilterChainProxyConfigTests {
|
||||
assertThat(getPattern(chains.get(0))).isEqualTo("/login*");
|
||||
assertThat(getPattern(chains.get(1))).isEqualTo("/logout");
|
||||
assertThat(((DefaultSecurityFilterChain) chains.get(2)).getRequestMatcher())
|
||||
.isInstanceOf(AnyRequestMatcher.class);
|
||||
.isInstanceOf(AnyRequestMatcher.class);
|
||||
}
|
||||
|
||||
private String getPattern(SecurityFilterChain chain) {
|
||||
|
||||
@@ -50,25 +50,26 @@ public class InvalidConfigurationTests {
|
||||
@Test
|
||||
public void passwordEncoderCannotAppearAtTopLevel() {
|
||||
assertThatExceptionOfType(XmlBeanDefinitionStoreException.class)
|
||||
.isThrownBy(() -> setContext("<password-encoder hash='md5'/>"));
|
||||
.isThrownBy(() -> setContext("<password-encoder hash='md5'/>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticationProviderCannotAppearAtTopLevel() {
|
||||
assertThatExceptionOfType(XmlBeanDefinitionStoreException.class)
|
||||
.isThrownBy(() -> setContext("<authentication-provider ref='blah'/>"));
|
||||
.isThrownBy(() -> setContext("<authentication-provider ref='blah'/>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void missingAuthenticationManagerGivesSensibleErrorMessage() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> setContext("<http auto-config='true' />")).satisfies((ex) -> {
|
||||
Throwable cause = ultimateCause(ex);
|
||||
assertThat(cause).isInstanceOf(NoSuchBeanDefinitionException.class);
|
||||
NoSuchBeanDefinitionException nsbe = (NoSuchBeanDefinitionException) cause;
|
||||
assertThat(nsbe.getBeanName()).isEqualTo(BeanIds.AUTHENTICATION_MANAGER);
|
||||
assertThat(nsbe.getMessage()).endsWith(AuthenticationManagerFactoryBean.MISSING_BEAN_ERROR_MESSAGE);
|
||||
});
|
||||
.isThrownBy(() -> setContext("<http auto-config='true' />"))
|
||||
.satisfies((ex) -> {
|
||||
Throwable cause = ultimateCause(ex);
|
||||
assertThat(cause).isInstanceOf(NoSuchBeanDefinitionException.class);
|
||||
NoSuchBeanDefinitionException nsbe = (NoSuchBeanDefinitionException) cause;
|
||||
assertThat(nsbe.getBeanName()).isEqualTo(BeanIds.AUTHENTICATION_MANAGER);
|
||||
assertThat(nsbe.getMessage()).endsWith(AuthenticationManagerFactoryBean.MISSING_BEAN_ERROR_MESSAGE);
|
||||
});
|
||||
}
|
||||
|
||||
private Throwable ultimateCause(Throwable ex) {
|
||||
|
||||
@@ -74,10 +74,10 @@ public class SecurityNamespaceHandlerTests {
|
||||
@Test
|
||||
public void pre32SchemaAreNotSupported() {
|
||||
assertThatExceptionOfType(BeanDefinitionParsingException.class)
|
||||
.isThrownBy(() -> new InMemoryXmlApplicationContext(
|
||||
"<user-service id='us'><user name='bob' password='bobspassword' authorities='ROLE_A' /></user-service>",
|
||||
"3.0.3", null))
|
||||
.withMessageContaining("You cannot use a spring-security-2.0.xsd");
|
||||
.isThrownBy(() -> new InMemoryXmlApplicationContext(
|
||||
"<user-service id='us'><user name='bob' password='bobspassword' authorities='ROLE_A' /></user-service>",
|
||||
"3.0.3", null))
|
||||
.withMessageContaining("You cannot use a spring-security-2.0.xsd");
|
||||
}
|
||||
|
||||
// SEC-1868
|
||||
@@ -97,8 +97,10 @@ public class SecurityNamespaceHandlerTests {
|
||||
String className = "jakarta.servlet.Filter";
|
||||
expectClassUtilsForNameThrowsNoClassDefFoundError(className);
|
||||
assertThatExceptionOfType(BeanDefinitionParsingException.class)
|
||||
.isThrownBy(() -> new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER + XML_HTTP_BLOCK))
|
||||
.havingRootCause().isInstanceOf(NoClassDefFoundError.class).withMessage(className);
|
||||
.isThrownBy(() -> new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER + XML_HTTP_BLOCK))
|
||||
.havingRootCause()
|
||||
.isInstanceOf(NoClassDefFoundError.class)
|
||||
.withMessage(className);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -114,8 +116,10 @@ public class SecurityNamespaceHandlerTests {
|
||||
String className = FILTER_CHAIN_PROXY_CLASSNAME;
|
||||
expectClassUtilsForNameThrowsClassNotFoundException(className);
|
||||
assertThatExceptionOfType(BeanDefinitionParsingException.class)
|
||||
.isThrownBy(() -> new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER + XML_HTTP_BLOCK))
|
||||
.havingRootCause().isInstanceOf(ClassNotFoundException.class).withMessage(className);
|
||||
.isThrownBy(() -> new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER + XML_HTTP_BLOCK))
|
||||
.havingRootCause()
|
||||
.isInstanceOf(ClassNotFoundException.class)
|
||||
.withMessage(className);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -137,18 +141,18 @@ public class SecurityNamespaceHandlerTests {
|
||||
@Test
|
||||
public void configureWhenOldVersionThenErrorMessageContainsCorrectVersion() {
|
||||
assertThatExceptionOfType(BeanDefinitionParsingException.class)
|
||||
.isThrownBy(() -> new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER, "3.0", null))
|
||||
.withMessageContaining(SpringSecurityVersions.getCurrentXsdVersionFromSpringSchemas());
|
||||
.isThrownBy(() -> new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER, "3.0", null))
|
||||
.withMessageContaining(SpringSecurityVersions.getCurrentXsdVersionFromSpringSchemas());
|
||||
}
|
||||
|
||||
private void expectClassUtilsForNameThrowsNoClassDefFoundError(String className) {
|
||||
this.classUtils.when(() -> ClassUtils.forName(eq(FILTER_CHAIN_PROXY_CLASSNAME), any()))
|
||||
.thenThrow(new NoClassDefFoundError(className));
|
||||
.thenThrow(new NoClassDefFoundError(className));
|
||||
}
|
||||
|
||||
private void expectClassUtilsForNameThrowsClassNotFoundException(String className) {
|
||||
this.classUtils.when(() -> ClassUtils.forName(eq(FILTER_CHAIN_PROXY_CLASSNAME), any()))
|
||||
.thenThrow(new ClassNotFoundException(className));
|
||||
.thenThrow(new ClassNotFoundException(className));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -37,7 +37,7 @@ public class SecurityConfigurerAdapterTests {
|
||||
this.adapter.addObjectPostProcessor(new OrderedObjectPostProcessor(Ordered.LOWEST_PRECEDENCE));
|
||||
this.adapter.addObjectPostProcessor(new OrderedObjectPostProcessor(Ordered.HIGHEST_PRECEDENCE));
|
||||
assertThat(this.adapter.postProcess("hi"))
|
||||
.isEqualTo("hi " + Ordered.HIGHEST_PRECEDENCE + " " + Ordered.LOWEST_PRECEDENCE);
|
||||
.isEqualTo("hi " + Ordered.HIGHEST_PRECEDENCE + " " + Ordered.LOWEST_PRECEDENCE);
|
||||
}
|
||||
|
||||
static class OrderedObjectPostProcessor implements ObjectPostProcessor<String>, Ordered {
|
||||
|
||||
@@ -91,19 +91,22 @@ public class AuthenticationManagerBuilderTests {
|
||||
AuthenticationEventPublisher aep = mock(AuthenticationEventPublisher.class);
|
||||
given(opp.postProcess(any())).willAnswer((a) -> a.getArgument(0));
|
||||
AuthenticationManager am = new AuthenticationManagerBuilder(opp).authenticationEventPublisher(aep)
|
||||
.inMemoryAuthentication().and().build();
|
||||
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
|
||||
() -> am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password")));
|
||||
.inMemoryAuthentication()
|
||||
.and()
|
||||
.build();
|
||||
assertThatExceptionOfType(AuthenticationException.class)
|
||||
.isThrownBy(() -> am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password")));
|
||||
verify(aep).publishAuthenticationFailure(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getAuthenticationManagerWhenGlobalPasswordEncoderBeanThenUsed() throws Exception {
|
||||
this.spring.register(PasswordEncoderGlobalConfig.class).autowire();
|
||||
AuthenticationManager manager = this.spring.getContext().getBean(AuthenticationConfiguration.class)
|
||||
.getAuthenticationManager();
|
||||
AuthenticationManager manager = this.spring.getContext()
|
||||
.getBean(AuthenticationConfiguration.class)
|
||||
.getAuthenticationManager();
|
||||
Authentication auth = manager
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
|
||||
assertThat(auth.getName()).isEqualTo("user");
|
||||
assertThat(auth.getAuthorities()).extracting(GrantedAuthority::getAuthority).containsOnly("ROLE_USER");
|
||||
}
|
||||
@@ -111,10 +114,11 @@ public class AuthenticationManagerBuilderTests {
|
||||
@Test
|
||||
public void getAuthenticationManagerWhenProtectedPasswordEncoderBeanThenUsed() throws Exception {
|
||||
this.spring.register(PasswordEncoderGlobalConfig.class).autowire();
|
||||
AuthenticationManager manager = this.spring.getContext().getBean(AuthenticationConfiguration.class)
|
||||
.getAuthenticationManager();
|
||||
AuthenticationManager manager = this.spring.getContext()
|
||||
.getBean(AuthenticationConfiguration.class)
|
||||
.getAuthenticationManager();
|
||||
Authentication auth = manager
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
|
||||
assertThat(auth.getName()).isEqualTo("user");
|
||||
assertThat(auth.getAuthorities()).extracting(GrantedAuthority::getAuthority).containsOnly("ROLE_USER");
|
||||
}
|
||||
@@ -123,10 +127,10 @@ public class AuthenticationManagerBuilderTests {
|
||||
public void authenticationManagerWhenMultipleProvidersThenWorks() throws Exception {
|
||||
this.spring.register(MultiAuthenticationProvidersConfig.class).autowire();
|
||||
SecurityMockMvcResultMatchers.AuthenticatedMatcher user = authenticated().withUsername("user")
|
||||
.withRoles("USER");
|
||||
.withRoles("USER");
|
||||
this.mockMvc.perform(formLogin()).andExpect(user);
|
||||
SecurityMockMvcResultMatchers.AuthenticatedMatcher admin = authenticated().withUsername("admin")
|
||||
.withRoles("USER", "ADMIN");
|
||||
.withRoles("USER", "ADMIN");
|
||||
this.mockMvc.perform(formLogin().user("admin")).andExpect(admin);
|
||||
}
|
||||
|
||||
@@ -161,7 +165,7 @@ public class AuthenticationManagerBuilderTests {
|
||||
public void buildWhenUserFromProperties() throws Exception {
|
||||
this.spring.register(UserFromPropertiesConfig.class).autowire();
|
||||
this.mockMvc.perform(formLogin().user("joe", "joespassword"))
|
||||
.andExpect(authenticated().withUsername("joe").withRoles("USER"));
|
||||
.andExpect(authenticated().withUsername("joe").withRoles("USER"));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
@@ -48,7 +48,7 @@ public class NamespaceAuthenticationManagerTests {
|
||||
public void authenticationMangerWhenDefaultThenEraseCredentialsIsTrue() throws Exception {
|
||||
this.spring.register(EraseCredentialsTrueDefaultConfig.class).autowire();
|
||||
SecurityMockMvcResultMatchers.AuthenticatedMatcher nullCredentials = authenticated()
|
||||
.withAuthentication((a) -> assertThat(a.getCredentials()).isNull());
|
||||
.withAuthentication((a) -> assertThat(a.getCredentials()).isNull());
|
||||
this.mockMvc.perform(formLogin()).andExpect(nullCredentials);
|
||||
this.mockMvc.perform(formLogin()).andExpect(nullCredentials);
|
||||
// no exception due to username being cleared out
|
||||
@@ -58,7 +58,7 @@ public class NamespaceAuthenticationManagerTests {
|
||||
public void authenticationMangerWhenEraseCredentialsIsFalseThenCredentialsNotNull() throws Exception {
|
||||
this.spring.register(EraseCredentialsFalseConfig.class).autowire();
|
||||
SecurityMockMvcResultMatchers.AuthenticatedMatcher notNullCredentials = authenticated()
|
||||
.withAuthentication((a) -> assertThat(a.getCredentials()).isNotNull());
|
||||
.withAuthentication((a) -> assertThat(a.getCredentials()).isNotNull());
|
||||
this.mockMvc.perform(formLogin()).andExpect(notNullCredentials);
|
||||
this.mockMvc.perform(formLogin()).andExpect(notNullCredentials);
|
||||
// no exception due to username being cleared out
|
||||
@@ -69,7 +69,7 @@ public class NamespaceAuthenticationManagerTests {
|
||||
public void authenticationManagerWhenGlobalAndEraseCredentialsIsFalseThenCredentialsNotNull() throws Exception {
|
||||
this.spring.register(GlobalEraseCredentialsFalseConfig.class).autowire();
|
||||
SecurityMockMvcResultMatchers.AuthenticatedMatcher notNullCredentials = authenticated()
|
||||
.withAuthentication((a) -> assertThat(a.getCredentials()).isNotNull());
|
||||
.withAuthentication((a) -> assertThat(a.getCredentials()).isNotNull());
|
||||
this.mockMvc.perform(formLogin()).andExpect(notNullCredentials);
|
||||
}
|
||||
|
||||
|
||||
@@ -146,8 +146,8 @@ public class NamespaceJdbcUserServiceTests {
|
||||
@Bean
|
||||
DataSource dataSource() {
|
||||
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder()
|
||||
// simulate that the DB already has the schema loaded and users in it
|
||||
.addScript("CustomJdbcUserServiceSampleConfig.sql");
|
||||
// simulate that the DB already has the schema loaded and users in it
|
||||
.addScript("CustomJdbcUserServiceSampleConfig.sql");
|
||||
return builder.setType(EmbeddedDatabaseType.HSQL).build();
|
||||
}
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ public class AuthenticationConfigurationPublishTests {
|
||||
@Test
|
||||
public void authenticationEventPublisherBeanUsedByDefault() {
|
||||
this.authenticationManager
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
|
||||
assertThat(this.listener.getEvents()).hasSize(1);
|
||||
}
|
||||
|
||||
|
||||
@@ -90,28 +90,34 @@ public class AuthenticationConfigurationTests {
|
||||
|
||||
@Test
|
||||
public void orderingAutowiredOnEnableGlobalMethodSecurity() {
|
||||
this.spring.register(AuthenticationTestConfiguration.class, GlobalMethodSecurityAutowiredConfig.class,
|
||||
ServicesConfig.class).autowire();
|
||||
this.spring
|
||||
.register(AuthenticationTestConfiguration.class, GlobalMethodSecurityAutowiredConfig.class,
|
||||
ServicesConfig.class)
|
||||
.autowire();
|
||||
SecurityContextHolder.getContext()
|
||||
.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
|
||||
.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
|
||||
this.service.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void orderingAutowiredOnEnableWebSecurity() {
|
||||
this.spring.register(AuthenticationTestConfiguration.class, WebSecurityConfig.class,
|
||||
GlobalMethodSecurityAutowiredConfig.class, ServicesConfig.class).autowire();
|
||||
this.spring
|
||||
.register(AuthenticationTestConfiguration.class, WebSecurityConfig.class,
|
||||
GlobalMethodSecurityAutowiredConfig.class, ServicesConfig.class)
|
||||
.autowire();
|
||||
SecurityContextHolder.getContext()
|
||||
.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
|
||||
.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
|
||||
this.service.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void orderingAutowiredOnEnableWebMvcSecurity() {
|
||||
this.spring.register(AuthenticationTestConfiguration.class, WebMvcSecurityConfig.class,
|
||||
GlobalMethodSecurityAutowiredConfig.class, ServicesConfig.class).autowire();
|
||||
this.spring
|
||||
.register(AuthenticationTestConfiguration.class, WebMvcSecurityConfig.class,
|
||||
GlobalMethodSecurityAutowiredConfig.class, ServicesConfig.class)
|
||||
.autowire();
|
||||
SecurityContextHolder.getContext()
|
||||
.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
|
||||
.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
|
||||
this.service.run();
|
||||
}
|
||||
|
||||
@@ -119,25 +125,30 @@ public class AuthenticationConfigurationTests {
|
||||
public void getAuthenticationManagerWhenNoAuthenticationThenNull() throws Exception {
|
||||
this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class).autowire();
|
||||
assertThat(this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager())
|
||||
.isNull();
|
||||
.isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getAuthenticationManagerWhenNoOpGlobalAuthenticationConfigurerAdapterThenNull() throws Exception {
|
||||
this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class,
|
||||
NoOpGlobalAuthenticationConfigurerAdapter.class).autowire();
|
||||
this.spring
|
||||
.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class,
|
||||
NoOpGlobalAuthenticationConfigurerAdapter.class)
|
||||
.autowire();
|
||||
assertThat(this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager())
|
||||
.isNull();
|
||||
.isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getAuthenticationWhenGlobalAuthenticationConfigurerAdapterThenAuthenticates() throws Exception {
|
||||
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user",
|
||||
"password");
|
||||
this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class,
|
||||
UserGlobalAuthenticationConfigurerAdapter.class).autowire();
|
||||
AuthenticationManager authentication = this.spring.getContext().getBean(AuthenticationConfiguration.class)
|
||||
.getAuthenticationManager();
|
||||
this.spring
|
||||
.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class,
|
||||
UserGlobalAuthenticationConfigurerAdapter.class)
|
||||
.autowire();
|
||||
AuthenticationManager authentication = this.spring.getContext()
|
||||
.getBean(AuthenticationConfiguration.class)
|
||||
.getAuthenticationManager();
|
||||
assertThat(authentication.authenticate(token).getName()).isEqualTo(token.getName());
|
||||
}
|
||||
|
||||
@@ -145,18 +156,23 @@ public class AuthenticationConfigurationTests {
|
||||
public void getAuthenticationWhenAuthenticationManagerBeanThenAuthenticates() throws Exception {
|
||||
UsernamePasswordAuthenticationToken token = UsernamePasswordAuthenticationToken.unauthenticated("user",
|
||||
"password");
|
||||
this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class,
|
||||
AuthenticationManagerBeanConfig.class).autowire();
|
||||
AuthenticationManager authentication = this.spring.getContext().getBean(AuthenticationConfiguration.class)
|
||||
.getAuthenticationManager();
|
||||
this.spring
|
||||
.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class,
|
||||
AuthenticationManagerBeanConfig.class)
|
||||
.autowire();
|
||||
AuthenticationManager authentication = this.spring.getContext()
|
||||
.getBean(AuthenticationConfiguration.class)
|
||||
.getAuthenticationManager();
|
||||
given(authentication.authenticate(token)).willReturn(TestAuthentication.authenticatedUser());
|
||||
assertThat(authentication.authenticate(token).getName()).isEqualTo(token.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getAuthenticationWhenMultipleThenOrdered() throws Exception {
|
||||
this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class,
|
||||
AuthenticationManagerBeanConfig.class).autowire();
|
||||
this.spring
|
||||
.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class,
|
||||
AuthenticationManagerBeanConfig.class)
|
||||
.autowire();
|
||||
AuthenticationConfiguration config = this.spring.getContext().getBean(AuthenticationConfiguration.class);
|
||||
config.setGlobalAuthenticationConfigurers(Arrays.asList(new LowestOrderGlobalAuthenticationConfigurerAdapter(),
|
||||
new HighestOrderGlobalAuthenticationConfigurerAdapter(),
|
||||
@@ -172,7 +188,7 @@ public class AuthenticationConfigurationTests {
|
||||
AuthenticationManager authenticationManager = config.getAuthenticationManager();
|
||||
authenticationManager.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
|
||||
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> authenticationManager
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("boot", "password")));
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("boot", "password")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -208,12 +224,13 @@ public class AuthenticationConfigurationTests {
|
||||
throws Exception {
|
||||
this.spring.register(UserDetailsServiceBeanConfig.class).autowire();
|
||||
UserDetailsService uds = this.spring.getContext().getBean(UserDetailsService.class);
|
||||
AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class)
|
||||
.getAuthenticationManager();
|
||||
AuthenticationManager am = this.spring.getContext()
|
||||
.getBean(AuthenticationConfiguration.class)
|
||||
.getAuthenticationManager();
|
||||
given(uds.loadUserByUsername("user")).willReturn(PasswordEncodedUser.user(), PasswordEncodedUser.user());
|
||||
am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
|
||||
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
|
||||
() -> am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "invalid")));
|
||||
assertThatExceptionOfType(AuthenticationException.class)
|
||||
.isThrownBy(() -> am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "invalid")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -222,13 +239,14 @@ public class AuthenticationConfigurationTests {
|
||||
AuthorityUtils.createAuthorityList("ROLE_USER"));
|
||||
this.spring.register(UserDetailsServiceBeanWithPasswordEncoderConfig.class).autowire();
|
||||
UserDetailsService uds = this.spring.getContext().getBean(UserDetailsService.class);
|
||||
AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class)
|
||||
.getAuthenticationManager();
|
||||
AuthenticationManager am = this.spring.getContext()
|
||||
.getBean(AuthenticationConfiguration.class)
|
||||
.getAuthenticationManager();
|
||||
given(uds.loadUserByUsername("user")).willReturn(User.withUserDetails(user).build(),
|
||||
User.withUserDetails(user).build());
|
||||
am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
|
||||
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(
|
||||
() -> am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "invalid")));
|
||||
assertThatExceptionOfType(AuthenticationException.class)
|
||||
.isThrownBy(() -> am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "invalid")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -236,9 +254,10 @@ public class AuthenticationConfigurationTests {
|
||||
UserDetails user = new User("user", "{noop}password", AuthorityUtils.createAuthorityList("ROLE_USER"));
|
||||
this.spring.register(UserDetailsPasswordManagerBeanConfig.class).autowire();
|
||||
UserDetailsPasswordManagerBeanConfig.Manager manager = this.spring.getContext()
|
||||
.getBean(UserDetailsPasswordManagerBeanConfig.Manager.class);
|
||||
AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class)
|
||||
.getAuthenticationManager();
|
||||
.getBean(UserDetailsPasswordManagerBeanConfig.Manager.class);
|
||||
AuthenticationManager am = this.spring.getContext()
|
||||
.getBean(AuthenticationConfiguration.class)
|
||||
.getAuthenticationManager();
|
||||
given(manager.loadUserByUsername("user")).willReturn(User.withUserDetails(user).build(),
|
||||
User.withUserDetails(user).build());
|
||||
given(manager.updatePassword(any(), any())).willReturn(user);
|
||||
@@ -251,8 +270,9 @@ public class AuthenticationConfigurationTests {
|
||||
throws Exception {
|
||||
this.spring.register(AuthenticationProviderBeanAndUserDetailsServiceConfig.class).autowire();
|
||||
AuthenticationProvider ap = this.spring.getContext().getBean(AuthenticationProvider.class);
|
||||
AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class)
|
||||
.getAuthenticationManager();
|
||||
AuthenticationManager am = this.spring.getContext()
|
||||
.getBean(AuthenticationConfiguration.class)
|
||||
.getAuthenticationManager();
|
||||
given(ap.supports(any())).willReturn(true);
|
||||
given(ap.authenticate(any())).willReturn(TestAuthentication.authenticatedUser());
|
||||
am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
|
||||
@@ -263,8 +283,9 @@ public class AuthenticationConfigurationTests {
|
||||
public void getAuthenticationWhenAuthenticationProviderBeanThenUsed() throws Exception {
|
||||
this.spring.register(AuthenticationProviderBeanConfig.class).autowire();
|
||||
AuthenticationProvider ap = this.spring.getContext().getBean(AuthenticationProvider.class);
|
||||
AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class)
|
||||
.getAuthenticationManager();
|
||||
AuthenticationManager am = this.spring.getContext()
|
||||
.getBean(AuthenticationConfiguration.class)
|
||||
.getAuthenticationManager();
|
||||
given(ap.supports(any())).willReturn(true);
|
||||
given(ap.authenticate(any())).willReturn(TestAuthentication.authenticatedUser());
|
||||
am.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
|
||||
@@ -273,14 +294,16 @@ public class AuthenticationConfigurationTests {
|
||||
@Test
|
||||
public void enableGlobalMethodSecurityWhenPreAuthorizeThenNoException() {
|
||||
this.spring.register(UsesPreAuthorizeMethodSecurityConfig.class, AuthenticationManagerBeanConfig.class)
|
||||
.autowire();
|
||||
.autowire();
|
||||
// no exception
|
||||
}
|
||||
|
||||
@Test
|
||||
public void enableGlobalMethodSecurityWhenPreAuthorizeThenUsesMethodSecurityService() {
|
||||
this.spring.register(ServicesConfig.class, UsesPreAuthorizeMethodSecurityConfig.class,
|
||||
AuthenticationManagerBeanConfig.class).autowire();
|
||||
this.spring
|
||||
.register(ServicesConfig.class, UsesPreAuthorizeMethodSecurityConfig.class,
|
||||
AuthenticationManagerBeanConfig.class)
|
||||
.autowire();
|
||||
// no exception
|
||||
}
|
||||
|
||||
@@ -303,22 +326,24 @@ public class AuthenticationConfigurationTests {
|
||||
public void configureWhenDefaultsThenDefaultAuthenticationEventPublisher() {
|
||||
this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class).autowire();
|
||||
AuthenticationManagerBuilder authenticationManagerBuilder = this.spring.getContext()
|
||||
.getBean(AuthenticationManagerBuilder.class);
|
||||
.getBean(AuthenticationManagerBuilder.class);
|
||||
AuthenticationEventPublisher eventPublisher = (AuthenticationEventPublisher) ReflectionTestUtils
|
||||
.getField(authenticationManagerBuilder, "eventPublisher");
|
||||
.getField(authenticationManagerBuilder, "eventPublisher");
|
||||
assertThat(eventPublisher).isInstanceOf(DefaultAuthenticationEventPublisher.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configureWhenCustomAuthenticationEventPublisherThenCustomAuthenticationEventPublisher() {
|
||||
this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class,
|
||||
CustomAuthenticationEventPublisherConfig.class).autowire();
|
||||
this.spring
|
||||
.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class,
|
||||
CustomAuthenticationEventPublisherConfig.class)
|
||||
.autowire();
|
||||
AuthenticationManagerBuilder authenticationManagerBuilder = this.spring.getContext()
|
||||
.getBean(AuthenticationManagerBuilder.class);
|
||||
.getBean(AuthenticationManagerBuilder.class);
|
||||
AuthenticationEventPublisher eventPublisher = (AuthenticationEventPublisher) ReflectionTestUtils
|
||||
.getField(authenticationManagerBuilder, "eventPublisher");
|
||||
.getField(authenticationManagerBuilder, "eventPublisher");
|
||||
assertThat(eventPublisher)
|
||||
.isInstanceOf(CustomAuthenticationEventPublisherConfig.MyAuthenticationEventPublisher.class);
|
||||
.isInstanceOf(CustomAuthenticationEventPublisherConfig.MyAuthenticationEventPublisher.class);
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
@@ -57,15 +57,17 @@ class AuthenticationManagerBeanRegistrationAotProcessorTests {
|
||||
@Test
|
||||
void shouldProcessWhenImplementsInterface() {
|
||||
process(MyAuthenticationManager.class);
|
||||
assertThat(RuntimeHintsPredicates.proxies().forInterfaces(AuthenticationManager.class, SpringProxy.class,
|
||||
Advised.class, DecoratingProxy.class)).accepts(this.generationContext.getRuntimeHints());
|
||||
assertThat(RuntimeHintsPredicates.proxies()
|
||||
.forInterfaces(AuthenticationManager.class, SpringProxy.class, Advised.class, DecoratingProxy.class))
|
||||
.accepts(this.generationContext.getRuntimeHints());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldProcessWhenSuperclassImplementsInterface() {
|
||||
process(ChildAuthenticationManager.class);
|
||||
assertThat(RuntimeHintsPredicates.proxies().forInterfaces(AuthenticationManager.class, SpringProxy.class,
|
||||
Advised.class, DecoratingProxy.class)).accepts(this.generationContext.getRuntimeHints());
|
||||
assertThat(RuntimeHintsPredicates.proxies()
|
||||
.forInterfaces(AuthenticationManager.class, SpringProxy.class, Advised.class, DecoratingProxy.class))
|
||||
.accepts(this.generationContext.getRuntimeHints());
|
||||
}
|
||||
|
||||
private void process(Class<?> beanClass) {
|
||||
|
||||
@@ -53,7 +53,7 @@ public class LdapAuthenticationProviderConfigurerTests {
|
||||
assertThat(ReflectionTestUtils.getField(this.configurer, "ldapAuthoritiesPopulator")).isNull();
|
||||
this.configurer.ldapAuthoritiesPopulator(new NullLdapAuthoritiesPopulator());
|
||||
assertThat(ReflectionTestUtils.getField(this.configurer, "ldapAuthoritiesPopulator"))
|
||||
.isInstanceOf(NullLdapAuthoritiesPopulator.class);
|
||||
.isInstanceOf(NullLdapAuthoritiesPopulator.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -57,7 +57,7 @@ public class Issue50Tests {
|
||||
@BeforeEach
|
||||
public void setup() {
|
||||
SecurityContextHolder.getContext()
|
||||
.setAuthentication(new TestingAuthenticationToken("test", null, "ROLE_ADMIN"));
|
||||
.setAuthentication(new TestingAuthenticationToken("test", null, "ROLE_ADMIN"));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
@@ -74,21 +74,21 @@ public class Issue50Tests {
|
||||
@Test
|
||||
public void authenticateWhenMissingUserThenUsernameNotFoundException() {
|
||||
assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> this.authenticationManager
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("test", "password")));
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("test", "password")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticateWhenInvalidPasswordThenBadCredentialsException() {
|
||||
this.userRepo.save(User.withUsernameAndPassword("test", "password"));
|
||||
assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> this.authenticationManager
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("test", "invalid")));
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("test", "invalid")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticateWhenValidUserThenAuthenticates() {
|
||||
this.userRepo.save(User.withUsernameAndPassword("test", "password"));
|
||||
Authentication result = this.authenticationManager
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("test", "password"));
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("test", "password"));
|
||||
assertThat(result.getName()).isEqualTo("test");
|
||||
}
|
||||
|
||||
@@ -97,7 +97,7 @@ public class Issue50Tests {
|
||||
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("test", null, "ROLE_USER"));
|
||||
this.userRepo.save(User.withUsernameAndPassword("denied", "password"));
|
||||
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.authenticationManager
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("test", "password")));
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("test", "password")));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -59,10 +59,10 @@ public class EnableAuthorizationManagerReactiveMethodSecurityTests {
|
||||
TestPublisher<String> result = TestPublisher.create();
|
||||
|
||||
Context withAdmin = ReactiveSecurityContextHolder
|
||||
.withAuthentication(new TestingAuthenticationToken("admin", "password", "ROLE_USER", "ROLE_ADMIN"));
|
||||
.withAuthentication(new TestingAuthenticationToken("admin", "password", "ROLE_USER", "ROLE_ADMIN"));
|
||||
|
||||
Context withUser = ReactiveSecurityContextHolder
|
||||
.withAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
|
||||
.withAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
|
||||
|
||||
@AfterEach
|
||||
public void cleanup() {
|
||||
@@ -77,10 +77,10 @@ public class EnableAuthorizationManagerReactiveMethodSecurityTests {
|
||||
@Test
|
||||
public void notPublisherPreAuthorizeFindByIdThenThrowsIllegalStateException() {
|
||||
assertThatIllegalStateException().isThrownBy(() -> this.messageService.notPublisherPreAuthorizeFindById(1L))
|
||||
.withMessage("The returnType class java.lang.String on public abstract java.lang.String "
|
||||
+ "org.springframework.security.config.annotation.method.configuration.ReactiveMessageService"
|
||||
+ ".notPublisherPreAuthorizeFindById(long) must return an instance of org.reactivestreams"
|
||||
+ ".Publisher (for example, a Mono or Flux) in order to support Reactor Context");
|
||||
.withMessage("The returnType class java.lang.String on public abstract java.lang.String "
|
||||
+ "org.springframework.security.config.annotation.method.configuration.ReactiveMessageService"
|
||||
+ ".notPublisherPreAuthorizeFindById(long) must return an instance of org.reactivestreams"
|
||||
+ ".Publisher (for example, a Mono or Flux) in order to support Reactor Context");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -153,7 +153,7 @@ public class EnableAuthorizationManagerReactiveMethodSecurityTests {
|
||||
public void monoPreAuthorizeBeanReactiveExpressionWhenGrantedThenSuccess() {
|
||||
given(this.delegate.monoPreAuthorizeBeanFindByIdReactiveExpression(2L)).willReturn(Mono.just("result"));
|
||||
Mono<String> findById = this.messageService.monoPreAuthorizeBeanFindByIdReactiveExpression(2L)
|
||||
.contextWrite(this.withAdmin);
|
||||
.contextWrite(this.withAdmin);
|
||||
StepVerifier.create(findById).expectNext("result").verifyComplete();
|
||||
}
|
||||
|
||||
@@ -176,7 +176,7 @@ public class EnableAuthorizationManagerReactiveMethodSecurityTests {
|
||||
public void monoPreAuthorizeBeanReactiveExpressionWhenNotAuthorizedThenDenied() {
|
||||
given(this.delegate.monoPreAuthorizeBeanFindByIdReactiveExpression(1L)).willReturn(Mono.from(this.result));
|
||||
Mono<String> findById = this.messageService.monoPreAuthorizeBeanFindByIdReactiveExpression(1L)
|
||||
.contextWrite(this.withUser);
|
||||
.contextWrite(this.withUser);
|
||||
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
|
||||
this.result.assertNoSubscribers();
|
||||
}
|
||||
@@ -321,29 +321,29 @@ public class EnableAuthorizationManagerReactiveMethodSecurityTests {
|
||||
@Test
|
||||
public void fluxManyAnnotationsWhenMeetsConditionsThenReturnsFilteredFlux() {
|
||||
Flux<String> flux = this.messageService.fluxManyAnnotations(Flux.just("harold", "jonathan", "pete", "bo"))
|
||||
.contextWrite(this.withAdmin);
|
||||
.contextWrite(this.withAdmin);
|
||||
StepVerifier.create(flux).expectNext("harold", "jonathan").verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void fluxManyAnnotationsWhenUserThenFails() {
|
||||
Flux<String> flux = this.messageService.fluxManyAnnotations(Flux.just("harold", "jonathan", "pete", "bo"))
|
||||
.contextWrite(this.withUser);
|
||||
.contextWrite(this.withUser);
|
||||
StepVerifier.create(flux).expectError(AccessDeniedException.class).verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void fluxManyAnnotationsWhenNameNotAllowedThenFails() {
|
||||
Flux<String> flux = this.messageService
|
||||
.fluxManyAnnotations(Flux.just("harold", "jonathan", "michael", "pete", "bo"))
|
||||
.contextWrite(this.withAdmin);
|
||||
.fluxManyAnnotations(Flux.just("harold", "jonathan", "michael", "pete", "bo"))
|
||||
.contextWrite(this.withAdmin);
|
||||
StepVerifier.create(flux).expectNext("harold", "jonathan").expectError(AccessDeniedException.class).verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void fluxPostFilterWhenFilteringThenWorks() {
|
||||
Flux<String> flux = this.messageService.fluxPostFilter(Flux.just("harold", "jonathan", "michael", "pete", "bo"))
|
||||
.contextWrite(this.withAdmin);
|
||||
.contextWrite(this.withAdmin);
|
||||
StepVerifier.create(flux).expectNext("harold", "jonathan", "michael").verifyComplete();
|
||||
}
|
||||
|
||||
@@ -365,7 +365,7 @@ public class EnableAuthorizationManagerReactiveMethodSecurityTests {
|
||||
public void publisherPreAuthorizeHasRoleWhenGrantedThenSuccess() {
|
||||
given(this.delegate.publisherPreAuthorizeHasRoleFindById(1L)).willReturn(publisherJust("result"));
|
||||
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeHasRoleFindById(1L))
|
||||
.contextWrite(this.withAdmin);
|
||||
.contextWrite(this.withAdmin);
|
||||
StepVerifier.create(findById).consumeNextWith((s) -> assertThat(s).isEqualTo("result")).verifyComplete();
|
||||
}
|
||||
|
||||
@@ -381,7 +381,7 @@ public class EnableAuthorizationManagerReactiveMethodSecurityTests {
|
||||
public void publisherPreAuthorizeHasRoleWhenNotAuthorizedThenDenied() {
|
||||
given(this.delegate.publisherPreAuthorizeHasRoleFindById(1L)).willReturn(this.result);
|
||||
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeHasRoleFindById(1L))
|
||||
.contextWrite(this.withUser);
|
||||
.contextWrite(this.withUser);
|
||||
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
|
||||
this.result.assertNoSubscribers();
|
||||
}
|
||||
@@ -390,7 +390,7 @@ public class EnableAuthorizationManagerReactiveMethodSecurityTests {
|
||||
public void publisherPreAuthorizeBeanWhenGrantedThenSuccess() {
|
||||
given(this.delegate.publisherPreAuthorizeBeanFindById(2L)).willReturn(publisherJust("result"));
|
||||
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeBeanFindById(2L))
|
||||
.contextWrite(this.withAdmin);
|
||||
.contextWrite(this.withAdmin);
|
||||
StepVerifier.create(findById).expectNext("result").verifyComplete();
|
||||
}
|
||||
|
||||
@@ -413,7 +413,7 @@ public class EnableAuthorizationManagerReactiveMethodSecurityTests {
|
||||
public void publisherPreAuthorizeBeanWhenNotAuthorizedThenDenied() {
|
||||
given(this.delegate.publisherPreAuthorizeBeanFindById(1L)).willReturn(this.result);
|
||||
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeBeanFindById(1L))
|
||||
.contextWrite(this.withUser);
|
||||
.contextWrite(this.withUser);
|
||||
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
|
||||
this.result.assertNoSubscribers();
|
||||
}
|
||||
@@ -422,7 +422,7 @@ public class EnableAuthorizationManagerReactiveMethodSecurityTests {
|
||||
public void publisherPostAuthorizeWhenAuthorizedThenSuccess() {
|
||||
given(this.delegate.publisherPostAuthorizeFindById(1L)).willReturn(publisherJust("user"));
|
||||
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeFindById(1L))
|
||||
.contextWrite(this.withUser);
|
||||
.contextWrite(this.withUser);
|
||||
StepVerifier.create(findById).expectNext("user").verifyComplete();
|
||||
}
|
||||
|
||||
@@ -430,7 +430,7 @@ public class EnableAuthorizationManagerReactiveMethodSecurityTests {
|
||||
public void publisherPostAuthorizeWhenNotAuthorizedThenDenied() {
|
||||
given(this.delegate.publisherPostAuthorizeBeanFindById(1L)).willReturn(publisherJust("not-authorized"));
|
||||
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeBeanFindById(1L))
|
||||
.contextWrite(this.withUser);
|
||||
.contextWrite(this.withUser);
|
||||
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
|
||||
}
|
||||
|
||||
@@ -438,7 +438,7 @@ public class EnableAuthorizationManagerReactiveMethodSecurityTests {
|
||||
public void publisherPostAuthorizeWhenBeanAndAuthorizedThenSuccess() {
|
||||
given(this.delegate.publisherPostAuthorizeBeanFindById(2L)).willReturn(publisherJust("user"));
|
||||
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeBeanFindById(2L))
|
||||
.contextWrite(this.withUser);
|
||||
.contextWrite(this.withUser);
|
||||
StepVerifier.create(findById).expectNext("user").verifyComplete();
|
||||
}
|
||||
|
||||
@@ -453,7 +453,7 @@ public class EnableAuthorizationManagerReactiveMethodSecurityTests {
|
||||
public void publisherPostAuthorizeWhenBeanAndNotAuthorizedThenDenied() {
|
||||
given(this.delegate.publisherPostAuthorizeBeanFindById(1L)).willReturn(publisherJust("not-authorized"));
|
||||
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeBeanFindById(1L))
|
||||
.contextWrite(this.withUser);
|
||||
.contextWrite(this.withUser);
|
||||
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
|
||||
}
|
||||
|
||||
|
||||
@@ -57,10 +57,10 @@ public class EnableReactiveMethodSecurityTests {
|
||||
TestPublisher<String> result = TestPublisher.create();
|
||||
|
||||
Context withAdmin = ReactiveSecurityContextHolder
|
||||
.withAuthentication(new TestingAuthenticationToken("admin", "password", "ROLE_USER", "ROLE_ADMIN"));
|
||||
.withAuthentication(new TestingAuthenticationToken("admin", "password", "ROLE_USER", "ROLE_ADMIN"));
|
||||
|
||||
Context withUser = ReactiveSecurityContextHolder
|
||||
.withAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
|
||||
.withAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
|
||||
|
||||
@AfterEach
|
||||
public void cleanup() {
|
||||
@@ -75,10 +75,10 @@ public class EnableReactiveMethodSecurityTests {
|
||||
@Test
|
||||
public void notPublisherPreAuthorizeFindByIdThenThrowsIllegalStateException() {
|
||||
assertThatIllegalStateException().isThrownBy(() -> this.messageService.notPublisherPreAuthorizeFindById(1L))
|
||||
.withMessage("The returnType class java.lang.String on public abstract java.lang.String "
|
||||
+ "org.springframework.security.config.annotation.method.configuration.ReactiveMessageService"
|
||||
+ ".notPublisherPreAuthorizeFindById(long) must return an instance of org.reactivestreams"
|
||||
+ ".Publisher (for example, a Mono or Flux) in order to support Reactor Context");
|
||||
.withMessage("The returnType class java.lang.String on public abstract java.lang.String "
|
||||
+ "org.springframework.security.config.annotation.method.configuration.ReactiveMessageService"
|
||||
+ ".notPublisherPreAuthorizeFindById(long) must return an instance of org.reactivestreams"
|
||||
+ ".Publisher (for example, a Mono or Flux) in order to support Reactor Context");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -302,7 +302,7 @@ public class EnableReactiveMethodSecurityTests {
|
||||
public void publisherPreAuthorizeHasRoleWhenGrantedThenSuccess() {
|
||||
given(this.delegate.publisherPreAuthorizeHasRoleFindById(1L)).willReturn(publisherJust("result"));
|
||||
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeHasRoleFindById(1L))
|
||||
.contextWrite(this.withAdmin);
|
||||
.contextWrite(this.withAdmin);
|
||||
StepVerifier.create(findById).consumeNextWith((s) -> assertThat(s).isEqualTo("result")).verifyComplete();
|
||||
}
|
||||
|
||||
@@ -318,7 +318,7 @@ public class EnableReactiveMethodSecurityTests {
|
||||
public void publisherPreAuthorizeHasRoleWhenNotAuthorizedThenDenied() {
|
||||
given(this.delegate.publisherPreAuthorizeHasRoleFindById(1L)).willReturn(this.result);
|
||||
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeHasRoleFindById(1L))
|
||||
.contextWrite(this.withUser);
|
||||
.contextWrite(this.withUser);
|
||||
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
|
||||
this.result.assertNoSubscribers();
|
||||
}
|
||||
@@ -327,7 +327,7 @@ public class EnableReactiveMethodSecurityTests {
|
||||
public void publisherPreAuthorizeBeanWhenGrantedThenSuccess() {
|
||||
given(this.delegate.publisherPreAuthorizeBeanFindById(2L)).willReturn(publisherJust("result"));
|
||||
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeBeanFindById(2L))
|
||||
.contextWrite(this.withAdmin);
|
||||
.contextWrite(this.withAdmin);
|
||||
StepVerifier.create(findById).expectNext("result").verifyComplete();
|
||||
}
|
||||
|
||||
@@ -350,7 +350,7 @@ public class EnableReactiveMethodSecurityTests {
|
||||
public void publisherPreAuthorizeBeanWhenNotAuthorizedThenDenied() {
|
||||
given(this.delegate.publisherPreAuthorizeBeanFindById(1L)).willReturn(this.result);
|
||||
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeBeanFindById(1L))
|
||||
.contextWrite(this.withUser);
|
||||
.contextWrite(this.withUser);
|
||||
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
|
||||
this.result.assertNoSubscribers();
|
||||
}
|
||||
@@ -359,7 +359,7 @@ public class EnableReactiveMethodSecurityTests {
|
||||
public void publisherPostAuthorizeWhenAuthorizedThenSuccess() {
|
||||
given(this.delegate.publisherPostAuthorizeFindById(1L)).willReturn(publisherJust("user"));
|
||||
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeFindById(1L))
|
||||
.contextWrite(this.withUser);
|
||||
.contextWrite(this.withUser);
|
||||
StepVerifier.create(findById).expectNext("user").verifyComplete();
|
||||
}
|
||||
|
||||
@@ -367,7 +367,7 @@ public class EnableReactiveMethodSecurityTests {
|
||||
public void publisherPostAuthorizeWhenNotAuthorizedThenDenied() {
|
||||
given(this.delegate.publisherPostAuthorizeBeanFindById(1L)).willReturn(publisherJust("not-authorized"));
|
||||
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeBeanFindById(1L))
|
||||
.contextWrite(this.withUser);
|
||||
.contextWrite(this.withUser);
|
||||
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
|
||||
}
|
||||
|
||||
@@ -375,7 +375,7 @@ public class EnableReactiveMethodSecurityTests {
|
||||
public void publisherPostAuthorizeWhenBeanAndAuthorizedThenSuccess() {
|
||||
given(this.delegate.publisherPostAuthorizeBeanFindById(2L)).willReturn(publisherJust("user"));
|
||||
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeBeanFindById(2L))
|
||||
.contextWrite(this.withUser);
|
||||
.contextWrite(this.withUser);
|
||||
StepVerifier.create(findById).expectNext("user").verifyComplete();
|
||||
}
|
||||
|
||||
@@ -390,7 +390,7 @@ public class EnableReactiveMethodSecurityTests {
|
||||
public void publisherPostAuthorizeWhenBeanAndNotAuthorizedThenDenied() {
|
||||
given(this.delegate.publisherPostAuthorizeBeanFindById(1L)).willReturn(publisherJust("not-authorized"));
|
||||
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeBeanFindById(1L))
|
||||
.contextWrite(this.withUser);
|
||||
.contextWrite(this.withUser);
|
||||
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
|
||||
}
|
||||
|
||||
|
||||
@@ -95,7 +95,7 @@ public class GlobalMethodSecurityConfigurationTests {
|
||||
@Test
|
||||
public void configureWhenGlobalMethodSecurityIsMissingMetadataSourceThenException() {
|
||||
assertThatExceptionOfType(UnsatisfiedDependencyException.class)
|
||||
.isThrownBy(() -> this.spring.register(IllegalStateGlobalMethodSecurityConfig.class).autowire());
|
||||
.isThrownBy(() -> this.spring.register(IllegalStateGlobalMethodSecurityConfig.class).autowire());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -107,9 +107,9 @@ public class GlobalMethodSecurityConfigurationTests {
|
||||
public void methodSecurityAuthenticationManagerPublishesEvent() {
|
||||
this.spring.register(InMemoryAuthWithGlobalMethodSecurityConfig.class).autowire();
|
||||
assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> this.authenticationManager
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("foo", "bar")));
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("foo", "bar")));
|
||||
assertThat(this.events.getEvents()).extracting(Object::getClass)
|
||||
.containsOnly((Class) AuthenticationFailureBadCredentialsEvent.class);
|
||||
.containsOnly((Class) AuthenticationFailureBadCredentialsEvent.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -119,7 +119,7 @@ public class GlobalMethodSecurityConfigurationTests {
|
||||
AuthenticationTrustResolver trustResolver = this.spring.getContext().getBean(AuthenticationTrustResolver.class);
|
||||
given(trustResolver.isAnonymous(any())).willReturn(true, false);
|
||||
assertThatExceptionOfType(AccessDeniedException.class)
|
||||
.isThrownBy(() -> this.service.preAuthorizeNotAnonymous());
|
||||
.isThrownBy(() -> this.service.preAuthorizeNotAnonymous());
|
||||
this.service.preAuthorizeNotAnonymous();
|
||||
verify(trustResolver, atLeastOnce()).isAnonymous(any());
|
||||
}
|
||||
@@ -152,7 +152,7 @@ public class GlobalMethodSecurityConfigurationTests {
|
||||
this.service.hasPermission("something");
|
||||
// no exception
|
||||
assertThatExceptionOfType(AccessDeniedException.class)
|
||||
.isThrownBy(() -> this.service.hasPermission("something"));
|
||||
.isThrownBy(() -> this.service.hasPermission("something"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -250,7 +250,7 @@ public class GlobalMethodSecurityConfigurationTests {
|
||||
public void grantedAuthorityDefaultsAutowires() {
|
||||
this.spring.register(CustomGrantedAuthorityConfig.class).autowire();
|
||||
CustomGrantedAuthorityConfig.CustomAuthorityService customService = this.spring.getContext()
|
||||
.getBean(CustomGrantedAuthorityConfig.CustomAuthorityService.class);
|
||||
.getBean(CustomGrantedAuthorityConfig.CustomAuthorityService.class);
|
||||
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize());
|
||||
customService.customPrefixRoleUser();
|
||||
// no exception
|
||||
@@ -261,7 +261,7 @@ public class GlobalMethodSecurityConfigurationTests {
|
||||
public void grantedAuthorityDefaultsWithEmptyRolePrefix() {
|
||||
this.spring.register(EmptyRolePrefixGrantedAuthorityConfig.class).autowire();
|
||||
EmptyRolePrefixGrantedAuthorityConfig.CustomAuthorityService customService = this.spring.getContext()
|
||||
.getBean(EmptyRolePrefixGrantedAuthorityConfig.CustomAuthorityService.class);
|
||||
.getBean(EmptyRolePrefixGrantedAuthorityConfig.CustomAuthorityService.class);
|
||||
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.securedUser());
|
||||
customService.emptyPrefixRoleUser();
|
||||
// no exception
|
||||
@@ -271,9 +271,9 @@ public class GlobalMethodSecurityConfigurationTests {
|
||||
public void methodSecurityInterceptorUsesMetadataSourceBeanWhenProxyingDisabled() {
|
||||
this.spring.register(CustomMetadataSourceBeanProxyEnabledConfig.class).autowire();
|
||||
MethodSecurityInterceptor methodInterceptor = (MethodSecurityInterceptor) this.spring.getContext()
|
||||
.getBean(MethodInterceptor.class);
|
||||
.getBean(MethodInterceptor.class);
|
||||
MethodSecurityMetadataSource methodSecurityMetadataSource = this.spring.getContext()
|
||||
.getBean(MethodSecurityMetadataSource.class);
|
||||
.getBean(MethodSecurityMetadataSource.class);
|
||||
assertThat(methodInterceptor.getSecurityMetadataSource()).isSameAs(methodSecurityMetadataSource);
|
||||
}
|
||||
|
||||
|
||||
@@ -64,7 +64,7 @@ public class NamespaceGlobalMethodSecurityExpressionHandlerTests {
|
||||
this.spring.register(CustomAccessDecisionManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
|
||||
assertThat(this.service.postHasPermission("granted")).isNull();
|
||||
assertThatExceptionOfType(AccessDeniedException.class)
|
||||
.isThrownBy(() -> this.service.postHasPermission("denied"));
|
||||
.isThrownBy(() -> this.service.postHasPermission("denied"));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
@@ -108,7 +108,7 @@ public class NamespaceGlobalMethodSecurityTests {
|
||||
@WithMockUser
|
||||
public void methodSecurityWhenCustomMethodSecurityMetadataSourceThenAuthorizes() {
|
||||
this.spring.register(CustomMethodSecurityMetadataSourceConfig.class, MethodSecurityServiceConfig.class)
|
||||
.autowire();
|
||||
.autowire();
|
||||
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.preAuthorize());
|
||||
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.secured());
|
||||
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.jsr250());
|
||||
@@ -118,9 +118,10 @@ public class NamespaceGlobalMethodSecurityTests {
|
||||
@WithMockUser
|
||||
public void contextRefreshWhenUsingAspectJThenAutowire() throws Exception {
|
||||
this.spring.register(AspectJModeConfig.class, MethodSecurityServiceConfig.class).autowire();
|
||||
assertThat(this.spring.getContext().getBean(
|
||||
Class.forName("org.springframework.security.access.intercept.aspectj.aspect.AnnotationSecurityAspect")))
|
||||
.isNotNull();
|
||||
assertThat(this.spring.getContext()
|
||||
.getBean(Class
|
||||
.forName("org.springframework.security.access.intercept.aspectj.aspect.AnnotationSecurityAspect")))
|
||||
.isNotNull();
|
||||
assertThat(this.spring.getContext().getBean(AspectJMethodSecurityInterceptor.class)).isNotNull();
|
||||
// TODO diagnose why aspectj isn't weaving method security advice around
|
||||
// MethodSecurityServiceImpl
|
||||
@@ -130,9 +131,10 @@ public class NamespaceGlobalMethodSecurityTests {
|
||||
public void contextRefreshWhenUsingAspectJAndCustomGlobalMethodSecurityConfigurationThenAutowire()
|
||||
throws Exception {
|
||||
this.spring.register(AspectJModeExtendsGMSCConfig.class).autowire();
|
||||
assertThat(this.spring.getContext().getBean(
|
||||
Class.forName("org.springframework.security.access.intercept.aspectj.aspect.AnnotationSecurityAspect")))
|
||||
.isNotNull();
|
||||
assertThat(this.spring.getContext()
|
||||
.getBean(Class
|
||||
.forName("org.springframework.security.access.intercept.aspectj.aspect.AnnotationSecurityAspect")))
|
||||
.isNotNull();
|
||||
assertThat(this.spring.getContext().getBean(AspectJMethodSecurityInterceptor.class)).isNotNull();
|
||||
}
|
||||
|
||||
@@ -140,8 +142,9 @@ public class NamespaceGlobalMethodSecurityTests {
|
||||
@WithMockUser
|
||||
public void methodSecurityWhenOrderSpecifiedThenConfigured() {
|
||||
this.spring.register(CustomOrderConfig.class, MethodSecurityServiceConfig.class).autowire();
|
||||
assertThat(this.spring.getContext().getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class)
|
||||
.getOrder()).isEqualTo(-135);
|
||||
assertThat(this.spring.getContext()
|
||||
.getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class)
|
||||
.getOrder()).isEqualTo(-135);
|
||||
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.service.jsr250());
|
||||
}
|
||||
|
||||
@@ -149,8 +152,9 @@ public class NamespaceGlobalMethodSecurityTests {
|
||||
@WithMockUser
|
||||
public void methodSecurityWhenOrderUnspecifiedThenConfiguredToLowestPrecedence() {
|
||||
this.spring.register(DefaultOrderConfig.class, MethodSecurityServiceConfig.class).autowire();
|
||||
assertThat(this.spring.getContext().getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class)
|
||||
.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE);
|
||||
assertThat(this.spring.getContext()
|
||||
.getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class)
|
||||
.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE);
|
||||
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> this.service.jsr250());
|
||||
}
|
||||
|
||||
@@ -158,9 +162,10 @@ public class NamespaceGlobalMethodSecurityTests {
|
||||
@WithMockUser
|
||||
public void methodSecurityWhenOrderUnspecifiedAndCustomGlobalMethodSecurityConfigurationThenConfiguredToLowestPrecedence() {
|
||||
this.spring.register(DefaultOrderExtendsMethodSecurityConfig.class, MethodSecurityServiceConfig.class)
|
||||
.autowire();
|
||||
assertThat(this.spring.getContext().getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class)
|
||||
.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE);
|
||||
.autowire();
|
||||
assertThat(this.spring.getContext()
|
||||
.getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class)
|
||||
.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE);
|
||||
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> this.service.jsr250());
|
||||
}
|
||||
|
||||
@@ -204,7 +209,7 @@ public class NamespaceGlobalMethodSecurityTests {
|
||||
public void methodSecurityWhenCustomRunAsManagerThenRunAsWrapsAuthentication() {
|
||||
this.spring.register(CustomRunAsManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
|
||||
assertThat(this.service.runAs().getAuthorities())
|
||||
.anyMatch((authority) -> "ROLE_RUN_AS_SUPER".equals(authority.getAuthority()));
|
||||
.anyMatch((authority) -> "ROLE_RUN_AS_SUPER".equals(authority.getAuthority()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -221,8 +226,8 @@ public class NamespaceGlobalMethodSecurityTests {
|
||||
@WithMockUser
|
||||
public void methodSecurityWhenMissingEnableAnnotationThenShowsHelpfulError() {
|
||||
assertThatExceptionOfType(Exception.class)
|
||||
.isThrownBy(() -> this.spring.register(ExtendsNoEnableAnntotationConfig.class).autowire())
|
||||
.withStackTraceContaining(EnableGlobalMethodSecurity.class.getName() + " is required");
|
||||
.isThrownBy(() -> this.spring.register(ExtendsNoEnableAnntotationConfig.class).autowire())
|
||||
.withStackTraceContaining(EnableGlobalMethodSecurity.class.getName() + " is required");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -366,7 +371,7 @@ public class NamespaceGlobalMethodSecurityTests {
|
||||
BeanDefinitionBuilder advice = BeanDefinitionBuilder.rootBeanDefinition(ExceptingInterceptor.class);
|
||||
registry.registerBeanDefinition("exceptingInterceptor", advice.getBeanDefinition());
|
||||
BeanDefinitionBuilder advisor = BeanDefinitionBuilder
|
||||
.rootBeanDefinition(MethodSecurityMetadataSourceAdvisor.class);
|
||||
.rootBeanDefinition(MethodSecurityMetadataSourceAdvisor.class);
|
||||
advisor.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
|
||||
advisor.addConstructorArgValue("exceptingInterceptor");
|
||||
advisor.addConstructorArgReference("methodSecurityMetadataSource");
|
||||
|
||||
@@ -100,7 +100,7 @@ public class PrePostMethodSecurityConfigurationTests {
|
||||
public void customMethodSecurityPreAuthorizeAdminWhenRoleUserThenAccessDeniedException() {
|
||||
this.spring.register(CustomMethodSecurityServiceConfig.class).autowire();
|
||||
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.methodSecurityService::preAuthorizeAdmin)
|
||||
.withMessage("Access Denied");
|
||||
.withMessage("Access Denied");
|
||||
}
|
||||
|
||||
@WithMockUser(roles = "ADMIN")
|
||||
@@ -115,7 +115,7 @@ public class PrePostMethodSecurityConfigurationTests {
|
||||
public void preAuthorizeWhenRoleAdminThenAccessDeniedException() {
|
||||
this.spring.register(MethodSecurityServiceConfig.class).autowire();
|
||||
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.methodSecurityService::preAuthorize)
|
||||
.withMessage("Access Denied");
|
||||
.withMessage("Access Denied");
|
||||
}
|
||||
|
||||
@WithAnonymousUser
|
||||
@@ -131,7 +131,8 @@ public class PrePostMethodSecurityConfigurationTests {
|
||||
public void preAuthorizeNotAnonymousWhenRoleAnonymousThenAccessDeniedException() {
|
||||
this.spring.register(MethodSecurityServiceConfig.class).autowire();
|
||||
assertThatExceptionOfType(AccessDeniedException.class)
|
||||
.isThrownBy(this.methodSecurityService::preAuthorizeNotAnonymous).withMessage("Access Denied");
|
||||
.isThrownBy(this.methodSecurityService::preAuthorizeNotAnonymous)
|
||||
.withMessage("Access Denied");
|
||||
}
|
||||
|
||||
@WithMockUser
|
||||
@@ -146,7 +147,7 @@ public class PrePostMethodSecurityConfigurationTests {
|
||||
public void securedWhenRoleUserThenAccessDeniedException() {
|
||||
this.spring.register(MethodSecurityServiceEnabledConfig.class).autowire();
|
||||
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.methodSecurityService::secured)
|
||||
.withMessage("Access Denied");
|
||||
.withMessage("Access Denied");
|
||||
}
|
||||
|
||||
@WithMockUser(roles = "ADMIN")
|
||||
@@ -162,7 +163,7 @@ public class PrePostMethodSecurityConfigurationTests {
|
||||
public void securedUserWhenRoleAdminThenAccessDeniedException() {
|
||||
this.spring.register(MethodSecurityServiceEnabledConfig.class).autowire();
|
||||
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.methodSecurityService::securedUser)
|
||||
.withMessage("Access Denied");
|
||||
.withMessage("Access Denied");
|
||||
SecurityContextHolderStrategy strategy = this.spring.getContext().getBean(SecurityContextHolderStrategy.class);
|
||||
verify(strategy, atLeastOnce()).getContext();
|
||||
}
|
||||
@@ -180,7 +181,7 @@ public class PrePostMethodSecurityConfigurationTests {
|
||||
public void preAuthorizeAdminWhenRoleUserThenAccessDeniedException() {
|
||||
this.spring.register(MethodSecurityServiceConfig.class).autowire();
|
||||
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.methodSecurityService::preAuthorizeAdmin)
|
||||
.withMessage("Access Denied");
|
||||
.withMessage("Access Denied");
|
||||
}
|
||||
|
||||
@WithMockUser(roles = "ADMIN")
|
||||
@@ -211,7 +212,8 @@ public class PrePostMethodSecurityConfigurationTests {
|
||||
public void postHasPermissionWhenParameterIsNotGrantThenAccessDeniedException() {
|
||||
this.spring.register(CustomPermissionEvaluatorConfig.class, MethodSecurityServiceConfig.class).autowire();
|
||||
assertThatExceptionOfType(AccessDeniedException.class)
|
||||
.isThrownBy(() -> this.methodSecurityService.postHasPermission("deny")).withMessage("Access Denied");
|
||||
.isThrownBy(() -> this.methodSecurityService.postHasPermission("deny"))
|
||||
.withMessage("Access Denied");
|
||||
}
|
||||
|
||||
@WithMockUser
|
||||
@@ -227,7 +229,8 @@ public class PrePostMethodSecurityConfigurationTests {
|
||||
public void postAnnotationWhenParameterIsNotGrantThenAccessDeniedException() {
|
||||
this.spring.register(MethodSecurityServiceConfig.class).autowire();
|
||||
assertThatExceptionOfType(AccessDeniedException.class)
|
||||
.isThrownBy(() -> this.methodSecurityService.postAnnotation("deny")).withMessage("Access Denied");
|
||||
.isThrownBy(() -> this.methodSecurityService.postAnnotation("deny"))
|
||||
.withMessage("Access Denied");
|
||||
}
|
||||
|
||||
@WithMockUser
|
||||
@@ -268,7 +271,7 @@ public class PrePostMethodSecurityConfigurationTests {
|
||||
@Test
|
||||
public void securedUserWhenCustomBeforeAdviceConfiguredAndNameBobThenPasses() {
|
||||
this.spring.register(CustomAuthorizationManagerBeforeAdviceConfig.class, MethodSecurityServiceConfig.class)
|
||||
.autowire();
|
||||
.autowire();
|
||||
String result = this.methodSecurityService.securedUser();
|
||||
assertThat(result).isNull();
|
||||
}
|
||||
@@ -277,16 +280,16 @@ public class PrePostMethodSecurityConfigurationTests {
|
||||
@Test
|
||||
public void securedUserWhenCustomBeforeAdviceConfiguredAndNameNotBobThenAccessDeniedException() {
|
||||
this.spring.register(CustomAuthorizationManagerBeforeAdviceConfig.class, MethodSecurityServiceConfig.class)
|
||||
.autowire();
|
||||
.autowire();
|
||||
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.methodSecurityService::securedUser)
|
||||
.withMessage("Access Denied");
|
||||
.withMessage("Access Denied");
|
||||
}
|
||||
|
||||
@WithMockUser("bob")
|
||||
@Test
|
||||
public void securedUserWhenCustomAfterAdviceConfiguredAndNameBobThenGranted() {
|
||||
this.spring.register(CustomAuthorizationManagerAfterAdviceConfig.class, MethodSecurityServiceConfig.class)
|
||||
.autowire();
|
||||
.autowire();
|
||||
String result = this.methodSecurityService.securedUser();
|
||||
assertThat(result).isEqualTo("granted");
|
||||
}
|
||||
@@ -295,9 +298,9 @@ public class PrePostMethodSecurityConfigurationTests {
|
||||
@Test
|
||||
public void securedUserWhenCustomAfterAdviceConfiguredAndNameNotBobThenAccessDeniedException() {
|
||||
this.spring.register(CustomAuthorizationManagerAfterAdviceConfig.class, MethodSecurityServiceConfig.class)
|
||||
.autowire();
|
||||
.autowire();
|
||||
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.methodSecurityService::securedUser)
|
||||
.withMessage("Access Denied for User 'joe'");
|
||||
.withMessage("Access Denied for User 'joe'");
|
||||
}
|
||||
|
||||
@WithMockUser(roles = "ADMIN")
|
||||
@@ -305,7 +308,7 @@ public class PrePostMethodSecurityConfigurationTests {
|
||||
public void jsr250WhenRoleAdminThenAccessDeniedException() {
|
||||
this.spring.register(MethodSecurityServiceEnabledConfig.class).autowire();
|
||||
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.methodSecurityService::jsr250)
|
||||
.withMessage("Access Denied");
|
||||
.withMessage("Access Denied");
|
||||
}
|
||||
|
||||
@WithAnonymousUser
|
||||
@@ -321,7 +324,7 @@ public class PrePostMethodSecurityConfigurationTests {
|
||||
public void rolesAllowedUserWhenRoleAdminThenAccessDeniedException() {
|
||||
this.spring.register(BusinessServiceConfig.class).autowire();
|
||||
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.businessService::rolesAllowedUser)
|
||||
.withMessage("Access Denied");
|
||||
.withMessage("Access Denied");
|
||||
SecurityContextHolderStrategy strategy = this.spring.getContext().getBean(SecurityContextHolderStrategy.class);
|
||||
verify(strategy, atLeastOnce()).getContext();
|
||||
}
|
||||
@@ -351,7 +354,7 @@ public class PrePostMethodSecurityConfigurationTests {
|
||||
List<String> names = Arrays.asList("harold", "jonathan", "pete", "bo");
|
||||
this.spring.register(MethodSecurityServiceEnabledConfig.class).autowire();
|
||||
assertThatExceptionOfType(AccessDeniedException.class)
|
||||
.isThrownBy(() -> this.methodSecurityService.manyAnnotations(new ArrayList<>(names)));
|
||||
.isThrownBy(() -> this.methodSecurityService.manyAnnotations(new ArrayList<>(names)));
|
||||
}
|
||||
|
||||
@WithMockUser
|
||||
@@ -360,7 +363,7 @@ public class PrePostMethodSecurityConfigurationTests {
|
||||
List<String> names = Arrays.asList("harold", "jonathan", "pete");
|
||||
this.spring.register(MethodSecurityServiceEnabledConfig.class).autowire();
|
||||
assertThatExceptionOfType(AccessDeniedException.class)
|
||||
.isThrownBy(() -> this.methodSecurityService.manyAnnotations(new ArrayList<>(names)));
|
||||
.isThrownBy(() -> this.methodSecurityService.manyAnnotations(new ArrayList<>(names)));
|
||||
}
|
||||
|
||||
@WithMockUser(roles = "ADMIN")
|
||||
@@ -369,7 +372,7 @@ public class PrePostMethodSecurityConfigurationTests {
|
||||
List<String> names = Arrays.asList("harold", "jonathan", "pete", "bo");
|
||||
this.spring.register(MethodSecurityServiceEnabledConfig.class).autowire();
|
||||
assertThatExceptionOfType(AccessDeniedException.class)
|
||||
.isThrownBy(() -> this.methodSecurityService.manyAnnotations(new ArrayList<>(names)));
|
||||
.isThrownBy(() -> this.methodSecurityService.manyAnnotations(new ArrayList<>(names)));
|
||||
}
|
||||
|
||||
// gh-3183
|
||||
@@ -377,7 +380,7 @@ public class PrePostMethodSecurityConfigurationTests {
|
||||
public void repeatedAnnotationsWhenPresentThenFails() {
|
||||
this.spring.register(MethodSecurityServiceConfig.class).autowire();
|
||||
assertThatExceptionOfType(AnnotationConfigurationException.class)
|
||||
.isThrownBy(() -> this.methodSecurityService.repeatedAnnotations());
|
||||
.isThrownBy(() -> this.methodSecurityService.repeatedAnnotations());
|
||||
}
|
||||
|
||||
// gh-3183
|
||||
@@ -385,7 +388,7 @@ public class PrePostMethodSecurityConfigurationTests {
|
||||
public void repeatedJsr250AnnotationsWhenPresentThenFails() {
|
||||
this.spring.register(Jsr250Config.class).autowire();
|
||||
assertThatExceptionOfType(AnnotationConfigurationException.class)
|
||||
.isThrownBy(() -> this.businessService.repeatedAnnotations());
|
||||
.isThrownBy(() -> this.businessService.repeatedAnnotations());
|
||||
}
|
||||
|
||||
// gh-3183
|
||||
@@ -393,7 +396,7 @@ public class PrePostMethodSecurityConfigurationTests {
|
||||
public void repeatedSecuredAnnotationsWhenPresentThenFails() {
|
||||
this.spring.register(SecuredConfig.class).autowire();
|
||||
assertThatExceptionOfType(AnnotationConfigurationException.class)
|
||||
.isThrownBy(() -> this.businessService.repeatedAnnotations());
|
||||
.isThrownBy(() -> this.businessService.repeatedAnnotations());
|
||||
}
|
||||
|
||||
@WithMockUser
|
||||
@@ -401,7 +404,7 @@ public class PrePostMethodSecurityConfigurationTests {
|
||||
public void preAuthorizeWhenAuthorizationEventPublisherThenUses() {
|
||||
this.spring.register(MethodSecurityServiceConfig.class, AuthorizationEventPublisherConfig.class).autowire();
|
||||
assertThatExceptionOfType(AccessDeniedException.class)
|
||||
.isThrownBy(() -> this.methodSecurityService.preAuthorize());
|
||||
.isThrownBy(() -> this.methodSecurityService.preAuthorize());
|
||||
AuthorizationEventPublisher publisher = this.spring.getContext().getBean(AuthorizationEventPublisher.class);
|
||||
verify(publisher).publishAuthorizationEvent(any(Supplier.class), any(MethodInvocation.class),
|
||||
any(AuthorizationDecision.class));
|
||||
@@ -440,7 +443,8 @@ public class PrePostMethodSecurityConfigurationTests {
|
||||
@Test
|
||||
public void configureWhenBeanOverridingDisallowedThenWorks() {
|
||||
this.spring.register(MethodSecurityServiceConfig.class, BusinessServiceConfig.class)
|
||||
.postProcessor(disallowBeanOverriding()).autowire();
|
||||
.postProcessor(disallowBeanOverriding())
|
||||
.autowire();
|
||||
}
|
||||
|
||||
private static Consumer<ConfigurableWebApplicationContext> disallowBeanOverriding() {
|
||||
|
||||
@@ -56,7 +56,7 @@ public class SampleEnableGlobalMethodSecurityTests {
|
||||
@BeforeEach
|
||||
public void setup() {
|
||||
SecurityContextHolder.getContext()
|
||||
.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
|
||||
.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -65,7 +65,7 @@ public class SampleEnableGlobalMethodSecurityTests {
|
||||
assertThat(this.methodSecurityService.secured()).isNull();
|
||||
assertThat(this.methodSecurityService.jsr250()).isNull();
|
||||
assertThatExceptionOfType(AccessDeniedException.class)
|
||||
.isThrownBy(() -> this.methodSecurityService.preAuthorize());
|
||||
.isThrownBy(() -> this.methodSecurityService.preAuthorize());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -73,7 +73,7 @@ public class SampleEnableGlobalMethodSecurityTests {
|
||||
this.spring.register(CustomPermissionEvaluatorWebSecurityConfig.class).autowire();
|
||||
assertThat(this.methodSecurityService.hasPermission("allowed")).isNull();
|
||||
assertThatExceptionOfType(AccessDeniedException.class)
|
||||
.isThrownBy(() -> this.methodSecurityService.hasPermission("denied"));
|
||||
.isThrownBy(() -> this.methodSecurityService.hasPermission("denied"));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
@@ -130,7 +130,7 @@ public class AbstractConfiguredSecurityBuilderTests {
|
||||
builder.apply(configurer1);
|
||||
builder.apply(configurer2);
|
||||
List<DelegateSecurityConfigurer> removedConfigurers = builder
|
||||
.removeConfigurers(DelegateSecurityConfigurer.class);
|
||||
.removeConfigurers(DelegateSecurityConfigurer.class);
|
||||
assertThat(removedConfigurers).hasSize(2);
|
||||
assertThat(removedConfigurers).containsExactly(configurer1, configurer2);
|
||||
assertThat(builder.getConfigurers(DelegateSecurityConfigurer.class)).isEmpty();
|
||||
|
||||
@@ -43,31 +43,31 @@ public class AbstractRequestMatcherRegistryAnyMatcherTests {
|
||||
@Test
|
||||
public void antMatchersCanNotWorkAfterAnyRequest() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> loadConfig(AntMatchersAfterAnyRequestConfig.class));
|
||||
.isThrownBy(() -> loadConfig(AntMatchersAfterAnyRequestConfig.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void mvcMatchersCanNotWorkAfterAnyRequest() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> loadConfig(MvcMatchersAfterAnyRequestConfig.class));
|
||||
.isThrownBy(() -> loadConfig(MvcMatchersAfterAnyRequestConfig.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void regexMatchersCanNotWorkAfterAnyRequest() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> loadConfig(RegexMatchersAfterAnyRequestConfig.class));
|
||||
.isThrownBy(() -> loadConfig(RegexMatchersAfterAnyRequestConfig.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void anyRequestCanNotWorkAfterItself() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> loadConfig(AnyRequestAfterItselfConfig.class));
|
||||
.isThrownBy(() -> loadConfig(AnyRequestAfterItselfConfig.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestMatchersCanNotWorkAfterAnyRequest() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> loadConfig(RequestMatchersAfterAnyRequestConfig.class));
|
||||
.isThrownBy(() -> loadConfig(RequestMatchersAfterAnyRequestConfig.class));
|
||||
}
|
||||
|
||||
private void loadConfig(Class<?>... configs) {
|
||||
|
||||
@@ -73,7 +73,7 @@ public class AbstractRequestMatcherRegistryTests {
|
||||
@Test
|
||||
public void regexMatchersWhenHttpMethodAndPatternParamsThenReturnRegexRequestMatcherType() {
|
||||
List<RequestMatcher> requestMatchers = this.matcherRegistry
|
||||
.requestMatchers(new RegexRequestMatcher("/a.*", HttpMethod.GET.name()));
|
||||
.requestMatchers(new RegexRequestMatcher("/a.*", HttpMethod.GET.name()));
|
||||
assertThat(requestMatchers).isNotEmpty();
|
||||
assertThat(requestMatchers).hasSize(1);
|
||||
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(RegexRequestMatcher.class);
|
||||
@@ -82,7 +82,7 @@ public class AbstractRequestMatcherRegistryTests {
|
||||
@Test
|
||||
public void regexMatchersWhenPatternParamThenReturnRegexRequestMatcherType() {
|
||||
List<RequestMatcher> requestMatchers = this.matcherRegistry
|
||||
.requestMatchers(new RegexRequestMatcher("/a.*", null));
|
||||
.requestMatchers(new RegexRequestMatcher("/a.*", null));
|
||||
assertThat(requestMatchers).isNotEmpty();
|
||||
assertThat(requestMatchers).hasSize(1);
|
||||
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(RegexRequestMatcher.class);
|
||||
@@ -91,7 +91,7 @@ public class AbstractRequestMatcherRegistryTests {
|
||||
@Test
|
||||
public void antMatchersWhenHttpMethodAndPatternParamsThenReturnAntPathRequestMatcherType() {
|
||||
List<RequestMatcher> requestMatchers = this.matcherRegistry
|
||||
.requestMatchers(new AntPathRequestMatcher("/a.*", HttpMethod.GET.name()));
|
||||
.requestMatchers(new AntPathRequestMatcher("/a.*", HttpMethod.GET.name()));
|
||||
assertThat(requestMatchers).isNotEmpty();
|
||||
assertThat(requestMatchers).hasSize(1);
|
||||
assertThat(requestMatchers.get(0)).isExactlyInstanceOf(AntPathRequestMatcher.class);
|
||||
@@ -150,8 +150,9 @@ public class AbstractRequestMatcherRegistryTests {
|
||||
public void requestMatchersWhenMvcPresentInClassPathAndMvcIntrospectorBeanNotAvailableThenException() {
|
||||
mockMvcIntrospector(false);
|
||||
assertThatExceptionOfType(NoSuchBeanDefinitionException.class)
|
||||
.isThrownBy(() -> this.matcherRegistry.requestMatchers("/path")).withMessageContaining(
|
||||
"Please ensure Spring Security & Spring MVC are configured in a shared ApplicationContext");
|
||||
.isThrownBy(() -> this.matcherRegistry.requestMatchers("/path"))
|
||||
.withMessageContaining(
|
||||
"Please ensure Spring Security & Spring MVC are configured in a shared ApplicationContext");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -177,7 +178,7 @@ public class AbstractRequestMatcherRegistryTests {
|
||||
servletContext.addServlet("dispatcherServlet", DispatcherServlet.class).addMapping("/");
|
||||
servletContext.addServlet("servletTwo", Servlet.class).addMapping("/servlet/**");
|
||||
assertThatExceptionOfType(IllegalArgumentException.class)
|
||||
.isThrownBy(() -> this.matcherRegistry.requestMatchers("/**"));
|
||||
.isThrownBy(() -> this.matcherRegistry.requestMatchers("/**"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -68,10 +68,10 @@ public class HttpConfigurationTests {
|
||||
@Test
|
||||
public void configureWhenAddFilterUnregisteredThenThrowsBeanCreationException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(UnregisteredFilterConfig.class).autowire())
|
||||
.withMessageContaining("The Filter class " + UnregisteredFilter.class.getName()
|
||||
+ " does not have a registered order and cannot be added without a specified order."
|
||||
+ " Consider using addFilterBefore or addFilterAfter instead.");
|
||||
.isThrownBy(() -> this.spring.register(UnregisteredFilterConfig.class).autowire())
|
||||
.withMessageContaining("The Filter class " + UnregisteredFilter.class.getName()
|
||||
+ " does not have a registered order and cannot be added without a specified order."
|
||||
+ " Consider using addFilterBefore or addFilterAfter instead.");
|
||||
}
|
||||
|
||||
// https://github.com/spring-projects/spring-security-javaconfig/issues/104
|
||||
|
||||
@@ -53,7 +53,7 @@ public class HttpSecurityAuthenticationManagerTests {
|
||||
this.spring.register(AuthenticationManagerConfig.class).autowire();
|
||||
|
||||
given(AuthenticationManagerConfig.AUTHENTICATION_MANAGER.authenticate(any()))
|
||||
.willReturn(new TestingAuthenticationToken("user", "test", "ROLE_USER"));
|
||||
.willReturn(new TestingAuthenticationToken("user", "test", "ROLE_USER"));
|
||||
|
||||
this.mvc.perform(get("/").with(httpBasic("user", "test")));
|
||||
|
||||
@@ -66,7 +66,7 @@ public class HttpSecurityAuthenticationManagerTests {
|
||||
this.spring.register(AuthenticationManagerBuilderConfig.class).autowire();
|
||||
|
||||
given(AuthenticationManagerBuilderConfig.AUTHENTICATION_MANAGER.authenticate(any()))
|
||||
.willReturn(new TestingAuthenticationToken("user", "test", "ROLE_USER"));
|
||||
.willReturn(new TestingAuthenticationToken("user", "test", "ROLE_USER"));
|
||||
|
||||
this.mvc.perform(get("/").with(httpBasic("user", "test")));
|
||||
|
||||
|
||||
@@ -55,17 +55,17 @@ public class HttpSecurityDeferAddFilterTests {
|
||||
@Test
|
||||
public void addFilterAfterFilterNotRegisteredYetThenThrowIllegalArgument() {
|
||||
assertThatExceptionOfType(UnsatisfiedDependencyException.class)
|
||||
.isThrownBy(
|
||||
() -> this.spring.register(MyOtherFilterAfterMyFilterNotRegisteredYetConfig.class).autowire())
|
||||
.havingRootCause().isInstanceOf(IllegalArgumentException.class);
|
||||
.isThrownBy(() -> this.spring.register(MyOtherFilterAfterMyFilterNotRegisteredYetConfig.class).autowire())
|
||||
.havingRootCause()
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addFilterBeforeFilterNotRegisteredYetThenThrowIllegalArgument() {
|
||||
assertThatExceptionOfType(UnsatisfiedDependencyException.class)
|
||||
.isThrownBy(
|
||||
() -> this.spring.register(MyOtherFilterBeforeMyFilterNotRegisteredYetConfig.class).autowire())
|
||||
.havingRootCause().isInstanceOf(IllegalArgumentException.class);
|
||||
.isThrownBy(() -> this.spring.register(MyOtherFilterBeforeMyFilterNotRegisteredYetConfig.class).autowire())
|
||||
.havingRootCause()
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -134,8 +134,10 @@ public class HttpSecurityDeferAddFilterTests {
|
||||
|
||||
private ListAssert<Class<?>> assertThatFilters() {
|
||||
FilterChainProxy filterChain = this.spring.getContext().getBean(FilterChainProxy.class);
|
||||
List<Class<?>> filters = filterChain.getFilters("/").stream().map(Object::getClass)
|
||||
.collect(Collectors.toList());
|
||||
List<Class<?>> filters = filterChain.getFilters("/")
|
||||
.stream()
|
||||
.map(Object::getClass)
|
||||
.collect(Collectors.toList());
|
||||
return assertThat(filters);
|
||||
}
|
||||
|
||||
|
||||
@@ -100,7 +100,7 @@ public class NamespaceHttpTests {
|
||||
AccessDecisionManagerRefConfig.ACCESS_DECISION_MANAGER = mock(AccessDecisionManager.class);
|
||||
given(AccessDecisionManagerRefConfig.ACCESS_DECISION_MANAGER.supports(FilterInvocation.class)).willReturn(true);
|
||||
given(AccessDecisionManagerRefConfig.ACCESS_DECISION_MANAGER.supports(any(ConfigAttribute.class)))
|
||||
.willReturn(true);
|
||||
.willReturn(true);
|
||||
this.spring.register(AccessDecisionManagerRefConfig.class).autowire();
|
||||
this.mockMvc.perform(get("/"));
|
||||
verify(AccessDecisionManagerRefConfig.ACCESS_DECISION_MANAGER, times(1)).decide(any(Authentication.class),
|
||||
@@ -110,8 +110,9 @@ public class NamespaceHttpTests {
|
||||
@Test // http@access-denied-page
|
||||
public void configureWhenAccessDeniedPageSetAndRequestForbiddenThenForwardedToAccessDeniedPage() throws Exception {
|
||||
this.spring.register(AccessDeniedPageConfig.class).autowire();
|
||||
this.mockMvc.perform(get("/admin").with(user(PasswordEncodedUser.user()))).andExpect(status().isForbidden())
|
||||
.andExpect(forwardedUrl("/AccessDeniedPage"));
|
||||
this.mockMvc.perform(get("/admin").with(user(PasswordEncodedUser.user())))
|
||||
.andExpect(status().isForbidden())
|
||||
.andExpect(forwardedUrl("/AccessDeniedPage"));
|
||||
}
|
||||
|
||||
@Test // http@authentication-manager-ref
|
||||
@@ -198,7 +199,7 @@ public class NamespaceHttpTests {
|
||||
FilterChainProxy filterChainProxy = this.spring.getContext().getBean(FilterChainProxy.class);
|
||||
assertThat(filterChainProxy.getFilterChains().get(0)).isInstanceOf(DefaultSecurityFilterChain.class);
|
||||
DefaultSecurityFilterChain securityFilterChain = (DefaultSecurityFilterChain) filterChainProxy.getFilterChains()
|
||||
.get(0);
|
||||
.get(0);
|
||||
assertThat(securityFilterChain.getRequestMatcher()).isInstanceOf(AntPathRequestMatcher.class);
|
||||
}
|
||||
|
||||
@@ -208,7 +209,7 @@ public class NamespaceHttpTests {
|
||||
FilterChainProxy filterChainProxy = this.spring.getContext().getBean(FilterChainProxy.class);
|
||||
assertThat(filterChainProxy.getFilterChains().get(0)).isInstanceOf(DefaultSecurityFilterChain.class);
|
||||
DefaultSecurityFilterChain securityFilterChain = (DefaultSecurityFilterChain) filterChainProxy.getFilterChains()
|
||||
.get(0);
|
||||
.get(0);
|
||||
assertThat(securityFilterChain.getRequestMatcher()).isInstanceOf(RegexRequestMatcher.class);
|
||||
}
|
||||
|
||||
@@ -218,9 +219,9 @@ public class NamespaceHttpTests {
|
||||
FilterChainProxy filterChainProxy = this.spring.getContext().getBean(FilterChainProxy.class);
|
||||
assertThat(filterChainProxy.getFilterChains().get(0)).isInstanceOf(DefaultSecurityFilterChain.class);
|
||||
DefaultSecurityFilterChain securityFilterChain = (DefaultSecurityFilterChain) filterChainProxy.getFilterChains()
|
||||
.get(0);
|
||||
.get(0);
|
||||
assertThat(securityFilterChain.getRequestMatcher())
|
||||
.isInstanceOf(RequestMatcherRefConfig.MyRequestMatcher.class);
|
||||
.isInstanceOf(RequestMatcherRefConfig.MyRequestMatcher.class);
|
||||
}
|
||||
|
||||
@Test // http@security=none
|
||||
@@ -229,16 +230,16 @@ public class NamespaceHttpTests {
|
||||
FilterChainProxy filterChainProxy = this.spring.getContext().getBean(FilterChainProxy.class);
|
||||
assertThat(filterChainProxy.getFilterChains().get(0)).isInstanceOf(DefaultSecurityFilterChain.class);
|
||||
DefaultSecurityFilterChain securityFilterChain = (DefaultSecurityFilterChain) filterChainProxy.getFilterChains()
|
||||
.get(0);
|
||||
.get(0);
|
||||
assertThat(securityFilterChain.getRequestMatcher()).isInstanceOf(AntPathRequestMatcher.class);
|
||||
assertThat(((AntPathRequestMatcher) securityFilterChain.getRequestMatcher()).getPattern())
|
||||
.isEqualTo("/resources/**");
|
||||
.isEqualTo("/resources/**");
|
||||
assertThat(securityFilterChain.getFilters()).isEmpty();
|
||||
assertThat(filterChainProxy.getFilterChains().get(1)).isInstanceOf(DefaultSecurityFilterChain.class);
|
||||
securityFilterChain = (DefaultSecurityFilterChain) filterChainProxy.getFilterChains().get(1);
|
||||
assertThat(securityFilterChain.getRequestMatcher()).isInstanceOf(AntPathRequestMatcher.class);
|
||||
assertThat(((AntPathRequestMatcher) securityFilterChain.getRequestMatcher()).getPattern())
|
||||
.isEqualTo("/public/**");
|
||||
.isEqualTo("/public/**");
|
||||
assertThat(securityFilterChain.getFilters()).isEmpty();
|
||||
}
|
||||
|
||||
@@ -255,7 +256,7 @@ public class NamespaceHttpTests {
|
||||
this.spring.register(ServletApiProvisionConfig.class, MainController.class).autowire();
|
||||
this.mockMvc.perform(get("/"));
|
||||
assertThat(MainController.HTTP_SERVLET_REQUEST_TYPE)
|
||||
.isNotInstanceOf(SecurityContextHolderAwareRequestWrapper.class);
|
||||
.isNotInstanceOf(SecurityContextHolderAwareRequestWrapper.class);
|
||||
}
|
||||
|
||||
@Test // http@servlet-api-provision defaults to true
|
||||
@@ -263,7 +264,7 @@ public class NamespaceHttpTests {
|
||||
this.spring.register(ServletApiProvisionDefaultsConfig.class, MainController.class).autowire();
|
||||
this.mockMvc.perform(get("/"));
|
||||
assertThat(SecurityContextHolderAwareRequestWrapper.class)
|
||||
.isAssignableFrom(MainController.HTTP_SERVLET_REQUEST_TYPE);
|
||||
.isAssignableFrom(MainController.HTTP_SERVLET_REQUEST_TYPE);
|
||||
}
|
||||
|
||||
@Test // http@use-expressions=true
|
||||
@@ -271,7 +272,7 @@ public class NamespaceHttpTests {
|
||||
this.spring.register(UseExpressionsConfig.class).autowire();
|
||||
UseExpressionsConfig config = this.spring.getContext().getBean(UseExpressionsConfig.class);
|
||||
assertThat(ExpressionBasedFilterInvocationSecurityMetadataSource.class)
|
||||
.isAssignableFrom(config.filterInvocationSecurityMetadataSourceType);
|
||||
.isAssignableFrom(config.filterInvocationSecurityMetadataSourceType);
|
||||
}
|
||||
|
||||
@Test // http@use-expressions=false
|
||||
@@ -279,7 +280,7 @@ public class NamespaceHttpTests {
|
||||
this.spring.register(DisableUseExpressionsConfig.class).autowire();
|
||||
DisableUseExpressionsConfig config = this.spring.getContext().getBean(DisableUseExpressionsConfig.class);
|
||||
assertThat(DefaultFilterInvocationSecurityMetadataSource.class)
|
||||
.isAssignableFrom(config.filterInvocationSecurityMetadataSourceType);
|
||||
.isAssignableFrom(config.filterInvocationSecurityMetadataSourceType);
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@@ -542,8 +543,8 @@ public class NamespaceHttpTests {
|
||||
|
||||
@Bean
|
||||
WebSecurityCustomizer webSecurityCustomizer() {
|
||||
return (web) -> web.ignoring().requestMatchers(new AntPathRequestMatcher("/resources/**"),
|
||||
new AntPathRequestMatcher("/public/**"));
|
||||
return (web) -> web.ignoring()
|
||||
.requestMatchers(new AntPathRequestMatcher("/resources/**"), new AntPathRequestMatcher("/public/**"));
|
||||
}
|
||||
|
||||
@Bean
|
||||
@@ -654,9 +655,10 @@ public class NamespaceHttpTests {
|
||||
WebSecurityCustomizer webSecurityCustomizer() {
|
||||
return (web) -> web.postBuildAction(() -> {
|
||||
FilterSecurityInterceptor securityInterceptor = this.httpSecurity
|
||||
.getSharedObject(FilterSecurityInterceptor.class);
|
||||
.getSharedObject(FilterSecurityInterceptor.class);
|
||||
UseExpressionsConfig.this.filterInvocationSecurityMetadataSourceType = securityInterceptor
|
||||
.getSecurityMetadataSource().getClass();
|
||||
.getSecurityMetadataSource()
|
||||
.getClass();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -689,9 +691,10 @@ public class NamespaceHttpTests {
|
||||
WebSecurityCustomizer webSecurityCustomizer() {
|
||||
return (web) -> web.postBuildAction(() -> {
|
||||
FilterSecurityInterceptor securityInterceptor = this.httpSecurity
|
||||
.getSharedObject(FilterSecurityInterceptor.class);
|
||||
.getSharedObject(FilterSecurityInterceptor.class);
|
||||
DisableUseExpressionsConfig.this.filterInvocationSecurityMetadataSourceType = securityInterceptor
|
||||
.getSecurityMetadataSource().getClass();
|
||||
.getSecurityMetadataSource()
|
||||
.getClass();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -30,10 +30,15 @@ public final class TestHttpSecurity {
|
||||
public static void disableDefaults(HttpSecurity http) throws Exception {
|
||||
List<Object> orderedFilters = (List<Object>) ReflectionTestUtils.getField(http, "filters");
|
||||
orderedFilters.clear();
|
||||
http.csrf((c) -> c.disable()).exceptionHandling((c) -> c.disable()).headers((c) -> c.disable())
|
||||
.sessionManagement((c) -> c.disable()).securityContext((c) -> c.disable())
|
||||
.requestCache((c) -> c.disable()).anonymous((c) -> c.disable()).servletApi((c) -> c.disable())
|
||||
.removeConfigurer(DefaultLoginPageConfigurer.class);
|
||||
http.csrf((c) -> c.disable())
|
||||
.exceptionHandling((c) -> c.disable())
|
||||
.headers((c) -> c.disable())
|
||||
.sessionManagement((c) -> c.disable())
|
||||
.securityContext((c) -> c.disable())
|
||||
.requestCache((c) -> c.disable())
|
||||
.anonymous((c) -> c.disable())
|
||||
.servletApi((c) -> c.disable())
|
||||
.removeConfigurer(DefaultLoginPageConfigurer.class);
|
||||
http.logout((c) -> c.disable());
|
||||
}
|
||||
|
||||
|
||||
@@ -264,7 +264,7 @@ public class WebSecurityTests {
|
||||
@Bean
|
||||
WebSecurityCustomizer webSecurityCustomizer() {
|
||||
return (web) -> web
|
||||
.requestRejectedHandler(new HttpStatusRequestRejectedHandler(HttpStatus.BAD_REQUEST.value()));
|
||||
.requestRejectedHandler(new HttpStatusRequestRejectedHandler(HttpStatus.BAD_REQUEST.value()));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -60,14 +60,14 @@ public class EnableWebSecurityTests {
|
||||
public void configureWhenEnableWebMvcThenAuthenticationPrincipalResolvable() throws Exception {
|
||||
this.spring.register(AuthenticationPrincipalConfig.class).autowire();
|
||||
this.mockMvc.perform(get("/").with(authentication(new TestingAuthenticationToken("user1", "password"))))
|
||||
.andExpect(content().string("user1"));
|
||||
.andExpect(content().string("user1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void securityFilterChainWhenEnableWebMvcThenAuthenticationPrincipalResolvable() throws Exception {
|
||||
this.spring.register(SecurityFilterChainAuthenticationPrincipalConfig.class).autowire();
|
||||
this.mockMvc.perform(get("/").with(authentication(new TestingAuthenticationToken("user1", "password"))))
|
||||
.andExpect(content().string("user1"));
|
||||
.andExpect(content().string("user1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -172,8 +172,10 @@ public class HttpSecurityConfigurationTests {
|
||||
|
||||
@Test
|
||||
public void asyncDispatchWhenCustomSecurityContextHolderStrategyThenUses() throws Exception {
|
||||
this.spring.register(DefaultWithFilterChainConfig.class, SecurityContextChangedListenerConfig.class,
|
||||
NameController.class).autowire();
|
||||
this.spring
|
||||
.register(DefaultWithFilterChainConfig.class, SecurityContextChangedListenerConfig.class,
|
||||
NameController.class)
|
||||
.autowire();
|
||||
// @formatter:off
|
||||
MockHttpServletRequestBuilder requestWithBob = get("/name").with(user("Bob"));
|
||||
MvcResult mvcResult = this.mockMvc.perform(requestWithBob)
|
||||
@@ -266,8 +268,8 @@ public class HttpSecurityConfigurationTests {
|
||||
@Test
|
||||
public void loginWhenUsingDefaultThenAuthenticationEventPublished() throws Exception {
|
||||
this.spring
|
||||
.register(SecurityEnabledConfig.class, UserDetailsConfig.class, AuthenticationEventListenerConfig.class)
|
||||
.autowire();
|
||||
.register(SecurityEnabledConfig.class, UserDetailsConfig.class, AuthenticationEventListenerConfig.class)
|
||||
.autowire();
|
||||
AuthenticationEventListenerConfig.clearEvents();
|
||||
this.mockMvc.perform(formLogin()).andExpect(status().is3xxRedirection());
|
||||
assertThat(AuthenticationEventListenerConfig.EVENTS).isNotEmpty();
|
||||
@@ -277,8 +279,8 @@ public class HttpSecurityConfigurationTests {
|
||||
@Test
|
||||
public void loginWhenUsingDefaultAndNoUserDetailsServiceThenAuthenticationEventPublished() throws Exception {
|
||||
this.spring
|
||||
.register(SecurityEnabledConfig.class, UserDetailsConfig.class, AuthenticationEventListenerConfig.class)
|
||||
.autowire();
|
||||
.register(SecurityEnabledConfig.class, UserDetailsConfig.class, AuthenticationEventListenerConfig.class)
|
||||
.autowire();
|
||||
AuthenticationEventListenerConfig.clearEvents();
|
||||
this.mockMvc.perform(formLogin()).andExpect(status().is3xxRedirection());
|
||||
assertThat(AuthenticationEventListenerConfig.EVENTS).isNotEmpty();
|
||||
@@ -287,8 +289,10 @@ public class HttpSecurityConfigurationTests {
|
||||
|
||||
@Test
|
||||
public void loginWhenUsingCustomAuthenticationEventPublisherThenAuthenticationEventPublished() throws Exception {
|
||||
this.spring.register(SecurityEnabledConfig.class, UserDetailsConfig.class,
|
||||
CustomAuthenticationEventPublisherConfig.class).autowire();
|
||||
this.spring
|
||||
.register(SecurityEnabledConfig.class, UserDetailsConfig.class,
|
||||
CustomAuthenticationEventPublisherConfig.class)
|
||||
.autowire();
|
||||
CustomAuthenticationEventPublisherConfig.clearEvents();
|
||||
this.mockMvc.perform(formLogin()).andExpect(status().is3xxRedirection());
|
||||
assertThat(CustomAuthenticationEventPublisherConfig.EVENTS).isNotEmpty();
|
||||
@@ -308,27 +312,25 @@ public class HttpSecurityConfigurationTests {
|
||||
@Test
|
||||
public void configureWhenAuthorizeHttpRequestsBeforeAuthorizeRequestThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(
|
||||
() -> this.spring.register(AuthorizeHttpRequestsBeforeAuthorizeRequestsConfig.class).autowire())
|
||||
.withMessageContaining(
|
||||
"authorizeHttpRequests cannot be used in conjunction with authorizeRequests. Please select just one.");
|
||||
.isThrownBy(() -> this.spring.register(AuthorizeHttpRequestsBeforeAuthorizeRequestsConfig.class).autowire())
|
||||
.withMessageContaining(
|
||||
"authorizeHttpRequests cannot be used in conjunction with authorizeRequests. Please select just one.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configureWhenAuthorizeHttpRequestsAfterAuthorizeRequestThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(
|
||||
() -> this.spring.register(AuthorizeHttpRequestsAfterAuthorizeRequestsConfig.class).autowire())
|
||||
.withMessageContaining(
|
||||
"authorizeHttpRequests cannot be used in conjunction with authorizeRequests. Please select just one.");
|
||||
.isThrownBy(() -> this.spring.register(AuthorizeHttpRequestsAfterAuthorizeRequestsConfig.class).autowire())
|
||||
.withMessageContaining(
|
||||
"authorizeHttpRequests cannot be used in conjunction with authorizeRequests. Please select just one.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configureWhenDefaultConfigurerAsSpringFactoryThenDefaultConfigurerApplied() {
|
||||
DefaultConfigurer configurer = new DefaultConfigurer();
|
||||
this.springFactoriesLoader.when(
|
||||
() -> SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, getClass().getClassLoader()))
|
||||
.thenReturn(Arrays.asList(configurer));
|
||||
this.springFactoriesLoader
|
||||
.when(() -> SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, getClass().getClassLoader()))
|
||||
.thenReturn(Arrays.asList(configurer));
|
||||
this.spring.register(DefaultWithFilterChainConfig.class).autowire();
|
||||
assertThat(configurer.init).isTrue();
|
||||
assertThat(configurer.configure).isTrue();
|
||||
@@ -339,7 +341,7 @@ public class HttpSecurityConfigurationTests {
|
||||
this.spring.register(CustomContentNegotiationStrategyConfig.class).autowire();
|
||||
this.mockMvc.perform(get("/"));
|
||||
verify(CustomContentNegotiationStrategyConfig.CNS, atLeastOnce())
|
||||
.resolveMediaTypes(any(NativeWebRequest.class));
|
||||
.resolveMediaTypes(any(NativeWebRequest.class));
|
||||
}
|
||||
|
||||
// gh-13084
|
||||
@@ -363,8 +365,11 @@ public class HttpSecurityConfigurationTests {
|
||||
public void configureWhenCorsConfigurationSourceThenApplyCors() {
|
||||
this.spring.register(CorsConfigurationSourceConfig.class, DefaultWithFilterChainConfig.class).autowire();
|
||||
SecurityFilterChain filterChain = this.spring.getContext().getBean(SecurityFilterChain.class);
|
||||
CorsFilter corsFilter = (CorsFilter) filterChain.getFilters().stream().filter((f) -> f instanceof CorsFilter)
|
||||
.findFirst().get();
|
||||
CorsFilter corsFilter = (CorsFilter) filterChain.getFilters()
|
||||
.stream()
|
||||
.filter((f) -> f instanceof CorsFilter)
|
||||
.findFirst()
|
||||
.get();
|
||||
Object configSource = ReflectionTestUtils.getField(corsFilter, "configSource");
|
||||
assertThat(configSource).isInstanceOf(UrlBasedCorsConfigurationSource.class);
|
||||
}
|
||||
@@ -380,9 +385,9 @@ public class HttpSecurityConfigurationTests {
|
||||
|
||||
@Test
|
||||
public void configureWhenCustomDslAddedFromFactoriesAndDisablingUsingWithThenNotApplied() throws Exception {
|
||||
this.springFactoriesLoader.when(
|
||||
() -> SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, getClass().getClassLoader()))
|
||||
.thenReturn(List.of(new WithCustomDsl()));
|
||||
this.springFactoriesLoader
|
||||
.when(() -> SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, getClass().getClassLoader()))
|
||||
.thenReturn(List.of(new WithCustomDsl()));
|
||||
this.spring.register(WithCustomDslDisabledConfig.class, UserDetailsConfig.class).autowire();
|
||||
SecurityFilterChain filterChain = this.spring.getContext().getBean(SecurityFilterChain.class);
|
||||
List<Filter> filters = filterChain.getFilters();
|
||||
|
||||
@@ -173,7 +173,7 @@ public class OAuth2AuthorizedClientManagerConfigurationTests {
|
||||
private void testRefreshTokenGrant() {
|
||||
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
|
||||
given(MOCK_RESPONSE_CLIENT.getTokenResponse(any(OAuth2RefreshTokenGrantRequest.class)))
|
||||
.willReturn(accessTokenResponse);
|
||||
.willReturn(accessTokenResponse);
|
||||
|
||||
TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", null);
|
||||
ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId("google");
|
||||
@@ -193,12 +193,12 @@ public class OAuth2AuthorizedClientManagerConfigurationTests {
|
||||
assertThat(authorizedClient).isNotNull();
|
||||
|
||||
ArgumentCaptor<OAuth2RefreshTokenGrantRequest> grantRequestCaptor = ArgumentCaptor
|
||||
.forClass(OAuth2RefreshTokenGrantRequest.class);
|
||||
.forClass(OAuth2RefreshTokenGrantRequest.class);
|
||||
verify(MOCK_RESPONSE_CLIENT).getTokenResponse(grantRequestCaptor.capture());
|
||||
|
||||
OAuth2RefreshTokenGrantRequest grantRequest = grantRequestCaptor.getValue();
|
||||
assertThat(grantRequest.getClientRegistration().getRegistrationId())
|
||||
.isEqualTo(clientRegistration.getRegistrationId());
|
||||
.isEqualTo(clientRegistration.getRegistrationId());
|
||||
assertThat(grantRequest.getGrantType()).isEqualTo(AuthorizationGrantType.REFRESH_TOKEN);
|
||||
assertThat(grantRequest.getAccessToken()).isEqualTo(existingAuthorizedClient.getAccessToken());
|
||||
assertThat(grantRequest.getRefreshToken()).isEqualTo(existingAuthorizedClient.getRefreshToken());
|
||||
@@ -219,7 +219,7 @@ public class OAuth2AuthorizedClientManagerConfigurationTests {
|
||||
private void testClientCredentialsGrant() {
|
||||
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
|
||||
given(MOCK_RESPONSE_CLIENT.getTokenResponse(any(OAuth2ClientCredentialsGrantRequest.class)))
|
||||
.willReturn(accessTokenResponse);
|
||||
.willReturn(accessTokenResponse);
|
||||
|
||||
TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", null);
|
||||
ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId("github");
|
||||
@@ -235,12 +235,12 @@ public class OAuth2AuthorizedClientManagerConfigurationTests {
|
||||
assertThat(authorizedClient).isNotNull();
|
||||
|
||||
ArgumentCaptor<OAuth2ClientCredentialsGrantRequest> grantRequestCaptor = ArgumentCaptor
|
||||
.forClass(OAuth2ClientCredentialsGrantRequest.class);
|
||||
.forClass(OAuth2ClientCredentialsGrantRequest.class);
|
||||
verify(MOCK_RESPONSE_CLIENT).getTokenResponse(grantRequestCaptor.capture());
|
||||
|
||||
OAuth2ClientCredentialsGrantRequest grantRequest = grantRequestCaptor.getValue();
|
||||
assertThat(grantRequest.getClientRegistration().getRegistrationId())
|
||||
.isEqualTo(clientRegistration.getRegistrationId());
|
||||
.isEqualTo(clientRegistration.getRegistrationId());
|
||||
assertThat(grantRequest.getGrantType()).isEqualTo(AuthorizationGrantType.CLIENT_CREDENTIALS);
|
||||
}
|
||||
|
||||
@@ -259,7 +259,7 @@ public class OAuth2AuthorizedClientManagerConfigurationTests {
|
||||
private void testPasswordGrant() {
|
||||
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
|
||||
given(MOCK_RESPONSE_CLIENT.getTokenResponse(any(OAuth2PasswordGrantRequest.class)))
|
||||
.willReturn(accessTokenResponse);
|
||||
.willReturn(accessTokenResponse);
|
||||
|
||||
TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "password");
|
||||
ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId("facebook");
|
||||
@@ -277,12 +277,12 @@ public class OAuth2AuthorizedClientManagerConfigurationTests {
|
||||
assertThat(authorizedClient).isNotNull();
|
||||
|
||||
ArgumentCaptor<OAuth2PasswordGrantRequest> grantRequestCaptor = ArgumentCaptor
|
||||
.forClass(OAuth2PasswordGrantRequest.class);
|
||||
.forClass(OAuth2PasswordGrantRequest.class);
|
||||
verify(MOCK_RESPONSE_CLIENT).getTokenResponse(grantRequestCaptor.capture());
|
||||
|
||||
OAuth2PasswordGrantRequest grantRequest = grantRequestCaptor.getValue();
|
||||
assertThat(grantRequest.getClientRegistration().getRegistrationId())
|
||||
.isEqualTo(clientRegistration.getRegistrationId());
|
||||
.isEqualTo(clientRegistration.getRegistrationId());
|
||||
assertThat(grantRequest.getGrantType()).isEqualTo(AuthorizationGrantType.PASSWORD);
|
||||
assertThat(grantRequest.getUsername()).isEqualTo("user");
|
||||
assertThat(grantRequest.getPassword()).isEqualTo("password");
|
||||
@@ -322,7 +322,7 @@ public class OAuth2AuthorizedClientManagerConfigurationTests {
|
||||
|
||||
JwtBearerGrantRequest grantRequest = grantRequestCaptor.getValue();
|
||||
assertThat(grantRequest.getClientRegistration().getRegistrationId())
|
||||
.isEqualTo(clientRegistration.getRegistrationId());
|
||||
.isEqualTo(clientRegistration.getRegistrationId());
|
||||
assertThat(grantRequest.getGrantType()).isEqualTo(AuthorizationGrantType.JWT_BEARER);
|
||||
assertThat(grantRequest.getJwt().getSubject()).isEqualTo("user");
|
||||
}
|
||||
@@ -475,21 +475,21 @@ public class OAuth2AuthorizedClientManagerConfigurationTests {
|
||||
@Bean
|
||||
Consumer<DefaultOAuth2AuthorizedClientManager> authorizedClientManagerConsumer() {
|
||||
return (authorizedClientManager) -> authorizedClientManager
|
||||
.setContextAttributesMapper((authorizeRequest) -> {
|
||||
HttpServletRequest request = Objects
|
||||
.requireNonNull(authorizeRequest.getAttribute(HttpServletRequest.class.getName()));
|
||||
String username = request.getParameter(OAuth2ParameterNames.USERNAME);
|
||||
String password = request.getParameter(OAuth2ParameterNames.PASSWORD);
|
||||
.setContextAttributesMapper((authorizeRequest) -> {
|
||||
HttpServletRequest request = Objects
|
||||
.requireNonNull(authorizeRequest.getAttribute(HttpServletRequest.class.getName()));
|
||||
String username = request.getParameter(OAuth2ParameterNames.USERNAME);
|
||||
String password = request.getParameter(OAuth2ParameterNames.PASSWORD);
|
||||
|
||||
Map<String, Object> attributes = Collections.emptyMap();
|
||||
if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
|
||||
attributes = new HashMap<>();
|
||||
attributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
|
||||
attributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
|
||||
}
|
||||
Map<String, Object> attributes = Collections.emptyMap();
|
||||
if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
|
||||
attributes = new HashMap<>();
|
||||
attributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
|
||||
attributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
|
||||
}
|
||||
|
||||
return attributes;
|
||||
});
|
||||
return attributes;
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -83,14 +83,16 @@ public class OAuth2ClientConfigurationTests {
|
||||
TestingAuthenticationToken authentication = new TestingAuthenticationToken(principalName, "password");
|
||||
ClientRegistrationRepository clientRegistrationRepository = mock(ClientRegistrationRepository.class);
|
||||
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
|
||||
.registrationId(clientRegistrationId).build();
|
||||
.registrationId(clientRegistrationId)
|
||||
.build();
|
||||
given(clientRegistrationRepository.findByRegistrationId(eq(clientRegistrationId)))
|
||||
.willReturn(clientRegistration);
|
||||
.willReturn(clientRegistration);
|
||||
OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
|
||||
OAuth2AuthorizedClient authorizedClient = mock(OAuth2AuthorizedClient.class);
|
||||
given(authorizedClient.getClientRegistration()).willReturn(clientRegistration);
|
||||
given(authorizedClientRepository.loadAuthorizedClient(eq(clientRegistrationId), eq(authentication),
|
||||
any(HttpServletRequest.class))).willReturn(authorizedClient);
|
||||
any(HttpServletRequest.class)))
|
||||
.willReturn(authorizedClient);
|
||||
OAuth2AccessToken accessToken = mock(OAuth2AccessToken.class);
|
||||
given(authorizedClient.getAccessToken()).willReturn(accessToken);
|
||||
OAuth2AccessTokenResponseClient accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
|
||||
@@ -116,7 +118,8 @@ public class OAuth2ClientConfigurationTests {
|
||||
OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
|
||||
OAuth2AccessTokenResponseClient accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
|
||||
ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials()
|
||||
.registrationId(clientRegistrationId).build();
|
||||
.registrationId(clientRegistrationId)
|
||||
.build();
|
||||
given(clientRegistrationRepository.findByRegistrationId(clientRegistrationId)).willReturn(clientRegistration);
|
||||
// @formatter:off
|
||||
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse
|
||||
@@ -126,13 +129,13 @@ public class OAuth2ClientConfigurationTests {
|
||||
.build();
|
||||
// @formatter:on
|
||||
given(accessTokenResponseClient.getTokenResponse(any(OAuth2ClientCredentialsGrantRequest.class)))
|
||||
.willReturn(accessTokenResponse);
|
||||
.willReturn(accessTokenResponse);
|
||||
OAuth2AuthorizedClientArgumentResolverConfig.CLIENT_REGISTRATION_REPOSITORY = clientRegistrationRepository;
|
||||
OAuth2AuthorizedClientArgumentResolverConfig.AUTHORIZED_CLIENT_REPOSITORY = authorizedClientRepository;
|
||||
OAuth2AuthorizedClientArgumentResolverConfig.ACCESS_TOKEN_RESPONSE_CLIENT = accessTokenResponseClient;
|
||||
this.spring.register(OAuth2AuthorizedClientArgumentResolverConfig.class).autowire();
|
||||
MockHttpServletRequestBuilder authenticatedRequest = get("/authorized-client")
|
||||
.with(authentication(authentication));
|
||||
.with(authentication(authentication));
|
||||
// @formatter:off
|
||||
this.mockMvc.perform(authenticatedRequest)
|
||||
.andExpect(status().isOk())
|
||||
@@ -144,20 +147,22 @@ public class OAuth2ClientConfigurationTests {
|
||||
// gh-5321
|
||||
@Test
|
||||
public void loadContextWhenOAuth2AuthorizedClientRepositoryRegisteredTwiceThenThrowNoUniqueBeanDefinitionException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class).isThrownBy(
|
||||
() -> this.spring.register(OAuth2AuthorizedClientRepositoryRegisteredTwiceConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(NoUniqueBeanDefinitionException.class).withMessageContaining(
|
||||
"Expected single matching bean of type '" + OAuth2AuthorizedClientRepository.class.getName()
|
||||
+ "' but found 2: authorizedClientRepository1,authorizedClientRepository2");
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(
|
||||
() -> this.spring.register(OAuth2AuthorizedClientRepositoryRegisteredTwiceConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(NoUniqueBeanDefinitionException.class)
|
||||
.withMessageContaining(
|
||||
"Expected single matching bean of type '" + OAuth2AuthorizedClientRepository.class.getName()
|
||||
+ "' but found 2: authorizedClientRepository1,authorizedClientRepository2");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadContextWhenClientRegistrationRepositoryNotRegisteredThenThrowNoSuchBeanDefinitionException() {
|
||||
assertThatExceptionOfType(Exception.class)
|
||||
.isThrownBy(
|
||||
() -> this.spring.register(ClientRegistrationRepositoryNotRegisteredConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(NoSuchBeanDefinitionException.class).withMessageContaining(
|
||||
"No qualifying bean of type '" + ClientRegistrationRepository.class.getName() + "' available");
|
||||
.isThrownBy(() -> this.spring.register(ClientRegistrationRepositoryNotRegisteredConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(NoSuchBeanDefinitionException.class)
|
||||
.withMessageContaining(
|
||||
"No qualifying bean of type '" + ClientRegistrationRepository.class.getName() + "' available");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -194,7 +199,8 @@ public class OAuth2ClientConfigurationTests {
|
||||
OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
|
||||
OAuth2AuthorizedClientManager authorizedClientManager = mock(OAuth2AuthorizedClientManager.class);
|
||||
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
|
||||
.registrationId(clientRegistrationId).build();
|
||||
.registrationId(clientRegistrationId)
|
||||
.build();
|
||||
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, principalName,
|
||||
TestOAuth2AccessTokens.noScopes());
|
||||
given(authorizedClientManager.authorize(any())).willReturn(authorizedClient);
|
||||
@@ -203,7 +209,7 @@ public class OAuth2ClientConfigurationTests {
|
||||
OAuth2AuthorizedClientManagerRegisteredConfig.AUTHORIZED_CLIENT_MANAGER = authorizedClientManager;
|
||||
this.spring.register(OAuth2AuthorizedClientManagerRegisteredConfig.class).autowire();
|
||||
MockHttpServletRequestBuilder authenticatedRequest = get("/authorized-client")
|
||||
.with(authentication(authentication));
|
||||
.with(authentication(authentication));
|
||||
// @formatter:off
|
||||
this.mockMvc
|
||||
.perform(authenticatedRequest)
|
||||
|
||||
@@ -93,8 +93,10 @@ public class SecurityReactorContextConfigurationResourceServerTests {
|
||||
@Test
|
||||
public void requestWhenCustomSecurityContextHolderStrategyThenUses() throws Exception {
|
||||
BearerTokenAuthentication authentication = TestBearerTokenAuthentications.bearer();
|
||||
this.spring.register(BearerFilterConfig.class, WebServerConfig.class, Controller.class,
|
||||
SecurityContextChangedListenerConfig.class).autowire();
|
||||
this.spring
|
||||
.register(BearerFilterConfig.class, WebServerConfig.class, Controller.class,
|
||||
SecurityContextChangedListenerConfig.class)
|
||||
.autowire();
|
||||
MockHttpServletRequestBuilder authenticatedRequest = get("/token").with(authentication(authentication));
|
||||
// @formatter:off
|
||||
this.mockMvc.perform(authenticatedRequest)
|
||||
|
||||
@@ -113,14 +113,14 @@ public class SecurityReactorContextConfigurationTests {
|
||||
}
|
||||
};
|
||||
CoreSubscriber<Object> resultSubscriber = this.subscriberRegistrar
|
||||
.createSubscriberIfNecessary(originalSubscriber);
|
||||
.createSubscriberIfNecessary(originalSubscriber);
|
||||
assertThat(resultSubscriber).isSameAs(originalSubscriber);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createSubscriberIfNecessaryWhenWebSecurityContextAvailableThenCreateWithParentContext() {
|
||||
RequestContextHolder
|
||||
.setRequestAttributes(new ServletRequestAttributes(this.servletRequest, this.servletResponse));
|
||||
.setRequestAttributes(new ServletRequestAttributes(this.servletRequest, this.servletResponse));
|
||||
SecurityContextHolder.getContext().setAuthentication(this.authentication);
|
||||
String testKey = "test_key";
|
||||
String testValue = "test_value";
|
||||
@@ -134,7 +134,7 @@ public class SecurityReactorContextConfigurationTests {
|
||||
Context resultContext = subscriber.currentContext();
|
||||
assertThat(resultContext.getOrEmpty(testKey)).hasValue(testValue);
|
||||
Map<Object, Object> securityContextAttributes = resultContext
|
||||
.getOrDefault(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES, null);
|
||||
.getOrDefault(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES, null);
|
||||
assertThat(securityContextAttributes).hasSize(3);
|
||||
assertThat(securityContextAttributes).contains(entry(HttpServletRequest.class, this.servletRequest),
|
||||
entry(HttpServletResponse.class, this.servletResponse),
|
||||
@@ -144,7 +144,7 @@ public class SecurityReactorContextConfigurationTests {
|
||||
@Test
|
||||
public void createSubscriberIfNecessaryWhenParentContextContainsSecurityContextAttributesThenUseParentContext() {
|
||||
RequestContextHolder
|
||||
.setRequestAttributes(new ServletRequestAttributes(this.servletRequest, this.servletResponse));
|
||||
.setRequestAttributes(new ServletRequestAttributes(this.servletRequest, this.servletResponse));
|
||||
SecurityContextHolder.getContext().setAuthentication(this.authentication);
|
||||
Context parentContext = Context.of(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES,
|
||||
new HashMap<>());
|
||||
@@ -200,7 +200,7 @@ public class SecurityReactorContextConfigurationTests {
|
||||
}
|
||||
});
|
||||
CoreSubscriber<Object> subscriber = this.subscriberRegistrar
|
||||
.createSubscriberIfNecessary(Operators.emptySubscriber());
|
||||
.createSubscriberIfNecessary(Operators.emptySubscriber());
|
||||
assertThat(subscriber).isInstanceOf(SecurityReactorContextConfiguration.SecurityReactorContextSubscriber.class);
|
||||
}
|
||||
|
||||
@@ -211,7 +211,7 @@ public class SecurityReactorContextConfigurationTests {
|
||||
this.spring.register(SecurityConfig.class).autowire();
|
||||
// Setup for SecurityReactorContextSubscriberRegistrar
|
||||
RequestContextHolder
|
||||
.setRequestAttributes(new ServletRequestAttributes(this.servletRequest, this.servletResponse));
|
||||
.setRequestAttributes(new ServletRequestAttributes(this.servletRequest, this.servletResponse));
|
||||
SecurityContextHolder.getContext().setAuthentication(this.authentication);
|
||||
ClientResponse clientResponseOk = ClientResponse.create(HttpStatus.OK).build();
|
||||
// @formatter:off
|
||||
@@ -237,7 +237,7 @@ public class SecurityReactorContextConfigurationTests {
|
||||
expectedContextAttributes.put(HttpServletResponse.class, this.servletResponse);
|
||||
expectedContextAttributes.put(Authentication.class, this.authentication);
|
||||
Mono<ClientResponse> clientResponseMono = filter.filter(clientRequest, exchange)
|
||||
.flatMap((response) -> filter.filter(clientRequest, exchange));
|
||||
.flatMap((response) -> filter.filter(clientRequest, exchange));
|
||||
// @formatter:off
|
||||
StepVerifier.create(clientResponseMono)
|
||||
.expectAccessibleContext()
|
||||
@@ -268,7 +268,7 @@ public class SecurityReactorContextConfigurationTests {
|
||||
expectedContextAttributes.put(HttpServletResponse.class, null);
|
||||
expectedContextAttributes.put(Authentication.class, this.authentication);
|
||||
Mono<ClientResponse> clientResponseMono = filter.filter(clientRequest, exchange)
|
||||
.flatMap((response) -> filter.filter(clientRequest, exchange));
|
||||
.flatMap((response) -> filter.filter(clientRequest, exchange));
|
||||
// @formatter:off
|
||||
StepVerifier.create(clientResponseMono)
|
||||
.expectAccessibleContext()
|
||||
|
||||
@@ -79,15 +79,15 @@ public class WebMvcSecurityConfigurationTests {
|
||||
@Test
|
||||
public void authenticationPrincipalResolved() throws Exception {
|
||||
this.mockMvc.perform(get("/authentication-principal"))
|
||||
.andExpect(assertResult(this.authentication.getPrincipal()))
|
||||
.andExpect(view().name("authentication-principal-view"));
|
||||
.andExpect(assertResult(this.authentication.getPrincipal()))
|
||||
.andExpect(view().name("authentication-principal-view"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deprecatedAuthenticationPrincipalResolved() throws Exception {
|
||||
this.mockMvc.perform(get("/deprecated-authentication-principal"))
|
||||
.andExpect(assertResult(this.authentication.getPrincipal()))
|
||||
.andExpect(view().name("deprecated-authentication-principal-view"));
|
||||
.andExpect(assertResult(this.authentication.getPrincipal()))
|
||||
.andExpect(view().name("deprecated-authentication-principal-view"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -126,31 +126,32 @@ public class WebSecurityConfigurationTests {
|
||||
PrivilegeEvaluatorConfigurerAdapterConfig.PRIVILEGE_EVALUATOR = mock(WebInvocationPrivilegeEvaluator.class);
|
||||
this.spring.register(PrivilegeEvaluatorConfigurerAdapterConfig.class).autowire();
|
||||
assertThat(this.spring.getContext().getBean(WebInvocationPrivilegeEvaluator.class))
|
||||
.isSameAs(PrivilegeEvaluatorConfigurerAdapterConfig.PRIVILEGE_EVALUATOR);
|
||||
.isSameAs(PrivilegeEvaluatorConfigurerAdapterConfig.PRIVILEGE_EVALUATOR);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadConfigWhenSecurityExpressionHandlerSetThenIsRegistered() {
|
||||
WebSecurityExpressionHandlerConfig.EXPRESSION_HANDLER = mock(SecurityExpressionHandler.class);
|
||||
given(WebSecurityExpressionHandlerConfig.EXPRESSION_HANDLER.getExpressionParser())
|
||||
.willReturn(mock(ExpressionParser.class));
|
||||
.willReturn(mock(ExpressionParser.class));
|
||||
this.spring.register(WebSecurityExpressionHandlerConfig.class).autowire();
|
||||
assertThat(this.spring.getContext().getBean(SecurityExpressionHandler.class))
|
||||
.isSameAs(WebSecurityExpressionHandlerConfig.EXPRESSION_HANDLER);
|
||||
.isSameAs(WebSecurityExpressionHandlerConfig.EXPRESSION_HANDLER);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadConfigWhenSecurityExpressionHandlerIsNullThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(NullWebSecurityExpressionHandlerConfig.class).autowire())
|
||||
.havingRootCause().isExactlyInstanceOf(IllegalArgumentException.class);
|
||||
.isThrownBy(() -> this.spring.register(NullWebSecurityExpressionHandlerConfig.class).autowire())
|
||||
.havingRootCause()
|
||||
.isExactlyInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadConfigWhenDefaultSecurityExpressionHandlerThenDefaultIsRegistered() {
|
||||
this.spring.register(WebSecurityExpressionHandlerDefaultsConfig.class).autowire();
|
||||
assertThat(this.spring.getContext().getBean(SecurityExpressionHandler.class))
|
||||
.isInstanceOf(DefaultWebSecurityExpressionHandler.class);
|
||||
.isInstanceOf(DefaultWebSecurityExpressionHandler.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -160,7 +161,7 @@ public class WebSecurityConfigurationTests {
|
||||
FilterInvocation invocation = new FilterInvocation(new MockHttpServletRequest("GET", ""),
|
||||
new MockHttpServletResponse(), new MockFilterChain());
|
||||
AbstractSecurityExpressionHandler handler = this.spring.getContext()
|
||||
.getBean(AbstractSecurityExpressionHandler.class);
|
||||
.getBean(AbstractSecurityExpressionHandler.class);
|
||||
EvaluationContext evaluationContext = handler.createEvaluationContext(authentication, invocation);
|
||||
Expression expression = handler.getExpressionParser().parseExpression("hasRole('ROLE_USER')");
|
||||
boolean granted = expression.getValue(evaluationContext, Boolean.class);
|
||||
@@ -174,7 +175,7 @@ public class WebSecurityConfigurationTests {
|
||||
FilterInvocation invocation = new FilterInvocation(new MockHttpServletRequest("GET", ""),
|
||||
new MockHttpServletResponse(), new MockFilterChain());
|
||||
AbstractSecurityExpressionHandler handler = this.spring.getContext()
|
||||
.getBean(AbstractSecurityExpressionHandler.class);
|
||||
.getBean(AbstractSecurityExpressionHandler.class);
|
||||
EvaluationContext evaluationContext = handler.createEvaluationContext(authentication, invocation);
|
||||
Expression expression = handler.getExpressionParser().parseExpression("hasPermission(#study,'DELETE')");
|
||||
boolean granted = expression.getValue(evaluationContext, Boolean.class);
|
||||
@@ -185,7 +186,7 @@ public class WebSecurityConfigurationTests {
|
||||
public void loadConfigWhenDefaultWebInvocationPrivilegeEvaluatorThenRequestMatcherIsRegistered() {
|
||||
this.spring.register(WebInvocationPrivilegeEvaluatorDefaultsConfig.class).autowire();
|
||||
assertThat(this.spring.getContext().getBean(WebInvocationPrivilegeEvaluator.class))
|
||||
.isInstanceOf(RequestMatcherDelegatingWebInvocationPrivilegeEvaluator.class);
|
||||
.isInstanceOf(RequestMatcherDelegatingWebInvocationPrivilegeEvaluator.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -193,7 +194,7 @@ public class WebSecurityConfigurationTests {
|
||||
this.spring.register(AuthorizeRequestsFilterChainConfig.class).autowire();
|
||||
|
||||
assertThat(this.spring.getContext().getBean(WebInvocationPrivilegeEvaluator.class))
|
||||
.isInstanceOf(RequestMatcherDelegatingWebInvocationPrivilegeEvaluator.class);
|
||||
.isInstanceOf(RequestMatcherDelegatingWebInvocationPrivilegeEvaluator.class);
|
||||
}
|
||||
|
||||
// SEC-2303
|
||||
@@ -279,14 +280,14 @@ public class WebSecurityConfigurationTests {
|
||||
public void loadConfigWhenTwoSecurityFilterChainsThenRequestMatcherDelegatingWebInvocationPrivilegeEvaluator() {
|
||||
this.spring.register(TwoSecurityFilterChainConfig.class).autowire();
|
||||
assertThat(this.spring.getContext().getBean(WebInvocationPrivilegeEvaluator.class))
|
||||
.isInstanceOf(RequestMatcherDelegatingWebInvocationPrivilegeEvaluator.class);
|
||||
.isInstanceOf(RequestMatcherDelegatingWebInvocationPrivilegeEvaluator.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadConfigWhenTwoSecurityFilterChainDebugThenRequestMatcherDelegatingWebInvocationPrivilegeEvaluator() {
|
||||
this.spring.register(TwoSecurityFilterChainConfig.class).autowire();
|
||||
assertThat(this.spring.getContext().getBean(WebInvocationPrivilegeEvaluator.class))
|
||||
.isInstanceOf(RequestMatcherDelegatingWebInvocationPrivilegeEvaluator.class);
|
||||
.isInstanceOf(RequestMatcherDelegatingWebInvocationPrivilegeEvaluator.class);
|
||||
}
|
||||
|
||||
// gh-10554
|
||||
@@ -294,7 +295,7 @@ public class WebSecurityConfigurationTests {
|
||||
public void loadConfigWhenMultipleSecurityFilterChainsThenWebInvocationPrivilegeEvaluatorApplySecurity() {
|
||||
this.spring.register(MultipleSecurityFilterChainConfig.class).autowire();
|
||||
WebInvocationPrivilegeEvaluator privilegeEvaluator = this.spring.getContext()
|
||||
.getBean(WebInvocationPrivilegeEvaluator.class);
|
||||
.getBean(WebInvocationPrivilegeEvaluator.class);
|
||||
assertUserPermissions(privilegeEvaluator);
|
||||
assertAdminPermissions(privilegeEvaluator);
|
||||
assertAnotherUserPermission(privilegeEvaluator);
|
||||
@@ -305,7 +306,7 @@ public class WebSecurityConfigurationTests {
|
||||
public void loadConfigWhenMultipleSecurityFilterChainAndIgnoringThenWebInvocationPrivilegeEvaluatorAcceptsNullAuthenticationOnIgnored() {
|
||||
this.spring.register(MultipleSecurityFilterChainIgnoringConfig.class).autowire();
|
||||
WebInvocationPrivilegeEvaluator privilegeEvaluator = this.spring.getContext()
|
||||
.getBean(WebInvocationPrivilegeEvaluator.class);
|
||||
.getBean(WebInvocationPrivilegeEvaluator.class);
|
||||
assertUserPermissions(privilegeEvaluator);
|
||||
assertAdminPermissions(privilegeEvaluator);
|
||||
assertAnotherUserPermission(privilegeEvaluator);
|
||||
|
||||
@@ -40,7 +40,7 @@ public class AbstractConfigAttributeRequestMatcherRegistryTests {
|
||||
@Test
|
||||
public void testGetRequestMatcherIsTypeRegexMatcher() {
|
||||
List<RequestMatcher> requestMatchers = this.registry
|
||||
.requestMatchers(new RegexRequestMatcher("/a.*", HttpMethod.GET.name()));
|
||||
.requestMatchers(new RegexRequestMatcher("/a.*", HttpMethod.GET.name()));
|
||||
for (RequestMatcher requestMatcher : requestMatchers) {
|
||||
assertThat(requestMatcher).isInstanceOf(RegexRequestMatcher.class);
|
||||
}
|
||||
@@ -57,7 +57,7 @@ public class AbstractConfigAttributeRequestMatcherRegistryTests {
|
||||
@Test
|
||||
public void testGetRequestMatcherIsTypeAntPathRequestMatcher() {
|
||||
List<RequestMatcher> requestMatchers = this.registry
|
||||
.requestMatchers(new AntPathRequestMatcher("/a.*", HttpMethod.GET.name()));
|
||||
.requestMatchers(new AntPathRequestMatcher("/a.*", HttpMethod.GET.name()));
|
||||
for (RequestMatcher requestMatcher : requestMatchers) {
|
||||
assertThat(requestMatcher).isInstanceOf(AntPathRequestMatcher.class);
|
||||
}
|
||||
|
||||
@@ -72,11 +72,13 @@ public class AnonymousConfigurerTests {
|
||||
|
||||
@Test
|
||||
public void requestWhenCustomSecurityContextHolderStrategyThenUses() throws Exception {
|
||||
this.spring.register(AnonymousPrincipalInLambdaConfig.class, SecurityContextChangedListenerConfig.class,
|
||||
PrincipalController.class).autowire();
|
||||
this.spring
|
||||
.register(AnonymousPrincipalInLambdaConfig.class, SecurityContextChangedListenerConfig.class,
|
||||
PrincipalController.class)
|
||||
.autowire();
|
||||
this.mockMvc.perform(get("/")).andExpect(content().string("principal"));
|
||||
SecurityContextChangedListener listener = this.spring.getContext()
|
||||
.getBean(SecurityContextChangedListener.class);
|
||||
.getBean(SecurityContextChangedListener.class);
|
||||
verify(listener).securityContextChanged(setAuthentication(AnonymousAuthenticationToken.class));
|
||||
}
|
||||
|
||||
|
||||
@@ -90,37 +90,38 @@ public class AuthorizeHttpRequestsConfigurerTests {
|
||||
@Test
|
||||
public void configureWhenAuthorizedHttpRequestsAndNoRequestsThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(NoRequestsConfig.class).autowire()).withMessageContaining(
|
||||
"At least one mapping is required (for example, authorizeHttpRequests().anyRequest().authenticated())");
|
||||
.isThrownBy(() -> this.spring.register(NoRequestsConfig.class).autowire())
|
||||
.withMessageContaining(
|
||||
"At least one mapping is required (for example, authorizeHttpRequests().anyRequest().authenticated())");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configureNoParameterWhenAuthorizedHttpRequestsAndNoRequestsThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(NoRequestsNoParameterConfig.class).autowire())
|
||||
.withMessageContaining(
|
||||
"At least one mapping is required (for example, authorizeHttpRequests().anyRequest().authenticated())");
|
||||
.isThrownBy(() -> this.spring.register(NoRequestsNoParameterConfig.class).autowire())
|
||||
.withMessageContaining(
|
||||
"At least one mapping is required (for example, authorizeHttpRequests().anyRequest().authenticated())");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configureWhenAnyRequestIncompleteMappingThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(IncompleteMappingConfig.class).autowire())
|
||||
.withMessageContaining("An incomplete mapping was found for ");
|
||||
.isThrownBy(() -> this.spring.register(IncompleteMappingConfig.class).autowire())
|
||||
.withMessageContaining("An incomplete mapping was found for ");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configureNoParameterWhenAnyRequestIncompleteMappingThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(IncompleteMappingNoParameterConfig.class).autowire())
|
||||
.withMessageContaining("An incomplete mapping was found for ");
|
||||
.isThrownBy(() -> this.spring.register(IncompleteMappingNoParameterConfig.class).autowire())
|
||||
.withMessageContaining("An incomplete mapping was found for ");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configureWhenMvcMatcherAfterAnyRequestThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(AfterAnyRequestConfig.class).autowire())
|
||||
.withMessageContaining("Can't configure mvcMatchers after anyRequest");
|
||||
.isThrownBy(() -> this.spring.register(AfterAnyRequestConfig.class).autowire())
|
||||
.withMessageContaining("Can't configure mvcMatchers after anyRequest");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -143,8 +144,8 @@ public class AuthorizeHttpRequestsConfigurerTests {
|
||||
public void configureMvcMatcherAccessAuthorizationManagerWhenNullThenException() {
|
||||
CustomAuthorizationManagerConfig.authorizationManager = null;
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(CustomAuthorizationManagerConfig.class).autowire())
|
||||
.withMessageContaining("manager cannot be null");
|
||||
.isThrownBy(() -> this.spring.register(CustomAuthorizationManagerConfig.class).autowire())
|
||||
.withMessageContaining("manager cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -958,7 +959,7 @@ public class AuthorizeHttpRequestsConfigurerTests {
|
||||
@Bean
|
||||
SecurityFilterChain filterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception {
|
||||
MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector)
|
||||
.servletPath("/spring");
|
||||
.servletPath("/spring");
|
||||
// @formatter:off
|
||||
return http
|
||||
.authorizeHttpRequests((requests) -> requests
|
||||
|
||||
@@ -154,8 +154,8 @@ public class AuthorizeRequestsTests {
|
||||
SecurityContext securityContext = new SecurityContextImpl();
|
||||
securityContext.setAuthentication(UsernamePasswordAuthenticationToken.authenticated("test", "notused",
|
||||
AuthorityUtils.createAuthorityList("ROLE_USER")));
|
||||
this.request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
|
||||
securityContext);
|
||||
this.request.getSession()
|
||||
.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext);
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
|
||||
}
|
||||
@@ -474,7 +474,7 @@ public class AuthorizeRequestsTests {
|
||||
@Bean
|
||||
SecurityFilterChain filterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception {
|
||||
MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector)
|
||||
.servletPath("/spring");
|
||||
.servletPath("/spring");
|
||||
// @formatter:off
|
||||
http
|
||||
.httpBasic().and()
|
||||
@@ -509,7 +509,7 @@ public class AuthorizeRequestsTests {
|
||||
@Bean
|
||||
SecurityFilterChain filterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception {
|
||||
MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector)
|
||||
.servletPath("/spring");
|
||||
.servletPath("/spring");
|
||||
// @formatter:off
|
||||
http
|
||||
.httpBasic(withDefaults())
|
||||
|
||||
@@ -68,62 +68,69 @@ public class CorsConfigurerTests {
|
||||
@Test
|
||||
public void configureWhenNoMvcThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(DefaultCorsConfig.class).autowire()).withMessageContaining(
|
||||
"Please ensure Spring Security & Spring MVC are configured in a shared ApplicationContext");
|
||||
.isThrownBy(() -> this.spring.register(DefaultCorsConfig.class).autowire())
|
||||
.withMessageContaining(
|
||||
"Please ensure Spring Security & Spring MVC are configured in a shared ApplicationContext");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getWhenCrossOriginAnnotationThenRespondsWithCorsHeaders() throws Exception {
|
||||
this.spring.register(MvcCorsConfig.class).autowire();
|
||||
this.mvc.perform(get("/").header(HttpHeaders.ORIGIN, "https://example.com"))
|
||||
.andExpect(header().exists("Access-Control-Allow-Origin"))
|
||||
.andExpect(header().exists("X-Content-Type-Options"));
|
||||
.andExpect(header().exists("Access-Control-Allow-Origin"))
|
||||
.andExpect(header().exists("X-Content-Type-Options"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void optionsWhenCrossOriginAnnotationThenRespondsWithCorsHeaders() throws Exception {
|
||||
this.spring.register(MvcCorsConfig.class).autowire();
|
||||
this.mvc.perform(options("/")
|
||||
this.mvc
|
||||
.perform(options("/")
|
||||
.header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
|
||||
.header(HttpHeaders.ORIGIN, "https://example.com")).andExpect(status().isOk())
|
||||
.andExpect(header().exists("Access-Control-Allow-Origin"))
|
||||
.andExpect(header().exists("X-Content-Type-Options"));
|
||||
.header(HttpHeaders.ORIGIN, "https://example.com"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().exists("Access-Control-Allow-Origin"))
|
||||
.andExpect(header().exists("X-Content-Type-Options"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getWhenDefaultsInLambdaAndCrossOriginAnnotationThenRespondsWithCorsHeaders() throws Exception {
|
||||
this.spring.register(MvcCorsInLambdaConfig.class).autowire();
|
||||
this.mvc.perform(get("/").header(HttpHeaders.ORIGIN, "https://example.com"))
|
||||
.andExpect(header().exists("Access-Control-Allow-Origin"))
|
||||
.andExpect(header().exists("X-Content-Type-Options"));
|
||||
.andExpect(header().exists("Access-Control-Allow-Origin"))
|
||||
.andExpect(header().exists("X-Content-Type-Options"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void optionsWhenDefaultsInLambdaAndCrossOriginAnnotationThenRespondsWithCorsHeaders() throws Exception {
|
||||
this.spring.register(MvcCorsInLambdaConfig.class).autowire();
|
||||
this.mvc.perform(options("/")
|
||||
this.mvc
|
||||
.perform(options("/")
|
||||
.header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
|
||||
.header(HttpHeaders.ORIGIN, "https://example.com")).andExpect(status().isOk())
|
||||
.andExpect(header().exists("Access-Control-Allow-Origin"))
|
||||
.andExpect(header().exists("X-Content-Type-Options"));
|
||||
.header(HttpHeaders.ORIGIN, "https://example.com"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().exists("Access-Control-Allow-Origin"))
|
||||
.andExpect(header().exists("X-Content-Type-Options"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getWhenCorsConfigurationSourceBeanThenRespondsWithCorsHeaders() throws Exception {
|
||||
this.spring.register(ConfigSourceConfig.class).autowire();
|
||||
this.mvc.perform(get("/").header(HttpHeaders.ORIGIN, "https://example.com"))
|
||||
.andExpect(header().exists("Access-Control-Allow-Origin"))
|
||||
.andExpect(header().exists("X-Content-Type-Options"));
|
||||
.andExpect(header().exists("Access-Control-Allow-Origin"))
|
||||
.andExpect(header().exists("X-Content-Type-Options"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void optionsWhenCorsConfigurationSourceBeanThenRespondsWithCorsHeaders() throws Exception {
|
||||
this.spring.register(ConfigSourceConfig.class).autowire();
|
||||
this.mvc.perform(options("/")
|
||||
this.mvc
|
||||
.perform(options("/")
|
||||
.header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
|
||||
.header(HttpHeaders.ORIGIN, "https://example.com")).andExpect(status().isOk())
|
||||
.andExpect(header().exists("Access-Control-Allow-Origin"))
|
||||
.andExpect(header().exists("X-Content-Type-Options"));
|
||||
.header(HttpHeaders.ORIGIN, "https://example.com"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().exists("Access-Control-Allow-Origin"))
|
||||
.andExpect(header().exists("X-Content-Type-Options"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -131,55 +138,61 @@ public class CorsConfigurerTests {
|
||||
throws Exception {
|
||||
this.spring.register(ConfigSourceInLambdaConfig.class).autowire();
|
||||
this.mvc.perform(get("/").header(HttpHeaders.ORIGIN, "https://example.com"))
|
||||
.andExpect(header().exists("Access-Control-Allow-Origin"))
|
||||
.andExpect(header().exists("X-Content-Type-Options"));
|
||||
.andExpect(header().exists("Access-Control-Allow-Origin"))
|
||||
.andExpect(header().exists("X-Content-Type-Options"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void optionsWhenMvcCorsInLambdaConfigAndCorsConfigurationSourceBeanThenRespondsWithCorsHeaders()
|
||||
throws Exception {
|
||||
this.spring.register(ConfigSourceInLambdaConfig.class).autowire();
|
||||
this.mvc.perform(options("/")
|
||||
this.mvc
|
||||
.perform(options("/")
|
||||
.header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
|
||||
.header(HttpHeaders.ORIGIN, "https://example.com")).andExpect(status().isOk())
|
||||
.andExpect(header().exists("Access-Control-Allow-Origin"))
|
||||
.andExpect(header().exists("X-Content-Type-Options"));
|
||||
.header(HttpHeaders.ORIGIN, "https://example.com"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().exists("Access-Control-Allow-Origin"))
|
||||
.andExpect(header().exists("X-Content-Type-Options"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getWhenCorsFilterBeanThenRespondsWithCorsHeaders() throws Exception {
|
||||
this.spring.register(CorsFilterConfig.class).autowire();
|
||||
this.mvc.perform(get("/").header(HttpHeaders.ORIGIN, "https://example.com"))
|
||||
.andExpect(header().exists("Access-Control-Allow-Origin"))
|
||||
.andExpect(header().exists("X-Content-Type-Options"));
|
||||
.andExpect(header().exists("Access-Control-Allow-Origin"))
|
||||
.andExpect(header().exists("X-Content-Type-Options"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void optionsWhenCorsFilterBeanThenRespondsWithCorsHeaders() throws Exception {
|
||||
this.spring.register(CorsFilterConfig.class).autowire();
|
||||
this.mvc.perform(options("/")
|
||||
this.mvc
|
||||
.perform(options("/")
|
||||
.header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
|
||||
.header(HttpHeaders.ORIGIN, "https://example.com")).andExpect(status().isOk())
|
||||
.andExpect(header().exists("Access-Control-Allow-Origin"))
|
||||
.andExpect(header().exists("X-Content-Type-Options"));
|
||||
.header(HttpHeaders.ORIGIN, "https://example.com"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().exists("Access-Control-Allow-Origin"))
|
||||
.andExpect(header().exists("X-Content-Type-Options"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getWhenConfigSourceInLambdaConfigAndCorsFilterBeanThenRespondsWithCorsHeaders() throws Exception {
|
||||
this.spring.register(CorsFilterInLambdaConfig.class).autowire();
|
||||
this.mvc.perform(get("/").header(HttpHeaders.ORIGIN, "https://example.com"))
|
||||
.andExpect(header().exists("Access-Control-Allow-Origin"))
|
||||
.andExpect(header().exists("X-Content-Type-Options"));
|
||||
.andExpect(header().exists("Access-Control-Allow-Origin"))
|
||||
.andExpect(header().exists("X-Content-Type-Options"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void optionsWhenConfigSourceInLambdaConfigAndCorsFilterBeanThenRespondsWithCorsHeaders() throws Exception {
|
||||
this.spring.register(CorsFilterInLambdaConfig.class).autowire();
|
||||
this.mvc.perform(options("/")
|
||||
this.mvc
|
||||
.perform(options("/")
|
||||
.header(org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.POST.name())
|
||||
.header(HttpHeaders.ORIGIN, "https://example.com")).andExpect(status().isOk())
|
||||
.andExpect(header().exists("Access-Control-Allow-Origin"))
|
||||
.andExpect(header().exists("X-Content-Type-Options"));
|
||||
.header(HttpHeaders.ORIGIN, "https://example.com"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().exists("Access-Control-Allow-Origin"))
|
||||
.andExpect(header().exists("X-Content-Type-Options"));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
@@ -64,7 +64,7 @@ public class CsrfConfigurerNoWebMvcTests {
|
||||
public void overrideCsrfRequestDataValueProcessor() {
|
||||
loadContext(EnableWebOverrideRequestDataConfig.class);
|
||||
assertThat(this.context.getBean(RequestDataValueProcessor.class).getClass())
|
||||
.isNotEqualTo(CsrfRequestDataValueProcessor.class);
|
||||
.isNotEqualTo(CsrfRequestDataValueProcessor.class);
|
||||
}
|
||||
|
||||
private void loadContext(Class<?> configs) {
|
||||
|
||||
@@ -116,72 +116,72 @@ public class CsrfConfigurerTests {
|
||||
@Test
|
||||
public void postWhenWebSecurityEnabledThenRespondsWithForbidden() throws Exception {
|
||||
this.spring
|
||||
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
this.mvc.perform(post("/")).andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void putWhenWebSecurityEnabledThenRespondsWithForbidden() throws Exception {
|
||||
this.spring
|
||||
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
this.mvc.perform(put("/")).andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void patchWhenWebSecurityEnabledThenRespondsWithForbidden() throws Exception {
|
||||
this.spring
|
||||
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
this.mvc.perform(patch("/")).andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deleteWhenWebSecurityEnabledThenRespondsWithForbidden() throws Exception {
|
||||
this.spring
|
||||
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
this.mvc.perform(delete("/")).andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invalidWhenWebSecurityEnabledThenRespondsWithForbidden() throws Exception {
|
||||
this.spring
|
||||
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
this.mvc.perform(request("INVALID", URI.create("/"))).andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getWhenWebSecurityEnabledThenRespondsWithOk() throws Exception {
|
||||
this.spring
|
||||
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
this.mvc.perform(get("/")).andExpect(status().isOk());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void headWhenWebSecurityEnabledThenRespondsWithOk() throws Exception {
|
||||
this.spring
|
||||
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
this.mvc.perform(head("/")).andExpect(status().isOk());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void traceWhenWebSecurityEnabledThenRespondsWithOk() throws Exception {
|
||||
this.spring
|
||||
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
this.mvc.perform(request(HttpMethod.TRACE, "/")).andExpect(status().isOk());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void optionsWhenWebSecurityEnabledThenRespondsWithOk() throws Exception {
|
||||
this.spring
|
||||
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
this.mvc.perform(options("/")).andExpect(status().isOk());
|
||||
}
|
||||
|
||||
@@ -210,9 +210,12 @@ public class CsrfConfigurerTests {
|
||||
MvcResult mvcResult = this.mvc.perform(post("/to-save")).andReturn();
|
||||
RequestCache requestCache = new HttpSessionRequestCache();
|
||||
String redirectUrl = requestCache.getRequest(mvcResult.getRequest(), mvcResult.getResponse()).getRedirectUrl();
|
||||
this.mvc.perform(post("/login").param("username", "user").param("password", "password")
|
||||
.session((MockHttpSession) mvcResult.getRequest().getSession())).andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl(redirectUrl));
|
||||
this.mvc
|
||||
.perform(post("/login").param("username", "user")
|
||||
.param("password", "password")
|
||||
.session((MockHttpSession) mvcResult.getRequest().getSession()))
|
||||
.andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl(redirectUrl));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -220,14 +223,19 @@ public class CsrfConfigurerTests {
|
||||
CsrfDisablesPostRequestFromRequestCacheConfig.REPO = mock(CsrfTokenRepository.class);
|
||||
DefaultCsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token");
|
||||
given(CsrfDisablesPostRequestFromRequestCacheConfig.REPO.loadDeferredToken(any(HttpServletRequest.class),
|
||||
any(HttpServletResponse.class))).willReturn(new TestDeferredCsrfToken(csrfToken));
|
||||
any(HttpServletResponse.class)))
|
||||
.willReturn(new TestDeferredCsrfToken(csrfToken));
|
||||
this.spring.register(CsrfDisablesPostRequestFromRequestCacheConfig.class).autowire();
|
||||
MvcResult mvcResult = this.mvc.perform(post("/some-url")).andReturn();
|
||||
this.mvc.perform(post("/login").param("username", "user").param("password", "password").with(csrf())
|
||||
.session((MockHttpSession) mvcResult.getRequest().getSession())).andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("/"));
|
||||
this.mvc
|
||||
.perform(post("/login").param("username", "user")
|
||||
.param("password", "password")
|
||||
.with(csrf())
|
||||
.session((MockHttpSession) mvcResult.getRequest().getSession()))
|
||||
.andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("/"));
|
||||
verify(CsrfDisablesPostRequestFromRequestCacheConfig.REPO, atLeastOnce())
|
||||
.loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
.loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -235,26 +243,33 @@ public class CsrfConfigurerTests {
|
||||
CsrfDisablesPostRequestFromRequestCacheConfig.REPO = mock(CsrfTokenRepository.class);
|
||||
DefaultCsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token");
|
||||
given(CsrfDisablesPostRequestFromRequestCacheConfig.REPO.loadDeferredToken(any(HttpServletRequest.class),
|
||||
any(HttpServletResponse.class))).willReturn(new TestDeferredCsrfToken(csrfToken));
|
||||
any(HttpServletResponse.class)))
|
||||
.willReturn(new TestDeferredCsrfToken(csrfToken));
|
||||
this.spring.register(CsrfDisablesPostRequestFromRequestCacheConfig.class).autowire();
|
||||
MvcResult mvcResult = this.mvc.perform(get("/some-url")).andReturn();
|
||||
RequestCache requestCache = new HttpSessionRequestCache();
|
||||
String redirectUrl = requestCache.getRequest(mvcResult.getRequest(), mvcResult.getResponse()).getRedirectUrl();
|
||||
this.mvc.perform(post("/login").param("username", "user").param("password", "password").with(csrf())
|
||||
.session((MockHttpSession) mvcResult.getRequest().getSession())).andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl(redirectUrl));
|
||||
this.mvc
|
||||
.perform(post("/login").param("username", "user")
|
||||
.param("password", "password")
|
||||
.with(csrf())
|
||||
.session((MockHttpSession) mvcResult.getRequest().getSession()))
|
||||
.andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl(redirectUrl));
|
||||
verify(CsrfDisablesPostRequestFromRequestCacheConfig.REPO, atLeastOnce())
|
||||
.loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
.loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
}
|
||||
|
||||
// SEC-2422
|
||||
@Test
|
||||
public void postWhenCsrfEnabledAndSessionIsExpiredThenRespondsWithForbidden() throws Exception {
|
||||
this.spring.register(InvalidSessionUrlConfig.class).autowire();
|
||||
MvcResult mvcResult = this.mvc.perform(post("/").param("_csrf", "abc")).andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("/error/sessionError")).andReturn();
|
||||
MvcResult mvcResult = this.mvc.perform(post("/").param("_csrf", "abc"))
|
||||
.andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("/error/sessionError"))
|
||||
.andReturn();
|
||||
this.mvc.perform(post("/").session((MockHttpSession) mvcResult.getRequest().getSession()))
|
||||
.andExpect(status().isForbidden());
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -293,7 +308,7 @@ public class CsrfConfigurerTests {
|
||||
CsrfTokenRepositoryConfig.REPO = mock(CsrfTokenRepository.class);
|
||||
given(CsrfTokenRepositoryConfig.REPO.loadDeferredToken(any(HttpServletRequest.class),
|
||||
any(HttpServletResponse.class)))
|
||||
.willReturn(new TestDeferredCsrfToken(new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token")));
|
||||
.willReturn(new TestDeferredCsrfToken(new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token")));
|
||||
this.spring.register(CsrfTokenRepositoryConfig.class, BasicController.class).autowire();
|
||||
this.mvc.perform(post("/"));
|
||||
verify(CsrfTokenRepositoryConfig.REPO).loadDeferredToken(any(HttpServletRequest.class),
|
||||
@@ -315,7 +330,8 @@ public class CsrfConfigurerTests {
|
||||
DefaultCsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token");
|
||||
given(CsrfTokenRepositoryConfig.REPO.loadToken(any())).willReturn(csrfToken);
|
||||
given(CsrfTokenRepositoryConfig.REPO.loadDeferredToken(any(HttpServletRequest.class),
|
||||
any(HttpServletResponse.class))).willReturn(new TestDeferredCsrfToken(csrfToken));
|
||||
any(HttpServletResponse.class)))
|
||||
.willReturn(new TestDeferredCsrfToken(csrfToken));
|
||||
this.spring.register(CsrfTokenRepositoryConfig.class, BasicController.class).autowire();
|
||||
// @formatter:off
|
||||
MockHttpServletRequestBuilder loginRequest = post("/login")
|
||||
@@ -334,7 +350,7 @@ public class CsrfConfigurerTests {
|
||||
CsrfTokenRepositoryInLambdaConfig.REPO = mock(CsrfTokenRepository.class);
|
||||
given(CsrfTokenRepositoryInLambdaConfig.REPO.loadDeferredToken(any(HttpServletRequest.class),
|
||||
any(HttpServletResponse.class)))
|
||||
.willReturn(new TestDeferredCsrfToken(new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token")));
|
||||
.willReturn(new TestDeferredCsrfToken(new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token")));
|
||||
this.spring.register(CsrfTokenRepositoryInLambdaConfig.class, BasicController.class).autowire();
|
||||
this.mvc.perform(post("/"));
|
||||
verify(CsrfTokenRepositoryInLambdaConfig.REPO).loadDeferredToken(any(HttpServletRequest.class),
|
||||
@@ -404,8 +420,8 @@ public class CsrfConfigurerTests {
|
||||
@Test
|
||||
public void configureWhenRequireCsrfProtectionMatcherNullThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(NullRequireCsrfProtectionMatcherConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
.isThrownBy(() -> this.spring.register(NullRequireCsrfProtectionMatcherConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -418,8 +434,8 @@ public class CsrfConfigurerTests {
|
||||
@Test
|
||||
public void getWhenNullAuthenticationStrategyThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(NullAuthenticationStrategy.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
.isThrownBy(() -> this.spring.register(NullAuthenticationStrategy.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -442,12 +458,13 @@ public class CsrfConfigurerTests {
|
||||
CsrfTokenRepository csrfTokenRepository = mock(CsrfTokenRepository.class);
|
||||
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token");
|
||||
given(csrfTokenRepository.loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class)))
|
||||
.willReturn(new TestDeferredCsrfToken(csrfToken));
|
||||
.willReturn(new TestDeferredCsrfToken(csrfToken));
|
||||
CsrfTokenRequestHandlerConfig.REPO = csrfTokenRepository;
|
||||
CsrfTokenRequestHandlerConfig.HANDLER = new CsrfTokenRequestAttributeHandler();
|
||||
this.spring.register(CsrfTokenRequestHandlerConfig.class, BasicController.class).autowire();
|
||||
this.mvc.perform(get("/login")).andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString(csrfToken.getToken())));
|
||||
this.mvc.perform(get("/login"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(containsString(csrfToken.getToken())));
|
||||
verify(csrfTokenRepository).loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
verifyNoMoreInteractions(csrfTokenRepository);
|
||||
}
|
||||
@@ -458,7 +475,7 @@ public class CsrfConfigurerTests {
|
||||
CsrfTokenRepository csrfTokenRepository = mock(CsrfTokenRepository.class);
|
||||
given(csrfTokenRepository.loadToken(any(HttpServletRequest.class))).willReturn(csrfToken);
|
||||
given(csrfTokenRepository.loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class)))
|
||||
.willReturn(new TestDeferredCsrfToken(csrfToken));
|
||||
.willReturn(new TestDeferredCsrfToken(csrfToken));
|
||||
CsrfTokenRequestHandlerConfig.REPO = csrfTokenRepository;
|
||||
CsrfTokenRequestHandlerConfig.HANDLER = new CsrfTokenRequestAttributeHandler();
|
||||
this.spring.register(CsrfTokenRequestHandlerConfig.class, BasicController.class).autowire();
|
||||
@@ -482,12 +499,13 @@ public class CsrfConfigurerTests {
|
||||
CsrfTokenRepository csrfTokenRepository = mock(CsrfTokenRepository.class);
|
||||
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "token");
|
||||
given(csrfTokenRepository.loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class)))
|
||||
.willReturn(new TestDeferredCsrfToken(csrfToken));
|
||||
.willReturn(new TestDeferredCsrfToken(csrfToken));
|
||||
CsrfTokenRequestHandlerConfig.REPO = csrfTokenRepository;
|
||||
CsrfTokenRequestHandlerConfig.HANDLER = new XorCsrfTokenRequestAttributeHandler();
|
||||
this.spring.register(CsrfTokenRequestHandlerConfig.class, BasicController.class).autowire();
|
||||
this.mvc.perform(get("/login")).andExpect(status().isOk())
|
||||
.andExpect(content().string(not(containsString(csrfToken.getToken()))));
|
||||
this.mvc.perform(get("/login"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(not(containsString(csrfToken.getToken()))));
|
||||
verify(csrfTokenRepository).loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
verifyNoMoreInteractions(csrfTokenRepository);
|
||||
}
|
||||
@@ -498,7 +516,7 @@ public class CsrfConfigurerTests {
|
||||
CsrfTokenRepository csrfTokenRepository = mock(CsrfTokenRepository.class);
|
||||
given(csrfTokenRepository.loadToken(any(HttpServletRequest.class))).willReturn(csrfToken);
|
||||
given(csrfTokenRepository.loadDeferredToken(any(HttpServletRequest.class), any(HttpServletResponse.class)))
|
||||
.willReturn(new TestDeferredCsrfToken(csrfToken));
|
||||
.willReturn(new TestDeferredCsrfToken(csrfToken));
|
||||
CsrfTokenRequestHandlerConfig.REPO = csrfTokenRepository;
|
||||
CsrfTokenRequestHandlerConfig.HANDLER = new XorCsrfTokenRequestAttributeHandler();
|
||||
this.spring.register(CsrfTokenRequestHandlerConfig.class, BasicController.class).autowire();
|
||||
|
||||
@@ -82,29 +82,35 @@ public class DefaultFiltersTests {
|
||||
@Test
|
||||
public void nullWebInvocationPrivilegeEvaluator() {
|
||||
this.spring.register(NullWebInvocationPrivilegeEvaluatorConfig.class, UserDetailsServiceConfig.class);
|
||||
List<SecurityFilterChain> filterChains = this.spring.getContext().getBean(FilterChainProxy.class)
|
||||
.getFilterChains();
|
||||
List<SecurityFilterChain> filterChains = this.spring.getContext()
|
||||
.getBean(FilterChainProxy.class)
|
||||
.getFilterChains();
|
||||
assertThat(filterChains).hasSize(1);
|
||||
DefaultSecurityFilterChain filterChain = (DefaultSecurityFilterChain) filterChains.get(0);
|
||||
assertThat(filterChain.getRequestMatcher()).isInstanceOf(AnyRequestMatcher.class);
|
||||
assertThat(filterChain.getFilters()).hasSize(1);
|
||||
long filter = filterChain.getFilters().stream()
|
||||
.filter((it) -> it instanceof UsernamePasswordAuthenticationFilter).count();
|
||||
long filter = filterChain.getFilters()
|
||||
.stream()
|
||||
.filter((it) -> it instanceof UsernamePasswordAuthenticationFilter)
|
||||
.count();
|
||||
assertThat(filter).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void filterChainProxyBuilderIgnoringResources() {
|
||||
this.spring.register(FilterChainProxyBuilderIgnoringConfig.class, UserDetailsServiceConfig.class);
|
||||
List<SecurityFilterChain> filterChains = this.spring.getContext().getBean(FilterChainProxy.class)
|
||||
.getFilterChains();
|
||||
List<SecurityFilterChain> filterChains = this.spring.getContext()
|
||||
.getBean(FilterChainProxy.class)
|
||||
.getFilterChains();
|
||||
assertThat(filterChains).hasSize(2);
|
||||
DefaultSecurityFilterChain firstFilter = (DefaultSecurityFilterChain) filterChains.get(0);
|
||||
DefaultSecurityFilterChain secondFilter = (DefaultSecurityFilterChain) filterChains.get(1);
|
||||
assertThat(firstFilter.getFilters().isEmpty()).isEqualTo(true);
|
||||
assertThat(secondFilter.getRequestMatcher()).isInstanceOf(AnyRequestMatcher.class);
|
||||
List<Class<? extends Filter>> classes = secondFilter.getFilters().stream().map(Filter::getClass)
|
||||
.collect(Collectors.toList());
|
||||
List<Class<? extends Filter>> classes = secondFilter.getFilters()
|
||||
.stream()
|
||||
.map(Filter::getClass)
|
||||
.collect(Collectors.toList());
|
||||
assertThat(classes).contains(WebAsyncManagerIntegrationFilter.class);
|
||||
assertThat(classes).contains(SecurityContextHolderFilter.class);
|
||||
assertThat(classes).contains(HeaderWriterFilter.class);
|
||||
@@ -130,8 +136,9 @@ public class DefaultFiltersTests {
|
||||
handler.handle(request, response, () -> csrfToken);
|
||||
CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
|
||||
request.setParameter(token.getParameterName(), token.getToken());
|
||||
this.spring.getContext().getBean("springSecurityFilterChain", Filter.class).doFilter(request, response,
|
||||
new MockFilterChain());
|
||||
this.spring.getContext()
|
||||
.getBean("springSecurityFilterChain", Filter.class)
|
||||
.doFilter(request, response, new MockFilterChain());
|
||||
assertThat(response.getRedirectedUrl()).isEqualTo("/login?logout");
|
||||
}
|
||||
|
||||
|
||||
@@ -286,7 +286,7 @@ public class DefaultLoginPageConfigurerTests {
|
||||
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
|
||||
this.spring.register(ObjectPostProcessorConfig.class).autowire();
|
||||
verify(ObjectPostProcessorConfig.objectPostProcessor)
|
||||
.postProcess(any(UsernamePasswordAuthenticationFilter.class));
|
||||
.postProcess(any(UsernamePasswordAuthenticationFilter.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -307,9 +307,12 @@ public class DefaultLoginPageConfigurerTests {
|
||||
public void configureWhenAuthenticationEntryPointThenNoDefaultLoginPageGeneratingFilter() {
|
||||
this.spring.register(DefaultLoginWithCustomAuthenticationEntryPointConfig.class).autowire();
|
||||
FilterChainProxy filterChain = this.spring.getContext().getBean(FilterChainProxy.class);
|
||||
assertThat(filterChain.getFilterChains().get(0).getFilters().stream()
|
||||
.filter((filter) -> filter.getClass().isAssignableFrom(DefaultLoginPageGeneratingFilter.class)).count())
|
||||
.isZero();
|
||||
assertThat(filterChain.getFilterChains()
|
||||
.get(0)
|
||||
.getFilters()
|
||||
.stream()
|
||||
.filter((filter) -> filter.getClass().isAssignableFrom(DefaultLoginPageGeneratingFilter.class))
|
||||
.count()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -81,7 +81,7 @@ public class ExceptionHandlingConfigurerAccessDeniedHandlerTests {
|
||||
static class RequestMatcherBasedAccessDeniedHandlerConfig {
|
||||
|
||||
AccessDeniedHandler teapotDeniedHandler = (request, response, exception) -> response
|
||||
.setStatus(HttpStatus.I_AM_A_TEAPOT.value());
|
||||
.setStatus(HttpStatus.I_AM_A_TEAPOT.value());
|
||||
|
||||
@Bean
|
||||
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
@@ -108,7 +108,7 @@ public class ExceptionHandlingConfigurerAccessDeniedHandlerTests {
|
||||
static class RequestMatcherBasedAccessDeniedHandlerInLambdaConfig {
|
||||
|
||||
AccessDeniedHandler teapotDeniedHandler = (request, response, exception) -> response
|
||||
.setStatus(HttpStatus.I_AM_A_TEAPOT.value());
|
||||
.setStatus(HttpStatus.I_AM_A_TEAPOT.value());
|
||||
|
||||
@Bean
|
||||
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
@@ -140,7 +140,7 @@ public class ExceptionHandlingConfigurerAccessDeniedHandlerTests {
|
||||
static class SingleRequestMatcherAccessDeniedHandlerConfig {
|
||||
|
||||
AccessDeniedHandler teapotDeniedHandler = (request, response, exception) -> response
|
||||
.setStatus(HttpStatus.I_AM_A_TEAPOT.value());
|
||||
.setStatus(HttpStatus.I_AM_A_TEAPOT.value());
|
||||
|
||||
@Bean
|
||||
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
|
||||
@@ -82,7 +82,7 @@ public class ExceptionHandlingConfigurerTests {
|
||||
public void getWhenAcceptHeaderIsApplicationXhtmlXmlThenRespondsWith302() throws Exception {
|
||||
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
|
||||
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XHTML_XML))
|
||||
.andExpect(status().isFound());
|
||||
.andExpect(status().isFound());
|
||||
}
|
||||
|
||||
// SEC-2199
|
||||
@@ -125,7 +125,7 @@ public class ExceptionHandlingConfigurerTests {
|
||||
public void getWhenAcceptHeaderIsApplicationAtomXmlThenRespondsWith401() throws Exception {
|
||||
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
|
||||
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_ATOM_XML))
|
||||
.andExpect(status().isUnauthorized());
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
// SEC-2199
|
||||
@@ -133,7 +133,7 @@ public class ExceptionHandlingConfigurerTests {
|
||||
public void getWhenAcceptHeaderIsApplicationFormUrlEncodedThenRespondsWith401() throws Exception {
|
||||
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
|
||||
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_FORM_URLENCODED))
|
||||
.andExpect(status().isUnauthorized());
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
// SEC-2199
|
||||
@@ -141,7 +141,7 @@ public class ExceptionHandlingConfigurerTests {
|
||||
public void getWhenAcceptHeaderIsApplicationJsonThenRespondsWith401() throws Exception {
|
||||
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
|
||||
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isUnauthorized());
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
// SEC-2199
|
||||
@@ -149,7 +149,7 @@ public class ExceptionHandlingConfigurerTests {
|
||||
public void getWhenAcceptHeaderIsApplicationOctetStreamThenRespondsWith401() throws Exception {
|
||||
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
|
||||
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_OCTET_STREAM))
|
||||
.andExpect(status().isUnauthorized());
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
// SEC-2199
|
||||
@@ -157,7 +157,7 @@ public class ExceptionHandlingConfigurerTests {
|
||||
public void getWhenAcceptHeaderIsMultipartFormDataThenRespondsWith401() throws Exception {
|
||||
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
|
||||
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.MULTIPART_FORM_DATA))
|
||||
.andExpect(status().isUnauthorized());
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
// SEC-2199
|
||||
@@ -177,25 +177,26 @@ public class ExceptionHandlingConfigurerTests {
|
||||
@Test
|
||||
public void getWhenAcceptIsChromeThenRespondsWith302() throws Exception {
|
||||
this.spring.register(DefaultSecurityConfig.class).autowire();
|
||||
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT,
|
||||
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"))
|
||||
.andExpect(status().isFound());
|
||||
this.mvc
|
||||
.perform(get("/").header(HttpHeaders.ACCEPT,
|
||||
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"))
|
||||
.andExpect(status().isFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getWhenAcceptIsTextPlainAndXRequestedWithIsXHRThenRespondsWith401() throws Exception {
|
||||
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
|
||||
this.mvc.perform(get("/").header("Accept", MediaType.TEXT_PLAIN).header("X-Requested-With", "XMLHttpRequest"))
|
||||
.andExpect(status().isUnauthorized());
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getWhenCustomContentNegotiationStrategyThenStrategyIsUsed() throws Exception {
|
||||
this.spring.register(OverrideContentNegotiationStrategySharedObjectConfig.class, DefaultSecurityConfig.class)
|
||||
.autowire();
|
||||
.autowire();
|
||||
this.mvc.perform(get("/"));
|
||||
verify(OverrideContentNegotiationStrategySharedObjectConfig.CNS, atLeastOnce())
|
||||
.resolveMediaTypes(any(NativeWebRequest.class));
|
||||
.resolveMediaTypes(any(NativeWebRequest.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -205,7 +206,7 @@ public class ExceptionHandlingConfigurerTests {
|
||||
SecurityContextHolderStrategy strategy = this.spring.getContext().getBean(SecurityContextHolderStrategy.class);
|
||||
verify(strategy, atLeastOnce()).getContext();
|
||||
SecurityContextChangedListener listener = this.spring.getContext()
|
||||
.getBean(SecurityContextChangedListener.class);
|
||||
.getBean(SecurityContextChangedListener.class);
|
||||
verify(listener).securityContextChanged(setAuthentication(AnonymousAuthenticationToken.class));
|
||||
}
|
||||
|
||||
@@ -213,7 +214,7 @@ public class ExceptionHandlingConfigurerTests {
|
||||
public void getWhenUsingDefaultsAndUnauthenticatedThenRedirectsToLogin() throws Exception {
|
||||
this.spring.register(DefaultHttpConfig.class).autowire();
|
||||
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, "bogus/type"))
|
||||
.andExpect(redirectedUrl("http://localhost/login"));
|
||||
.andExpect(redirectedUrl("http://localhost/login"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -95,9 +95,10 @@ public class ExpressionUrlAuthorizationConfigurerTests {
|
||||
@Test
|
||||
public void configureWhenHasRoleStartingWithStringRoleThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(HasRoleStartingWithRoleConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class).withMessageContaining(
|
||||
"role should not start with 'ROLE_' since it is automatically inserted. Got 'ROLE_USER'");
|
||||
.isThrownBy(() -> this.spring.register(HasRoleStartingWithRoleConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class)
|
||||
.withMessageContaining(
|
||||
"role should not start with 'ROLE_' since it is automatically inserted. Got 'ROLE_USER'");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -109,15 +110,16 @@ public class ExpressionUrlAuthorizationConfigurerTests {
|
||||
@Test
|
||||
public void configureWhenAuthorizedRequestsAndNoRequestsThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(NoRequestsConfig.class).autowire()).withMessageContaining(
|
||||
"At least one mapping is required (i.e. authorizeRequests().anyRequest().authenticated())");
|
||||
.isThrownBy(() -> this.spring.register(NoRequestsConfig.class).autowire())
|
||||
.withMessageContaining(
|
||||
"At least one mapping is required (i.e. authorizeRequests().anyRequest().authenticated())");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configureWhenAnyRequestIncompleteMappingThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(IncompleteMappingConfig.class).autowire())
|
||||
.withMessageContaining("An incomplete mapping was found for ");
|
||||
.isThrownBy(() -> this.spring.register(IncompleteMappingConfig.class).autowire())
|
||||
.withMessageContaining("An incomplete mapping was found for ");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -120,7 +120,7 @@ public class FormLoginConfigurerTests {
|
||||
SecurityContextHolderStrategy strategy = this.spring.getContext().getBean(SecurityContextHolderStrategy.class);
|
||||
verify(strategy, atLeastOnce()).getContext();
|
||||
SecurityContextChangedListener listener = this.spring.getContext()
|
||||
.getBean(SecurityContextChangedListener.class);
|
||||
.getBean(SecurityContextChangedListener.class);
|
||||
verify(listener).securityContextChanged(setAuthentication(UsernamePasswordAuthenticationToken.class));
|
||||
}
|
||||
|
||||
@@ -361,7 +361,7 @@ public class FormLoginConfigurerTests {
|
||||
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
|
||||
this.spring.register(ObjectPostProcessorConfig.class).autowire();
|
||||
verify(ObjectPostProcessorConfig.objectPostProcessor)
|
||||
.postProcess(any(UsernamePasswordAuthenticationFilter.class));
|
||||
.postProcess(any(UsernamePasswordAuthenticationFilter.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -618,7 +618,8 @@ public class FormLoginConfigurerTests {
|
||||
.portMapper(PORT_MAPPER);
|
||||
// @formatter:on
|
||||
LoginUrlAuthenticationEntryPoint authenticationEntryPoint = (LoginUrlAuthenticationEntryPoint) http
|
||||
.getConfigurer(FormLoginConfigurer.class).getAuthenticationEntryPoint();
|
||||
.getConfigurer(FormLoginConfigurer.class)
|
||||
.getAuthenticationEntryPoint();
|
||||
authenticationEntryPoint.setForceHttps(true);
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@@ -53,13 +53,14 @@ public class HeadersConfigurerEagerHeadersTests {
|
||||
@Test
|
||||
public void requestWhenHeadersEagerlyConfiguredThenHeadersAreWritten() throws Exception {
|
||||
this.spring.register(HeadersAtTheBeginningOfRequestConfig.class, HomeController.class).autowire();
|
||||
this.mvc.perform(get("/").secure(true)).andExpect(header().string("X-Content-Type-Options", "nosniff"))
|
||||
.andExpect(header().string("X-Frame-Options", "DENY"))
|
||||
.andExpect(header().string("Strict-Transport-Security", "max-age=31536000 ; includeSubDomains"))
|
||||
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate"))
|
||||
.andExpect(header().string(HttpHeaders.EXPIRES, "0"))
|
||||
.andExpect(header().string(HttpHeaders.PRAGMA, "no-cache"))
|
||||
.andExpect(header().string("X-XSS-Protection", "0"));
|
||||
this.mvc.perform(get("/").secure(true))
|
||||
.andExpect(header().string("X-Content-Type-Options", "nosniff"))
|
||||
.andExpect(header().string("X-Frame-Options", "DENY"))
|
||||
.andExpect(header().string("Strict-Transport-Security", "max-age=31536000 ; includeSubDomains"))
|
||||
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate"))
|
||||
.andExpect(header().string(HttpHeaders.EXPIRES, "0"))
|
||||
.andExpect(header().string(HttpHeaders.PRAGMA, "no-cache"))
|
||||
.andExpect(header().string("X-XSS-Protection", "0"));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
@@ -73,14 +73,14 @@ public class HeadersConfigurerTests {
|
||||
public void getWhenHeadersConfiguredThenDefaultHeadersInResponse() throws Exception {
|
||||
this.spring.register(HeadersConfig.class).autowire();
|
||||
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
|
||||
.andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff"))
|
||||
.andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.DENY.name()))
|
||||
.andExpect(
|
||||
header().string(HttpHeaders.STRICT_TRANSPORT_SECURITY, "max-age=31536000 ; includeSubDomains"))
|
||||
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate"))
|
||||
.andExpect(header().string(HttpHeaders.EXPIRES, "0"))
|
||||
.andExpect(header().string(HttpHeaders.PRAGMA, "no-cache"))
|
||||
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "0")).andReturn();
|
||||
.andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff"))
|
||||
.andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.DENY.name()))
|
||||
.andExpect(header().string(HttpHeaders.STRICT_TRANSPORT_SECURITY, "max-age=31536000 ; includeSubDomains"))
|
||||
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate"))
|
||||
.andExpect(header().string(HttpHeaders.EXPIRES, "0"))
|
||||
.andExpect(header().string(HttpHeaders.PRAGMA, "no-cache"))
|
||||
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "0"))
|
||||
.andReturn();
|
||||
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactlyInAnyOrder(
|
||||
HttpHeaders.X_CONTENT_TYPE_OPTIONS, HttpHeaders.X_FRAME_OPTIONS, HttpHeaders.STRICT_TRANSPORT_SECURITY,
|
||||
HttpHeaders.CACHE_CONTROL, HttpHeaders.EXPIRES, HttpHeaders.PRAGMA, HttpHeaders.X_XSS_PROTECTION);
|
||||
@@ -90,14 +90,14 @@ public class HeadersConfigurerTests {
|
||||
public void getWhenHeadersConfiguredInLambdaThenDefaultHeadersInResponse() throws Exception {
|
||||
this.spring.register(HeadersInLambdaConfig.class).autowire();
|
||||
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
|
||||
.andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff"))
|
||||
.andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.DENY.name()))
|
||||
.andExpect(
|
||||
header().string(HttpHeaders.STRICT_TRANSPORT_SECURITY, "max-age=31536000 ; includeSubDomains"))
|
||||
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate"))
|
||||
.andExpect(header().string(HttpHeaders.EXPIRES, "0"))
|
||||
.andExpect(header().string(HttpHeaders.PRAGMA, "no-cache"))
|
||||
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "0")).andReturn();
|
||||
.andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff"))
|
||||
.andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.DENY.name()))
|
||||
.andExpect(header().string(HttpHeaders.STRICT_TRANSPORT_SECURITY, "max-age=31536000 ; includeSubDomains"))
|
||||
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate"))
|
||||
.andExpect(header().string(HttpHeaders.EXPIRES, "0"))
|
||||
.andExpect(header().string(HttpHeaders.PRAGMA, "no-cache"))
|
||||
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "0"))
|
||||
.andReturn();
|
||||
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactlyInAnyOrder(
|
||||
HttpHeaders.X_CONTENT_TYPE_OPTIONS, HttpHeaders.X_FRAME_OPTIONS, HttpHeaders.STRICT_TRANSPORT_SECURITY,
|
||||
HttpHeaders.CACHE_CONTROL, HttpHeaders.EXPIRES, HttpHeaders.PRAGMA, HttpHeaders.X_XSS_PROTECTION);
|
||||
@@ -108,7 +108,8 @@ public class HeadersConfigurerTests {
|
||||
throws Exception {
|
||||
this.spring.register(ContentTypeOptionsConfig.class).autowire();
|
||||
MvcResult mvcResult = this.mvc.perform(get("/"))
|
||||
.andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff")).andReturn();
|
||||
.andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff"))
|
||||
.andReturn();
|
||||
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_CONTENT_TYPE_OPTIONS);
|
||||
}
|
||||
|
||||
@@ -116,7 +117,8 @@ public class HeadersConfigurerTests {
|
||||
public void getWhenOnlyContentTypeConfiguredInLambdaThenOnlyContentTypeHeaderInResponse() throws Exception {
|
||||
this.spring.register(ContentTypeOptionsInLambdaConfig.class).autowire();
|
||||
MvcResult mvcResult = this.mvc.perform(get("/"))
|
||||
.andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff")).andReturn();
|
||||
.andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff"))
|
||||
.andReturn();
|
||||
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_CONTENT_TYPE_OPTIONS);
|
||||
}
|
||||
|
||||
@@ -125,7 +127,8 @@ public class HeadersConfigurerTests {
|
||||
throws Exception {
|
||||
this.spring.register(FrameOptionsConfig.class).autowire();
|
||||
MvcResult mvcResult = this.mvc.perform(get("/"))
|
||||
.andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.DENY.name())).andReturn();
|
||||
.andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.DENY.name()))
|
||||
.andReturn();
|
||||
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_FRAME_OPTIONS);
|
||||
}
|
||||
|
||||
@@ -134,9 +137,8 @@ public class HeadersConfigurerTests {
|
||||
throws Exception {
|
||||
this.spring.register(HstsConfig.class).autowire();
|
||||
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
|
||||
.andExpect(
|
||||
header().string(HttpHeaders.STRICT_TRANSPORT_SECURITY, "max-age=31536000 ; includeSubDomains"))
|
||||
.andReturn();
|
||||
.andExpect(header().string(HttpHeaders.STRICT_TRANSPORT_SECURITY, "max-age=31536000 ; includeSubDomains"))
|
||||
.andReturn();
|
||||
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.STRICT_TRANSPORT_SECURITY);
|
||||
}
|
||||
|
||||
@@ -145,9 +147,10 @@ public class HeadersConfigurerTests {
|
||||
throws Exception {
|
||||
this.spring.register(CacheControlConfig.class).autowire();
|
||||
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
|
||||
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate"))
|
||||
.andExpect(header().string(HttpHeaders.EXPIRES, "0"))
|
||||
.andExpect(header().string(HttpHeaders.PRAGMA, "no-cache")).andReturn();
|
||||
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate"))
|
||||
.andExpect(header().string(HttpHeaders.EXPIRES, "0"))
|
||||
.andExpect(header().string(HttpHeaders.PRAGMA, "no-cache"))
|
||||
.andReturn();
|
||||
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactlyInAnyOrder(HttpHeaders.CACHE_CONTROL,
|
||||
HttpHeaders.EXPIRES, HttpHeaders.PRAGMA);
|
||||
}
|
||||
@@ -157,9 +160,10 @@ public class HeadersConfigurerTests {
|
||||
throws Exception {
|
||||
this.spring.register(CacheControlInLambdaConfig.class).autowire();
|
||||
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
|
||||
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate"))
|
||||
.andExpect(header().string(HttpHeaders.EXPIRES, "0"))
|
||||
.andExpect(header().string(HttpHeaders.PRAGMA, "no-cache")).andReturn();
|
||||
.andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0, must-revalidate"))
|
||||
.andExpect(header().string(HttpHeaders.EXPIRES, "0"))
|
||||
.andExpect(header().string(HttpHeaders.PRAGMA, "no-cache"))
|
||||
.andReturn();
|
||||
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactlyInAnyOrder(HttpHeaders.CACHE_CONTROL,
|
||||
HttpHeaders.EXPIRES, HttpHeaders.PRAGMA);
|
||||
}
|
||||
@@ -169,7 +173,8 @@ public class HeadersConfigurerTests {
|
||||
throws Exception {
|
||||
this.spring.register(XssProtectionConfig.class).autowire();
|
||||
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
|
||||
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "0")).andReturn();
|
||||
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "0"))
|
||||
.andReturn();
|
||||
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_XSS_PROTECTION);
|
||||
}
|
||||
|
||||
@@ -178,7 +183,8 @@ public class HeadersConfigurerTests {
|
||||
throws Exception {
|
||||
this.spring.register(XssProtectionValueEnabledModeBlockConfig.class).autowire();
|
||||
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
|
||||
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "1; mode=block")).andReturn();
|
||||
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "1; mode=block"))
|
||||
.andReturn();
|
||||
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_XSS_PROTECTION);
|
||||
}
|
||||
|
||||
@@ -186,7 +192,8 @@ public class HeadersConfigurerTests {
|
||||
public void getWhenOnlyXssProtectionConfiguredInLambdaThenOnlyXssProtectionHeaderInResponse() throws Exception {
|
||||
this.spring.register(XssProtectionInLambdaConfig.class).autowire();
|
||||
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
|
||||
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "0")).andReturn();
|
||||
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "0"))
|
||||
.andReturn();
|
||||
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_XSS_PROTECTION);
|
||||
}
|
||||
|
||||
@@ -195,7 +202,8 @@ public class HeadersConfigurerTests {
|
||||
throws Exception {
|
||||
this.spring.register(XssProtectionValueEnabledModeBlockInLambdaConfig.class).autowire();
|
||||
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
|
||||
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "1; mode=block")).andReturn();
|
||||
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "1; mode=block"))
|
||||
.andReturn();
|
||||
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_XSS_PROTECTION);
|
||||
}
|
||||
|
||||
@@ -203,8 +211,8 @@ public class HeadersConfigurerTests {
|
||||
public void getWhenFrameOptionsSameOriginConfiguredThenFrameOptionsHeaderHasValueSameOrigin() throws Exception {
|
||||
this.spring.register(HeadersCustomSameOriginConfig.class).autowire();
|
||||
this.mvc.perform(get("/").secure(true))
|
||||
.andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.SAMEORIGIN.name()))
|
||||
.andReturn();
|
||||
.andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.SAMEORIGIN.name()))
|
||||
.andReturn();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -212,8 +220,8 @@ public class HeadersConfigurerTests {
|
||||
throws Exception {
|
||||
this.spring.register(HeadersCustomSameOriginInLambdaConfig.class).autowire();
|
||||
this.mvc.perform(get("/").secure(true))
|
||||
.andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.SAMEORIGIN.name()))
|
||||
.andReturn();
|
||||
.andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS, XFrameOptionsMode.SAMEORIGIN.name()))
|
||||
.andReturn();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -362,7 +370,7 @@ public class HeadersConfigurerTests {
|
||||
.andReturn();
|
||||
// @formatter:on
|
||||
assertThat(mvcResult.getResponse().getHeaderNames())
|
||||
.containsExactly(HttpHeaders.CONTENT_SECURITY_POLICY_REPORT_ONLY);
|
||||
.containsExactly(HttpHeaders.CONTENT_SECURITY_POLICY_REPORT_ONLY);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -377,21 +385,21 @@ public class HeadersConfigurerTests {
|
||||
.andReturn();
|
||||
// @formatter:on
|
||||
assertThat(mvcResult.getResponse().getHeaderNames())
|
||||
.containsExactly(HttpHeaders.CONTENT_SECURITY_POLICY_REPORT_ONLY);
|
||||
.containsExactly(HttpHeaders.CONTENT_SECURITY_POLICY_REPORT_ONLY);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configureWhenContentSecurityPolicyEmptyThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(ContentSecurityPolicyInvalidConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
.isThrownBy(() -> this.spring.register(ContentSecurityPolicyInvalidConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configureWhenContentSecurityPolicyEmptyInLambdaThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(ContentSecurityPolicyInvalidInLambdaConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
.isThrownBy(() -> this.spring.register(ContentSecurityPolicyInvalidInLambdaConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -470,8 +478,8 @@ public class HeadersConfigurerTests {
|
||||
@Test
|
||||
public void configureWhenFeaturePolicyEmptyThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(FeaturePolicyInvalidConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
.isThrownBy(() -> this.spring.register(FeaturePolicyInvalidConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -501,15 +509,15 @@ public class HeadersConfigurerTests {
|
||||
@Test
|
||||
public void configureWhenPermissionsPolicyEmptyThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(PermissionsPolicyInvalidConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
.isThrownBy(() -> this.spring.register(PermissionsPolicyInvalidConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configureWhenPermissionsPolicyStringEmptyThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(PermissionsPolicyInvalidStringConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
.isThrownBy(() -> this.spring.register(PermissionsPolicyInvalidStringConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -545,9 +553,10 @@ public class HeadersConfigurerTests {
|
||||
throws Exception {
|
||||
this.spring.register(CrossOriginCustomPoliciesInLambdaConfig.class).autowire();
|
||||
MvcResult mvcResult = this.mvc.perform(get("/"))
|
||||
.andExpect(header().string(HttpHeaders.CROSS_ORIGIN_OPENER_POLICY, "same-origin"))
|
||||
.andExpect(header().string(HttpHeaders.CROSS_ORIGIN_EMBEDDER_POLICY, "require-corp"))
|
||||
.andExpect(header().string(HttpHeaders.CROSS_ORIGIN_RESOURCE_POLICY, "same-origin")).andReturn();
|
||||
.andExpect(header().string(HttpHeaders.CROSS_ORIGIN_OPENER_POLICY, "same-origin"))
|
||||
.andExpect(header().string(HttpHeaders.CROSS_ORIGIN_EMBEDDER_POLICY, "require-corp"))
|
||||
.andExpect(header().string(HttpHeaders.CROSS_ORIGIN_RESOURCE_POLICY, "same-origin"))
|
||||
.andReturn();
|
||||
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.CROSS_ORIGIN_OPENER_POLICY,
|
||||
HttpHeaders.CROSS_ORIGIN_EMBEDDER_POLICY, HttpHeaders.CROSS_ORIGIN_RESOURCE_POLICY);
|
||||
}
|
||||
@@ -557,9 +566,10 @@ public class HeadersConfigurerTests {
|
||||
throws Exception {
|
||||
this.spring.register(CrossOriginCustomPoliciesConfig.class).autowire();
|
||||
MvcResult mvcResult = this.mvc.perform(get("/"))
|
||||
.andExpect(header().string(HttpHeaders.CROSS_ORIGIN_OPENER_POLICY, "same-origin"))
|
||||
.andExpect(header().string(HttpHeaders.CROSS_ORIGIN_EMBEDDER_POLICY, "require-corp"))
|
||||
.andExpect(header().string(HttpHeaders.CROSS_ORIGIN_RESOURCE_POLICY, "same-origin")).andReturn();
|
||||
.andExpect(header().string(HttpHeaders.CROSS_ORIGIN_OPENER_POLICY, "same-origin"))
|
||||
.andExpect(header().string(HttpHeaders.CROSS_ORIGIN_EMBEDDER_POLICY, "require-corp"))
|
||||
.andExpect(header().string(HttpHeaders.CROSS_ORIGIN_RESOURCE_POLICY, "same-origin"))
|
||||
.andReturn();
|
||||
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.CROSS_ORIGIN_OPENER_POLICY,
|
||||
HttpHeaders.CROSS_ORIGIN_EMBEDDER_POLICY, HttpHeaders.CROSS_ORIGIN_RESOURCE_POLICY);
|
||||
}
|
||||
|
||||
@@ -127,35 +127,38 @@ public class HttpBasicConfigurerTests {
|
||||
public void httpBasicWhenRememberMeConfiguredThenSetsRememberMeCookie() throws Exception {
|
||||
this.spring.register(BasicUsesRememberMeConfig.class, Home.class).autowire();
|
||||
MockHttpServletRequestBuilder rememberMeRequest = get("/").with(httpBasic("user", "password"))
|
||||
.param("remember-me", "true");
|
||||
.param("remember-me", "true");
|
||||
this.mvc.perform(rememberMeRequest).andExpect(cookie().exists("remember-me"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void httpBasicWhenDefaultsThenAcceptsBasicCredentials() throws Exception {
|
||||
this.spring.register(HttpBasic.class, Users.class, Home.class).autowire();
|
||||
this.mvc.perform(get("/").with(httpBasic("user", "password"))).andExpect(status().isOk())
|
||||
.andExpect(content().string("user"));
|
||||
this.mvc.perform(get("/").with(httpBasic("user", "password")))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("user"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void httpBasicWhenCustomSecurityContextHolderStrategyThenUses() throws Exception {
|
||||
this.spring.register(HttpBasic.class, Users.class, Home.class, SecurityContextChangedListenerConfig.class)
|
||||
.autowire();
|
||||
this.mvc.perform(get("/").with(httpBasic("user", "password"))).andExpect(status().isOk())
|
||||
.andExpect(content().string("user"));
|
||||
.autowire();
|
||||
this.mvc.perform(get("/").with(httpBasic("user", "password")))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("user"));
|
||||
SecurityContextChangedListener listener = this.spring.getContext()
|
||||
.getBean(SecurityContextChangedListener.class);
|
||||
.getBean(SecurityContextChangedListener.class);
|
||||
verify(listener).securityContextChanged(setAuthentication(UsernamePasswordAuthenticationToken.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void httpBasicWhenUsingCustomSecurityContextRepositoryThenUses() throws Exception {
|
||||
this.spring.register(CustomSecurityContextRepositoryConfig.class, Users.class, Home.class).autowire();
|
||||
this.mvc.perform(get("/").with(httpBasic("user", "password"))).andExpect(status().isOk())
|
||||
.andExpect(content().string("user"));
|
||||
this.mvc.perform(get("/").with(httpBasic("user", "password")))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("user"));
|
||||
verify(CustomSecurityContextRepositoryConfig.SECURITY_CONTEXT_REPOSITORY)
|
||||
.saveContext(any(SecurityContext.class), any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
.saveContext(any(SecurityContext.class), any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@@ -327,7 +330,7 @@ public class HttpBasicConfigurerTests {
|
||||
@Bean
|
||||
SecurityFilterChain web(HttpSecurity http) throws Exception {
|
||||
http.authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated())
|
||||
.httpBasic(Customizer.withDefaults());
|
||||
.httpBasic(Customizer.withDefaults());
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@@ -77,8 +77,8 @@ public class HttpSecurityLogoutTests {
|
||||
loadConfig(ClearAuthenticationFalseConfig.class);
|
||||
SecurityContext currentContext = SecurityContextHolder.createEmptyContext();
|
||||
currentContext.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
|
||||
this.request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
|
||||
currentContext);
|
||||
this.request.getSession()
|
||||
.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, currentContext);
|
||||
this.request.setMethod("POST");
|
||||
this.request.setServletPath("/logout");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
|
||||
@@ -92,10 +92,13 @@ public class HttpSecuritySecurityMatchersNoMvcTests {
|
||||
setup();
|
||||
this.request.setServletPath("/path/");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
List<RequestMatcher> requestMatchers = this.springSecurityFilterChain.getFilterChains().stream()
|
||||
.map((chain) -> ((DefaultSecurityFilterChain) chain).getRequestMatcher())
|
||||
.map((matcher) -> ReflectionTestUtils.getField(matcher, "requestMatchers"))
|
||||
.map((matchers) -> (List<RequestMatcher>) matchers).findFirst().get();
|
||||
List<RequestMatcher> requestMatchers = this.springSecurityFilterChain.getFilterChains()
|
||||
.stream()
|
||||
.map((chain) -> ((DefaultSecurityFilterChain) chain).getRequestMatcher())
|
||||
.map((matcher) -> ReflectionTestUtils.getField(matcher, "requestMatchers"))
|
||||
.map((matchers) -> (List<RequestMatcher>) matchers)
|
||||
.findFirst()
|
||||
.get();
|
||||
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
|
||||
assertThat(requestMatchers).hasOnlyElementsOfType(AntPathRequestMatcher.class);
|
||||
}
|
||||
|
||||
@@ -123,10 +123,13 @@ public class HttpSecuritySecurityMatchersTests {
|
||||
setup();
|
||||
this.request.setServletPath("/path/");
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
|
||||
List<RequestMatcher> requestMatchers = this.springSecurityFilterChain.getFilterChains().stream()
|
||||
.map((chain) -> ((DefaultSecurityFilterChain) chain).getRequestMatcher())
|
||||
.map((matcher) -> ReflectionTestUtils.getField(matcher, "requestMatchers"))
|
||||
.map((matchers) -> (List<RequestMatcher>) matchers).findFirst().get();
|
||||
List<RequestMatcher> requestMatchers = this.springSecurityFilterChain.getFilterChains()
|
||||
.stream()
|
||||
.map((chain) -> ((DefaultSecurityFilterChain) chain).getRequestMatcher())
|
||||
.map((matcher) -> ReflectionTestUtils.getField(matcher, "requestMatchers"))
|
||||
.map((matchers) -> (List<RequestMatcher>) matchers)
|
||||
.findFirst()
|
||||
.get();
|
||||
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
assertThat(requestMatchers).hasOnlyElementsOfType(MvcRequestMatcher.class);
|
||||
}
|
||||
@@ -421,7 +424,7 @@ public class HttpSecuritySecurityMatchersTests {
|
||||
@Bean
|
||||
SecurityFilterChain appSecurity(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception {
|
||||
MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector)
|
||||
.servletPath("/spring");
|
||||
.servletPath("/spring");
|
||||
// @formatter:off
|
||||
http
|
||||
.securityMatchers()
|
||||
@@ -456,7 +459,7 @@ public class HttpSecuritySecurityMatchersTests {
|
||||
@Bean
|
||||
SecurityFilterChain appSecurity(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception {
|
||||
MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector)
|
||||
.servletPath("/spring");
|
||||
.servletPath("/spring");
|
||||
// @formatter:off
|
||||
http
|
||||
.securityMatchers((matchers) -> matchers
|
||||
@@ -488,8 +491,11 @@ public class HttpSecuritySecurityMatchersTests {
|
||||
|
||||
@Bean
|
||||
UserDetailsService userDetailsService() {
|
||||
UserDetails user = User.withDefaultPasswordEncoder().username("user").password("password").roles("USER")
|
||||
.build();
|
||||
UserDetails user = User.withDefaultPasswordEncoder()
|
||||
.username("user")
|
||||
.password("password")
|
||||
.roles("USER")
|
||||
.build();
|
||||
return new InMemoryUserDetailsManager(user);
|
||||
}
|
||||
|
||||
|
||||
@@ -66,7 +66,7 @@ public class JeeConfigurerTests {
|
||||
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
|
||||
this.spring.register(ObjectPostProcessorConfig.class).autowire();
|
||||
verify(ObjectPostProcessorConfig.objectPostProcessor)
|
||||
.postProcess(any(J2eePreAuthenticatedProcessingFilter.class));
|
||||
.postProcess(any(J2eePreAuthenticatedProcessingFilter.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -74,7 +74,7 @@ public class JeeConfigurerTests {
|
||||
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
|
||||
this.spring.register(ObjectPostProcessorConfig.class).autowire();
|
||||
verify(ObjectPostProcessorConfig.objectPostProcessor)
|
||||
.postProcess(any(J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.class));
|
||||
.postProcess(any(J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -126,7 +126,7 @@ public class JeeConfigurerTests {
|
||||
});
|
||||
// @formatter:on
|
||||
SecurityMockMvcResultMatchers.AuthenticatedMatcher authenticatedAsUser = authenticated()
|
||||
.withAuthorities(AuthorityUtils.createAuthorityList("ROLE_USER"));
|
||||
.withAuthorities(AuthorityUtils.createAuthorityList("ROLE_USER"));
|
||||
this.mvc.perform(authRequest).andExpect(authenticatedAsUser);
|
||||
}
|
||||
|
||||
@@ -139,7 +139,7 @@ public class JeeConfigurerTests {
|
||||
AuthorityUtils.createAuthorityList("ROLE_USER"));
|
||||
given(user.getName()).willReturn("user");
|
||||
given(JeeCustomAuthenticatedUserDetailsServiceConfig.authenticationUserDetailsService.loadUserDetails(any()))
|
||||
.willReturn(userDetails);
|
||||
.willReturn(userDetails);
|
||||
// @formatter:off
|
||||
MockHttpServletRequestBuilder authRequest = get("/")
|
||||
.principal(user)
|
||||
|
||||
@@ -82,36 +82,36 @@ public class LogoutConfigurerTests {
|
||||
@Test
|
||||
public void configureWhenDefaultLogoutSuccessHandlerForHasNullLogoutHandlerThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(NullLogoutSuccessHandlerConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
.isThrownBy(() -> this.spring.register(NullLogoutSuccessHandlerConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configureWhenDefaultLogoutSuccessHandlerForHasNullLogoutHandlerInLambdaThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(NullLogoutSuccessHandlerInLambdaConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
.isThrownBy(() -> this.spring.register(NullLogoutSuccessHandlerInLambdaConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configureWhenDefaultLogoutSuccessHandlerForHasNullMatcherThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(NullMatcherConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
.isThrownBy(() -> this.spring.register(NullMatcherConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configureWhenDefaultLogoutSuccessHandlerForHasNullMatcherInLambdaThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(NullMatcherInLambdaConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
.isThrownBy(() -> this.spring.register(NullMatcherInLambdaConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnLogoutFilter() {
|
||||
this.spring.register(ObjectPostProcessorConfig.class).autowire();
|
||||
ObjectPostProcessor<LogoutFilter> objectPostProcessor = this.spring.getContext()
|
||||
.getBean(ObjectPostProcessor.class);
|
||||
.getBean(ObjectPostProcessor.class);
|
||||
verify(objectPostProcessor).postProcess(any(LogoutFilter.class));
|
||||
}
|
||||
|
||||
@@ -221,23 +221,24 @@ public class LogoutConfigurerTests {
|
||||
@Test
|
||||
public void configureWhenLogoutHandlerNullThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(NullLogoutHandlerConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
.isThrownBy(() -> this.spring.register(NullLogoutHandlerConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configureWhenLogoutHandlerNullInLambdaThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(NullLogoutHandlerInLambdaConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
.isThrownBy(() -> this.spring.register(NullLogoutHandlerInLambdaConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
// SEC-3170
|
||||
@Test
|
||||
public void rememberMeWhenRememberMeServicesNotLogoutHandlerThenRedirectsToLogin() throws Exception {
|
||||
this.spring.register(RememberMeNoLogoutHandler.class).autowire();
|
||||
this.mvc.perform(post("/logout").with(csrf())).andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("/login?logout"));
|
||||
this.mvc.perform(post("/logout").with(csrf()))
|
||||
.andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("/login?logout"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -211,9 +211,10 @@ public class NamespaceHttpAnonymousTests {
|
||||
}
|
||||
|
||||
Optional<AnonymousAuthenticationToken> anonymousToken() {
|
||||
return Optional.of(SecurityContextHolder.getContext()).map(SecurityContext::getAuthentication)
|
||||
.filter((a) -> a instanceof AnonymousAuthenticationToken)
|
||||
.map(AnonymousAuthenticationToken.class::cast);
|
||||
return Optional.of(SecurityContextHolder.getContext())
|
||||
.map(SecurityContext::getAuthentication)
|
||||
.filter((a) -> a instanceof AnonymousAuthenticationToken)
|
||||
.map(AnonymousAuthenticationToken.class::cast);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -123,7 +123,7 @@ public class NamespaceHttpBasicTests {
|
||||
public void basicAuthenticationWhenUsingAuthenticationDetailsSourceRefThenMatchesNamespace() throws Exception {
|
||||
this.spring.register(AuthenticationDetailsSourceHttpBasicConfig.class, UserConfig.class).autowire();
|
||||
AuthenticationDetailsSource<HttpServletRequest, ?> source = this.spring.getContext()
|
||||
.getBean(AuthenticationDetailsSource.class);
|
||||
.getBean(AuthenticationDetailsSource.class);
|
||||
this.mvc.perform(get("/").with(httpBasic("user", "password")));
|
||||
verify(source).buildDetails(any(HttpServletRequest.class));
|
||||
}
|
||||
@@ -133,7 +133,7 @@ public class NamespaceHttpBasicTests {
|
||||
throws Exception {
|
||||
this.spring.register(AuthenticationDetailsSourceHttpBasicLambdaConfig.class, UserConfig.class).autowire();
|
||||
AuthenticationDetailsSource<HttpServletRequest, ?> source = this.spring.getContext()
|
||||
.getBean(AuthenticationDetailsSource.class);
|
||||
.getBean(AuthenticationDetailsSource.class);
|
||||
this.mvc.perform(get("/").with(httpBasic("user", "password")));
|
||||
verify(source).buildDetails(any(HttpServletRequest.class));
|
||||
}
|
||||
|
||||
@@ -94,8 +94,10 @@ public class NamespaceHttpCustomFilterTests {
|
||||
|
||||
private ListAssert<Class<?>> assertThatFilters() {
|
||||
FilterChainProxy filterChain = this.spring.getContext().getBean(FilterChainProxy.class);
|
||||
List<Class<?>> filters = filterChain.getFilters("/").stream().map(Object::getClass)
|
||||
.collect(Collectors.toList());
|
||||
List<Class<?>> filters = filterChain.getFilters("/")
|
||||
.stream()
|
||||
.map(Object::getClass)
|
||||
.collect(Collectors.toList());
|
||||
return assertThat(filters);
|
||||
}
|
||||
|
||||
|
||||
@@ -85,8 +85,11 @@ public class NamespaceHttpExpressionHandlerTests {
|
||||
|
||||
@Bean
|
||||
UserDetailsService userDetailsService() {
|
||||
UserDetails user = User.withDefaultPasswordEncoder().username("rod").password("password")
|
||||
.roles("USER", "ADMIN").build();
|
||||
UserDetails user = User.withDefaultPasswordEncoder()
|
||||
.username("rod")
|
||||
.password("password")
|
||||
.roles("USER", "ADMIN")
|
||||
.build();
|
||||
return new InMemoryUserDetailsManager(user);
|
||||
}
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ public class NamespaceHttpFormLoginTests {
|
||||
this.spring.register(FormLoginCustomConfig.class, UserDetailsServiceConfig.class).autowire();
|
||||
this.mvc.perform(get("/")).andExpect(redirectedUrl("http://localhost/authentication/login"));
|
||||
this.mvc.perform(post("/authentication/login/process").with(csrf()))
|
||||
.andExpect(redirectedUrl("/authentication/login?failed"));
|
||||
.andExpect(redirectedUrl("/authentication/login?failed"));
|
||||
// @formatter:off
|
||||
MockHttpServletRequestBuilder request = post("/authentication/login/process")
|
||||
.param("username", "user")
|
||||
|
||||
@@ -91,7 +91,7 @@ public class NamespaceHttpHeadersTests {
|
||||
public void requestWhenHstsCustomThenBehaviorMatchesNamespace() throws Exception {
|
||||
this.spring.register(HstsCustomConfig.class).autowire();
|
||||
this.mvc.perform(get("/"))
|
||||
.andExpect(includes(Collections.singletonMap("Strict-Transport-Security", "max-age=15768000")));
|
||||
.andExpect(includes(Collections.singletonMap("Strict-Transport-Security", "max-age=15768000")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -104,7 +104,7 @@ public class NamespaceHttpHeadersTests {
|
||||
public void requestWhenFrameOptionsAllowFromThenBehaviorMatchesNamespace() throws Exception {
|
||||
this.spring.register(FrameOptionsAllowFromConfig.class).autowire();
|
||||
this.mvc.perform(get("/"))
|
||||
.andExpect(includes(Collections.singletonMap("X-Frame-Options", "ALLOW-FROM https://example.com")));
|
||||
.andExpect(includes(Collections.singletonMap("X-Frame-Options", "ALLOW-FROM https://example.com")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -129,7 +129,7 @@ public class NamespaceHttpHeadersTests {
|
||||
public void requestWhenCustomHeaderOnlyThenBehaviorMatchesNamespace() throws Exception {
|
||||
this.spring.register(HeaderRefConfig.class).autowire();
|
||||
this.mvc.perform(get("/"))
|
||||
.andExpect(includes(Collections.singletonMap("customHeaderName", "customHeaderValue")));
|
||||
.andExpect(includes(Collections.singletonMap("customHeaderName", "customHeaderValue")));
|
||||
}
|
||||
|
||||
private static ResultMatcher includesDefaults() {
|
||||
|
||||
@@ -92,7 +92,7 @@ public class NamespaceHttpInterceptUrlTests {
|
||||
MockHttpServletRequestBuilder postWithUser = post("/admin/post").with(authentication(user("ROLE_USER")));
|
||||
this.mvc.perform(postWithUser).andExpect(status().isForbidden());
|
||||
MockHttpServletRequestBuilder requestWithAdmin = post("/admin/post").with(csrf())
|
||||
.with(authentication(user("ROLE_ADMIN")));
|
||||
.with(authentication(user("ROLE_ADMIN")));
|
||||
this.mvc.perform(requestWithAdmin).andExpect(status().isOk());
|
||||
}
|
||||
|
||||
|
||||
@@ -82,8 +82,9 @@ public class NamespaceHttpJeeTests {
|
||||
User result = new User(user.getName(), "N/A", true, true, true, true,
|
||||
AuthorityUtils.createAuthorityList("ROLE_user"));
|
||||
given(bean(AuthenticationUserDetailsService.class).loadUserDetails(any())).willReturn(result);
|
||||
this.mvc.perform(get("/roles").principal(user)).andExpect(status().isOk())
|
||||
.andExpect(content().string("ROLE_user"));
|
||||
this.mvc.perform(get("/roles").principal(user))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string("ROLE_user"));
|
||||
verifyBean(AuthenticationUserDetailsService.class).loadUserDetails(any());
|
||||
}
|
||||
|
||||
|
||||
@@ -152,7 +152,8 @@ public class NamespaceHttpLogoutTests {
|
||||
|
||||
ResultMatcher authenticated(boolean authenticated) {
|
||||
return (result) -> assertThat(Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
|
||||
.map(Authentication::isAuthenticated).orElse(false)).isEqualTo(authenticated);
|
||||
.map(Authentication::isAuthenticated)
|
||||
.orElse(false)).isEqualTo(authenticated);
|
||||
}
|
||||
|
||||
ResultMatcher noCookies() {
|
||||
@@ -161,7 +162,7 @@ public class NamespaceHttpLogoutTests {
|
||||
|
||||
ResultMatcher session(Predicate<HttpSession> sessionPredicate) {
|
||||
return (result) -> assertThat(result.getRequest().getSession(false))
|
||||
.is(new Condition<>(sessionPredicate, "sessionPredicate failed"));
|
||||
.is(new Condition<>(sessionPredicate, "sessionPredicate failed"));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
@@ -57,7 +57,7 @@ public class NamespaceHttpPortMappingsTests {
|
||||
this.spring.register(HttpInterceptUrlWithPortMapperConfig.class).autowire();
|
||||
this.mvc.perform(get("http://localhost:9080/login")).andExpect(redirectedUrl("https://localhost:9443/login"));
|
||||
this.mvc.perform(get("http://localhost:9080/secured/a"))
|
||||
.andExpect(redirectedUrl("https://localhost:9443/secured/a"));
|
||||
.andExpect(redirectedUrl("https://localhost:9443/secured/a"));
|
||||
this.mvc.perform(get("https://localhost:9443/user")).andExpect(redirectedUrl("http://localhost:9080/user"));
|
||||
}
|
||||
|
||||
|
||||
@@ -141,8 +141,11 @@ public class NamespaceHttpX509Tests {
|
||||
|
||||
@Bean
|
||||
UserDetailsService userDetailsService() {
|
||||
UserDetails user = User.withDefaultPasswordEncoder().username("rod").password("password")
|
||||
.roles("USER", "ADMIN").build();
|
||||
UserDetails user = User.withDefaultPasswordEncoder()
|
||||
.username("rod")
|
||||
.password("password")
|
||||
.roles("USER", "ADMIN")
|
||||
.build();
|
||||
return new InMemoryUserDetailsManager(user);
|
||||
}
|
||||
|
||||
@@ -167,8 +170,11 @@ public class NamespaceHttpX509Tests {
|
||||
|
||||
@Bean
|
||||
UserDetailsService userDetailsService() {
|
||||
UserDetails user = User.withDefaultPasswordEncoder().username("rod").password("password")
|
||||
.roles("USER", "ADMIN").build();
|
||||
UserDetails user = User.withDefaultPasswordEncoder()
|
||||
.username("rod")
|
||||
.password("password")
|
||||
.roles("USER", "ADMIN")
|
||||
.build();
|
||||
return new InMemoryUserDetailsManager(user);
|
||||
}
|
||||
|
||||
@@ -199,8 +205,11 @@ public class NamespaceHttpX509Tests {
|
||||
|
||||
@Bean
|
||||
UserDetailsService userDetailsService() {
|
||||
UserDetails user = User.withDefaultPasswordEncoder().username("rod").password("password")
|
||||
.roles("USER", "ADMIN").build();
|
||||
UserDetails user = User.withDefaultPasswordEncoder()
|
||||
.username("rod")
|
||||
.password("password")
|
||||
.roles("USER", "ADMIN")
|
||||
.build();
|
||||
return new InMemoryUserDetailsManager(user);
|
||||
}
|
||||
|
||||
@@ -226,8 +235,11 @@ public class NamespaceHttpX509Tests {
|
||||
|
||||
@Bean
|
||||
UserDetailsService userDetailsService() {
|
||||
UserDetails user = User.withDefaultPasswordEncoder().username("rod@example.com").password("password")
|
||||
.roles("USER", "ADMIN").build();
|
||||
UserDetails user = User.withDefaultPasswordEncoder()
|
||||
.username("rod@example.com")
|
||||
.password("password")
|
||||
.roles("USER", "ADMIN")
|
||||
.build();
|
||||
return new InMemoryUserDetailsManager(user);
|
||||
}
|
||||
|
||||
@@ -258,8 +270,11 @@ public class NamespaceHttpX509Tests {
|
||||
|
||||
@Bean
|
||||
UserDetailsService userDetailsService() {
|
||||
UserDetails user = User.withDefaultPasswordEncoder().username("rod").password("password")
|
||||
.roles("USER", "ADMIN").build();
|
||||
UserDetails user = User.withDefaultPasswordEncoder()
|
||||
.username("rod")
|
||||
.password("password")
|
||||
.roles("USER", "ADMIN")
|
||||
.build();
|
||||
return new InMemoryUserDetailsManager(user);
|
||||
}
|
||||
|
||||
@@ -285,8 +300,11 @@ public class NamespaceHttpX509Tests {
|
||||
|
||||
@Bean
|
||||
UserDetailsService userDetailsService() {
|
||||
UserDetails user = User.withDefaultPasswordEncoder().username("rod").password("password")
|
||||
.roles("USER", "ADMIN").build();
|
||||
UserDetails user = User.withDefaultPasswordEncoder()
|
||||
.username("rod")
|
||||
.password("password")
|
||||
.roles("USER", "ADMIN")
|
||||
.build();
|
||||
return new InMemoryUserDetailsManager(user);
|
||||
}
|
||||
|
||||
|
||||
@@ -87,7 +87,7 @@ public class NamespaceRememberMeTests {
|
||||
Cookie rememberMe = result.getResponse().getCookie("remember-me");
|
||||
assertThat(rememberMe).isNotNull();
|
||||
this.mvc.perform(get("/authentication-class").cookie(rememberMe))
|
||||
.andExpect(content().string(RememberMeAuthenticationToken.class.getName()));
|
||||
.andExpect(content().string(RememberMeAuthenticationToken.class.getName()));
|
||||
// @formatter:off
|
||||
MockHttpServletRequestBuilder logoutRequest = post("/logout")
|
||||
.with(csrf())
|
||||
|
||||
@@ -83,7 +83,7 @@ public class NamespaceSessionManagementTests {
|
||||
@Test
|
||||
public void authenticateWhenDefaultSessionManagementThenMatchesNamespace() throws Exception {
|
||||
this.spring.register(SessionManagementConfig.class, BasicController.class, UserDetailsServiceConfig.class)
|
||||
.autowire();
|
||||
.autowire();
|
||||
MockHttpSession session = new MockHttpSession();
|
||||
String sessionId = session.getId();
|
||||
MockHttpServletRequestBuilder request = get("/auth").session(session).with(httpBasic("user", "password"));
|
||||
@@ -120,16 +120,16 @@ public class NamespaceSessionManagementTests {
|
||||
@Test
|
||||
public void authenticateWhenUsingMaxSessionsThenMatchesNamespace() throws Exception {
|
||||
this.spring.register(CustomSessionManagementConfig.class, BasicController.class, UserDetailsServiceConfig.class)
|
||||
.autowire();
|
||||
.autowire();
|
||||
this.mvc.perform(get("/auth").with(httpBasic("user", "password"))).andExpect(status().isOk());
|
||||
this.mvc.perform(get("/auth").with(httpBasic("user", "password")))
|
||||
.andExpect(redirectedUrl("/session-auth-error"));
|
||||
.andExpect(redirectedUrl("/session-auth-error"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticateWhenUsingFailureUrlThenMatchesNamespace() throws Exception {
|
||||
this.spring.register(CustomSessionManagementConfig.class, BasicController.class, UserDetailsServiceConfig.class)
|
||||
.autowire();
|
||||
.autowire();
|
||||
MockHttpServletRequest mock = spy(MockHttpServletRequest.class);
|
||||
mock.setSession(new MockHttpSession());
|
||||
given(mock.changeSessionId()).willThrow(SessionAuthenticationException.class);
|
||||
@@ -145,7 +145,7 @@ public class NamespaceSessionManagementTests {
|
||||
@Test
|
||||
public void authenticateWhenUsingSessionRegistryThenMatchesNamespace() throws Exception {
|
||||
this.spring.register(CustomSessionManagementConfig.class, BasicController.class, UserDetailsServiceConfig.class)
|
||||
.autowire();
|
||||
.autowire();
|
||||
SessionRegistry sessionRegistry = this.spring.getContext().getBean(SessionRegistry.class);
|
||||
MockHttpServletRequestBuilder request = get("/auth").with(httpBasic("user", "password"));
|
||||
this.mvc.perform(request).andExpect(status().isOk());
|
||||
@@ -169,7 +169,7 @@ public class NamespaceSessionManagementTests {
|
||||
@Test
|
||||
public void authenticateWhenUsingCustomSessionAuthenticationStrategyThenMatchesNamespace() throws Exception {
|
||||
this.spring.register(RefsSessionManagementConfig.class, BasicController.class, UserDetailsServiceConfig.class)
|
||||
.autowire();
|
||||
.autowire();
|
||||
MockHttpServletRequestBuilder request = get("/auth").with(httpBasic("user", "password"));
|
||||
this.mvc.perform(request).andExpect(status().isOk());
|
||||
verifyBean(SessionAuthenticationStrategy.class).onAuthentication(any(Authentication.class),
|
||||
@@ -179,8 +179,8 @@ public class NamespaceSessionManagementTests {
|
||||
@Test
|
||||
public void authenticateWhenNoSessionFixationProtectionThenMatchesNamespace() throws Exception {
|
||||
this.spring
|
||||
.register(SFPNoneSessionManagementConfig.class, BasicController.class, UserDetailsServiceConfig.class)
|
||||
.autowire();
|
||||
.register(SFPNoneSessionManagementConfig.class, BasicController.class, UserDetailsServiceConfig.class)
|
||||
.autowire();
|
||||
MockHttpSession givenSession = new MockHttpSession();
|
||||
String givenSessionId = givenSession.getId();
|
||||
// @formatter:off
|
||||
@@ -198,8 +198,9 @@ public class NamespaceSessionManagementTests {
|
||||
|
||||
@Test
|
||||
public void authenticateWhenMigrateSessionFixationProtectionThenMatchesNamespace() throws Exception {
|
||||
this.spring.register(SFPMigrateSessionManagementConfig.class, BasicController.class,
|
||||
UserDetailsServiceConfig.class).autowire();
|
||||
this.spring
|
||||
.register(SFPMigrateSessionManagementConfig.class, BasicController.class, UserDetailsServiceConfig.class)
|
||||
.autowire();
|
||||
MockHttpSession givenSession = new MockHttpSession();
|
||||
String givenSessionId = givenSession.getId();
|
||||
givenSession.setAttribute("name", "value");
|
||||
|
||||
@@ -52,37 +52,39 @@ public class PasswordManagementConfigurerTests {
|
||||
public void whenChangePasswordPageNotSetThenDefaultChangePasswordPageUsed() throws Exception {
|
||||
this.spring.register(PasswordManagementWithDefaultChangePasswordPageConfig.class).autowire();
|
||||
|
||||
this.mvc.perform(get("/.well-known/change-password")).andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("/change-password"));
|
||||
this.mvc.perform(get("/.well-known/change-password"))
|
||||
.andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("/change-password"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenChangePasswordPageSetThenSpecifiedChangePasswordPageUsed() throws Exception {
|
||||
this.spring.register(PasswordManagementWithCustomChangePasswordPageConfig.class).autowire();
|
||||
|
||||
this.mvc.perform(get("/.well-known/change-password")).andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("/custom-change-password-page"));
|
||||
this.mvc.perform(get("/.well-known/change-password"))
|
||||
.andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("/custom-change-password-page"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSettingNullChangePasswordPage() {
|
||||
PasswordManagementConfigurer configurer = new PasswordManagementConfigurer();
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> configurer.changePasswordPage(null))
|
||||
.withMessage("changePasswordPage cannot be empty");
|
||||
.withMessage("changePasswordPage cannot be empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSettingEmptyChangePasswordPage() {
|
||||
PasswordManagementConfigurer configurer = new PasswordManagementConfigurer();
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> configurer.changePasswordPage(""))
|
||||
.withMessage("changePasswordPage cannot be empty");
|
||||
.withMessage("changePasswordPage cannot be empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSettingBlankChangePasswordPage() {
|
||||
PasswordManagementConfigurer configurer = new PasswordManagementConfigurer();
|
||||
assertThatIllegalArgumentException().isThrownBy(() -> configurer.changePasswordPage(" "))
|
||||
.withMessage("changePasswordPage cannot be empty");
|
||||
.withMessage("changePasswordPage cannot be empty");
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
@@ -79,16 +79,17 @@ public class PermitAllSupportTests {
|
||||
@Test
|
||||
public void configureWhenNotAuthorizeRequestsThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(NoAuthorizedUrlsConfig.class).autowire()).withMessageContaining(
|
||||
"permitAll only works with either HttpSecurity.authorizeRequests() or HttpSecurity.authorizeHttpRequests()");
|
||||
.isThrownBy(() -> this.spring.register(NoAuthorizedUrlsConfig.class).autowire())
|
||||
.withMessageContaining(
|
||||
"permitAll only works with either HttpSecurity.authorizeRequests() or HttpSecurity.authorizeHttpRequests()");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configureWhenBothAuthorizeRequestsAndAuthorizeHttpRequestsThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(PermitAllConfigWithBothConfigs.class).autowire())
|
||||
.withMessageContaining(
|
||||
"permitAll only works with either HttpSecurity.authorizeRequests() or HttpSecurity.authorizeHttpRequests()");
|
||||
.isThrownBy(() -> this.spring.register(PermitAllConfigWithBothConfigs.class).autowire())
|
||||
.withMessageContaining(
|
||||
"permitAll only works with either HttpSecurity.authorizeRequests() or HttpSecurity.authorizeHttpRequests()");
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
@@ -95,21 +95,21 @@ public class RememberMeConfigurerTests {
|
||||
@Test
|
||||
public void postWhenNoUserDetailsServiceThenException() {
|
||||
assertThatExceptionOfType(UnsatisfiedDependencyException.class)
|
||||
.isThrownBy(() -> this.spring.register(NullUserDetailsConfig.class).autowire())
|
||||
.withMessageContaining("userDetailsService cannot be null");
|
||||
.isThrownBy(() -> this.spring.register(NullUserDetailsConfig.class).autowire())
|
||||
.withMessageContaining("userDetailsService cannot be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnRememberMeAuthenticationFilter() {
|
||||
this.spring.register(ObjectPostProcessorConfig.class).autowire();
|
||||
verify(this.spring.getContext().getBean(ObjectPostProcessor.class))
|
||||
.postProcess(any(RememberMeAuthenticationFilter.class));
|
||||
.postProcess(any(RememberMeAuthenticationFilter.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rememberMeWhenInvokedTwiceThenUsesOriginalUserDetailsService() throws Exception {
|
||||
given(DuplicateDoesNotOverrideConfig.userDetailsService.loadUserByUsername(anyString()))
|
||||
.willReturn(new User("user", "password", Collections.emptyList()));
|
||||
.willReturn(new User("user", "password", Collections.emptyList()));
|
||||
this.spring.register(DuplicateDoesNotOverrideConfig.class).autowire();
|
||||
// @formatter:off
|
||||
MockHttpServletRequestBuilder request = get("/")
|
||||
@@ -123,8 +123,12 @@ public class RememberMeConfigurerTests {
|
||||
@Test
|
||||
public void rememberMeWhenUserDetailsServiceNotConfiguredThenUsesBean() throws Exception {
|
||||
this.spring.register(UserDetailsServiceBeanConfig.class).autowire();
|
||||
MvcResult mvcResult = this.mvc.perform(post("/login").with(csrf()).param("username", "user")
|
||||
.param("password", "password").param("remember-me", "true")).andReturn();
|
||||
MvcResult mvcResult = this.mvc
|
||||
.perform(post("/login").with(csrf())
|
||||
.param("username", "user")
|
||||
.param("password", "password")
|
||||
.param("remember-me", "true"))
|
||||
.andReturn();
|
||||
Cookie rememberMeCookie = mvcResult.getResponse().getCookie("remember-me");
|
||||
// @formatter:off
|
||||
MockHttpServletRequestBuilder request = get("/abc").cookie(rememberMeCookie);
|
||||
@@ -137,8 +141,12 @@ public class RememberMeConfigurerTests {
|
||||
@Test
|
||||
public void rememberMeWhenCustomSecurityContextHolderStrategyThenUses() throws Exception {
|
||||
this.spring.register(UserDetailsServiceBeanConfig.class, SecurityContextChangedListenerConfig.class).autowire();
|
||||
MvcResult mvcResult = this.mvc.perform(post("/login").with(csrf()).param("username", "user")
|
||||
.param("password", "password").param("remember-me", "true")).andReturn();
|
||||
MvcResult mvcResult = this.mvc
|
||||
.perform(post("/login").with(csrf())
|
||||
.param("username", "user")
|
||||
.param("password", "password")
|
||||
.param("remember-me", "true"))
|
||||
.andReturn();
|
||||
Cookie rememberMeCookie = mvcResult.getResponse().getCookie("remember-me");
|
||||
// @formatter:off
|
||||
MockHttpServletRequestBuilder request = get("/abc").cookie(rememberMeCookie);
|
||||
@@ -165,8 +173,12 @@ public class RememberMeConfigurerTests {
|
||||
@Test
|
||||
public void getWhenRememberMeCookieThenAuthenticationIsRememberMeAuthenticationToken() throws Exception {
|
||||
this.spring.register(RememberMeConfig.class).autowire();
|
||||
MvcResult mvcResult = this.mvc.perform(post("/login").with(csrf()).param("username", "user")
|
||||
.param("password", "password").param("remember-me", "true")).andReturn();
|
||||
MvcResult mvcResult = this.mvc
|
||||
.perform(post("/login").with(csrf())
|
||||
.param("username", "user")
|
||||
.param("password", "password")
|
||||
.param("remember-me", "true"))
|
||||
.andReturn();
|
||||
Cookie rememberMeCookie = mvcResult.getResponse().getCookie("remember-me");
|
||||
// @formatter:off
|
||||
MockHttpServletRequestBuilder request = get("/abc").cookie(rememberMeCookie);
|
||||
@@ -275,10 +287,9 @@ public class RememberMeConfigurerTests {
|
||||
@Test
|
||||
public void configureWhenRememberMeCookieNameAndRememberMeServicesThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(
|
||||
() -> this.spring.register(RememberMeCookieNameAndRememberMeServicesConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class)
|
||||
.withMessageContaining("Can not set rememberMeCookieName and custom rememberMeServices.");
|
||||
.isThrownBy(() -> this.spring.register(RememberMeCookieNameAndRememberMeServicesConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(IllegalArgumentException.class)
|
||||
.withMessageContaining("Can not set rememberMeCookieName and custom rememberMeServices.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -306,8 +317,12 @@ public class RememberMeConfigurerTests {
|
||||
public void getWhenCustomSecurityContextRepositoryThenUses() throws Exception {
|
||||
this.spring.register(SecurityContextRepositoryConfig.class).autowire();
|
||||
SecurityContextRepository repository = this.spring.getContext().getBean(SecurityContextRepository.class);
|
||||
MvcResult mvcResult = this.mvc.perform(post("/login").with(csrf()).param("username", "user")
|
||||
.param("password", "password").param("remember-me", "true")).andReturn();
|
||||
MvcResult mvcResult = this.mvc
|
||||
.perform(post("/login").with(csrf())
|
||||
.param("username", "user")
|
||||
.param("password", "password")
|
||||
.param("remember-me", "true"))
|
||||
.andReturn();
|
||||
Cookie rememberMeCookie = mvcResult.getResponse().getCookie("remember-me");
|
||||
reset(repository);
|
||||
// @formatter:off
|
||||
|
||||
@@ -85,7 +85,7 @@ public class SecurityContextConfigurerTests {
|
||||
public void securityContextWhenInvokedTwiceThenUsesOriginalSecurityContextRepository() throws Exception {
|
||||
this.spring.register(DuplicateDoesNotOverrideConfig.class).autowire();
|
||||
given(DuplicateDoesNotOverrideConfig.SCR.loadDeferredContext(any(HttpServletRequest.class)))
|
||||
.willReturn(new TestDeferredSecurityContext(mock(SecurityContext.class), false));
|
||||
.willReturn(new TestDeferredSecurityContext(mock(SecurityContext.class), false));
|
||||
this.mvc.perform(get("/"));
|
||||
verify(DuplicateDoesNotOverrideConfig.SCR).loadDeferredContext(any(HttpServletRequest.class));
|
||||
}
|
||||
@@ -138,7 +138,7 @@ public class SecurityContextConfigurerTests {
|
||||
// @formatter:on
|
||||
MvcResult mvcResult = this.mvc.perform(formLogin()).andReturn();
|
||||
SecurityContext securityContext = repository
|
||||
.loadContext(new HttpRequestResponseHolder(mvcResult.getRequest(), mvcResult.getResponse()));
|
||||
.loadContext(new HttpRequestResponseHolder(mvcResult.getRequest(), mvcResult.getResponse()));
|
||||
assertThat(securityContext.getAuthentication()).isNotNull();
|
||||
}
|
||||
|
||||
|
||||
@@ -94,7 +94,7 @@ public class ServletApiConfigurerTests {
|
||||
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnSecurityContextHolderAwareRequestFilter() {
|
||||
this.spring.register(ObjectPostProcessorConfig.class).autowire();
|
||||
verify(ObjectPostProcessorConfig.objectPostProcessor)
|
||||
.postProcess(any(SecurityContextHolderAwareRequestFilter.class));
|
||||
.postProcess(any(SecurityContextHolderAwareRequestFilter.class));
|
||||
}
|
||||
|
||||
// SEC-2215
|
||||
@@ -155,7 +155,7 @@ public class ServletApiConfigurerTests {
|
||||
public void requestWhenServletApiWithDefaultsInLambdaThenUsesDefaultRolePrefix() throws Exception {
|
||||
this.spring.register(ServletApiWithDefaultsInLambdaConfig.class, AdminController.class).autowire();
|
||||
MockHttpServletRequestBuilder request = get("/admin")
|
||||
.with(user("user").authorities(AuthorityUtils.createAuthorityList("ROLE_ADMIN")));
|
||||
.with(user("user").authorities(AuthorityUtils.createAuthorityList("ROLE_ADMIN")));
|
||||
this.mvc.perform(request).andExpect(status().isOk());
|
||||
}
|
||||
|
||||
|
||||
@@ -57,8 +57,8 @@ public class SessionManagementConfigurerSessionAuthenticationStrategyTests {
|
||||
public void requestWhenCustomSessionAuthenticationStrategyProvidedThenCalled() throws Exception {
|
||||
this.spring.register(CustomSessionAuthenticationStrategyConfig.class).autowire();
|
||||
this.mvc.perform(formLogin().user("user").password("password"));
|
||||
verify(CustomSessionAuthenticationStrategyConfig.customSessionAuthenticationStrategy).onAuthentication(
|
||||
any(Authentication.class), any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
verify(CustomSessionAuthenticationStrategyConfig.customSessionAuthenticationStrategy)
|
||||
.onAuthentication(any(Authentication.class), any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
@@ -119,8 +119,8 @@ public class SessionManagementConfigurerTests {
|
||||
public void sessionManagementWhenConfiguredThenDoesNotOverrideSecurityContextRepository() throws Exception {
|
||||
SessionManagementSecurityContextRepositoryConfig.SECURITY_CONTEXT_REPO = mock(SecurityContextRepository.class);
|
||||
given(SessionManagementSecurityContextRepositoryConfig.SECURITY_CONTEXT_REPO
|
||||
.loadDeferredContext(any(HttpServletRequest.class)))
|
||||
.willReturn(new TestDeferredSecurityContext(mock(SecurityContext.class), false));
|
||||
.loadDeferredContext(any(HttpServletRequest.class)))
|
||||
.willReturn(new TestDeferredSecurityContext(mock(SecurityContext.class), false));
|
||||
this.spring.register(SessionManagementSecurityContextRepositoryConfig.class).autowire();
|
||||
this.mvc.perform(get("/"));
|
||||
}
|
||||
@@ -129,12 +129,12 @@ public class SessionManagementConfigurerTests {
|
||||
public void sessionManagementWhenSecurityContextRepositoryIsConfiguredThenUseIt() throws Exception {
|
||||
SessionManagementSecurityContextRepositoryConfig.SECURITY_CONTEXT_REPO = mock(SecurityContextRepository.class);
|
||||
given(SessionManagementSecurityContextRepositoryConfig.SECURITY_CONTEXT_REPO
|
||||
.loadDeferredContext(any(HttpServletRequest.class)))
|
||||
.willReturn(new TestDeferredSecurityContext(mock(SecurityContext.class), false));
|
||||
.loadDeferredContext(any(HttpServletRequest.class)))
|
||||
.willReturn(new TestDeferredSecurityContext(mock(SecurityContext.class), false));
|
||||
this.spring.register(SessionManagementSecurityContextRepositoryConfig.class).autowire();
|
||||
this.mvc.perform(get("/"));
|
||||
verify(SessionManagementSecurityContextRepositoryConfig.SECURITY_CONTEXT_REPO)
|
||||
.containsContext(any(HttpServletRequest.class));
|
||||
.containsContext(any(HttpServletRequest.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -274,7 +274,7 @@ public class SessionManagementConfigurerTests {
|
||||
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
|
||||
this.spring.register(ObjectPostProcessorConfig.class).autowire();
|
||||
verify(ObjectPostProcessorConfig.objectPostProcessor)
|
||||
.postProcess(any(ConcurrentSessionControlAuthenticationStrategy.class));
|
||||
.postProcess(any(ConcurrentSessionControlAuthenticationStrategy.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -282,7 +282,7 @@ public class SessionManagementConfigurerTests {
|
||||
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
|
||||
this.spring.register(ObjectPostProcessorConfig.class).autowire();
|
||||
verify(ObjectPostProcessorConfig.objectPostProcessor)
|
||||
.postProcess(any(CompositeSessionAuthenticationStrategy.class));
|
||||
.postProcess(any(CompositeSessionAuthenticationStrategy.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -290,7 +290,7 @@ public class SessionManagementConfigurerTests {
|
||||
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
|
||||
this.spring.register(ObjectPostProcessorConfig.class).autowire();
|
||||
verify(ObjectPostProcessorConfig.objectPostProcessor)
|
||||
.postProcess(any(RegisterSessionAuthenticationStrategy.class));
|
||||
.postProcess(any(RegisterSessionAuthenticationStrategy.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -298,7 +298,7 @@ public class SessionManagementConfigurerTests {
|
||||
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
|
||||
this.spring.register(ObjectPostProcessorConfig.class).autowire();
|
||||
verify(ObjectPostProcessorConfig.objectPostProcessor)
|
||||
.postProcess(any(ChangeSessionIdAuthenticationStrategy.class));
|
||||
.postProcess(any(ChangeSessionIdAuthenticationStrategy.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -379,7 +379,7 @@ public class SessionManagementConfigurerTests {
|
||||
HttpSession session = mvcResult.getRequest().getSession(false);
|
||||
assertThat(session).isNull();
|
||||
SecurityContext securityContext = (SecurityContext) mvcResult.getRequest()
|
||||
.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME);
|
||||
.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME);
|
||||
assertThat(securityContext).isNotNull();
|
||||
}
|
||||
|
||||
|
||||
@@ -290,8 +290,11 @@ public class UrlAuthorizationConfigurerTests {
|
||||
|
||||
@Bean
|
||||
UserDetailsService userDetailsService() {
|
||||
UserDetails user = User.withDefaultPasswordEncoder().username("user").password("password").roles("USER")
|
||||
.build();
|
||||
UserDetails user = User.withDefaultPasswordEncoder()
|
||||
.username("user")
|
||||
.password("password")
|
||||
.roles("USER")
|
||||
.build();
|
||||
return new InMemoryUserDetailsManager(user);
|
||||
}
|
||||
|
||||
|
||||
@@ -162,7 +162,8 @@ public class UrlAuthorizationsTests {
|
||||
@Bean
|
||||
SecurityFilterChain filterChain(HttpSecurity http, ApplicationContext context) throws Exception {
|
||||
UrlAuthorizationConfigurer<HttpSecurity>.StandardInterceptUrlRegistry registry = http
|
||||
.apply(new UrlAuthorizationConfigurer(context)).getRegistry();
|
||||
.apply(new UrlAuthorizationConfigurer(context))
|
||||
.getRegistry();
|
||||
// @formatter:off
|
||||
registry
|
||||
.requestMatchers("/a").hasRole("ADMIN")
|
||||
|
||||
@@ -109,7 +109,7 @@ public class X509ConfigurerTests {
|
||||
SecurityContextHolderStrategy strategy = this.spring.getContext().getBean(SecurityContextHolderStrategy.class);
|
||||
verify(strategy, atLeastOnce()).getContext();
|
||||
SecurityContextChangedListener listener = this.spring.getContext()
|
||||
.getBean(SecurityContextChangedListener.class);
|
||||
.getBean(SecurityContextChangedListener.class);
|
||||
verify(listener).securityContextChanged(setAuthentication(PreAuthenticatedAuthenticationToken.class));
|
||||
}
|
||||
|
||||
@@ -214,8 +214,11 @@ public class X509ConfigurerTests {
|
||||
|
||||
@Bean
|
||||
UserDetailsService userDetailsService() {
|
||||
UserDetails user = User.withDefaultPasswordEncoder().username("rod").password("password")
|
||||
.roles("USER", "ADMIN").build();
|
||||
UserDetails user = User.withDefaultPasswordEncoder()
|
||||
.username("rod")
|
||||
.password("password")
|
||||
.roles("USER", "ADMIN")
|
||||
.build();
|
||||
return new InMemoryUserDetailsManager(user);
|
||||
}
|
||||
|
||||
@@ -236,8 +239,11 @@ public class X509ConfigurerTests {
|
||||
|
||||
@Bean
|
||||
UserDetailsService userDetailsService() {
|
||||
UserDetails user = User.withDefaultPasswordEncoder().username("rod").password("password")
|
||||
.roles("USER", "ADMIN").build();
|
||||
UserDetails user = User.withDefaultPasswordEncoder()
|
||||
.username("rod")
|
||||
.password("password")
|
||||
.roles("USER", "ADMIN")
|
||||
.build();
|
||||
return new InMemoryUserDetailsManager(user);
|
||||
}
|
||||
|
||||
@@ -261,8 +267,11 @@ public class X509ConfigurerTests {
|
||||
|
||||
@Bean
|
||||
UserDetailsService userDetailsService() {
|
||||
UserDetails user = User.withDefaultPasswordEncoder().username("rod").password("password")
|
||||
.roles("USER", "ADMIN").build();
|
||||
UserDetails user = User.withDefaultPasswordEncoder()
|
||||
.username("rod")
|
||||
.password("password")
|
||||
.roles("USER", "ADMIN")
|
||||
.build();
|
||||
return new InMemoryUserDetailsManager(user);
|
||||
}
|
||||
|
||||
@@ -341,8 +350,11 @@ public class X509ConfigurerTests {
|
||||
|
||||
@Bean
|
||||
UserDetailsService userDetailsService() {
|
||||
UserDetails user = User.withDefaultPasswordEncoder().username("rod").password("password")
|
||||
.roles("USER", "ADMIN").build();
|
||||
UserDetails user = User.withDefaultPasswordEncoder()
|
||||
.username("rod")
|
||||
.password("password")
|
||||
.roles("USER", "ADMIN")
|
||||
.build();
|
||||
return new InMemoryUserDetailsManager(user);
|
||||
}
|
||||
|
||||
|
||||
@@ -138,10 +138,12 @@ public class OAuth2ClientConfigurerTests {
|
||||
"/oauth2/authorization");
|
||||
authorizationRedirectStrategy = new DefaultRedirectStrategy();
|
||||
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234")
|
||||
.tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(300).build();
|
||||
.tokenType(OAuth2AccessToken.TokenType.BEARER)
|
||||
.expiresIn(300)
|
||||
.build();
|
||||
accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
|
||||
given(accessTokenResponseClient.getTokenResponse(any(OAuth2AuthorizationCodeGrantRequest.class)))
|
||||
.willReturn(accessTokenResponse);
|
||||
.willReturn(accessTokenResponse);
|
||||
requestCache = mock(RequestCache.class);
|
||||
}
|
||||
|
||||
@@ -161,10 +163,11 @@ public class OAuth2ClientConfigurerTests {
|
||||
public void configureWhenOauth2ClientInLambdaThenRedirectForAuthorization() throws Exception {
|
||||
this.spring.register(OAuth2ClientInLambdaConfig.class).autowire();
|
||||
MvcResult mvcResult = this.mockMvc.perform(get("/oauth2/authorization/registration-1"))
|
||||
.andExpect(status().is3xxRedirection()).andReturn();
|
||||
.andExpect(status().is3xxRedirection())
|
||||
.andReturn();
|
||||
assertThat(mvcResult.getResponse().getRedirectedUrl())
|
||||
.matches("https://provider.com/oauth2/authorize\\?" + "response_type=code&client_id=client-1&"
|
||||
+ "scope=user&state=.{15,}&" + "redirect_uri=http://localhost/client-1");
|
||||
.matches("https://provider.com/oauth2/authorize\\?" + "response_type=code&client_id=client-1&"
|
||||
+ "scope=user&state=.{15,}&" + "redirect_uri=http://localhost/client-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -200,7 +203,7 @@ public class OAuth2ClientConfigurerTests {
|
||||
.andExpect(redirectedUrl("http://localhost/client-1"));
|
||||
// @formatter:on
|
||||
OAuth2AuthorizedClient authorizedClient = authorizedClientRepository
|
||||
.loadAuthorizedClient(this.registration1.getRegistrationId(), authentication, request);
|
||||
.loadAuthorizedClient(this.registration1.getRegistrationId(), authentication, request);
|
||||
assertThat(authorizedClient).isNotNull();
|
||||
}
|
||||
|
||||
@@ -209,10 +212,11 @@ public class OAuth2ClientConfigurerTests {
|
||||
throws Exception {
|
||||
this.spring.register(OAuth2ClientConfig.class).autowire();
|
||||
MvcResult mvcResult = this.mockMvc.perform(get("/resource1").with(user("user1")))
|
||||
.andExpect(status().is3xxRedirection()).andReturn();
|
||||
.andExpect(status().is3xxRedirection())
|
||||
.andReturn();
|
||||
assertThat(mvcResult.getResponse().getRedirectedUrl())
|
||||
.matches("https://provider.com/oauth2/authorize\\?" + "response_type=code&client_id=client-1&"
|
||||
+ "scope=user&state=.{15,}&" + "redirect_uri=http://localhost/client-1");
|
||||
.matches("https://provider.com/oauth2/authorize\\?" + "response_type=code&client_id=client-1&"
|
||||
+ "scope=user&state=.{15,}&" + "redirect_uri=http://localhost/client-1");
|
||||
verify(requestCache).saveRequest(any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
}
|
||||
|
||||
@@ -258,7 +262,7 @@ public class OAuth2ClientConfigurerTests {
|
||||
OAuth2AuthorizationRequestResolver defaultAuthorizationRequestResolver = authorizationRequestResolver;
|
||||
authorizationRequestResolver = mock(OAuth2AuthorizationRequestResolver.class);
|
||||
given(authorizationRequestResolver.resolve(any()))
|
||||
.willAnswer((invocation) -> defaultAuthorizationRequestResolver.resolve(invocation.getArgument(0)));
|
||||
.willAnswer((invocation) -> defaultAuthorizationRequestResolver.resolve(invocation.getArgument(0)));
|
||||
this.spring.register(OAuth2ClientConfig.class).autowire();
|
||||
// @formatter:off
|
||||
this.mockMvc.perform(get("/oauth2/authorization/registration-1"))
|
||||
|
||||
@@ -196,10 +196,12 @@ public class OAuth2LoginConfigurerTests {
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
|
||||
// assertions
|
||||
Authentication authentication = this.securityContextRepository
|
||||
.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
|
||||
.loadContext(new HttpRequestResponseHolder(this.request, this.response))
|
||||
.getAuthentication();
|
||||
assertThat(authentication.getAuthorities()).hasSize(1);
|
||||
assertThat(authentication.getAuthorities()).first().isInstanceOf(OAuth2UserAuthority.class)
|
||||
.hasToString("OAUTH2_USER");
|
||||
assertThat(authentication.getAuthorities()).first()
|
||||
.isInstanceOf(OAuth2UserAuthority.class)
|
||||
.hasToString("OAUTH2_USER");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -211,10 +213,12 @@ public class OAuth2LoginConfigurerTests {
|
||||
this.request.setParameter("state", authorizationRequest.getState());
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
|
||||
Authentication authentication = this.securityContextRepository
|
||||
.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
|
||||
.loadContext(new HttpRequestResponseHolder(this.request, this.response))
|
||||
.getAuthentication();
|
||||
assertThat(authentication.getAuthorities()).hasSize(1);
|
||||
assertThat(authentication.getAuthorities()).first().isInstanceOf(OAuth2UserAuthority.class)
|
||||
.hasToString("OAUTH2_USER");
|
||||
assertThat(authentication.getAuthorities()).first()
|
||||
.isInstanceOf(OAuth2UserAuthority.class)
|
||||
.hasToString("OAUTH2_USER");
|
||||
SecurityContextHolderStrategy strategy = this.context.getBean(SecurityContextHolderStrategy.class);
|
||||
verify(strategy, atLeastOnce()).getDeferredContext();
|
||||
SecurityContextChangedListener listener = this.context.getBean(SecurityContextChangedListener.class);
|
||||
@@ -230,10 +234,12 @@ public class OAuth2LoginConfigurerTests {
|
||||
this.request.setParameter("state", authorizationRequest.getState());
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
|
||||
Authentication authentication = this.securityContextRepository
|
||||
.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
|
||||
.loadContext(new HttpRequestResponseHolder(this.request, this.response))
|
||||
.getAuthentication();
|
||||
assertThat(authentication.getAuthorities()).hasSize(1);
|
||||
assertThat(authentication.getAuthorities()).first().isInstanceOf(OAuth2UserAuthority.class)
|
||||
.hasToString("OAUTH2_USER");
|
||||
assertThat(authentication.getAuthorities()).first()
|
||||
.isInstanceOf(OAuth2UserAuthority.class)
|
||||
.hasToString("OAUTH2_USER");
|
||||
}
|
||||
|
||||
// gh-6009
|
||||
@@ -269,7 +275,8 @@ public class OAuth2LoginConfigurerTests {
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
|
||||
// assertions
|
||||
Authentication authentication = this.securityContextRepository
|
||||
.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
|
||||
.loadContext(new HttpRequestResponseHolder(this.request, this.response))
|
||||
.getAuthentication();
|
||||
assertThat(authentication.getAuthorities()).hasSize(2);
|
||||
assertThat(authentication.getAuthorities()).first().hasToString("OAUTH2_USER");
|
||||
assertThat(authentication.getAuthorities()).last().hasToString("ROLE_OAUTH2_USER");
|
||||
@@ -289,7 +296,8 @@ public class OAuth2LoginConfigurerTests {
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
|
||||
// assertions
|
||||
Authentication authentication = this.securityContextRepository
|
||||
.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
|
||||
.loadContext(new HttpRequestResponseHolder(this.request, this.response))
|
||||
.getAuthentication();
|
||||
assertThat(authentication.getAuthorities()).hasSize(2);
|
||||
assertThat(authentication.getAuthorities()).first().hasToString("OAUTH2_USER");
|
||||
assertThat(authentication.getAuthorities()).last().hasToString("ROLE_OAUTH2_USER");
|
||||
@@ -309,7 +317,8 @@ public class OAuth2LoginConfigurerTests {
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
|
||||
// assertions
|
||||
Authentication authentication = this.securityContextRepository
|
||||
.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
|
||||
.loadContext(new HttpRequestResponseHolder(this.request, this.response))
|
||||
.getAuthentication();
|
||||
assertThat(authentication.getAuthorities()).hasSize(2);
|
||||
assertThat(authentication.getAuthorities()).first().hasToString("OAUTH2_USER");
|
||||
assertThat(authentication.getAuthorities()).last().hasToString("ROLE_OAUTH2_USER");
|
||||
@@ -331,10 +340,12 @@ public class OAuth2LoginConfigurerTests {
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
|
||||
// assertions
|
||||
Authentication authentication = this.securityContextRepository
|
||||
.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
|
||||
.loadContext(new HttpRequestResponseHolder(this.request, this.response))
|
||||
.getAuthentication();
|
||||
assertThat(authentication.getAuthorities()).hasSize(1);
|
||||
assertThat(authentication.getAuthorities()).first().isInstanceOf(OAuth2UserAuthority.class)
|
||||
.hasToString("OAUTH2_USER");
|
||||
assertThat(authentication.getAuthorities()).first()
|
||||
.isInstanceOf(OAuth2UserAuthority.class)
|
||||
.hasToString("OAUTH2_USER");
|
||||
}
|
||||
|
||||
// gh-5521
|
||||
@@ -342,7 +353,7 @@ public class OAuth2LoginConfigurerTests {
|
||||
public void oauth2LoginWithCustomAuthorizationRequestParameters() throws Exception {
|
||||
loadConfig(OAuth2LoginConfigCustomAuthorizationRequestResolver.class);
|
||||
OAuth2AuthorizationRequestResolver resolver = this.context
|
||||
.getBean(OAuth2LoginConfigCustomAuthorizationRequestResolver.class).resolver;
|
||||
.getBean(OAuth2LoginConfigCustomAuthorizationRequestResolver.class).resolver;
|
||||
// @formatter:off
|
||||
OAuth2AuthorizationRequest result = OAuth2AuthorizationRequest.authorizationCode()
|
||||
.authorizationUri("https://accounts.google.com/authorize")
|
||||
@@ -366,7 +377,7 @@ public class OAuth2LoginConfigurerTests {
|
||||
throws Exception {
|
||||
loadConfig(OAuth2LoginConfigCustomAuthorizationRequestResolverInLambda.class);
|
||||
OAuth2AuthorizationRequestResolver resolver = this.context
|
||||
.getBean(OAuth2LoginConfigCustomAuthorizationRequestResolverInLambda.class).resolver;
|
||||
.getBean(OAuth2LoginConfigCustomAuthorizationRequestResolverInLambda.class).resolver;
|
||||
// @formatter:off
|
||||
OAuth2AuthorizationRequest result = OAuth2AuthorizationRequest.authorizationCode()
|
||||
.authorizationUri("https://accounts.google.com/authorize")
|
||||
@@ -390,7 +401,7 @@ public class OAuth2LoginConfigurerTests {
|
||||
throws Exception {
|
||||
loadConfig(OAuth2LoginConfigCustomAuthorizationRedirectStrategy.class);
|
||||
RedirectStrategy redirectStrategy = this.context
|
||||
.getBean(OAuth2LoginConfigCustomAuthorizationRedirectStrategy.class).redirectStrategy;
|
||||
.getBean(OAuth2LoginConfigCustomAuthorizationRedirectStrategy.class).redirectStrategy;
|
||||
String requestUri = "/oauth2/authorization/google";
|
||||
this.request = new MockHttpServletRequest("GET", requestUri);
|
||||
this.request.setServletPath(requestUri);
|
||||
@@ -403,7 +414,7 @@ public class OAuth2LoginConfigurerTests {
|
||||
throws Exception {
|
||||
loadConfig(OAuth2LoginConfigCustomAuthorizationRedirectStrategyInLambda.class);
|
||||
RedirectStrategy redirectStrategy = this.context
|
||||
.getBean(OAuth2LoginConfigCustomAuthorizationRedirectStrategyInLambda.class).redirectStrategy;
|
||||
.getBean(OAuth2LoginConfigCustomAuthorizationRedirectStrategyInLambda.class).redirectStrategy;
|
||||
String requestUri = "/oauth2/authorization/google";
|
||||
this.request = new MockHttpServletRequest("GET", requestUri);
|
||||
this.request.setServletPath(requestUri);
|
||||
@@ -540,10 +551,12 @@ public class OAuth2LoginConfigurerTests {
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
|
||||
// assertions
|
||||
Authentication authentication = this.securityContextRepository
|
||||
.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
|
||||
.loadContext(new HttpRequestResponseHolder(this.request, this.response))
|
||||
.getAuthentication();
|
||||
assertThat(authentication.getAuthorities()).hasSize(1);
|
||||
assertThat(authentication.getAuthorities()).first().isInstanceOf(OidcUserAuthority.class)
|
||||
.hasToString("OIDC_USER");
|
||||
assertThat(authentication.getAuthorities()).first()
|
||||
.isInstanceOf(OidcUserAuthority.class)
|
||||
.hasToString("OIDC_USER");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -560,10 +573,12 @@ public class OAuth2LoginConfigurerTests {
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
|
||||
// assertions
|
||||
Authentication authentication = this.securityContextRepository
|
||||
.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
|
||||
.loadContext(new HttpRequestResponseHolder(this.request, this.response))
|
||||
.getAuthentication();
|
||||
assertThat(authentication.getAuthorities()).hasSize(1);
|
||||
assertThat(authentication.getAuthorities()).first().isInstanceOf(OidcUserAuthority.class)
|
||||
.hasToString("OIDC_USER");
|
||||
assertThat(authentication.getAuthorities()).first()
|
||||
.isInstanceOf(OidcUserAuthority.class)
|
||||
.hasToString("OIDC_USER");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -580,7 +595,8 @@ public class OAuth2LoginConfigurerTests {
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
|
||||
// assertions
|
||||
Authentication authentication = this.securityContextRepository
|
||||
.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
|
||||
.loadContext(new HttpRequestResponseHolder(this.request, this.response))
|
||||
.getAuthentication();
|
||||
assertThat(authentication.getAuthorities()).hasSize(2);
|
||||
assertThat(authentication.getAuthorities()).first().hasToString("OIDC_USER");
|
||||
assertThat(authentication.getAuthorities()).last().hasToString("ROLE_OIDC_USER");
|
||||
@@ -600,7 +616,8 @@ public class OAuth2LoginConfigurerTests {
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
|
||||
// assertions
|
||||
Authentication authentication = this.securityContextRepository
|
||||
.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
|
||||
.loadContext(new HttpRequestResponseHolder(this.request, this.response))
|
||||
.getAuthentication();
|
||||
assertThat(authentication.getAuthorities()).hasSize(2);
|
||||
assertThat(authentication.getAuthorities()).first().hasToString("OIDC_USER");
|
||||
assertThat(authentication.getAuthorities()).last().hasToString("ROLE_OIDC_USER");
|
||||
@@ -609,11 +626,11 @@ public class OAuth2LoginConfigurerTests {
|
||||
@Test
|
||||
public void oidcLoginCustomWithNoUniqueJwtDecoderFactory() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> loadConfig(OAuth2LoginConfig.class, NoUniqueJwtDecoderFactoryConfig.class))
|
||||
.withRootCauseInstanceOf(NoUniqueBeanDefinitionException.class)
|
||||
.withMessageContaining("No qualifying bean of type "
|
||||
+ "'org.springframework.security.oauth2.jwt.JwtDecoderFactory<org.springframework.security.oauth2.client.registration.ClientRegistration>' "
|
||||
+ "available: expected single matching bean but found 2: jwtDecoderFactory1,jwtDecoderFactory2");
|
||||
.isThrownBy(() -> loadConfig(OAuth2LoginConfig.class, NoUniqueJwtDecoderFactoryConfig.class))
|
||||
.withRootCauseInstanceOf(NoUniqueBeanDefinitionException.class)
|
||||
.withMessageContaining("No qualifying bean of type "
|
||||
+ "'org.springframework.security.oauth2.jwt.JwtDecoderFactory<org.springframework.security.oauth2.client.registration.ClientRegistration>' "
|
||||
+ "available: expected single matching bean but found 2: jwtDecoderFactory1,jwtDecoderFactory2");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -622,7 +639,7 @@ public class OAuth2LoginConfigurerTests {
|
||||
OAuth2AuthenticationToken token = new OAuth2AuthenticationToken(TestOidcUsers.create(),
|
||||
AuthorityUtils.NO_AUTHORITIES, "registration-id");
|
||||
this.mvc.perform(post("/logout").with(authentication(token)).with(csrf()))
|
||||
.andExpect(redirectedUrl("https://logout?id_token_hint=id-token"));
|
||||
.andExpect(redirectedUrl("https://logout?id_token_hint=id-token"));
|
||||
}
|
||||
|
||||
private void loadConfig(Class<?>... configs) {
|
||||
@@ -658,8 +675,10 @@ public class OAuth2LoginConfigurerTests {
|
||||
if (request.getAuthorizationExchange().getAuthorizationRequest().getScopes().contains("openid")) {
|
||||
additionalParameters.put(OidcParameterNames.ID_TOKEN, "token123");
|
||||
}
|
||||
return OAuth2AccessTokenResponse.withToken("accessToken123").tokenType(OAuth2AccessToken.TokenType.BEARER)
|
||||
.additionalParameters(additionalParameters).build();
|
||||
return OAuth2AccessTokenResponse.withToken("accessToken123")
|
||||
.tokenType(OAuth2AccessToken.TokenType.BEARER)
|
||||
.additionalParameters(additionalParameters)
|
||||
.build();
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1073,7 +1092,8 @@ public class OAuth2LoginConfigurerTests {
|
||||
ClientRegistrationRepository clientRegistrationRepository() {
|
||||
Map<String, Object> providerMetadata = Collections.singletonMap("end_session_endpoint", "https://logout");
|
||||
return new InMemoryClientRegistrationRepository(TestClientRegistrations.clientRegistration()
|
||||
.providerConfigurationMetadata(providerMetadata).build());
|
||||
.providerConfigurationMetadata(providerMetadata)
|
||||
.build());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -124,10 +124,15 @@ public class OidcLogoutConfigurerTests {
|
||||
this.spring.register(WebServerConfig.class, OidcProviderConfig.class, DefaultConfig.class).autowire();
|
||||
String registrationId = this.clientRegistration.getRegistrationId();
|
||||
MockHttpSession session = login();
|
||||
String logoutToken = this.mvc.perform(get("/token/logout").session(session)).andExpect(status().isOk())
|
||||
.andReturn().getResponse().getContentAsString();
|
||||
this.mvc.perform(post(this.web.url("/logout/connect/back-channel/" + registrationId).toString())
|
||||
.param("logout_token", logoutToken)).andExpect(status().isOk());
|
||||
String logoutToken = this.mvc.perform(get("/token/logout").session(session))
|
||||
.andExpect(status().isOk())
|
||||
.andReturn()
|
||||
.getResponse()
|
||||
.getContentAsString();
|
||||
this.mvc
|
||||
.perform(post(this.web.url("/logout/connect/back-channel/" + registrationId).toString())
|
||||
.param("logout_token", logoutToken))
|
||||
.andExpect(status().isOk());
|
||||
this.mvc.perform(get("/token/logout").session(session)).andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
@@ -137,18 +142,27 @@ public class OidcLogoutConfigurerTests {
|
||||
this.mvc.perform(get("/token/logout")).andExpect(status().isUnauthorized());
|
||||
String registrationId = this.clientRegistration.getRegistrationId();
|
||||
MvcResult result = this.mvc.perform(get("/oauth2/authorization/" + registrationId))
|
||||
.andExpect(status().isFound()).andReturn();
|
||||
.andExpect(status().isFound())
|
||||
.andReturn();
|
||||
MockHttpSession session = (MockHttpSession) result.getRequest().getSession();
|
||||
String redirectUrl = UrlUtils.decode(result.getResponse().getRedirectedUrl());
|
||||
String state = this.mvc
|
||||
.perform(get(redirectUrl).with(
|
||||
httpBasic(this.clientRegistration.getClientId(), this.clientRegistration.getClientSecret())))
|
||||
.andReturn().getResponse().getContentAsString();
|
||||
result = this.mvc.perform(get("/login/oauth2/code/" + registrationId).param("code", "code")
|
||||
.param("state", state).session(session)).andExpect(status().isFound()).andReturn();
|
||||
.perform(get(redirectUrl)
|
||||
.with(httpBasic(this.clientRegistration.getClientId(), this.clientRegistration.getClientSecret())))
|
||||
.andReturn()
|
||||
.getResponse()
|
||||
.getContentAsString();
|
||||
result = this.mvc
|
||||
.perform(get("/login/oauth2/code/" + registrationId).param("code", "code")
|
||||
.param("state", state)
|
||||
.session(session))
|
||||
.andExpect(status().isFound())
|
||||
.andReturn();
|
||||
session = (MockHttpSession) result.getRequest().getSession();
|
||||
this.mvc.perform(post(this.web.url("/logout/connect/back-channel/" + registrationId).toString())
|
||||
.param("logout_token", "invalid")).andExpect(status().isBadRequest());
|
||||
this.mvc
|
||||
.perform(post(this.web.url("/logout/connect/back-channel/" + registrationId).toString())
|
||||
.param("logout_token", "invalid"))
|
||||
.andExpect(status().isBadRequest());
|
||||
this.mvc.perform(get("/token/logout").session(session)).andExpect(status().isOk());
|
||||
}
|
||||
|
||||
@@ -159,16 +173,26 @@ public class OidcLogoutConfigurerTests {
|
||||
MockHttpSession one = login();
|
||||
MockHttpSession two = login();
|
||||
MockHttpSession three = login();
|
||||
String logoutToken = this.mvc.perform(get("/token/logout").session(one)).andExpect(status().isOk()).andReturn()
|
||||
.getResponse().getContentAsString();
|
||||
this.mvc.perform(post(this.web.url("/logout/connect/back-channel/" + registrationId).toString())
|
||||
.param("logout_token", logoutToken)).andExpect(status().isOk());
|
||||
String logoutToken = this.mvc.perform(get("/token/logout").session(one))
|
||||
.andExpect(status().isOk())
|
||||
.andReturn()
|
||||
.getResponse()
|
||||
.getContentAsString();
|
||||
this.mvc
|
||||
.perform(post(this.web.url("/logout/connect/back-channel/" + registrationId).toString())
|
||||
.param("logout_token", logoutToken))
|
||||
.andExpect(status().isOk());
|
||||
this.mvc.perform(get("/token/logout").session(one)).andExpect(status().isUnauthorized());
|
||||
this.mvc.perform(get("/token/logout").session(two)).andExpect(status().isOk());
|
||||
logoutToken = this.mvc.perform(get("/token/logout/all").session(three)).andExpect(status().isOk()).andReturn()
|
||||
.getResponse().getContentAsString();
|
||||
this.mvc.perform(post(this.web.url("/logout/connect/back-channel/" + registrationId).toString())
|
||||
.param("logout_token", logoutToken)).andExpect(status().isOk());
|
||||
logoutToken = this.mvc.perform(get("/token/logout/all").session(three))
|
||||
.andExpect(status().isOk())
|
||||
.andReturn()
|
||||
.getResponse()
|
||||
.getContentAsString();
|
||||
this.mvc
|
||||
.perform(post(this.web.url("/logout/connect/back-channel/" + registrationId).toString())
|
||||
.param("logout_token", logoutToken))
|
||||
.andExpect(status().isOk());
|
||||
this.mvc.perform(get("/token/logout").session(two)).andExpect(status().isUnauthorized());
|
||||
this.mvc.perform(get("/token/logout").session(three)).andExpect(status().isUnauthorized());
|
||||
}
|
||||
@@ -180,24 +204,34 @@ public class OidcLogoutConfigurerTests {
|
||||
willThrow(IllegalStateException.class).given(logoutHandler).logout(any(), any(), any());
|
||||
String registrationId = this.clientRegistration.getRegistrationId();
|
||||
MockHttpSession one = login();
|
||||
String logoutToken = this.mvc.perform(get("/token/logout/all").session(one)).andExpect(status().isOk())
|
||||
.andReturn().getResponse().getContentAsString();
|
||||
this.mvc.perform(post(this.web.url("/logout/connect/back-channel/" + registrationId).toString())
|
||||
.param("logout_token", logoutToken)).andExpect(status().isBadRequest())
|
||||
.andExpect(content().string(containsString("partial_logout")));
|
||||
String logoutToken = this.mvc.perform(get("/token/logout/all").session(one))
|
||||
.andExpect(status().isOk())
|
||||
.andReturn()
|
||||
.getResponse()
|
||||
.getContentAsString();
|
||||
this.mvc
|
||||
.perform(post(this.web.url("/logout/connect/back-channel/" + registrationId).toString())
|
||||
.param("logout_token", logoutToken))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(content().string(containsString("partial_logout")));
|
||||
this.mvc.perform(get("/token/logout").session(one)).andExpect(status().isOk());
|
||||
}
|
||||
|
||||
@Test
|
||||
void logoutWhenCustomComponentsThenUses() throws Exception {
|
||||
this.spring.register(WebServerConfig.class, OidcProviderConfig.class, WithCustomComponentsConfig.class)
|
||||
.autowire();
|
||||
.autowire();
|
||||
String registrationId = this.clientRegistration.getRegistrationId();
|
||||
MockHttpSession session = login();
|
||||
String logoutToken = this.mvc.perform(get("/token/logout").session(session)).andExpect(status().isOk())
|
||||
.andReturn().getResponse().getContentAsString();
|
||||
this.mvc.perform(post(this.web.url("/logout/connect/back-channel/" + registrationId).toString())
|
||||
.param("logout_token", logoutToken)).andExpect(status().isOk());
|
||||
String logoutToken = this.mvc.perform(get("/token/logout").session(session))
|
||||
.andExpect(status().isOk())
|
||||
.andReturn()
|
||||
.getResponse()
|
||||
.getContentAsString();
|
||||
this.mvc
|
||||
.perform(post(this.web.url("/logout/connect/back-channel/" + registrationId).toString())
|
||||
.param("logout_token", logoutToken))
|
||||
.andExpect(status().isOk());
|
||||
this.mvc.perform(get("/token/logout").session(session)).andExpect(status().isUnauthorized());
|
||||
OidcSessionRegistry sessionRegistry = this.spring.getContext().getBean(OidcSessionRegistry.class);
|
||||
verify(sessionRegistry).saveSessionInformation(any());
|
||||
@@ -209,15 +243,22 @@ public class OidcLogoutConfigurerTests {
|
||||
this.mvc.perform(get("/token/logout")).andExpect(status().isUnauthorized());
|
||||
String registrationId = this.clientRegistration.getRegistrationId();
|
||||
MvcResult result = this.mvc.perform(get("/oauth2/authorization/" + registrationId))
|
||||
.andExpect(status().isFound()).andReturn();
|
||||
.andExpect(status().isFound())
|
||||
.andReturn();
|
||||
MockHttpSession session = (MockHttpSession) result.getRequest().getSession();
|
||||
String redirectUrl = UrlUtils.decode(result.getResponse().getRedirectedUrl());
|
||||
String state = this.mvc
|
||||
.perform(get(redirectUrl).with(
|
||||
httpBasic(this.clientRegistration.getClientId(), this.clientRegistration.getClientSecret())))
|
||||
.andReturn().getResponse().getContentAsString();
|
||||
result = this.mvc.perform(get("/login/oauth2/code/" + registrationId).param("code", "code")
|
||||
.param("state", state).session(session)).andExpect(status().isFound()).andReturn();
|
||||
.perform(get(redirectUrl)
|
||||
.with(httpBasic(this.clientRegistration.getClientId(), this.clientRegistration.getClientSecret())))
|
||||
.andReturn()
|
||||
.getResponse()
|
||||
.getContentAsString();
|
||||
result = this.mvc
|
||||
.perform(get("/login/oauth2/code/" + registrationId).param("code", "code")
|
||||
.param("state", state)
|
||||
.session(session))
|
||||
.andExpect(status().isFound())
|
||||
.andReturn();
|
||||
session = (MockHttpSession) result.getRequest().getSession();
|
||||
dispatcher.registerSession(session);
|
||||
return session;
|
||||
@@ -235,8 +276,13 @@ public class OidcLogoutConfigurerTests {
|
||||
return TestClientRegistrations.clientRegistration().build();
|
||||
}
|
||||
String issuer = this.web.url("/").toString();
|
||||
return TestClientRegistrations.clientRegistration().issuerUri(issuer).jwkSetUri(issuer + "jwks")
|
||||
.tokenUri(issuer + "token").userInfoUri(issuer + "user").scope("openid").build();
|
||||
return TestClientRegistrations.clientRegistration()
|
||||
.issuerUri(issuer)
|
||||
.jwkSetUri(issuer + "jwks")
|
||||
.tokenUri(issuer + "token")
|
||||
.userInfoUri(issuer + "user")
|
||||
.scope("openid")
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
|
||||
@@ -226,8 +226,10 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
|
||||
@Test
|
||||
public void getWhenCustomSecurityContextHolderStrategyThenUses() throws Exception {
|
||||
this.spring.register(RestOperationsConfig.class, DefaultConfig.class, BasicController.class,
|
||||
SecurityContextChangedListenerConfig.class).autowire();
|
||||
this.spring
|
||||
.register(RestOperationsConfig.class, DefaultConfig.class, BasicController.class,
|
||||
SecurityContextChangedListenerConfig.class)
|
||||
.autowire();
|
||||
mockRestOperations(jwks("Default"));
|
||||
String token = this.token("ValidNoScopes");
|
||||
// @formatter:off
|
||||
@@ -240,8 +242,10 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
|
||||
@Test
|
||||
public void getWhenSecurityContextHolderStrategyThenUses() throws Exception {
|
||||
this.spring.register(RestOperationsConfig.class, DefaultConfig.class,
|
||||
SecurityContextChangedListenerConfig.class, BasicController.class).autowire();
|
||||
this.spring
|
||||
.register(RestOperationsConfig.class, DefaultConfig.class, SecurityContextChangedListenerConfig.class,
|
||||
BasicController.class)
|
||||
.autowire();
|
||||
mockRestOperations(jwks("Default"));
|
||||
String token = this.token("ValidNoScopes");
|
||||
// @formatter:off
|
||||
@@ -639,7 +643,7 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
@Test
|
||||
public void requestWhenSessionManagementConfiguredThenUserConfigurationOverrides() throws Exception {
|
||||
this.spring.register(RestOperationsConfig.class, AlwaysSessionCreationConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
.autowire();
|
||||
mockRestOperations(jwks("Default"));
|
||||
String token = this.token("ValidNoScopes");
|
||||
// @formatter:off
|
||||
@@ -654,7 +658,7 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
public void requestWhenBearerTokenResolverAllowsRequestBodyThenEitherHeaderOrRequestBodyIsAccepted()
|
||||
throws Exception {
|
||||
this.spring.register(AllowBearerTokenInRequestBodyConfig.class, JwtDecoderConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
.autowire();
|
||||
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
|
||||
given(decoder.decode(anyString())).willReturn(JWT);
|
||||
// @formatter:off
|
||||
@@ -671,8 +675,8 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
public void requestWhenBearerTokenResolverAllowsQueryParameterThenEitherHeaderOrQueryParameterIsAccepted()
|
||||
throws Exception {
|
||||
this.spring
|
||||
.register(AllowBearerTokenAsQueryParameterConfig.class, JwtDecoderConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
.register(AllowBearerTokenAsQueryParameterConfig.class, JwtDecoderConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
|
||||
given(decoder.decode(anyString())).willReturn(JWT);
|
||||
// @formatter:off
|
||||
@@ -689,7 +693,7 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
public void requestWhenBearerTokenResolverAllowsRequestBodyAndRequestContainsTwoTokensThenInvalidRequest()
|
||||
throws Exception {
|
||||
this.spring.register(AllowBearerTokenInRequestBodyConfig.class, JwtDecoderConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
.autowire();
|
||||
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
|
||||
given(decoder.decode(anyString())).willReturn(JWT);
|
||||
// @formatter:off
|
||||
@@ -708,8 +712,8 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
public void requestWhenBearerTokenResolverAllowsQueryParameterAndRequestContainsTwoTokensThenInvalidRequest()
|
||||
throws Exception {
|
||||
this.spring
|
||||
.register(AllowBearerTokenAsQueryParameterConfig.class, JwtDecoderConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
.register(AllowBearerTokenAsQueryParameterConfig.class, JwtDecoderConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
|
||||
given(decoder.decode(anyString())).willReturn(JWT);
|
||||
// @formatter:off
|
||||
@@ -738,9 +742,9 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
@Test
|
||||
public void getBearerTokenResolverWhenDuplicateResolverBeansThenWiringException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring
|
||||
.register(MultipleBearerTokenResolverBeansConfig.class, JwtDecoderConfig.class).autowire())
|
||||
.withRootCauseInstanceOf(NoUniqueBeanDefinitionException.class);
|
||||
.isThrownBy(() -> this.spring.register(MultipleBearerTokenResolverBeansConfig.class, JwtDecoderConfig.class)
|
||||
.autowire())
|
||||
.withRootCauseInstanceOf(NoUniqueBeanDefinitionException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -765,11 +769,12 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
@Test
|
||||
public void requestWhenCustomAuthenticationDetailsSourceThenUsed() throws Exception {
|
||||
this.spring.register(CustomAuthenticationDetailsSource.class, JwtDecoderConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
.autowire();
|
||||
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
|
||||
given(decoder.decode(anyString())).willReturn(JWT);
|
||||
this.mvc.perform(get("/authenticated").with(bearerToken(JWT_TOKEN))).andExpect(status().isOk())
|
||||
.andExpect(content().string(JWT_SUBJECT));
|
||||
this.mvc.perform(get("/authenticated").with(bearerToken(JWT_TOKEN)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().string(JWT_SUBJECT));
|
||||
verifyBean(AuthenticationDetailsSource.class).buildDetails(any());
|
||||
}
|
||||
|
||||
@@ -914,8 +919,9 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
this.spring.register(RestOperationsConfig.class, CustomJwtValidatorConfig.class).autowire();
|
||||
mockRestOperations(jwks("Default"));
|
||||
String token = this.token("ValidNoScopes");
|
||||
OAuth2TokenValidator<Jwt> jwtValidator = this.spring.getContext().getBean(CustomJwtValidatorConfig.class)
|
||||
.getJwtValidator();
|
||||
OAuth2TokenValidator<Jwt> jwtValidator = this.spring.getContext()
|
||||
.getBean(CustomJwtValidatorConfig.class)
|
||||
.getJwtValidator();
|
||||
OAuth2Error error = new OAuth2Error("custom-error", "custom-description", "custom-uri");
|
||||
given(jwtValidator.validate(any(Jwt.class))).willReturn(OAuth2TokenValidatorResult.failure(error));
|
||||
// @formatter:off
|
||||
@@ -928,7 +934,7 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
@Test
|
||||
public void requestWhenClockSkewSetThenTimestampWindowRelaxedAccordingly() throws Exception {
|
||||
this.spring.register(RestOperationsConfig.class, UnexpiredJwtClockSkewConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
.autowire();
|
||||
mockRestOperations(jwks("Default"));
|
||||
String token = this.token("ExpiresAt4687177990");
|
||||
// @formatter:off
|
||||
@@ -940,7 +946,7 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
@Test
|
||||
public void requestWhenClockSkewSetButJwtStillTooLateThenReportsExpired() throws Exception {
|
||||
this.spring.register(RestOperationsConfig.class, ExpiredJwtClockSkewConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
.autowire();
|
||||
mockRestOperations(jwks("Default"));
|
||||
String token = this.token("ExpiresAt4687177990");
|
||||
// @formatter:off
|
||||
@@ -952,10 +958,12 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
|
||||
@Test
|
||||
public void requestWhenJwtAuthenticationConverterConfiguredOnDslThenIsUsed() throws Exception {
|
||||
this.spring.register(JwtDecoderConfig.class, JwtAuthenticationConverterConfiguredOnDsl.class,
|
||||
BasicController.class).autowire();
|
||||
this.spring
|
||||
.register(JwtDecoderConfig.class, JwtAuthenticationConverterConfiguredOnDsl.class, BasicController.class)
|
||||
.autowire();
|
||||
Converter<Jwt, JwtAuthenticationToken> jwtAuthenticationConverter = this.spring.getContext()
|
||||
.getBean(JwtAuthenticationConverterConfiguredOnDsl.class).getJwtAuthenticationConverter();
|
||||
.getBean(JwtAuthenticationConverterConfiguredOnDsl.class)
|
||||
.getJwtAuthenticationConverter();
|
||||
given(jwtAuthenticationConverter.convert(JWT)).willReturn(JWT_AUTHENTICATION_TOKEN);
|
||||
JwtDecoder jwtDecoder = this.spring.getContext().getBean(JwtDecoder.class);
|
||||
given(jwtDecoder.decode(anyString())).willReturn(JWT);
|
||||
@@ -970,7 +978,7 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
public void requestWhenJwtAuthenticationConverterCustomizedAuthoritiesThenThoseAuthoritiesArePropagated()
|
||||
throws Exception {
|
||||
this.spring.register(JwtDecoderConfig.class, CustomAuthorityMappingConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
.autowire();
|
||||
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
|
||||
given(decoder.decode(JWT_TOKEN)).willReturn(JWT);
|
||||
// @formatter:off
|
||||
@@ -1016,14 +1024,14 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
given(bean(JwtDecoder.class).decode(anyString())).willThrow(new BadJwtException("problem"));
|
||||
this.mvc.perform(get("/").with(bearerToken("token")));
|
||||
verifyBean(AuthenticationEventPublisher.class)
|
||||
.publishAuthenticationFailure(any(OAuth2AuthenticationException.class), any(Authentication.class));
|
||||
.publishAuthenticationFailure(any(OAuth2AuthenticationException.class), any(Authentication.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getWhenCustomJwtAuthenticationManagerThenUsed() throws Exception {
|
||||
this.spring.register(JwtAuthenticationManagerConfig.class, BasicController.class).autowire();
|
||||
given(bean(AuthenticationProvider.class).authenticate(any(Authentication.class)))
|
||||
.willReturn(JWT_AUTHENTICATION_TOKEN);
|
||||
.willReturn(JWT_AUTHENTICATION_TOKEN);
|
||||
// @formatter:off
|
||||
this.mvc.perform(get("/authenticated").with(bearerToken("token")))
|
||||
.andExpect(status().isOk())
|
||||
@@ -1036,11 +1044,11 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
public void getWhenDefaultAndCustomJwtAuthenticationManagerThenCustomUsed() throws Exception {
|
||||
this.spring.register(DefaultAndJwtAuthenticationManagerConfig.class, BasicController.class).autowire();
|
||||
DefaultAndJwtAuthenticationManagerConfig config = this.spring.getContext()
|
||||
.getBean(DefaultAndJwtAuthenticationManagerConfig.class);
|
||||
.getBean(DefaultAndJwtAuthenticationManagerConfig.class);
|
||||
AuthenticationManager defaultAuthenticationManager = config.defaultAuthenticationManager();
|
||||
AuthenticationManager jwtAuthenticationManager = config.jwtAuthenticationManager();
|
||||
given(defaultAuthenticationManager.authenticate(any()))
|
||||
.willThrow(new RuntimeException("should not interact with default auth manager"));
|
||||
.willThrow(new RuntimeException("should not interact with default auth manager"));
|
||||
given(jwtAuthenticationManager.authenticate(any())).willReturn(JWT_AUTHENTICATION_TOKEN);
|
||||
// @formatter:off
|
||||
this.mvc.perform(get("/authenticated").with(bearerToken("token")))
|
||||
@@ -1064,7 +1072,7 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
@Test
|
||||
public void getWhenOpaqueTokenInLambdaAndIntrospectingThenOk() throws Exception {
|
||||
this.spring.register(RestOperationsConfig.class, OpaqueTokenInLambdaConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
.autowire();
|
||||
mockRestOperations(json("Active"));
|
||||
// @formatter:off
|
||||
this.mvc.perform(get("/authenticated").with(bearerToken("token")))
|
||||
@@ -1099,7 +1107,7 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
public void getWhenCustomIntrospectionAuthenticationManagerThenUsed() throws Exception {
|
||||
this.spring.register(OpaqueTokenAuthenticationManagerConfig.class, BasicController.class).autowire();
|
||||
given(bean(AuthenticationProvider.class).authenticate(any(Authentication.class)))
|
||||
.willReturn(INTROSPECTION_AUTHENTICATION_TOKEN);
|
||||
.willReturn(INTROSPECTION_AUTHENTICATION_TOKEN);
|
||||
// @formatter:off
|
||||
this.mvc.perform(get("/authenticated").with(bearerToken("token")))
|
||||
.andExpect(status().isOk())
|
||||
@@ -1112,11 +1120,11 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
public void getWhenDefaultAndCustomIntrospectionAuthenticationManagerThenCustomUsed() throws Exception {
|
||||
this.spring.register(DefaultAndOpaqueTokenAuthenticationManagerConfig.class, BasicController.class).autowire();
|
||||
DefaultAndOpaqueTokenAuthenticationManagerConfig config = this.spring.getContext()
|
||||
.getBean(DefaultAndOpaqueTokenAuthenticationManagerConfig.class);
|
||||
.getBean(DefaultAndOpaqueTokenAuthenticationManagerConfig.class);
|
||||
AuthenticationManager defaultAuthenticationManager = config.defaultAuthenticationManager();
|
||||
AuthenticationManager opaqueTokenAuthenticationManager = config.opaqueTokenAuthenticationManager();
|
||||
given(defaultAuthenticationManager.authenticate(any()))
|
||||
.willThrow(new RuntimeException("should not interact with default auth manager"));
|
||||
.willThrow(new RuntimeException("should not interact with default auth manager"));
|
||||
given(opaqueTokenAuthenticationManager.authenticate(any())).willReturn(INTROSPECTION_AUTHENTICATION_TOKEN);
|
||||
// @formatter:off
|
||||
this.mvc.perform(get("/authenticated").with(bearerToken("token")))
|
||||
@@ -1130,7 +1138,7 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
public void getWhenCustomIntrospectionAuthenticationManagerInLambdaThenUsed() throws Exception {
|
||||
this.spring.register(OpaqueTokenAuthenticationManagerInLambdaConfig.class, BasicController.class).autowire();
|
||||
given(bean(AuthenticationProvider.class).authenticate(any(Authentication.class)))
|
||||
.willReturn(INTROSPECTION_AUTHENTICATION_TOKEN);
|
||||
.willReturn(INTROSPECTION_AUTHENTICATION_TOKEN);
|
||||
// @formatter:off
|
||||
this.mvc.perform(get("/authenticated").with(bearerToken("token")))
|
||||
.andExpect(status().isOk())
|
||||
@@ -1142,14 +1150,15 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
@Test
|
||||
public void configureWhenOnlyIntrospectionUrlThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(OpaqueTokenHalfConfiguredConfig.class).autowire());
|
||||
.isThrownBy(() -> this.spring.register(OpaqueTokenHalfConfiguredConfig.class).autowire());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getIntrospectionClientWhenConfiguredWithClientAndIntrospectionUriThenLastOneWins() {
|
||||
ApplicationContext context = mock(ApplicationContext.class);
|
||||
OAuth2ResourceServerConfigurer.OpaqueTokenConfigurer opaqueTokenConfigurer = new OAuth2ResourceServerConfigurer(
|
||||
context).opaqueToken();
|
||||
context)
|
||||
.opaqueToken();
|
||||
OpaqueTokenIntrospector client = mock(OpaqueTokenIntrospector.class);
|
||||
opaqueTokenConfigurer.introspectionUri(INTROSPECTION_URI);
|
||||
opaqueTokenConfigurer.introspectionClientCredentials(CLIENT_ID, CLIENT_SECRET);
|
||||
@@ -1168,7 +1177,7 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
registerMockBean(context, "introspectionClientOne", OpaqueTokenIntrospector.class);
|
||||
registerMockBean(context, "introspectionClientTwo", OpaqueTokenIntrospector.class);
|
||||
OAuth2ResourceServerConfigurer.OpaqueTokenConfigurer opaqueToken = new OAuth2ResourceServerConfigurer(context)
|
||||
.opaqueToken();
|
||||
.opaqueToken();
|
||||
opaqueToken.introspectionUri(INTROSPECTION_URI);
|
||||
opaqueToken.introspectionClientCredentials(CLIENT_ID, CLIENT_SECRET);
|
||||
assertThat(opaqueToken.getIntrospector()).isNotNull();
|
||||
@@ -1225,8 +1234,8 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
@Test
|
||||
public void requestWhenDefaultAndResourceServerAccessDeniedHandlersThenMatchedByRequest() throws Exception {
|
||||
this.spring
|
||||
.register(ExceptionHandlingAndResourceServerWithAccessDeniedHandlerConfig.class, JwtDecoderConfig.class)
|
||||
.autowire();
|
||||
.register(ExceptionHandlingAndResourceServerWithAccessDeniedHandlerConfig.class, JwtDecoderConfig.class)
|
||||
.autowire();
|
||||
JwtDecoder decoder = this.spring.getContext().getBean(JwtDecoder.class);
|
||||
given(decoder.decode(anyString())).willReturn(JWT);
|
||||
// @formatter:off
|
||||
@@ -1242,7 +1251,7 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
@Test
|
||||
public void getWhenAlsoUsingHttpBasicThenCorrectProviderEngages() throws Exception {
|
||||
this.spring.register(RestOperationsConfig.class, BasicAndResourceServerConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
.autowire();
|
||||
mockRestOperations(jwks("Default"));
|
||||
String token = this.token("ValidNoScopes");
|
||||
// @formatter:off
|
||||
@@ -1264,8 +1273,9 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
oauth2ResourceServer.jwt().authenticationManager(authenticationManager).decoder(mock(JwtDecoder.class));
|
||||
assertThat(oauth2ResourceServer.getAuthenticationManager(http)).isSameAs(authenticationManager);
|
||||
oauth2ResourceServer = new OAuth2ResourceServerConfigurer(context);
|
||||
oauth2ResourceServer.opaqueToken().authenticationManager(authenticationManager)
|
||||
.introspector(mock(OpaqueTokenIntrospector.class));
|
||||
oauth2ResourceServer.opaqueToken()
|
||||
.authenticationManager(authenticationManager)
|
||||
.introspector(mock(OpaqueTokenIntrospector.class));
|
||||
assertThat(oauth2ResourceServer.getAuthenticationManager(http)).isSameAs(authenticationManager);
|
||||
verify(http, never()).authenticationProvider(any(AuthenticationProvider.class));
|
||||
}
|
||||
@@ -1309,29 +1319,29 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
@Test
|
||||
public void configuredWhenMissingJwtAuthenticationProviderThenWiringException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(JwtlessConfig.class).autowire())
|
||||
.withMessageContaining("neither was found");
|
||||
.isThrownBy(() -> this.spring.register(JwtlessConfig.class).autowire())
|
||||
.withMessageContaining("neither was found");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configureWhenMissingJwkSetUriThenWiringException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(JwtHalfConfiguredConfig.class).autowire())
|
||||
.withMessageContaining("No qualifying bean of type");
|
||||
.isThrownBy(() -> this.spring.register(JwtHalfConfiguredConfig.class).autowire())
|
||||
.withMessageContaining("No qualifying bean of type");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configureWhenUsingBothJwtAndOpaqueThenWiringException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(OpaqueAndJwtConfig.class).autowire())
|
||||
.withMessageContaining("Spring Security only supports JWTs or Opaque Tokens");
|
||||
.isThrownBy(() -> this.spring.register(OpaqueAndJwtConfig.class).autowire())
|
||||
.withMessageContaining("Spring Security only supports JWTs or Opaque Tokens");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configureWhenUsingBothAuthenticationManagerResolverAndOpaqueThenWiringException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(AuthenticationManagerResolverPlusOtherConfig.class).autowire())
|
||||
.withMessageContaining("authenticationManagerResolver");
|
||||
.isThrownBy(() -> this.spring.register(AuthenticationManagerResolverPlusOtherConfig.class).autowire())
|
||||
.withMessageContaining("authenticationManagerResolver");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1385,16 +1395,17 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
this.spring.context(context).autowire();
|
||||
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
|
||||
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class)
|
||||
.isThrownBy(jwtConfigurer::getJwtAuthenticationConverter);
|
||||
.isThrownBy(jwtConfigurer::getJwtAuthenticationConverter);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getWhenCustomAuthenticationConverterThenUsed() throws Exception {
|
||||
this.spring.register(RestOperationsConfig.class, OpaqueTokenAuthenticationConverterConfig.class,
|
||||
BasicController.class).autowire();
|
||||
this.spring
|
||||
.register(RestOperationsConfig.class, OpaqueTokenAuthenticationConverterConfig.class, BasicController.class)
|
||||
.autowire();
|
||||
OpaqueTokenAuthenticationConverter authenticationConverter = bean(OpaqueTokenAuthenticationConverter.class);
|
||||
given(authenticationConverter.convert(anyString(), any(OAuth2AuthenticatedPrincipal.class)))
|
||||
.willReturn(new TestingAuthenticationToken("jdoe", null, Collections.emptyList()));
|
||||
.willReturn(new TestingAuthenticationToken("jdoe", null, Collections.emptyList()));
|
||||
mockRestOperations(json("Active"));
|
||||
// @formatter:off
|
||||
this.mvc.perform(get("/authenticated").with(bearerToken("token")))
|
||||
@@ -1449,7 +1460,8 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
|
||||
private void mockWebServer(String response) {
|
||||
this.web.enqueue(new MockResponse().setResponseCode(200)
|
||||
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).setBody(response));
|
||||
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
|
||||
.setBody(response));
|
||||
}
|
||||
|
||||
private void mockRestOperations(String response) {
|
||||
@@ -2293,7 +2305,7 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
@Bean
|
||||
JwtDecoder decoder() throws Exception {
|
||||
RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA")
|
||||
.generatePublic(new X509EncodedKeySpec(this.spec));
|
||||
.generatePublic(new X509EncodedKeySpec(this.spec));
|
||||
return NimbusJwtDecoder.withPublicKey(publicKey).build();
|
||||
}
|
||||
|
||||
@@ -2601,8 +2613,11 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
|
||||
@GetMapping("/requires-read-scope")
|
||||
String requiresReadScope(JwtAuthenticationToken token) {
|
||||
return token.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList())
|
||||
.toString();
|
||||
return token.getAuthorities()
|
||||
.stream()
|
||||
.map(GrantedAuthority::getAuthority)
|
||||
.collect(Collectors.toList())
|
||||
.toString();
|
||||
}
|
||||
|
||||
@GetMapping("/ms-requires-read-scope")
|
||||
@@ -2633,7 +2648,7 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
public void setEnvironment(Environment environment) {
|
||||
if (environment instanceof ConfigurableEnvironment) {
|
||||
((ConfigurableEnvironment) environment).getPropertySources()
|
||||
.addFirst(new MockWebServerPropertySource());
|
||||
.addFirst(new MockWebServerPropertySource());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2674,8 +2689,9 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
|
||||
@Bean
|
||||
NimbusJwtDecoder jwtDecoder() {
|
||||
return NimbusJwtDecoder.withJwkSetUri("https://example.org/.well-known/jwks.json").restOperations(this.rest)
|
||||
.build();
|
||||
return NimbusJwtDecoder.withJwkSetUri("https://example.org/.well-known/jwks.json")
|
||||
.restOperations(this.rest)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
|
||||
@@ -127,10 +127,10 @@ public class Saml2LoginConfigurerTests {
|
||||
}
|
||||
|
||||
private static final RelyingPartyRegistration registration = TestRelyingPartyRegistrations.noCredentials()
|
||||
.signingX509Credentials((c) -> c.add(TestSaml2X509Credentials.assertingPartySigningCredential()))
|
||||
.assertingPartyDetails((party) -> party.verificationX509Credentials(
|
||||
(c) -> c.add(TestSaml2X509Credentials.relyingPartyVerifyingCredential())))
|
||||
.build();
|
||||
.signingX509Credentials((c) -> c.add(TestSaml2X509Credentials.assertingPartySigningCredential()))
|
||||
.assertingPartyDetails((party) -> party
|
||||
.verificationX509Credentials((c) -> c.add(TestSaml2X509Credentials.relyingPartyVerifyingCredential())))
|
||||
.build();
|
||||
|
||||
private static String SIGNED_RESPONSE;
|
||||
|
||||
@@ -207,8 +207,8 @@ public class Saml2LoginConfigurerTests {
|
||||
@Test
|
||||
public void saml2LoginWhenCustomSecurityContextHolderStrategyThenUses() throws Exception {
|
||||
this.spring
|
||||
.register(Saml2LoginConfig.class, SecurityContextChangedListenerConfig.class, ResourceController.class)
|
||||
.autowire();
|
||||
.register(Saml2LoginConfig.class, SecurityContextChangedListenerConfig.class, ResourceController.class)
|
||||
.autowire();
|
||||
// @formatter:off
|
||||
MockHttpSession session = (MockHttpSession) this.mvc
|
||||
.perform(post("/login/saml2/sso/registration-id")
|
||||
@@ -220,7 +220,7 @@ public class Saml2LoginConfigurerTests {
|
||||
SecurityContextHolderStrategy strategy = this.spring.getContext().getBean(SecurityContextHolderStrategy.class);
|
||||
verify(strategy, atLeastOnce()).getContext();
|
||||
SecurityContextChangedListener listener = this.spring.getContext()
|
||||
.getBean(SecurityContextChangedListener.class);
|
||||
.getBean(SecurityContextChangedListener.class);
|
||||
verify(listener, times(2)).securityContextChanged(setAuthentication(Saml2Authentication.class));
|
||||
}
|
||||
|
||||
@@ -265,7 +265,7 @@ public class Saml2LoginConfigurerTests {
|
||||
RelyingPartyRegistration relyingPartyRegistration = this.repository.findByRegistrationId("registration-id");
|
||||
String response = new String(Saml2Utils.samlDecode(SIGNED_RESPONSE));
|
||||
given(CustomAuthenticationConverter.authenticationConverter.convert(any(HttpServletRequest.class)))
|
||||
.willReturn(new Saml2AuthenticationToken(relyingPartyRegistration, response));
|
||||
.willReturn(new Saml2AuthenticationToken(relyingPartyRegistration, response));
|
||||
// @formatter:off
|
||||
MockHttpServletRequestBuilder request = post("/login/saml2/sso/" + relyingPartyRegistration.getRegistrationId())
|
||||
.param("SAMLResponse", SIGNED_RESPONSE);
|
||||
@@ -278,11 +278,11 @@ public class Saml2LoginConfigurerTests {
|
||||
public void authenticateWhenCustomAuthenticationConverterBeanThenUses() throws Exception {
|
||||
this.spring.register(CustomAuthenticationConverterBean.class).autowire();
|
||||
Saml2AuthenticationTokenConverter authenticationConverter = this.spring.getContext()
|
||||
.getBean(Saml2AuthenticationTokenConverter.class);
|
||||
.getBean(Saml2AuthenticationTokenConverter.class);
|
||||
RelyingPartyRegistration relyingPartyRegistration = this.repository.findByRegistrationId("registration-id");
|
||||
String response = new String(Saml2Utils.samlDecode(SIGNED_RESPONSE));
|
||||
given(authenticationConverter.convert(any(HttpServletRequest.class)))
|
||||
.willReturn(new Saml2AuthenticationToken(relyingPartyRegistration, response));
|
||||
.willReturn(new Saml2AuthenticationToken(relyingPartyRegistration, response));
|
||||
// @formatter:off
|
||||
MockHttpServletRequestBuilder request = post("/login/saml2/sso/" + relyingPartyRegistration.getRegistrationId())
|
||||
.param("SAMLResponse", SIGNED_RESPONSE);
|
||||
@@ -300,9 +300,9 @@ public class Saml2LoginConfigurerTests {
|
||||
encoded);
|
||||
this.mvc.perform(request);
|
||||
ArgumentCaptor<Saml2AuthenticationException> captor = ArgumentCaptor
|
||||
.forClass(Saml2AuthenticationException.class);
|
||||
verify(CustomAuthenticationFailureHandler.authenticationFailureHandler).onAuthenticationFailure(
|
||||
any(HttpServletRequest.class), any(HttpServletResponse.class), captor.capture());
|
||||
.forClass(Saml2AuthenticationException.class);
|
||||
verify(CustomAuthenticationFailureHandler.authenticationFailureHandler)
|
||||
.onAuthenticationFailure(any(HttpServletRequest.class), any(HttpServletResponse.class), captor.capture());
|
||||
Saml2AuthenticationException exception = captor.getValue();
|
||||
assertThat(exception.getSaml2Error().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_RESPONSE);
|
||||
assertThat(exception.getSaml2Error().getDescription()).isEqualTo("Unable to inflate string");
|
||||
@@ -315,7 +315,7 @@ public class Saml2LoginConfigurerTests {
|
||||
MockHttpServletRequestBuilder request = get("/saml2/authenticate/registration-id");
|
||||
this.mvc.perform(request).andExpect(status().isFound());
|
||||
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> repository = this.spring.getContext()
|
||||
.getBean(Saml2AuthenticationRequestRepository.class);
|
||||
.getBean(Saml2AuthenticationRequestRepository.class);
|
||||
verify(repository).saveAuthenticationRequest(any(AbstractSaml2AuthenticationRequest.class),
|
||||
any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
}
|
||||
@@ -326,7 +326,7 @@ public class Saml2LoginConfigurerTests {
|
||||
MockHttpServletRequestBuilder request = post("/login/saml2/sso/registration-id").param("SAMLResponse",
|
||||
SIGNED_RESPONSE);
|
||||
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> repository = this.spring.getContext()
|
||||
.getBean(Saml2AuthenticationRequestRepository.class);
|
||||
.getBean(Saml2AuthenticationRequestRepository.class);
|
||||
this.mvc.perform(request);
|
||||
verify(repository).loadAuthenticationRequest(any(HttpServletRequest.class));
|
||||
verify(repository).removeAuthenticationRequest(any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
@@ -338,7 +338,7 @@ public class Saml2LoginConfigurerTests {
|
||||
MockHttpServletRequestBuilder request = get("/custom/auth/registration-id");
|
||||
this.mvc.perform(request).andExpect(status().isFound());
|
||||
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> repository = this.spring.getContext()
|
||||
.getBean(Saml2AuthenticationRequestRepository.class);
|
||||
.getBean(Saml2AuthenticationRequestRepository.class);
|
||||
verify(repository).saveAuthenticationRequest(any(AbstractSaml2AuthenticationRequest.class),
|
||||
any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
}
|
||||
@@ -356,7 +356,7 @@ public class Saml2LoginConfigurerTests {
|
||||
RelyingPartyRegistration relyingPartyRegistration = this.repository.findByRegistrationId("registration-id");
|
||||
String response = new String(Saml2Utils.samlDecode(SIGNED_RESPONSE));
|
||||
given(AUTHENTICATION_CONVERTER.convert(any(HttpServletRequest.class)))
|
||||
.willReturn(new Saml2AuthenticationToken(relyingPartyRegistration, response));
|
||||
.willReturn(new Saml2AuthenticationToken(relyingPartyRegistration, response));
|
||||
// @formatter:off
|
||||
MockHttpServletRequestBuilder request = post("/my/custom/url").param("SAMLResponse", SIGNED_RESPONSE);
|
||||
// @formatter:on
|
||||
@@ -369,11 +369,11 @@ public class Saml2LoginConfigurerTests {
|
||||
throws Exception {
|
||||
this.spring.register(CustomLoginProcessingUrlSaml2AuthenticationTokenConverterBean.class).autowire();
|
||||
Saml2AuthenticationTokenConverter authenticationConverter = this.spring.getContext()
|
||||
.getBean(Saml2AuthenticationTokenConverter.class);
|
||||
.getBean(Saml2AuthenticationTokenConverter.class);
|
||||
RelyingPartyRegistration relyingPartyRegistration = this.repository.findByRegistrationId("registration-id");
|
||||
String response = new String(Saml2Utils.samlDecode(SIGNED_RESPONSE));
|
||||
given(authenticationConverter.convert(any(HttpServletRequest.class)))
|
||||
.willReturn(new Saml2AuthenticationToken(relyingPartyRegistration, response));
|
||||
.willReturn(new Saml2AuthenticationToken(relyingPartyRegistration, response));
|
||||
// @formatter:off
|
||||
MockHttpServletRequestBuilder request = post("/my/custom/url").param("SAMLResponse", SIGNED_RESPONSE);
|
||||
// @formatter:on
|
||||
@@ -385,10 +385,12 @@ public class Saml2LoginConfigurerTests {
|
||||
@Test
|
||||
public void getFaviconWhenDefaultConfigurationThenDoesNotSaveAuthnRequest() throws Exception {
|
||||
this.spring.register(Saml2LoginConfig.class).autowire();
|
||||
this.mvc.perform(get("/favicon.ico").accept(MediaType.TEXT_HTML)).andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("http://localhost/login"));
|
||||
this.mvc.perform(get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("http://localhost/saml2/authenticate/registration-id"));
|
||||
this.mvc.perform(get("/favicon.ico").accept(MediaType.TEXT_HTML))
|
||||
.andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("http://localhost/login"));
|
||||
this.mvc.perform(get("/").accept(MediaType.TEXT_HTML))
|
||||
.andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("http://localhost/saml2/authenticate/registration-id"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -396,7 +398,7 @@ public class Saml2LoginConfigurerTests {
|
||||
this.spring.register(CustomAuthenticationProviderConfig.class).autowire();
|
||||
AuthenticationProvider provider = this.spring.getContext().getBean(AuthenticationProvider.class);
|
||||
this.mvc.perform(post("/login/saml2/sso/registration-id").param("SAMLResponse", SIGNED_RESPONSE))
|
||||
.andExpect(status().isFound());
|
||||
.andExpect(status().isFound());
|
||||
verify(provider).authenticate(any());
|
||||
}
|
||||
|
||||
@@ -410,11 +412,13 @@ public class Saml2LoginConfigurerTests {
|
||||
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
|
||||
// assertions
|
||||
Authentication authentication = this.securityContextRepository
|
||||
.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
|
||||
.loadContext(new HttpRequestResponseHolder(this.request, this.response))
|
||||
.getAuthentication();
|
||||
assertThat(authentication).as("Expected a valid authentication object.").isNotNull();
|
||||
assertThat(authentication.getAuthorities()).hasSize(1);
|
||||
assertThat(authentication.getAuthorities()).first().isInstanceOf(SimpleGrantedAuthority.class)
|
||||
.hasToString(expected);
|
||||
assertThat(authentication.getAuthorities()).first()
|
||||
.isInstanceOf(SimpleGrantedAuthority.class)
|
||||
.hasToString(expected);
|
||||
}
|
||||
|
||||
private static AuthenticationManager getAuthenticationManagerMock(String role) {
|
||||
@@ -443,7 +447,7 @@ public class Saml2LoginConfigurerTests {
|
||||
@Bean
|
||||
SecurityFilterChain web(HttpSecurity http) throws Exception {
|
||||
http.authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated())
|
||||
.saml2Login(Customizer.withDefaults());
|
||||
.saml2Login(Customizer.withDefaults());
|
||||
|
||||
return http.build();
|
||||
}
|
||||
@@ -493,7 +497,7 @@ public class Saml2LoginConfigurerTests {
|
||||
@Bean
|
||||
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
http.authorizeRequests((authz) -> authz.anyRequest().authenticated())
|
||||
.saml2Login((saml2) -> saml2.failureHandler(authenticationFailureHandler));
|
||||
.saml2Login((saml2) -> saml2.failureHandler(authenticationFailureHandler));
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@@ -573,7 +577,7 @@ public class Saml2LoginConfigurerTests {
|
||||
@Bean
|
||||
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
http.authorizeRequests((authz) -> authz.anyRequest().authenticated())
|
||||
.saml2Login((saml2) -> saml2.authenticationConverter(authenticationConverter));
|
||||
.saml2Login((saml2) -> saml2.authenticationConverter(authenticationConverter));
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@@ -590,7 +594,7 @@ public class Saml2LoginConfigurerTests {
|
||||
@Bean
|
||||
SecurityFilterChain app(HttpSecurity http) throws Exception {
|
||||
http.authorizeHttpRequests((authz) -> authz.anyRequest().authenticated())
|
||||
.saml2Login(Customizer.withDefaults());
|
||||
.saml2Login(Customizer.withDefaults());
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@@ -721,7 +725,7 @@ public class Saml2LoginConfigurerTests {
|
||||
@Bean
|
||||
SecurityFilterChain web(HttpSecurity http) throws Exception {
|
||||
http.authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated())
|
||||
.saml2Login(Customizer.withDefaults());
|
||||
.saml2Login(Customizer.withDefaults());
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@@ -175,7 +175,8 @@ public class Saml2LogoutConfigurerTests {
|
||||
this.spring.register(Saml2LogoutDefaultsConfig.class).autowire();
|
||||
TestingAuthenticationToken user = new TestingAuthenticationToken("user", "password");
|
||||
MvcResult result = this.mvc.perform(post("/logout").with(authentication(user)).with(csrf()))
|
||||
.andExpect(status().isFound()).andReturn();
|
||||
.andExpect(status().isFound())
|
||||
.andReturn();
|
||||
String location = result.getResponse().getHeader("Location");
|
||||
LogoutHandler logoutHandler = this.spring.getContext().getBean(LogoutHandler.class);
|
||||
assertThat(location).isEqualTo("/login?logout");
|
||||
@@ -186,7 +187,8 @@ public class Saml2LogoutConfigurerTests {
|
||||
public void saml2LogoutWhenDefaultsThenLogsOutAndSendsLogoutRequest() throws Exception {
|
||||
this.spring.register(Saml2LogoutDefaultsConfig.class).autowire();
|
||||
MvcResult result = this.mvc.perform(post("/logout").with(authentication(this.user)).with(csrf()))
|
||||
.andExpect(status().isFound()).andReturn();
|
||||
.andExpect(status().isFound())
|
||||
.andReturn();
|
||||
String location = result.getResponse().getHeader("Location");
|
||||
LogoutHandler logoutHandler = this.spring.getContext().getBean(LogoutHandler.class);
|
||||
assertThat(location).startsWith("https://ap.example.org/logout/saml2/request");
|
||||
@@ -196,8 +198,9 @@ public class Saml2LogoutConfigurerTests {
|
||||
@Test
|
||||
public void saml2LogoutWhenUnauthenticatedThenEntryPoint() throws Exception {
|
||||
this.spring.register(Saml2LogoutDefaultsConfig.class).autowire();
|
||||
this.mvc.perform(post("/logout").with(csrf())).andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("/login?logout"));
|
||||
this.mvc.perform(post("/logout").with(csrf()))
|
||||
.andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("/login?logout"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -210,8 +213,9 @@ public class Saml2LogoutConfigurerTests {
|
||||
@Test
|
||||
public void saml2LogoutWhenGetThenDefaultLogoutPage() throws Exception {
|
||||
this.spring.register(Saml2LogoutDefaultsConfig.class).autowire();
|
||||
MvcResult result = this.mvc.perform(get("/logout").with(authentication(this.user))).andExpect(status().isOk())
|
||||
.andReturn();
|
||||
MvcResult result = this.mvc.perform(get("/logout").with(authentication(this.user)))
|
||||
.andExpect(status().isOk())
|
||||
.andReturn();
|
||||
assertThat(result.getResponse().getContentAsString()).contains("Are you sure you want to log out?");
|
||||
verifyNoInteractions(getBean(LogoutHandler.class));
|
||||
}
|
||||
@@ -221,7 +225,7 @@ public class Saml2LogoutConfigurerTests {
|
||||
this.spring.register(Saml2LogoutDefaultsConfig.class).autowire();
|
||||
this.mvc.perform(put("/logout").with(authentication(this.user)).with(csrf())).andExpect(status().isNotFound());
|
||||
this.mvc.perform(delete("/logout").with(authentication(this.user)).with(csrf()))
|
||||
.andExpect(status().isNotFound());
|
||||
.andExpect(status().isNotFound());
|
||||
verifyNoInteractions(this.spring.getContext().getBean(LogoutHandler.class));
|
||||
}
|
||||
|
||||
@@ -234,7 +238,7 @@ public class Saml2LogoutConfigurerTests {
|
||||
Saml2Authentication authentication = new Saml2Authentication(principal, "response",
|
||||
AuthorityUtils.createAuthorityList("ROLE_USER"));
|
||||
this.mvc.perform(post("/logout").with(authentication(authentication)).with(csrf()))
|
||||
.andExpect(status().isUnauthorized());
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -250,8 +254,11 @@ public class Saml2LogoutConfigurerTests {
|
||||
this.spring.register(Saml2LogoutComponentsConfig.class).autowire();
|
||||
RelyingPartyRegistration registration = this.repository.findByRegistrationId("registration-id");
|
||||
Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration)
|
||||
.samlRequest(this.rpLogoutRequest).id(this.rpLogoutRequestId).relayState(this.rpLogoutRequestRelayState)
|
||||
.parameters((params) -> params.put("Signature", this.rpLogoutRequestSignature)).build();
|
||||
.samlRequest(this.rpLogoutRequest)
|
||||
.id(this.rpLogoutRequestId)
|
||||
.relayState(this.rpLogoutRequestRelayState)
|
||||
.parameters((params) -> params.put("Signature", this.rpLogoutRequestSignature))
|
||||
.build();
|
||||
given(getBean(Saml2LogoutRequestResolver.class).resolve(any(), any())).willReturn(logoutRequest);
|
||||
this.mvc.perform(post("/logout").with(authentication(this.user)).with(csrf()));
|
||||
verify(getBean(Saml2LogoutRequestResolver.class)).resolve(any(), any());
|
||||
@@ -265,10 +272,15 @@ public class Saml2LogoutConfigurerTests {
|
||||
principal.setRelyingPartyRegistrationId("get");
|
||||
Saml2Authentication user = new Saml2Authentication(principal, "response",
|
||||
AuthorityUtils.createAuthorityList("ROLE_USER"));
|
||||
MvcResult result = this.mvc.perform(get("/logout/saml2/slo").param("SAMLRequest", this.apLogoutRequest)
|
||||
.param("RelayState", this.apLogoutRequestRelayState).param("SigAlg", this.apLogoutRequestSigAlg)
|
||||
.param("Signature", this.apLogoutRequestSignature).with(samlQueryString()).with(authentication(user)))
|
||||
.andExpect(status().isFound()).andReturn();
|
||||
MvcResult result = this.mvc
|
||||
.perform(get("/logout/saml2/slo").param("SAMLRequest", this.apLogoutRequest)
|
||||
.param("RelayState", this.apLogoutRequestRelayState)
|
||||
.param("SigAlg", this.apLogoutRequestSigAlg)
|
||||
.param("Signature", this.apLogoutRequestSignature)
|
||||
.with(samlQueryString())
|
||||
.with(authentication(user)))
|
||||
.andExpect(status().isFound())
|
||||
.andReturn();
|
||||
String location = result.getResponse().getHeader("Location");
|
||||
assertThat(location).startsWith("https://ap.example.org/logout/saml2/response");
|
||||
verify(getBean(LogoutHandler.class)).logout(any(), any(), any());
|
||||
@@ -282,10 +294,15 @@ public class Saml2LogoutConfigurerTests {
|
||||
principal.setRelyingPartyRegistrationId("get");
|
||||
Saml2Authentication user = new Saml2Authentication(principal, "response",
|
||||
AuthorityUtils.createAuthorityList("ROLE_USER"));
|
||||
MvcResult result = this.mvc.perform(get("/logout/saml2/slo").param("SAMLRequest", this.apLogoutRequest)
|
||||
.param("RelayState", this.apLogoutRequestRelayState).param("SigAlg", this.apLogoutRequestSigAlg)
|
||||
.param("Signature", this.apLogoutRequestSignature).with(samlQueryString()).with(authentication(user)))
|
||||
.andExpect(status().isFound()).andReturn();
|
||||
MvcResult result = this.mvc
|
||||
.perform(get("/logout/saml2/slo").param("SAMLRequest", this.apLogoutRequest)
|
||||
.param("RelayState", this.apLogoutRequestRelayState)
|
||||
.param("SigAlg", this.apLogoutRequestSigAlg)
|
||||
.param("Signature", this.apLogoutRequestSignature)
|
||||
.with(samlQueryString())
|
||||
.with(authentication(user)))
|
||||
.andExpect(status().isFound())
|
||||
.andReturn();
|
||||
String location = result.getResponse().getHeader("Location");
|
||||
assertThat(location).startsWith("https://ap.example.org/logout/saml2/response");
|
||||
verify(getBean(LogoutHandler.class)).logout(any(), any(), any());
|
||||
@@ -309,11 +326,14 @@ public class Saml2LogoutConfigurerTests {
|
||||
Saml2Authentication user = new Saml2Authentication(principal, "response",
|
||||
AuthorityUtils.createAuthorityList("ROLE_USER"));
|
||||
MvcResult result = this.mvc
|
||||
.perform(get("/logout/saml2/slo").param("SAMLRequest", apLogoutRequest)
|
||||
.param("RelayState", apLogoutRequestRelayState).param("SigAlg", this.apLogoutRequestSigAlg)
|
||||
.param("Signature", apLogoutRequestSignature)
|
||||
.with(new SamlQueryStringRequestPostProcessor(true)).with(authentication(user)))
|
||||
.andExpect(status().isFound()).andReturn();
|
||||
.perform(get("/logout/saml2/slo").param("SAMLRequest", apLogoutRequest)
|
||||
.param("RelayState", apLogoutRequestRelayState)
|
||||
.param("SigAlg", this.apLogoutRequestSigAlg)
|
||||
.param("Signature", apLogoutRequestSignature)
|
||||
.with(new SamlQueryStringRequestPostProcessor(true))
|
||||
.with(authentication(user)))
|
||||
.andExpect(status().isFound())
|
||||
.andReturn();
|
||||
String location = result.getResponse().getHeader("Location");
|
||||
assertThat(location).startsWith("https://ap.example.org/logout/saml2/response");
|
||||
verify(getBean(LogoutHandler.class)).logout(any(), any(), any());
|
||||
@@ -337,11 +357,14 @@ public class Saml2LogoutConfigurerTests {
|
||||
Saml2Authentication user = new Saml2Authentication(principal, "response",
|
||||
AuthorityUtils.createAuthorityList("ROLE_USER"));
|
||||
MvcResult result = this.mvc
|
||||
.perform(get("/logout/saml2/slo").param("SAMLRequest", apLogoutRequest)
|
||||
.param("SigAlg", this.apLogoutRequestSigAlg).param("RelayState", apLogoutRequestRelayState)
|
||||
.param("Signature", apLogoutRequestSignature)
|
||||
.with(new SamlQueryStringRequestPostProcessor(true)).with(authentication(user)))
|
||||
.andExpect(status().isFound()).andReturn();
|
||||
.perform(get("/logout/saml2/slo").param("SAMLRequest", apLogoutRequest)
|
||||
.param("SigAlg", this.apLogoutRequestSigAlg)
|
||||
.param("RelayState", apLogoutRequestRelayState)
|
||||
.param("Signature", apLogoutRequestSignature)
|
||||
.with(new SamlQueryStringRequestPostProcessor(true))
|
||||
.with(authentication(user)))
|
||||
.andExpect(status().isFound())
|
||||
.andReturn();
|
||||
String location = result.getResponse().getHeader("Location");
|
||||
assertThat(location).startsWith("https://ap.example.org/logout/saml2/response");
|
||||
verify(getBean(LogoutHandler.class)).logout(any(), any(), any());
|
||||
@@ -355,19 +378,25 @@ public class Saml2LogoutConfigurerTests {
|
||||
principal.setRelyingPartyRegistrationId("wrong");
|
||||
Saml2Authentication user = new Saml2Authentication(principal, "response",
|
||||
AuthorityUtils.createAuthorityList("ROLE_USER"));
|
||||
this.mvc.perform(get("/logout/saml2/slo").param("SAMLRequest", this.apLogoutRequest)
|
||||
.param("RelayState", this.apLogoutRequestRelayState).param("SigAlg", this.apLogoutRequestSigAlg)
|
||||
.param("Signature", this.apLogoutRequestSignature).with(authentication(user)))
|
||||
.andExpect(status().isBadRequest());
|
||||
this.mvc
|
||||
.perform(get("/logout/saml2/slo").param("SAMLRequest", this.apLogoutRequest)
|
||||
.param("RelayState", this.apLogoutRequestRelayState)
|
||||
.param("SigAlg", this.apLogoutRequestSigAlg)
|
||||
.param("Signature", this.apLogoutRequestSignature)
|
||||
.with(authentication(user)))
|
||||
.andExpect(status().isBadRequest());
|
||||
verifyNoInteractions(getBean(LogoutHandler.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void saml2LogoutRequestWhenInvalidSamlRequestThen401() throws Exception {
|
||||
this.spring.register(Saml2LogoutDefaultsConfig.class).autowire();
|
||||
this.mvc.perform(get("/logout/saml2/slo").param("SAMLRequest", this.apLogoutRequest)
|
||||
.param("RelayState", this.apLogoutRequestRelayState).param("SigAlg", this.apLogoutRequestSigAlg)
|
||||
.with(authentication(this.user))).andExpect(status().isUnauthorized());
|
||||
this.mvc
|
||||
.perform(get("/logout/saml2/slo").param("SAMLRequest", this.apLogoutRequest)
|
||||
.param("RelayState", this.apLogoutRequestRelayState)
|
||||
.param("SigAlg", this.apLogoutRequestSigAlg)
|
||||
.with(authentication(this.user)))
|
||||
.andExpect(status().isUnauthorized());
|
||||
verifyNoInteractions(getBean(LogoutHandler.class));
|
||||
}
|
||||
|
||||
@@ -378,11 +407,11 @@ public class Saml2LogoutConfigurerTests {
|
||||
LogoutRequest logoutRequest = TestOpenSamlObjects.assertingPartyLogoutRequest(registration);
|
||||
logoutRequest.setIssueInstant(Instant.now());
|
||||
given(getBean(Saml2LogoutRequestValidator.class).validate(any()))
|
||||
.willReturn(Saml2LogoutValidatorResult.success());
|
||||
.willReturn(Saml2LogoutValidatorResult.success());
|
||||
Saml2LogoutResponse logoutResponse = Saml2LogoutResponse.withRelyingPartyRegistration(registration).build();
|
||||
given(getBean(Saml2LogoutResponseResolver.class).resolve(any(), any())).willReturn(logoutResponse);
|
||||
this.mvc.perform(post("/logout/saml2/slo").param("SAMLRequest", "samlRequest").with(authentication(this.user)))
|
||||
.andReturn();
|
||||
.andReturn();
|
||||
verify(getBean(Saml2LogoutRequestValidator.class)).validate(any());
|
||||
verify(getBean(Saml2LogoutResponseResolver.class)).resolve(any(), any());
|
||||
}
|
||||
@@ -392,15 +421,23 @@ public class Saml2LogoutConfigurerTests {
|
||||
this.spring.register(Saml2LogoutDefaultsConfig.class).autowire();
|
||||
RelyingPartyRegistration registration = this.repository.findByRegistrationId("get");
|
||||
Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration)
|
||||
.samlRequest(this.rpLogoutRequest).id(this.rpLogoutRequestId).relayState(this.rpLogoutRequestRelayState)
|
||||
.parameters((params) -> params.put("Signature", this.rpLogoutRequestSignature)).build();
|
||||
.samlRequest(this.rpLogoutRequest)
|
||||
.id(this.rpLogoutRequestId)
|
||||
.relayState(this.rpLogoutRequestRelayState)
|
||||
.parameters((params) -> params.put("Signature", this.rpLogoutRequestSignature))
|
||||
.build();
|
||||
this.logoutRequestRepository.saveLogoutRequest(logoutRequest, this.request, this.response);
|
||||
this.request.setParameter("RelayState", logoutRequest.getRelayState());
|
||||
assertThat(this.logoutRequestRepository.loadLogoutRequest(this.request)).isNotNull();
|
||||
this.mvc.perform(get("/logout/saml2/slo").session(((MockHttpSession) this.request.getSession()))
|
||||
.param("SAMLResponse", this.apLogoutResponse).param("RelayState", this.apLogoutResponseRelayState)
|
||||
.param("SigAlg", this.apLogoutResponseSigAlg).param("Signature", this.apLogoutResponseSignature)
|
||||
.with(samlQueryString())).andExpect(status().isFound()).andExpect(redirectedUrl("/login?logout"));
|
||||
this.mvc
|
||||
.perform(get("/logout/saml2/slo").session(((MockHttpSession) this.request.getSession()))
|
||||
.param("SAMLResponse", this.apLogoutResponse)
|
||||
.param("RelayState", this.apLogoutResponseRelayState)
|
||||
.param("SigAlg", this.apLogoutResponseSigAlg)
|
||||
.param("Signature", this.apLogoutResponseSignature)
|
||||
.with(samlQueryString()))
|
||||
.andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("/login?logout"));
|
||||
verifyNoInteractions(getBean(LogoutHandler.class));
|
||||
assertThat(this.logoutRequestRepository.loadLogoutRequest(this.request)).isNull();
|
||||
}
|
||||
@@ -410,16 +447,23 @@ public class Saml2LogoutConfigurerTests {
|
||||
this.spring.register(Saml2LogoutDefaultsConfig.class).autowire();
|
||||
RelyingPartyRegistration registration = this.repository.findByRegistrationId("registration-id");
|
||||
Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration)
|
||||
.samlRequest(this.rpLogoutRequest).id(this.rpLogoutRequestId).relayState(this.rpLogoutRequestRelayState)
|
||||
.parameters((params) -> params.put("Signature", this.rpLogoutRequestSignature)).build();
|
||||
.samlRequest(this.rpLogoutRequest)
|
||||
.id(this.rpLogoutRequestId)
|
||||
.relayState(this.rpLogoutRequestRelayState)
|
||||
.parameters((params) -> params.put("Signature", this.rpLogoutRequestSignature))
|
||||
.build();
|
||||
this.logoutRequestRepository.saveLogoutRequest(logoutRequest, this.request, this.response);
|
||||
String deflatedApLogoutResponse = Saml2Utils.samlEncode(
|
||||
Saml2Utils.samlInflate(Saml2Utils.samlDecode(this.apLogoutResponse)).getBytes(StandardCharsets.UTF_8));
|
||||
this.mvc.perform(post("/logout/saml2/slo").session((MockHttpSession) this.request.getSession())
|
||||
.param("SAMLResponse", deflatedApLogoutResponse).param("RelayState", this.rpLogoutRequestRelayState)
|
||||
.param("SigAlg", this.apLogoutRequestSigAlg).param("Signature", this.apLogoutResponseSignature)
|
||||
.with(samlQueryString())).andExpect(status().reason(containsString("invalid_signature")))
|
||||
.andExpect(status().isUnauthorized());
|
||||
this.mvc
|
||||
.perform(post("/logout/saml2/slo").session((MockHttpSession) this.request.getSession())
|
||||
.param("SAMLResponse", deflatedApLogoutResponse)
|
||||
.param("RelayState", this.rpLogoutRequestRelayState)
|
||||
.param("SigAlg", this.apLogoutRequestSigAlg)
|
||||
.param("Signature", this.apLogoutResponseSignature)
|
||||
.with(samlQueryString()))
|
||||
.andExpect(status().reason(containsString("invalid_signature")))
|
||||
.andExpect(status().isUnauthorized());
|
||||
verifyNoInteractions(getBean(LogoutHandler.class));
|
||||
}
|
||||
|
||||
@@ -428,11 +472,14 @@ public class Saml2LogoutConfigurerTests {
|
||||
this.spring.register(Saml2LogoutComponentsConfig.class).autowire();
|
||||
RelyingPartyRegistration registration = this.repository.findByRegistrationId("get");
|
||||
Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration)
|
||||
.samlRequest(this.rpLogoutRequest).id(this.rpLogoutRequestId).relayState(this.rpLogoutRequestRelayState)
|
||||
.parameters((params) -> params.put("Signature", this.rpLogoutRequestSignature)).build();
|
||||
.samlRequest(this.rpLogoutRequest)
|
||||
.id(this.rpLogoutRequestId)
|
||||
.relayState(this.rpLogoutRequestRelayState)
|
||||
.parameters((params) -> params.put("Signature", this.rpLogoutRequestSignature))
|
||||
.build();
|
||||
given(getBean(Saml2LogoutRequestRepository.class).removeLogoutRequest(any(), any())).willReturn(logoutRequest);
|
||||
given(getBean(Saml2LogoutResponseValidator.class).validate(any()))
|
||||
.willReturn(Saml2LogoutValidatorResult.success());
|
||||
.willReturn(Saml2LogoutValidatorResult.success());
|
||||
this.mvc.perform(get("/logout/saml2/slo").param("SAMLResponse", "samlResponse")).andReturn();
|
||||
verify(getBean(Saml2LogoutResponseValidator.class)).validate(any());
|
||||
}
|
||||
@@ -442,8 +489,11 @@ public class Saml2LogoutConfigurerTests {
|
||||
this.spring.register(Saml2LogoutComponentsConfig.class).autowire();
|
||||
RelyingPartyRegistration registration = this.repository.findByRegistrationId("registration-id");
|
||||
Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration)
|
||||
.samlRequest(this.rpLogoutRequest).id(this.rpLogoutRequestId).relayState(this.rpLogoutRequestRelayState)
|
||||
.parameters((params) -> params.put("Signature", this.rpLogoutRequestSignature)).build();
|
||||
.samlRequest(this.rpLogoutRequest)
|
||||
.id(this.rpLogoutRequestId)
|
||||
.relayState(this.rpLogoutRequestRelayState)
|
||||
.parameters((params) -> params.put("Signature", this.rpLogoutRequestSignature))
|
||||
.build();
|
||||
given(getBean(Saml2LogoutRequestResolver.class).resolve(any(), any())).willReturn(logoutRequest);
|
||||
this.mvc.perform(post("/logout").with(authentication(this.user)).with(csrf()));
|
||||
verify(getBean(Saml2LogoutRequestRepository.class)).saveLogoutRequest(eq(logoutRequest), any(), any());
|
||||
@@ -453,7 +503,8 @@ public class Saml2LogoutConfigurerTests {
|
||||
public void saml2LogoutWhenLogoutGetThenLogsOutAndSendsLogoutRequest() throws Exception {
|
||||
this.spring.register(Saml2LogoutWithHttpGet.class).autowire();
|
||||
MvcResult result = this.mvc.perform(get("/logout").with(authentication(this.user)))
|
||||
.andExpect(status().isFound()).andReturn();
|
||||
.andExpect(status().isFound())
|
||||
.andReturn();
|
||||
String location = result.getResponse().getHeader("Location");
|
||||
LogoutHandler logoutHandler = this.spring.getContext().getBean(LogoutHandler.class);
|
||||
assertThat(location).startsWith("https://ap.example.org/logout/saml2/request");
|
||||
@@ -466,7 +517,7 @@ public class Saml2LogoutConfigurerTests {
|
||||
Saml2DefaultsWithObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
|
||||
this.spring.register(Saml2DefaultsWithObjectPostProcessorConfig.class).autowire();
|
||||
verify(Saml2DefaultsWithObjectPostProcessorConfig.objectPostProcessor)
|
||||
.postProcess(any(Saml2LogoutRequestFilter.class));
|
||||
.postProcess(any(Saml2LogoutRequestFilter.class));
|
||||
|
||||
}
|
||||
|
||||
@@ -476,7 +527,7 @@ public class Saml2LogoutConfigurerTests {
|
||||
Saml2DefaultsWithObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
|
||||
this.spring.register(Saml2DefaultsWithObjectPostProcessorConfig.class).autowire();
|
||||
verify(Saml2DefaultsWithObjectPostProcessorConfig.objectPostProcessor)
|
||||
.postProcess(any(Saml2LogoutResponseFilter.class));
|
||||
.postProcess(any(Saml2LogoutResponseFilter.class));
|
||||
|
||||
}
|
||||
|
||||
@@ -486,7 +537,7 @@ public class Saml2LogoutConfigurerTests {
|
||||
Saml2DefaultsWithObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
|
||||
this.spring.register(Saml2DefaultsWithObjectPostProcessorConfig.class).autowire();
|
||||
verify(Saml2DefaultsWithObjectPostProcessorConfig.objectPostProcessor, atLeastOnce())
|
||||
.postProcess(any(LogoutFilter.class));
|
||||
.postProcess(any(LogoutFilter.class));
|
||||
|
||||
}
|
||||
|
||||
@@ -678,16 +729,18 @@ public class Saml2LogoutConfigurerTests {
|
||||
Saml2X509Credential signing = TestSaml2X509Credentials.assertingPartySigningCredential();
|
||||
Saml2X509Credential verification = TestSaml2X509Credentials.relyingPartyVerifyingCredential();
|
||||
RelyingPartyRegistration.Builder withCreds = TestRelyingPartyRegistrations.noCredentials()
|
||||
.signingX509Credentials(credential(signing))
|
||||
.assertingPartyDetails((party) -> party.verificationX509Credentials(credential(verification)));
|
||||
.signingX509Credentials(credential(signing))
|
||||
.assertingPartyDetails((party) -> party.verificationX509Credentials(credential(verification)));
|
||||
RelyingPartyRegistration post = withCreds.build();
|
||||
RelyingPartyRegistration get = withCreds.registrationId("get")
|
||||
.singleLogoutServiceBinding(Saml2MessageBinding.REDIRECT).build();
|
||||
RelyingPartyRegistration ap = withCreds.registrationId("ap").entityId("ap-entity-id")
|
||||
.assertingPartyDetails((party) -> party
|
||||
.singleLogoutServiceLocation("https://rp.example.org/logout/saml2/request")
|
||||
.singleLogoutServiceBinding(Saml2MessageBinding.REDIRECT)
|
||||
.build();
|
||||
RelyingPartyRegistration ap = withCreds.registrationId("ap")
|
||||
.entityId("ap-entity-id")
|
||||
.assertingPartyDetails(
|
||||
(party) -> party.singleLogoutServiceLocation("https://rp.example.org/logout/saml2/request")
|
||||
.singleLogoutServiceResponseLocation("https://rp.example.org/logout/saml2/response"))
|
||||
.build();
|
||||
.build();
|
||||
|
||||
return new InMemoryRelyingPartyRegistrationRepository(ap, get, post);
|
||||
}
|
||||
|
||||
@@ -68,54 +68,59 @@ public class Saml2MetadataConfigurerTests {
|
||||
void saml2MetadataRegistrationIdWhenDefaultsThenReturnsMetadata() throws Exception {
|
||||
this.spring.register(DefaultConfig.class).autowire();
|
||||
String filename = "saml-" + registration.getRegistrationId() + "-metadata.xml";
|
||||
this.mvc.perform(get("/saml2/metadata/" + registration.getRegistrationId())).andExpect(status().isOk())
|
||||
.andExpect(header().string(HttpHeaders.CONTENT_DISPOSITION, containsString(filename)))
|
||||
.andExpect(content().string(containsString("md:EntityDescriptor")));
|
||||
this.mvc.perform(get("/saml2/metadata/" + registration.getRegistrationId()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().string(HttpHeaders.CONTENT_DISPOSITION, containsString(filename)))
|
||||
.andExpect(content().string(containsString("md:EntityDescriptor")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void saml2MetadataRegistrationIdWhenWrongIdThenUnauthorized() throws Exception {
|
||||
this.spring.register(DefaultConfig.class).autowire();
|
||||
this.mvc.perform(get("/saml2/metadata/" + registration.getRegistrationId() + "wrong"))
|
||||
.andExpect(status().isUnauthorized());
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
@Test
|
||||
void saml2MetadataWhenDefaultsThenReturnsMetadata() throws Exception {
|
||||
this.spring.register(DefaultConfig.class).autowire();
|
||||
this.mvc.perform(get("/saml2/metadata")).andExpect(status().isOk())
|
||||
.andExpect(header().string(HttpHeaders.CONTENT_DISPOSITION, containsString("-metadata.xml")))
|
||||
.andExpect(content().string(containsString("md:EntityDescriptor")));
|
||||
this.mvc.perform(get("/saml2/metadata"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().string(HttpHeaders.CONTENT_DISPOSITION, containsString("-metadata.xml")))
|
||||
.andExpect(content().string(containsString("md:EntityDescriptor")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void saml2MetadataWhenMetadataResponseResolverThenUses() throws Exception {
|
||||
this.spring.register(DefaultConfig.class, MetadataResponseResolverConfig.class).autowire();
|
||||
Saml2MetadataResponseResolver metadataResponseResolver = this.spring.getContext()
|
||||
.getBean(Saml2MetadataResponseResolver.class);
|
||||
.getBean(Saml2MetadataResponseResolver.class);
|
||||
given(metadataResponseResolver.resolve(any(HttpServletRequest.class)))
|
||||
.willReturn(new Saml2MetadataResponse("metadata", "filename"));
|
||||
this.mvc.perform(get("/saml2/metadata")).andExpect(status().isOk())
|
||||
.andExpect(header().string(HttpHeaders.CONTENT_DISPOSITION, containsString("filename")))
|
||||
.andExpect(content().string(containsString("metadata")));
|
||||
.willReturn(new Saml2MetadataResponse("metadata", "filename"));
|
||||
this.mvc.perform(get("/saml2/metadata"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().string(HttpHeaders.CONTENT_DISPOSITION, containsString("filename")))
|
||||
.andExpect(content().string(containsString("metadata")));
|
||||
verify(metadataResponseResolver).resolve(any(HttpServletRequest.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void saml2MetadataWhenMetadataResponseResolverDslThenUses() throws Exception {
|
||||
this.spring.register(MetadataResponseResolverDslConfig.class).autowire();
|
||||
this.mvc.perform(get("/saml2/metadata")).andExpect(status().isOk())
|
||||
.andExpect(header().string(HttpHeaders.CONTENT_DISPOSITION, containsString("filename")))
|
||||
.andExpect(content().string(containsString("metadata")));
|
||||
this.mvc.perform(get("/saml2/metadata"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().string(HttpHeaders.CONTENT_DISPOSITION, containsString("filename")))
|
||||
.andExpect(content().string(containsString("metadata")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void saml2MetadataWhenMetadataUrlThenUses() throws Exception {
|
||||
this.spring.register(MetadataUrlConfig.class).autowire();
|
||||
String filename = "saml-" + registration.getRegistrationId() + "-metadata.xml";
|
||||
this.mvc.perform(get("/saml/metadata")).andExpect(status().isOk())
|
||||
.andExpect(header().string(HttpHeaders.CONTENT_DISPOSITION, containsString(filename)))
|
||||
.andExpect(content().string(containsString("md:EntityDescriptor")));
|
||||
this.mvc.perform(get("/saml/metadata"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().string(HttpHeaders.CONTENT_DISPOSITION, containsString(filename)))
|
||||
.andExpect(content().string(containsString("md:EntityDescriptor")));
|
||||
this.mvc.perform(get("/saml2/metadata")).andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@@ -168,7 +173,7 @@ public class Saml2MetadataConfigurerTests {
|
||||
|
||||
{
|
||||
given(this.metadataResponseResolver.resolve(any(HttpServletRequest.class)))
|
||||
.willReturn(new Saml2MetadataResponse("metadata", "filename"));
|
||||
.willReturn(new Saml2MetadataResponse("metadata", "filename"));
|
||||
}
|
||||
|
||||
@Bean
|
||||
|
||||
@@ -68,7 +68,7 @@ public final class TestSaml2Credentials {
|
||||
try {
|
||||
final CertificateFactory factory = CertificateFactory.getInstance("X.509");
|
||||
return (X509Certificate) factory
|
||||
.generateCertificate(new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8)));
|
||||
.generateCertificate(new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
catch (Exception ex) {
|
||||
throw new IllegalArgumentException(ex);
|
||||
|
||||
@@ -305,8 +305,10 @@ public class EnableWebFluxSecurityTests {
|
||||
@Test
|
||||
// gh-8596
|
||||
public void resolveAuthenticationPrincipalArgumentResolverFirstDoesNotCauseBeanCurrentlyInCreationException() {
|
||||
this.spring.register(EnableWebFluxSecurityConfiguration.class, ReactiveAuthenticationTestConfiguration.class,
|
||||
DelegatingWebFluxConfiguration.class).autowire();
|
||||
this.spring
|
||||
.register(EnableWebFluxSecurityConfiguration.class, ReactiveAuthenticationTestConfiguration.class,
|
||||
DelegatingWebFluxConfiguration.class)
|
||||
.autowire();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -369,8 +371,10 @@ public class EnableWebFluxSecurityTests {
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
@Bean
|
||||
SecurityWebFilterChain apiHttpSecurity(ServerHttpSecurity http) {
|
||||
http.securityMatcher(new PathPatternParserServerWebExchangeMatcher("/api/**")).authorizeExchange()
|
||||
.anyExchange().denyAll();
|
||||
http.securityMatcher(new PathPatternParserServerWebExchangeMatcher("/api/**"))
|
||||
.authorizeExchange()
|
||||
.anyExchange()
|
||||
.denyAll();
|
||||
return http.build();
|
||||
}
|
||||
|
||||
|
||||
@@ -79,7 +79,8 @@ public class ReactiveOAuth2ClientImportSelectorTests {
|
||||
ReactiveOAuth2AuthorizedClientManager authorizedClientManager = mock(
|
||||
ReactiveOAuth2AuthorizedClientManager.class);
|
||||
ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials()
|
||||
.registrationId(clientRegistrationId).build();
|
||||
.registrationId(clientRegistrationId)
|
||||
.build();
|
||||
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, principalName,
|
||||
TestOAuth2AccessTokens.noScopes());
|
||||
given(authorizedClientManager.authorize(any())).willReturn(Mono.just(authorizedClient));
|
||||
@@ -108,14 +109,15 @@ public class ReactiveOAuth2ClientImportSelectorTests {
|
||||
ServerOAuth2AuthorizedClientRepository authorizedClientRepository = mock(
|
||||
ServerOAuth2AuthorizedClientRepository.class);
|
||||
ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials()
|
||||
.registrationId(clientRegistrationId).build();
|
||||
.registrationId(clientRegistrationId)
|
||||
.build();
|
||||
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, principalName,
|
||||
TestOAuth2AccessTokens.noScopes());
|
||||
OAuth2AuthorizedClientManagerRegisteredConfig.CLIENT_REGISTRATION_REPOSITORY = clientRegistrationRepository;
|
||||
OAuth2AuthorizedClientManagerRegisteredConfig.AUTHORIZED_CLIENT_REPOSITORY = authorizedClientRepository;
|
||||
OAuth2AuthorizedClientManagerRegisteredConfig.AUTHORIZED_CLIENT_MANAGER = null;
|
||||
given(authorizedClientRepository.loadAuthorizedClient(any(), any(), any()))
|
||||
.willReturn(Mono.just(authorizedClient));
|
||||
.willReturn(Mono.just(authorizedClient));
|
||||
this.spring.register(OAuth2AuthorizedClientManagerRegisteredConfig.class).autowire();
|
||||
// @formatter:off
|
||||
this.client
|
||||
|
||||
@@ -37,7 +37,7 @@ public final class ServerHttpSecurityConfigurationBuilder {
|
||||
|
||||
public static ServerHttpSecurity httpWithDefaultAuthentication() {
|
||||
ReactiveUserDetailsService reactiveUserDetailsService = ReactiveAuthenticationTestConfiguration
|
||||
.userDetailsService();
|
||||
.userDetailsService();
|
||||
ReactiveAuthenticationManager authenticationManager = new UserDetailsRepositoryReactiveAuthenticationManager(
|
||||
reactiveUserDetailsService);
|
||||
return http().authenticationManager(authenticationManager);
|
||||
|
||||
@@ -39,16 +39,20 @@ public class ServerHttpSecurityConfigurationTests {
|
||||
|
||||
@Test
|
||||
public void loadConfigWhenReactiveUserDetailsServiceConfiguredThenServerHttpSecurityExists() {
|
||||
this.spring.register(ServerHttpSecurityConfiguration.class, ReactiveAuthenticationTestConfiguration.class,
|
||||
WebFluxSecurityConfiguration.class).autowire();
|
||||
this.spring
|
||||
.register(ServerHttpSecurityConfiguration.class, ReactiveAuthenticationTestConfiguration.class,
|
||||
WebFluxSecurityConfiguration.class)
|
||||
.autowire();
|
||||
ServerHttpSecurity serverHttpSecurity = this.spring.getContext().getBean(ServerHttpSecurity.class);
|
||||
assertThat(serverHttpSecurity).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadConfigWhenProxyingEnabledAndSubclassThenServerHttpSecurityExists() {
|
||||
this.spring.register(SubclassConfig.class, ReactiveAuthenticationTestConfiguration.class,
|
||||
WebFluxSecurityConfiguration.class).autowire();
|
||||
this.spring
|
||||
.register(SubclassConfig.class, ReactiveAuthenticationTestConfiguration.class,
|
||||
WebFluxSecurityConfiguration.class)
|
||||
.autowire();
|
||||
ServerHttpSecurity serverHttpSecurity = this.spring.getContext().getBean(ServerHttpSecurity.class);
|
||||
assertThat(serverHttpSecurity).isNotNull();
|
||||
}
|
||||
|
||||
@@ -39,16 +39,20 @@ public class WebFluxSecurityConfigurationTests {
|
||||
|
||||
@Test
|
||||
public void loadConfigWhenReactiveUserDetailsServiceConfiguredThenWebFilterChainProxyExists() {
|
||||
this.spring.register(ServerHttpSecurityConfiguration.class, ReactiveAuthenticationTestConfiguration.class,
|
||||
WebFluxSecurityConfiguration.class).autowire();
|
||||
this.spring
|
||||
.register(ServerHttpSecurityConfiguration.class, ReactiveAuthenticationTestConfiguration.class,
|
||||
WebFluxSecurityConfiguration.class)
|
||||
.autowire();
|
||||
WebFilterChainProxy webFilterChainProxy = this.spring.getContext().getBean(WebFilterChainProxy.class);
|
||||
assertThat(webFilterChainProxy).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadConfigWhenBeanProxyingEnabledAndSubclassThenWebFilterChainProxyExists() {
|
||||
this.spring.register(ServerHttpSecurityConfiguration.class, ReactiveAuthenticationTestConfiguration.class,
|
||||
WebFluxSecurityConfigurationTests.SubclassConfig.class).autowire();
|
||||
this.spring
|
||||
.register(ServerHttpSecurityConfiguration.class, ReactiveAuthenticationTestConfiguration.class,
|
||||
WebFluxSecurityConfigurationTests.SubclassConfig.class)
|
||||
.autowire();
|
||||
WebFilterChainProxy webFilterChainProxy = this.spring.getContext().getBean(WebFilterChainProxy.class);
|
||||
assertThat(webFilterChainProxy).isNotNull();
|
||||
}
|
||||
|
||||
@@ -76,8 +76,8 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerDocTests {
|
||||
loadConfig(WebSocketSecurityConfig.class);
|
||||
clientInboundChannel().send(message("/user/queue/errors", SimpMessageType.SUBSCRIBE));
|
||||
assertThatExceptionOfType(MessageDeliveryException.class)
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/denyAll", SimpMessageType.MESSAGE)))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/denyAll", SimpMessageType.MESSAGE)))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
}
|
||||
|
||||
private void loadConfig(Class<?>... configs) {
|
||||
@@ -124,15 +124,21 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerDocTests {
|
||||
|
||||
@Override
|
||||
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
|
||||
messages.nullDestMatcher().authenticated()
|
||||
// <1>
|
||||
.simpSubscribeDestMatchers("/user/queue/errors").permitAll()
|
||||
// <2>
|
||||
.simpDestMatchers("/app/**").hasRole("USER")
|
||||
// <3>
|
||||
.simpSubscribeDestMatchers("/user/**", "/topic/friends/*").hasRole("USER") // <4>
|
||||
.simpTypeMatchers(SimpMessageType.MESSAGE, SimpMessageType.SUBSCRIBE).denyAll() // <5>
|
||||
.anyMessage().denyAll(); // <6>
|
||||
messages.nullDestMatcher()
|
||||
.authenticated()
|
||||
// <1>
|
||||
.simpSubscribeDestMatchers("/user/queue/errors")
|
||||
.permitAll()
|
||||
// <2>
|
||||
.simpDestMatchers("/app/**")
|
||||
.hasRole("USER")
|
||||
// <3>
|
||||
.simpSubscribeDestMatchers("/user/**", "/topic/friends/*")
|
||||
.hasRole("USER") // <4>
|
||||
.simpTypeMatchers(SimpMessageType.MESSAGE, SimpMessageType.SUBSCRIBE)
|
||||
.denyAll() // <5>
|
||||
.anyMessage()
|
||||
.denyAll(); // <6>
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -110,8 +110,8 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
|
||||
loadConfig(SockJsSecurityConfig.class);
|
||||
clientInboundChannel().send(message("/permitAll"));
|
||||
assertThatExceptionOfType(MessageDeliveryException.class)
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/denyAll")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/denyAll")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -136,7 +136,7 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
|
||||
Message<String> message = message("/permitAll/authentication");
|
||||
messageChannel.send(message);
|
||||
assertThat(this.context.getBean(MyController.class).authenticationPrincipal)
|
||||
.isEqualTo((String) this.messageUser.getPrincipal());
|
||||
.isEqualTo((String) this.messageUser.getPrincipal());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -146,7 +146,7 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
|
||||
Message<String> message = message("/permitAll/authentication");
|
||||
messageChannel.send(message);
|
||||
assertThat(this.context.getBean(MyController.class).authenticationPrincipal)
|
||||
.isEqualTo((String) this.messageUser.getPrincipal());
|
||||
.isEqualTo((String) this.messageUser.getPrincipal());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -156,7 +156,7 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
|
||||
Message<?> message = message(headers, "/authentication");
|
||||
MessageChannel messageChannel = clientInboundChannel();
|
||||
assertThatExceptionOfType(MessageDeliveryException.class).isThrownBy(() -> messageChannel.send(message))
|
||||
.withCauseInstanceOf(MissingCsrfTokenException.class);
|
||||
.withCauseInstanceOf(MissingCsrfTokenException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -166,7 +166,7 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
|
||||
Message<?> message = message(headers, "/authentication");
|
||||
MessageChannel messageChannel = clientInboundChannel();
|
||||
assertThatExceptionOfType(MessageDeliveryException.class).isThrownBy(() -> messageChannel.send(message))
|
||||
.withCauseInstanceOf(MissingCsrfTokenException.class);
|
||||
.withCauseInstanceOf(MissingCsrfTokenException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -224,8 +224,8 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
|
||||
loadConfig(MsmsRegistryCustomPatternMatcherConfig.class);
|
||||
clientInboundChannel().send(message("/app/a.b"));
|
||||
assertThatExceptionOfType(MessageDeliveryException.class)
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/app/a.b.c")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/app/a.b.c")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -233,8 +233,8 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
|
||||
loadConfig(OverrideMsmsRegistryCustomPatternMatcherConfig.class);
|
||||
clientInboundChannel().send(message("/app/a/b"));
|
||||
assertThatExceptionOfType(MessageDeliveryException.class)
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/app/a/b/c")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/app/a/b/c")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -242,8 +242,8 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
|
||||
loadConfig(DefaultPatternMatcherConfig.class);
|
||||
clientInboundChannel().send(message("/app/a/b"));
|
||||
assertThatExceptionOfType(MessageDeliveryException.class)
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/app/a/b/c")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/app/a/b/c")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -252,8 +252,8 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
|
||||
clientInboundChannel().send(message("/denyRob"));
|
||||
this.messageUser = new TestingAuthenticationToken("rob", "password", "ROLE_USER");
|
||||
assertThatExceptionOfType(MessageDeliveryException.class)
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/denyRob")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/denyRob")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -261,7 +261,7 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
|
||||
loadConfig(SockJsProxylessSecurityConfig.class);
|
||||
ChannelSecurityInterceptor channelSecurityInterceptor = this.context.getBean(ChannelSecurityInterceptor.class);
|
||||
MessageSecurityMetadataSource messageSecurityMetadataSource = this.context
|
||||
.getBean(MessageSecurityMetadataSource.class);
|
||||
.getBean(MessageSecurityMetadataSource.class);
|
||||
assertThat(channelSecurityInterceptor.obtainSecurityMetadataSource()).isSameAs(messageSecurityMetadataSource);
|
||||
}
|
||||
|
||||
@@ -270,9 +270,9 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
|
||||
loadConfig(SockJsProxylessSecurityConfig.class);
|
||||
MessageChannel messageChannel = clientInboundChannel();
|
||||
SecurityContextChannelInterceptor securityContextChannelInterceptor = this.context
|
||||
.getBean(SecurityContextChannelInterceptor.class);
|
||||
.getBean(SecurityContextChannelInterceptor.class);
|
||||
assertThat(((AbstractMessageChannel) messageChannel).getInterceptors())
|
||||
.contains(securityContextChannelInterceptor);
|
||||
.contains(securityContextChannelInterceptor);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -546,7 +546,7 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
|
||||
// work around SPR-12716
|
||||
SockJsWebSocketHandler sockJs = (SockJsWebSocketHandler) wsHandler;
|
||||
WebSocketServerSockJsSession session = (WebSocketServerSockJsSession) ReflectionTestUtils
|
||||
.getField(sockJs, "sockJsSession");
|
||||
.getField(sockJs, "sockJsSession");
|
||||
this.attributes = session.getAttributes();
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -77,8 +77,8 @@ public class WebSocketMessageBrokerSecurityConfigurationDocTests {
|
||||
loadConfig(WebSocketSecurityConfig.class);
|
||||
clientInboundChannel().send(message("/user/queue/errors", SimpMessageType.SUBSCRIBE));
|
||||
assertThatExceptionOfType(MessageDeliveryException.class)
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/denyAll", SimpMessageType.MESSAGE)))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/denyAll", SimpMessageType.MESSAGE)))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
}
|
||||
|
||||
private void loadConfig(Class<?>... configs) {
|
||||
@@ -127,15 +127,21 @@ public class WebSocketMessageBrokerSecurityConfigurationDocTests {
|
||||
@Bean
|
||||
AuthorizationManager<Message<?>> authorizationManager(
|
||||
MessageMatcherDelegatingAuthorizationManager.Builder messages) {
|
||||
messages.nullDestMatcher().authenticated()
|
||||
// <1>
|
||||
.simpSubscribeDestMatchers("/user/queue/errors").permitAll()
|
||||
// <2>
|
||||
.simpDestMatchers("/app/**").hasRole("USER")
|
||||
// <3>
|
||||
.simpSubscribeDestMatchers("/user/**", "/topic/friends/*").hasRole("USER") // <4>
|
||||
.simpTypeMatchers(SimpMessageType.MESSAGE, SimpMessageType.SUBSCRIBE).denyAll() // <5>
|
||||
.anyMessage().denyAll(); // <6>
|
||||
messages.nullDestMatcher()
|
||||
.authenticated()
|
||||
// <1>
|
||||
.simpSubscribeDestMatchers("/user/queue/errors")
|
||||
.permitAll()
|
||||
// <2>
|
||||
.simpDestMatchers("/app/**")
|
||||
.hasRole("USER")
|
||||
// <3>
|
||||
.simpSubscribeDestMatchers("/user/**", "/topic/friends/*")
|
||||
.hasRole("USER") // <4>
|
||||
.simpTypeMatchers(SimpMessageType.MESSAGE, SimpMessageType.SUBSCRIBE)
|
||||
.denyAll() // <5>
|
||||
.anyMessage()
|
||||
.denyAll(); // <6>
|
||||
return messages.build();
|
||||
}
|
||||
|
||||
|
||||
@@ -125,8 +125,8 @@ public class WebSocketMessageBrokerSecurityConfigurationTests {
|
||||
loadConfig(SockJsSecurityConfig.class);
|
||||
clientInboundChannel().send(message("/permitAll"));
|
||||
assertThatExceptionOfType(MessageDeliveryException.class)
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/denyAll")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/denyAll")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -151,7 +151,7 @@ public class WebSocketMessageBrokerSecurityConfigurationTests {
|
||||
Message<String> message = message("/permitAll/authentication");
|
||||
messageChannel.send(message);
|
||||
assertThat(this.context.getBean(MyController.class).authenticationPrincipal)
|
||||
.isEqualTo((String) this.messageUser.getPrincipal());
|
||||
.isEqualTo((String) this.messageUser.getPrincipal());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -161,7 +161,7 @@ public class WebSocketMessageBrokerSecurityConfigurationTests {
|
||||
Message<String> message = message("/permitAll/authentication");
|
||||
messageChannel.send(message);
|
||||
assertThat(this.context.getBean(MyController.class).authenticationPrincipal)
|
||||
.isEqualTo((String) this.messageUser.getPrincipal());
|
||||
.isEqualTo((String) this.messageUser.getPrincipal());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -171,7 +171,7 @@ public class WebSocketMessageBrokerSecurityConfigurationTests {
|
||||
Message<?> message = message(headers, "/authentication");
|
||||
MessageChannel messageChannel = clientInboundChannel();
|
||||
assertThatExceptionOfType(MessageDeliveryException.class).isThrownBy(() -> messageChannel.send(message))
|
||||
.withCauseInstanceOf(MissingCsrfTokenException.class);
|
||||
.withCauseInstanceOf(MissingCsrfTokenException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -181,7 +181,7 @@ public class WebSocketMessageBrokerSecurityConfigurationTests {
|
||||
Message<?> message = message(headers, "/authentication");
|
||||
MessageChannel messageChannel = clientInboundChannel();
|
||||
assertThatExceptionOfType(MessageDeliveryException.class).isThrownBy(() -> messageChannel.send(message))
|
||||
.withCauseInstanceOf(MissingCsrfTokenException.class);
|
||||
.withCauseInstanceOf(MissingCsrfTokenException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -199,7 +199,9 @@ public class WebSocketMessageBrokerSecurityConfigurationTests {
|
||||
loadConfig(SockJsProxylessSecurityConfig.class);
|
||||
MessageChannel messageChannel = clientInboundChannel();
|
||||
Stream<Class<? extends ChannelInterceptor>> interceptors = ((AbstractMessageChannel) messageChannel)
|
||||
.getInterceptors().stream().map(ChannelInterceptor::getClass);
|
||||
.getInterceptors()
|
||||
.stream()
|
||||
.map(ChannelInterceptor::getClass);
|
||||
assertThat(interceptors).contains(XorCsrfChannelInterceptor.class);
|
||||
}
|
||||
|
||||
@@ -253,8 +255,8 @@ public class WebSocketMessageBrokerSecurityConfigurationTests {
|
||||
loadConfig(MsmsRegistryCustomPatternMatcherConfig.class);
|
||||
clientInboundChannel().send(message("/app/a.b"));
|
||||
assertThatExceptionOfType(MessageDeliveryException.class)
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/app/a.b.c")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/app/a.b.c")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -262,8 +264,8 @@ public class WebSocketMessageBrokerSecurityConfigurationTests {
|
||||
loadConfig(OverrideMsmsRegistryCustomPatternMatcherConfig.class);
|
||||
clientInboundChannel().send(message("/app/a/b"));
|
||||
assertThatExceptionOfType(MessageDeliveryException.class)
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/app/a/b/c")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/app/a/b/c")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -271,8 +273,8 @@ public class WebSocketMessageBrokerSecurityConfigurationTests {
|
||||
loadConfig(DefaultPatternMatcherConfig.class);
|
||||
clientInboundChannel().send(message("/app/a/b"));
|
||||
assertThatExceptionOfType(MessageDeliveryException.class)
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/app/a/b/c")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/app/a/b/c")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -281,8 +283,8 @@ public class WebSocketMessageBrokerSecurityConfigurationTests {
|
||||
clientInboundChannel().send(message("/denyRob"));
|
||||
this.messageUser = new TestingAuthenticationToken("rob", "password", "ROLE_USER");
|
||||
assertThatExceptionOfType(MessageDeliveryException.class)
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/denyRob")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/denyRob")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -293,7 +295,7 @@ public class WebSocketMessageBrokerSecurityConfigurationTests {
|
||||
for (ChannelInterceptor interceptor : messageChannel.getInterceptors()) {
|
||||
if (interceptor instanceof AuthorizationChannelInterceptor) {
|
||||
assertThat(ReflectionTestUtils.getField(interceptor, "preSendAuthorizationManager"))
|
||||
.isSameAs(authorizationManager);
|
||||
.isSameAs(authorizationManager);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -305,7 +307,9 @@ public class WebSocketMessageBrokerSecurityConfigurationTests {
|
||||
loadConfig(SockJsProxylessSecurityConfig.class);
|
||||
MessageChannel messageChannel = clientInboundChannel();
|
||||
Stream<Class<? extends ChannelInterceptor>> interceptors = ((AbstractMessageChannel) messageChannel)
|
||||
.getInterceptors().stream().map(ChannelInterceptor::getClass);
|
||||
.getInterceptors()
|
||||
.stream()
|
||||
.map(ChannelInterceptor::getClass);
|
||||
assertThat(interceptors).contains(SecurityContextChannelInterceptor.class);
|
||||
}
|
||||
|
||||
@@ -314,7 +318,9 @@ public class WebSocketMessageBrokerSecurityConfigurationTests {
|
||||
loadConfig(SockJsProxylessSecurityConfig.class);
|
||||
MessageChannel messageChannel = clientInboundChannel();
|
||||
Stream<Class<? extends ChannelInterceptor>> interceptors = ((AbstractMessageChannel) messageChannel)
|
||||
.getInterceptors().stream().map(ChannelInterceptor::getClass);
|
||||
.getInterceptors()
|
||||
.stream()
|
||||
.map(ChannelInterceptor::getClass);
|
||||
assertThat(interceptors).contains(AuthorizationChannelInterceptor.class);
|
||||
}
|
||||
|
||||
@@ -324,8 +330,8 @@ public class WebSocketMessageBrokerSecurityConfigurationTests {
|
||||
this.messageUser = new RememberMeAuthenticationToken("key", "user",
|
||||
AuthorityUtils.createAuthorityList("ROLE_USER"));
|
||||
assertThatExceptionOfType(MessageDeliveryException.class)
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/fullyAuthenticated")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/fullyAuthenticated")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -339,8 +345,8 @@ public class WebSocketMessageBrokerSecurityConfigurationTests {
|
||||
loadConfig(WebSocketSecurityConfig.class);
|
||||
this.messageUser = null;
|
||||
assertThatExceptionOfType(MessageDeliveryException.class)
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/rememberMe")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/rememberMe")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -363,8 +369,8 @@ public class WebSocketMessageBrokerSecurityConfigurationTests {
|
||||
public void sendMessageWhenAnonymousConfiguredAndLoggedInUserThenAccessDeniedException() {
|
||||
loadConfig(WebSocketSecurityConfig.class);
|
||||
assertThatExceptionOfType(MessageDeliveryException.class)
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/anonymous")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
.isThrownBy(() -> clientInboundChannel().send(message("/anonymous")))
|
||||
.withCauseInstanceOf(AccessDeniedException.class);
|
||||
|
||||
}
|
||||
|
||||
@@ -630,7 +636,7 @@ public class WebSocketMessageBrokerSecurityConfigurationTests {
|
||||
if (wsHandler instanceof SockJsWebSocketHandler sockJs) {
|
||||
// work around SPR-12716
|
||||
WebSocketServerSockJsSession session = (WebSocketServerSockJsSession) ReflectionTestUtils
|
||||
.getField(sockJs, "sockJsSession");
|
||||
.getField(sockJs, "sockJsSession");
|
||||
this.attributes = session.getAttributes();
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -40,14 +40,16 @@ class OAuth2LoginRuntimeHintsTests {
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
SpringFactoriesLoader.forResourceLocation("META-INF/spring/aot.factories").load(RuntimeHintsRegistrar.class)
|
||||
.forEach((registrar) -> registrar.registerHints(this.hints, ClassUtils.getDefaultClassLoader()));
|
||||
SpringFactoriesLoader.forResourceLocation("META-INF/spring/aot.factories")
|
||||
.load(RuntimeHintsRegistrar.class)
|
||||
.forEach((registrar) -> registrar.registerHints(this.hints, ClassUtils.getDefaultClassLoader()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void jwtDecoderHasHints() {
|
||||
assertThat(RuntimeHintsPredicates.reflection().onType(JwtDecoder.class)
|
||||
.withMemberCategories(MemberCategory.INVOKE_PUBLIC_METHODS)).accepts(this.hints);
|
||||
assertThat(RuntimeHintsPredicates.reflection()
|
||||
.onType(JwtDecoder.class)
|
||||
.withMemberCategories(MemberCategory.INVOKE_PUBLIC_METHODS)).accepts(this.hints);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ public class AuthenticationConfigurationGh3935Tests {
|
||||
AuthenticationManager authenticationManager = this.adapter.authenticationManager;
|
||||
assertThat(authenticationManager).isNotNull();
|
||||
Authentication auth = authenticationManager
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated(username, password));
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated(username, password));
|
||||
verify(this.uds).loadUserByUsername(username);
|
||||
assertThat(auth.getPrincipal()).isEqualTo(PasswordEncodedUser.user());
|
||||
}
|
||||
|
||||
@@ -124,7 +124,8 @@ public class AuthenticationManagerBeanDefinitionParserTests {
|
||||
@Test
|
||||
public void clearCredentialsPropertyIsRespected() {
|
||||
ConfigurableApplicationContext appContext = this.spring
|
||||
.context("<authentication-manager erase-credentials='false'/>").getContext();
|
||||
.context("<authentication-manager erase-credentials='false'/>")
|
||||
.getContext();
|
||||
ProviderManager pm = (ProviderManager) appContext.getBeansOfType(ProviderManager.class).values().toArray()[0];
|
||||
assertThat(pm.isEraseCredentialsAfterAuthentication()).isFalse();
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user