Apply updated Code Style
Closes gh-13881
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() instanceof AnyRequestMatcher)
|
||||
.isTrue();
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
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,8 @@ public class SecurityNamespaceHandlerTests {
|
||||
String className = "javax.servlet.Filter";
|
||||
expectClassUtilsForNameThrowsNoClassDefFoundError(className);
|
||||
assertThatExceptionOfType(BeanDefinitionParsingException.class)
|
||||
.isThrownBy(() -> new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER + XML_HTTP_BLOCK))
|
||||
.withMessageContaining("NoClassDefFoundError: " + className);
|
||||
.isThrownBy(() -> new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER + XML_HTTP_BLOCK))
|
||||
.withMessageContaining("NoClassDefFoundError: " + className);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -114,8 +114,8 @@ public class SecurityNamespaceHandlerTests {
|
||||
String className = FILTER_CHAIN_PROXY_CLASSNAME;
|
||||
expectClassUtilsForNameThrowsClassNotFoundException(className);
|
||||
assertThatExceptionOfType(BeanDefinitionParsingException.class)
|
||||
.isThrownBy(() -> new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER + XML_HTTP_BLOCK))
|
||||
.withMessageContaining("ClassNotFoundException: " + className);
|
||||
.isThrownBy(() -> new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER + XML_HTTP_BLOCK))
|
||||
.withMessageContaining("ClassNotFoundException: " + className);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -137,18 +137,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 {
|
||||
|
||||
@@ -92,19 +92,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");
|
||||
}
|
||||
@@ -112,10 +115,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");
|
||||
}
|
||||
@@ -124,10 +128,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);
|
||||
}
|
||||
|
||||
@@ -162,7 +166,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"));
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -151,8 +151,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();
|
||||
}
|
||||
|
||||
|
||||
@@ -48,7 +48,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);
|
||||
}
|
||||
|
||||
|
||||
@@ -91,28 +91,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();
|
||||
}
|
||||
|
||||
@@ -120,25 +126,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());
|
||||
}
|
||||
|
||||
@@ -146,18 +157,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(),
|
||||
@@ -173,7 +189,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
|
||||
@@ -209,12 +225,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
|
||||
@@ -223,13 +240,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
|
||||
@@ -237,9 +255,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);
|
||||
@@ -252,8 +271,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"));
|
||||
@@ -264,8 +284,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"));
|
||||
@@ -274,14 +295,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
|
||||
}
|
||||
|
||||
@@ -304,22 +327,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);
|
||||
}
|
||||
|
||||
@EnableGlobalMethodSecurity(securedEnabled = true)
|
||||
|
||||
@@ -58,7 +58,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
|
||||
@@ -75,21 +75,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");
|
||||
}
|
||||
|
||||
@@ -98,7 +98,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")));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -58,10 +58,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() {
|
||||
@@ -76,10 +76,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
|
||||
@@ -152,7 +152,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();
|
||||
}
|
||||
|
||||
@@ -175,7 +175,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();
|
||||
}
|
||||
@@ -320,29 +320,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();
|
||||
}
|
||||
|
||||
@@ -364,7 +364,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();
|
||||
}
|
||||
|
||||
@@ -380,7 +380,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();
|
||||
}
|
||||
@@ -389,7 +389,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();
|
||||
}
|
||||
|
||||
@@ -412,7 +412,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();
|
||||
}
|
||||
@@ -421,7 +421,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();
|
||||
}
|
||||
|
||||
@@ -429,7 +429,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();
|
||||
}
|
||||
|
||||
@@ -437,7 +437,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();
|
||||
}
|
||||
|
||||
@@ -452,7 +452,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();
|
||||
}
|
||||
|
||||
|
||||
@@ -56,10 +56,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() {
|
||||
@@ -74,11 +74,11 @@ 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 (i.e. Mono / Flux) or the function must be a Kotlin coroutine "
|
||||
+ "function 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 (i.e. Mono / Flux) or the function must be a Kotlin coroutine "
|
||||
+ "function in order to support Reactor Context");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -98,7 +98,7 @@ public class EnableReactiveMethodSecurityTests {
|
||||
public void monoPreAuthorizeHasRoleWhenGrantedThenSuccess() {
|
||||
given(this.delegate.monoPreAuthorizeHasRoleFindById(1L)).willReturn(Mono.just("result"));
|
||||
Mono<String> findById = this.messageService.monoPreAuthorizeHasRoleFindById(1L)
|
||||
.subscriberContext(this.withAdmin);
|
||||
.subscriberContext(this.withAdmin);
|
||||
StepVerifier.create(findById).expectNext("result").verifyComplete();
|
||||
}
|
||||
|
||||
@@ -114,7 +114,7 @@ public class EnableReactiveMethodSecurityTests {
|
||||
public void monoPreAuthorizeHasRoleWhenNotAuthorizedThenDenied() {
|
||||
given(this.delegate.monoPreAuthorizeHasRoleFindById(1L)).willReturn(Mono.from(this.result));
|
||||
Mono<String> findById = this.messageService.monoPreAuthorizeHasRoleFindById(1L)
|
||||
.subscriberContext(this.withUser);
|
||||
.subscriberContext(this.withUser);
|
||||
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
|
||||
this.result.assertNoSubscribers();
|
||||
}
|
||||
@@ -202,7 +202,7 @@ public class EnableReactiveMethodSecurityTests {
|
||||
public void fluxPreAuthorizeHasRoleWhenGrantedThenSuccess() {
|
||||
given(this.delegate.fluxPreAuthorizeHasRoleFindById(1L)).willReturn(Flux.just("result"));
|
||||
Flux<String> findById = this.messageService.fluxPreAuthorizeHasRoleFindById(1L)
|
||||
.subscriberContext(this.withAdmin);
|
||||
.subscriberContext(this.withAdmin);
|
||||
StepVerifier.create(findById).consumeNextWith((s) -> assertThat(s).isEqualTo("result")).verifyComplete();
|
||||
}
|
||||
|
||||
@@ -218,7 +218,7 @@ public class EnableReactiveMethodSecurityTests {
|
||||
public void fluxPreAuthorizeHasRoleWhenNotAuthorizedThenDenied() {
|
||||
given(this.delegate.fluxPreAuthorizeHasRoleFindById(1L)).willReturn(Flux.from(this.result));
|
||||
Flux<String> findById = this.messageService.fluxPreAuthorizeHasRoleFindById(1L)
|
||||
.subscriberContext(this.withUser);
|
||||
.subscriberContext(this.withUser);
|
||||
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
|
||||
this.result.assertNoSubscribers();
|
||||
}
|
||||
@@ -306,7 +306,7 @@ public class EnableReactiveMethodSecurityTests {
|
||||
public void publisherPreAuthorizeHasRoleWhenGrantedThenSuccess() {
|
||||
given(this.delegate.publisherPreAuthorizeHasRoleFindById(1L)).willReturn(publisherJust("result"));
|
||||
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeHasRoleFindById(1L))
|
||||
.subscriberContext(this.withAdmin);
|
||||
.subscriberContext(this.withAdmin);
|
||||
StepVerifier.create(findById).consumeNextWith((s) -> assertThat(s).isEqualTo("result")).verifyComplete();
|
||||
}
|
||||
|
||||
@@ -322,7 +322,7 @@ public class EnableReactiveMethodSecurityTests {
|
||||
public void publisherPreAuthorizeHasRoleWhenNotAuthorizedThenDenied() {
|
||||
given(this.delegate.publisherPreAuthorizeHasRoleFindById(1L)).willReturn(this.result);
|
||||
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeHasRoleFindById(1L))
|
||||
.subscriberContext(this.withUser);
|
||||
.subscriberContext(this.withUser);
|
||||
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
|
||||
this.result.assertNoSubscribers();
|
||||
}
|
||||
@@ -331,7 +331,7 @@ public class EnableReactiveMethodSecurityTests {
|
||||
public void publisherPreAuthorizeBeanWhenGrantedThenSuccess() {
|
||||
given(this.delegate.publisherPreAuthorizeBeanFindById(2L)).willReturn(publisherJust("result"));
|
||||
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeBeanFindById(2L))
|
||||
.subscriberContext(this.withAdmin);
|
||||
.subscriberContext(this.withAdmin);
|
||||
StepVerifier.create(findById).expectNext("result").verifyComplete();
|
||||
}
|
||||
|
||||
@@ -354,7 +354,7 @@ public class EnableReactiveMethodSecurityTests {
|
||||
public void publisherPreAuthorizeBeanWhenNotAuthorizedThenDenied() {
|
||||
given(this.delegate.publisherPreAuthorizeBeanFindById(1L)).willReturn(this.result);
|
||||
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeBeanFindById(1L))
|
||||
.subscriberContext(this.withUser);
|
||||
.subscriberContext(this.withUser);
|
||||
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
|
||||
this.result.assertNoSubscribers();
|
||||
}
|
||||
@@ -363,7 +363,7 @@ public class EnableReactiveMethodSecurityTests {
|
||||
public void publisherPostAuthorizeWhenAuthorizedThenSuccess() {
|
||||
given(this.delegate.publisherPostAuthorizeFindById(1L)).willReturn(publisherJust("user"));
|
||||
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeFindById(1L))
|
||||
.subscriberContext(this.withUser);
|
||||
.subscriberContext(this.withUser);
|
||||
StepVerifier.create(findById).expectNext("user").verifyComplete();
|
||||
}
|
||||
|
||||
@@ -371,7 +371,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))
|
||||
.subscriberContext(this.withUser);
|
||||
.subscriberContext(this.withUser);
|
||||
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
|
||||
}
|
||||
|
||||
@@ -379,7 +379,7 @@ public class EnableReactiveMethodSecurityTests {
|
||||
public void publisherPostAuthorizeWhenBeanAndAuthorizedThenSuccess() {
|
||||
given(this.delegate.publisherPostAuthorizeBeanFindById(2L)).willReturn(publisherJust("user"));
|
||||
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeBeanFindById(2L))
|
||||
.subscriberContext(this.withUser);
|
||||
.subscriberContext(this.withUser);
|
||||
StepVerifier.create(findById).expectNext("user").verifyComplete();
|
||||
}
|
||||
|
||||
@@ -394,7 +394,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))
|
||||
.subscriberContext(this.withUser);
|
||||
.subscriberContext(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);
|
||||
}
|
||||
|
||||
|
||||
@@ -63,7 +63,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"));
|
||||
}
|
||||
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true)
|
||||
|
||||
@@ -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
|
||||
@@ -360,7 +365,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 preAuthorizeWhenRoleAdminThenAccessDeniedException() {
|
||||
this.spring.register(MethodSecurityServiceConfig.class).autowire();
|
||||
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.methodSecurityService::preAuthorize)
|
||||
.withMessage("Access Denied");
|
||||
.withMessage("Access Denied");
|
||||
}
|
||||
|
||||
@WithAnonymousUser
|
||||
@@ -116,7 +116,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
|
||||
@@ -131,7 +132,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")
|
||||
@@ -147,7 +148,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();
|
||||
}
|
||||
@@ -165,7 +166,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")
|
||||
@@ -196,7 +197,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
|
||||
@@ -212,7 +214,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
|
||||
@@ -253,7 +256,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();
|
||||
}
|
||||
@@ -262,16 +265,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");
|
||||
}
|
||||
@@ -280,9 +283,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")
|
||||
@@ -290,7 +293,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
|
||||
@@ -306,7 +309,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();
|
||||
}
|
||||
@@ -336,7 +339,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
|
||||
@@ -345,7 +348,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")
|
||||
@@ -354,7 +357,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
|
||||
@@ -362,7 +365,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
|
||||
@@ -370,7 +373,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
|
||||
@@ -378,7 +381,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
|
||||
@@ -386,7 +389,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));
|
||||
@@ -425,7 +428,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() {
|
||||
|
||||
@@ -55,7 +55,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
|
||||
@@ -64,7 +64,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
|
||||
@@ -72,7 +72,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"));
|
||||
}
|
||||
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true)
|
||||
|
||||
@@ -129,7 +129,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();
|
||||
|
||||
@@ -38,31 +38,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) {
|
||||
|
||||
@@ -188,8 +188,9 @@ public class AbstractRequestMatcherRegistryTests {
|
||||
mockMvcPresentClasspath(true);
|
||||
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
|
||||
@@ -215,7 +216,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
|
||||
|
||||
@@ -78,9 +78,9 @@ public class WebSecurityConfigurerAdapterMockitoTests {
|
||||
@Test
|
||||
public void loadConfigWhenDefaultConfigurerAsSpringFactoryhenDefaultConfigurerApplied() {
|
||||
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));
|
||||
loadConfig(Config.class);
|
||||
assertThat(configurer.init).isTrue();
|
||||
assertThat(configurer.configure).isTrue();
|
||||
@@ -92,13 +92,15 @@ public class WebSecurityConfigurerAdapterMockitoTests {
|
||||
WebAsyncManager webAsyncManager = mock(WebAsyncManager.class);
|
||||
this.mockMvc.perform(get("/").requestAttr(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE, webAsyncManager));
|
||||
ArgumentCaptor<CallableProcessingInterceptor> callableProcessingInterceptorArgCaptor = ArgumentCaptor
|
||||
.forClass(CallableProcessingInterceptor.class);
|
||||
.forClass(CallableProcessingInterceptor.class);
|
||||
verify(webAsyncManager, atLeastOnce()).registerCallableInterceptor(any(),
|
||||
callableProcessingInterceptorArgCaptor.capture());
|
||||
CallableProcessingInterceptor callableProcessingInterceptor = callableProcessingInterceptorArgCaptor
|
||||
.getAllValues().stream()
|
||||
.filter((e) -> SecurityContextCallableProcessingInterceptor.class.isAssignableFrom(e.getClass()))
|
||||
.findFirst().orElse(null);
|
||||
.getAllValues()
|
||||
.stream()
|
||||
.filter((e) -> SecurityContextCallableProcessingInterceptor.class.isAssignableFrom(e.getClass()))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
assertThat(callableProcessingInterceptor).isNotNull();
|
||||
}
|
||||
|
||||
|
||||
@@ -126,20 +126,20 @@ public class WebSecurityConfigurerAdapterTests {
|
||||
ContentNegotiationStrategy.class);
|
||||
this.spring.register(OverrideContentNegotiationStrategySharedObjectConfig.class).autowire();
|
||||
OverrideContentNegotiationStrategySharedObjectConfig securityConfig = this.spring.getContext()
|
||||
.getBean(OverrideContentNegotiationStrategySharedObjectConfig.class);
|
||||
.getBean(OverrideContentNegotiationStrategySharedObjectConfig.class);
|
||||
assertThat(securityConfig.contentNegotiationStrategySharedObject).isNotNull();
|
||||
assertThat(securityConfig.contentNegotiationStrategySharedObject)
|
||||
.isSameAs(OverrideContentNegotiationStrategySharedObjectConfig.CONTENT_NEGOTIATION_STRATEGY_BEAN);
|
||||
.isSameAs(OverrideContentNegotiationStrategySharedObjectConfig.CONTENT_NEGOTIATION_STRATEGY_BEAN);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadConfigWhenDefaultContentNegotiationStrategyThenHeaderContentNegotiationStrategy() {
|
||||
this.spring.register(ContentNegotiationStrategyDefaultSharedObjectConfig.class).autowire();
|
||||
ContentNegotiationStrategyDefaultSharedObjectConfig securityConfig = this.spring.getContext()
|
||||
.getBean(ContentNegotiationStrategyDefaultSharedObjectConfig.class);
|
||||
.getBean(ContentNegotiationStrategyDefaultSharedObjectConfig.class);
|
||||
assertThat(securityConfig.contentNegotiationStrategySharedObject).isNotNull();
|
||||
assertThat(securityConfig.contentNegotiationStrategySharedObject)
|
||||
.isInstanceOf(HeaderContentNegotiationStrategy.class);
|
||||
.isInstanceOf(HeaderContentNegotiationStrategy.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -148,7 +148,7 @@ public class WebSecurityConfigurerAdapterTests {
|
||||
MyFilter myFilter = this.spring.getContext().getBean(MyFilter.class);
|
||||
myFilter.userDetailsService.loadUserByUsername("user");
|
||||
assertThatExceptionOfType(UsernameNotFoundException.class)
|
||||
.isThrownBy(() -> myFilter.userDetailsService.loadUserByUsername("admin"));
|
||||
.isThrownBy(() -> myFilter.userDetailsService.loadUserByUsername("admin"));
|
||||
}
|
||||
|
||||
// SEC-2274: WebSecurityConfigurer adds ApplicationContext as a shared object
|
||||
@@ -156,7 +156,7 @@ public class WebSecurityConfigurerAdapterTests {
|
||||
public void loadConfigWhenSharedObjectsCreatedThenApplicationContextAdded() {
|
||||
this.spring.register(ApplicationContextSharedObjectConfig.class).autowire();
|
||||
ApplicationContextSharedObjectConfig securityConfig = this.spring.getContext()
|
||||
.getBean(ApplicationContextSharedObjectConfig.class);
|
||||
.getBean(ApplicationContextSharedObjectConfig.class);
|
||||
assertThat(securityConfig.applicationContextSharedObject).isNotNull();
|
||||
assertThat(securityConfig.applicationContextSharedObject).isSameAs(this.spring.getContext());
|
||||
}
|
||||
@@ -168,14 +168,14 @@ public class WebSecurityConfigurerAdapterTests {
|
||||
CustomTrustResolverConfig securityConfig = this.spring.getContext().getBean(CustomTrustResolverConfig.class);
|
||||
assertThat(securityConfig.authenticationTrustResolverSharedObject).isNotNull();
|
||||
assertThat(securityConfig.authenticationTrustResolverSharedObject)
|
||||
.isSameAs(CustomTrustResolverConfig.AUTHENTICATION_TRUST_RESOLVER_BEAN);
|
||||
.isSameAs(CustomTrustResolverConfig.AUTHENTICATION_TRUST_RESOLVER_BEAN);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void compareOrderWebSecurityConfigurerAdapterWhenLowestOrderToDefaultOrderThenGreaterThanZero() {
|
||||
AnnotationAwareOrderComparator comparator = new AnnotationAwareOrderComparator();
|
||||
assertThat(comparator.compare(new LowestPriorityWebSecurityConfig(), new DefaultOrderWebSecurityConfig()))
|
||||
.isGreaterThan(0);
|
||||
.isGreaterThan(0);
|
||||
}
|
||||
|
||||
// gh-7515
|
||||
@@ -183,7 +183,7 @@ public class WebSecurityConfigurerAdapterTests {
|
||||
public void performWhenUsingAuthenticationEventPublisherBeanThenUses() throws Exception {
|
||||
this.spring.register(CustomAuthenticationEventPublisherBean.class).autowire();
|
||||
AuthenticationEventPublisher authenticationEventPublisher = this.spring.getContext()
|
||||
.getBean(AuthenticationEventPublisher.class);
|
||||
.getBean(AuthenticationEventPublisher.class);
|
||||
this.mockMvc.perform(get("/").with(httpBasic("user", "password")));
|
||||
verify(authenticationEventPublisher).publishAuthenticationSuccess(any(Authentication.class));
|
||||
}
|
||||
|
||||
@@ -64,10 +64,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
|
||||
|
||||
@@ -56,17 +56,17 @@ public class HttpSecurityAddFilterTests {
|
||||
@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
|
||||
@@ -135,8 +135,10 @@ public class HttpSecurityAddFilterTests {
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
@@ -52,7 +52,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")));
|
||||
|
||||
@@ -65,7 +65,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")));
|
||||
|
||||
|
||||
@@ -93,7 +93,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),
|
||||
@@ -103,8 +103,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
|
||||
@@ -191,7 +192,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);
|
||||
}
|
||||
|
||||
@@ -201,7 +202,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);
|
||||
}
|
||||
|
||||
@@ -211,9 +212,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
|
||||
@@ -222,16 +223,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();
|
||||
}
|
||||
|
||||
@@ -248,7 +249,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
|
||||
@@ -256,7 +257,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
|
||||
@@ -264,7 +265,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
|
||||
@@ -272,7 +273,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);
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
@@ -610,7 +611,8 @@ public class NamespaceHttpTests {
|
||||
web.postBuildAction(() -> {
|
||||
FilterSecurityInterceptor securityInterceptor = http.getSharedObject(FilterSecurityInterceptor.class);
|
||||
UseExpressionsConfig.this.filterInvocationSecurityMetadataSourceType = securityInterceptor
|
||||
.getSecurityMetadataSource().getClass();
|
||||
.getSecurityMetadataSource()
|
||||
.getClass();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -639,7 +641,8 @@ public class NamespaceHttpTests {
|
||||
web.postBuildAction(() -> {
|
||||
FilterSecurityInterceptor securityInterceptor = http.getSharedObject(FilterSecurityInterceptor.class);
|
||||
DisableUseExpressionsConfig.this.filterInvocationSecurityMetadataSourceType = securityInterceptor
|
||||
.getSecurityMetadataSource().getClass();
|
||||
.getSecurityMetadataSource()
|
||||
.getClass();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ public class EnableWebSecurityTests {
|
||||
this.spring.register(SecurityConfig.class).autowire();
|
||||
AuthenticationManager authenticationManager = this.spring.getContext().getBean(AuthenticationManager.class);
|
||||
Authentication authentication = authenticationManager
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
|
||||
.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("user", "password"));
|
||||
assertThat(authentication.isAuthenticated()).isTrue();
|
||||
}
|
||||
|
||||
@@ -74,14 +74,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
|
||||
|
||||
@@ -158,8 +158,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)
|
||||
@@ -251,8 +253,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();
|
||||
@@ -262,8 +264,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();
|
||||
@@ -272,8 +274,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();
|
||||
@@ -293,27 +297,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();
|
||||
@@ -324,7 +326,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-13203
|
||||
|
||||
@@ -82,14 +82,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);
|
||||
@@ -115,7 +117,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
|
||||
@@ -125,13 +128,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())
|
||||
@@ -143,20 +146,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
|
||||
@@ -192,7 +197,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);
|
||||
@@ -201,7 +207,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)
|
||||
|
||||
@@ -46,13 +46,13 @@ public class Sec2515Tests {
|
||||
@Test
|
||||
public void loadConfigWhenAuthenticationManagerNotConfiguredAndRegisterBeanThenThrowFatalBeanException() {
|
||||
assertThatExceptionOfType(FatalBeanException.class)
|
||||
.isThrownBy(() -> this.spring.register(StackOverflowSecurityConfig.class).autowire());
|
||||
.isThrownBy(() -> this.spring.register(StackOverflowSecurityConfig.class).autowire());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void loadConfigWhenAuthenticationManagerNotConfiguredAndRegisterBeanCustomNameThenThrowFatalBeanException() {
|
||||
assertThatExceptionOfType(FatalBeanException.class)
|
||||
.isThrownBy(() -> this.spring.register(CustomBeanNameStackOverflowSecurityConfig.class).autowire());
|
||||
.isThrownBy(() -> this.spring.register(CustomBeanNameStackOverflowSecurityConfig.class).autowire());
|
||||
}
|
||||
|
||||
// SEC-2549
|
||||
@@ -61,7 +61,7 @@ public class Sec2515Tests {
|
||||
CanLoadWithChildConfig.AUTHENTICATION_MANAGER = mock(AuthenticationManager.class);
|
||||
this.spring.register(CanLoadWithChildConfig.class);
|
||||
AnnotationConfigWebApplicationContext context = (AnnotationConfigWebApplicationContext) this.spring
|
||||
.getContext();
|
||||
.getContext();
|
||||
context.setClassLoader(new URLClassLoader(new URL[0], context.getClassLoader()));
|
||||
this.spring.autowire();
|
||||
assertThat(this.spring.getContext().getBean(AuthenticationManager.class)).isNotNull();
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -102,14 +102,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";
|
||||
@@ -123,7 +123,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),
|
||||
@@ -133,7 +133,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<>());
|
||||
@@ -189,7 +189,7 @@ public class SecurityReactorContextConfigurationTests {
|
||||
}
|
||||
});
|
||||
CoreSubscriber<Object> subscriber = this.subscriberRegistrar
|
||||
.createSubscriberIfNecessary(Operators.emptySubscriber());
|
||||
.createSubscriberIfNecessary(Operators.emptySubscriber());
|
||||
assertThat(subscriber).isInstanceOf(SecurityReactorContextConfiguration.SecurityReactorContextSubscriber.class);
|
||||
}
|
||||
|
||||
@@ -200,7 +200,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
|
||||
@@ -226,7 +226,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()
|
||||
@@ -257,7 +257,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
|
||||
|
||||
@@ -153,10 +153,10 @@ public class WebSecurityConfigurationTests {
|
||||
@Test
|
||||
public void loadConfigWhenWebSecurityConfigurersHaveSameOrderThenThrowBeanCreationException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(DuplicateOrderConfig.class).autowire())
|
||||
.withMessageContaining("@Order on WebSecurityConfigurers must be unique")
|
||||
.withMessageContaining(DuplicateOrderConfig.WebConfigurer1.class.getName())
|
||||
.withMessageContaining(DuplicateOrderConfig.WebConfigurer2.class.getName());
|
||||
.isThrownBy(() -> this.spring.register(DuplicateOrderConfig.class).autowire())
|
||||
.withMessageContaining("@Order on WebSecurityConfigurers must be unique")
|
||||
.withMessageContaining(DuplicateOrderConfig.WebConfigurer1.class.getName())
|
||||
.withMessageContaining(DuplicateOrderConfig.WebConfigurer2.class.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -164,31 +164,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
|
||||
@@ -198,7 +199,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);
|
||||
@@ -212,7 +213,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);
|
||||
@@ -223,7 +224,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
|
||||
@@ -231,7 +232,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
|
||||
@@ -265,7 +266,7 @@ public class WebSecurityConfigurationTests {
|
||||
@Test
|
||||
public void loadConfigWhenBeanProxyingEnabledAndSubclassThenFilterChainsCreated() {
|
||||
this.spring.register(GlobalAuthenticationWebSecurityConfigurerAdaptersConfig.class, SubclassConfig.class)
|
||||
.autowire();
|
||||
.autowire();
|
||||
FilterChainProxy filterChainProxy = this.spring.getContext().getBean(FilterChainProxy.class);
|
||||
List<SecurityFilterChain> filterChains = filterChainProxy.getFilterChains();
|
||||
assertThat(filterChains).hasSize(4);
|
||||
@@ -274,9 +275,9 @@ public class WebSecurityConfigurationTests {
|
||||
@Test
|
||||
public void loadConfigWhenBothAdapterAndFilterChainConfiguredThenException() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(AdapterAndFilterChainConfig.class).autowire())
|
||||
.withRootCauseExactlyInstanceOf(IllegalStateException.class)
|
||||
.withMessageContaining("Found WebSecurityConfigurerAdapter as well as SecurityFilterChain.");
|
||||
.isThrownBy(() -> this.spring.register(AdapterAndFilterChainConfig.class).autowire())
|
||||
.withRootCauseExactlyInstanceOf(IllegalStateException.class)
|
||||
.withMessageContaining("Found WebSecurityConfigurerAdapter as well as SecurityFilterChain.");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -381,14 +382,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
|
||||
@@ -396,7 +397,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);
|
||||
@@ -407,7 +408,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);
|
||||
|
||||
@@ -69,11 +69,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));
|
||||
}
|
||||
|
||||
|
||||
@@ -86,37 +86,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
|
||||
@@ -139,8 +140,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
|
||||
|
||||
@@ -152,8 +152,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);
|
||||
}
|
||||
|
||||
@@ -67,62 +67,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
|
||||
@@ -130,55 +137,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"));
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
|
||||
@@ -63,7 +63,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) {
|
||||
|
||||
@@ -114,72 +114,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());
|
||||
}
|
||||
|
||||
@@ -206,9 +206,12 @@ public class CsrfConfigurerTests {
|
||||
public void loginWhenCsrfDisabledThenRedirectsToPreviousPostRequest() throws Exception {
|
||||
this.spring.register(DisableCsrfEnablesRequestCacheConfig.class).autowire();
|
||||
MvcResult mvcResult = this.mvc.perform(post("/to-save")).andReturn();
|
||||
this.mvc.perform(post("/login").param("username", "user").param("password", "password")
|
||||
.session((MockHttpSession) mvcResult.getRequest().getSession())).andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("http://localhost/to-save"));
|
||||
this.mvc
|
||||
.perform(post("/login").param("username", "user")
|
||||
.param("password", "password")
|
||||
.session((MockHttpSession) mvcResult.getRequest().getSession()))
|
||||
.andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("http://localhost/to-save"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -216,14 +219,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
|
||||
@@ -231,24 +239,31 @@ 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();
|
||||
this.mvc.perform(post("/login").param("username", "user").param("password", "password").with(csrf())
|
||||
.session((MockHttpSession) mvcResult.getRequest().getSession())).andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("http://localhost/some-url"));
|
||||
this.mvc
|
||||
.perform(post("/login").param("username", "user")
|
||||
.param("password", "password")
|
||||
.with(csrf())
|
||||
.session((MockHttpSession) mvcResult.getRequest().getSession()))
|
||||
.andExpect(status().isFound())
|
||||
.andExpect(redirectedUrl("http://localhost/some-url"));
|
||||
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
|
||||
@@ -287,7 +302,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(get("/")).andExpect(status().isOk());
|
||||
verify(CsrfTokenRepositoryConfig.REPO).loadDeferredToken(any(HttpServletRequest.class),
|
||||
@@ -309,7 +324,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")
|
||||
@@ -328,7 +344,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(get("/")).andExpect(status().isOk());
|
||||
verify(CsrfTokenRepositoryInLambdaConfig.REPO).loadDeferredToken(any(HttpServletRequest.class),
|
||||
@@ -398,8 +414,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
|
||||
@@ -412,8 +428,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
|
||||
@@ -436,12 +452,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);
|
||||
}
|
||||
@@ -452,7 +469,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();
|
||||
@@ -476,12 +493,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);
|
||||
}
|
||||
@@ -492,7 +510,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.size()).isEqualTo(1);
|
||||
DefaultSecurityFilterChain filterChain = (DefaultSecurityFilterChain) filterChains.get(0);
|
||||
assertThat(filterChain.getRequestMatcher()).isInstanceOf(AnyRequestMatcher.class);
|
||||
assertThat(filterChain.getFilters().size()).isEqualTo(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.size()).isEqualTo(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<? extends Class<? extends Filter>> classes = secondFilter.getFilters().stream().map(Filter::getClass)
|
||||
.collect(Collectors.toList());
|
||||
List<? extends Class<? extends Filter>> classes = secondFilter.getFilters()
|
||||
.stream()
|
||||
.map(Filter::getClass)
|
||||
.collect(Collectors.toList());
|
||||
assertThat(classes.contains(WebAsyncManagerIntegrationFilter.class)).isTrue();
|
||||
assertThat(classes.contains(SecurityContextPersistenceFilter.class)).isTrue();
|
||||
assertThat(classes.contains(HeaderWriterFilter.class)).isTrue();
|
||||
@@ -127,8 +133,9 @@ public class DefaultFiltersTests {
|
||||
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "BaseSpringSpec_CSRFTOKEN");
|
||||
new HttpSessionCsrfTokenRepository().saveToken(csrfToken, request, response);
|
||||
request.setParameter(csrfToken.getParameterName(), csrfToken.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");
|
||||
}
|
||||
|
||||
|
||||
@@ -353,7 +353,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
|
||||
@@ -374,9 +374,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
|
||||
|
||||
@@ -78,7 +78,7 @@ public class ExceptionHandlingConfigurerAccessDeniedHandlerTests {
|
||||
static class RequestMatcherBasedAccessDeniedHandlerConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
AccessDeniedHandler teapotDeniedHandler = (request, response, exception) -> response
|
||||
.setStatus(HttpStatus.I_AM_A_TEAPOT.value());
|
||||
.setStatus(HttpStatus.I_AM_A_TEAPOT.value());
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
@@ -103,7 +103,7 @@ public class ExceptionHandlingConfigurerAccessDeniedHandlerTests {
|
||||
static class RequestMatcherBasedAccessDeniedHandlerInLambdaConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
AccessDeniedHandler teapotDeniedHandler = (request, response, exception) -> response
|
||||
.setStatus(HttpStatus.I_AM_A_TEAPOT.value());
|
||||
.setStatus(HttpStatus.I_AM_A_TEAPOT.value());
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
@@ -133,7 +133,7 @@ public class ExceptionHandlingConfigurerAccessDeniedHandlerTests {
|
||||
static class SingleRequestMatcherAccessDeniedHandlerConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
AccessDeniedHandler teapotDeniedHandler = (request, response, exception) -> response
|
||||
.setStatus(HttpStatus.I_AM_A_TEAPOT.value());
|
||||
.setStatus(HttpStatus.I_AM_A_TEAPOT.value());
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
|
||||
@@ -81,7 +81,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
|
||||
@@ -124,7 +124,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
|
||||
@@ -132,7 +132,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
|
||||
@@ -140,7 +140,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
|
||||
@@ -148,7 +148,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
|
||||
@@ -156,7 +156,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
|
||||
@@ -176,25 +176,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
|
||||
@@ -204,7 +205,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));
|
||||
}
|
||||
|
||||
@@ -212,7 +213,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
|
||||
|
||||
@@ -89,9 +89,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
|
||||
@@ -103,15 +104,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
|
||||
|
||||
@@ -117,7 +117,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));
|
||||
}
|
||||
|
||||
@@ -358,7 +358,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
|
||||
@@ -616,7 +616,8 @@ public class FormLoginConfigurerTests {
|
||||
.portMapper(PORT_MAPPER);
|
||||
// @formatter:on
|
||||
LoginUrlAuthenticationEntryPoint authenticationEntryPoint = (LoginUrlAuthenticationEntryPoint) http
|
||||
.getConfigurer(FormLoginConfigurer.class).getAuthenticationEntryPoint();
|
||||
.getConfigurer(FormLoginConfigurer.class)
|
||||
.getAuthenticationEntryPoint();
|
||||
authenticationEntryPoint.setForceHttps(true);
|
||||
}
|
||||
|
||||
|
||||
@@ -49,13 +49,14 @@ public class HeadersConfigurerEagerHeadersTests {
|
||||
@Test
|
||||
public void requestWhenHeadersEagerlyConfiguredThenHeadersAreWritten() throws Exception {
|
||||
this.spring.register(HeadersAtTheBeginningOfRequestConfig.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", "1; mode=block"));
|
||||
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", "1; mode=block"));
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
|
||||
@@ -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, "1; mode=block")).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, "1; mode=block"))
|
||||
.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, "1; mode=block")).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, "1; mode=block"))
|
||||
.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, "1; mode=block")).andReturn();
|
||||
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "1; mode=block"))
|
||||
.andReturn();
|
||||
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_XSS_PROTECTION);
|
||||
}
|
||||
|
||||
@@ -178,7 +183,8 @@ public class HeadersConfigurerTests {
|
||||
throws Exception {
|
||||
this.spring.register(XssProtectionValueDisabledConfig.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);
|
||||
}
|
||||
|
||||
@@ -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, "1; mode=block")).andReturn();
|
||||
.andExpect(header().string(HttpHeaders.X_XSS_PROTECTION, "1; mode=block"))
|
||||
.andReturn();
|
||||
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_XSS_PROTECTION);
|
||||
}
|
||||
|
||||
@@ -195,7 +202,8 @@ public class HeadersConfigurerTests {
|
||||
throws Exception {
|
||||
this.spring.register(XssProtectionValueDisabledInLambdaConfig.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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -126,25 +126,27 @@ public class HttpBasicConfigurerTests {
|
||||
public void httpBasicWhenRememberMeConfiguredThenSetsRememberMeCookie() throws Exception {
|
||||
this.spring.register(BasicUsesRememberMeConfig.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));
|
||||
}
|
||||
|
||||
@@ -318,7 +320,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();
|
||||
}
|
||||
|
||||
@@ -75,8 +75,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);
|
||||
|
||||
@@ -479,7 +479,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()
|
||||
@@ -514,7 +514,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
|
||||
@@ -546,8 +546,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);
|
||||
}
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ public class Issue55Tests {
|
||||
FilterSecurityInterceptor secondFilter = (FilterSecurityInterceptor) findFilter(FilterSecurityInterceptor.class,
|
||||
1);
|
||||
assertThat(secondFilter.getAuthenticationManager().authenticate(token))
|
||||
.isEqualTo(CustomAuthenticationManager.RESULT);
|
||||
.isEqualTo(CustomAuthenticationManager.RESULT);
|
||||
}
|
||||
|
||||
Filter findFilter(Class<?> filter, int index) {
|
||||
|
||||
@@ -65,7 +65,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
|
||||
@@ -73,7 +73,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
|
||||
@@ -125,7 +125,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);
|
||||
}
|
||||
|
||||
@@ -138,7 +138,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
|
||||
|
||||
@@ -198,9 +198,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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -124,7 +124,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));
|
||||
}
|
||||
@@ -134,7 +134,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);
|
||||
}
|
||||
|
||||
|
||||
@@ -56,21 +56,21 @@ public class NamespaceHttpFirewallTests {
|
||||
public void requestWhenPathContainsDoubleDotsThenBehaviorMatchesNamespace() {
|
||||
this.rule.register(HttpFirewallConfig.class).autowire();
|
||||
assertThatExceptionOfType(RequestRejectedException.class)
|
||||
.isThrownBy(() -> this.mvc.perform(get("/public/../private/")));
|
||||
.isThrownBy(() -> this.mvc.perform(get("/public/../private/")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestWithCustomFirewallThenBehaviorMatchesNamespace() {
|
||||
this.rule.register(CustomHttpFirewallConfig.class).autowire();
|
||||
assertThatExceptionOfType(RequestRejectedException.class)
|
||||
.isThrownBy(() -> this.mvc.perform(get("/").param("deny", "true")));
|
||||
.isThrownBy(() -> this.mvc.perform(get("/").param("deny", "true")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestWithCustomFirewallBeanThenBehaviorMatchesNamespace() {
|
||||
this.rule.register(CustomHttpFirewallBeanConfig.class).autowire();
|
||||
assertThatExceptionOfType(RequestRejectedException.class)
|
||||
.isThrownBy(() -> this.mvc.perform(get("/").param("deny", "true")));
|
||||
.isThrownBy(() -> this.mvc.perform(get("/").param("deny", "true")));
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -89,7 +89,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
|
||||
@@ -102,7 +102,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
|
||||
@@ -127,7 +127,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() {
|
||||
|
||||
@@ -87,7 +87,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());
|
||||
}
|
||||
|
||||
|
||||
@@ -81,8 +81,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());
|
||||
}
|
||||
|
||||
|
||||
@@ -151,7 +151,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() {
|
||||
@@ -160,7 +161,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"));
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
|
||||
@@ -102,31 +102,40 @@ public class NamespaceHttpOpenIDLoginTests {
|
||||
DiscoveryInformation mockDiscoveryInformation = mock(DiscoveryInformation.class);
|
||||
given(mockAuthRequest.getDestinationUrl(anyBoolean())).willReturn("mockUrl");
|
||||
given(OpenIDLoginAttributeExchangeConfig.CONSUMER_MANAGER.associate(any()))
|
||||
.willReturn(mockDiscoveryInformation);
|
||||
.willReturn(mockDiscoveryInformation);
|
||||
given(OpenIDLoginAttributeExchangeConfig.CONSUMER_MANAGER.authenticate(any(DiscoveryInformation.class), any(),
|
||||
any())).willReturn(mockAuthRequest);
|
||||
any()))
|
||||
.willReturn(mockAuthRequest);
|
||||
this.spring.register(OpenIDLoginAttributeExchangeConfig.class).autowire();
|
||||
try (MockWebServer server = new MockWebServer()) {
|
||||
String endpoint = server.url("/").toString();
|
||||
server.enqueue(new MockResponse().addHeader(YadisResolver.YADIS_XRDS_LOCATION, endpoint));
|
||||
server.enqueue(new MockResponse()
|
||||
.setBody(String.format("<XRDS><XRD><Service><URI>%s</URI></Service></XRD></XRDS>", endpoint)));
|
||||
MvcResult mvcResult = this.mvc.perform(get("/login/openid")
|
||||
.param(OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD, "https://www.google.com/1"))
|
||||
.andExpect(status().isFound()).andReturn();
|
||||
Object attributeObject = mvcResult.getRequest().getSession()
|
||||
.getAttribute("SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST");
|
||||
.setBody(String.format("<XRDS><XRD><Service><URI>%s</URI></Service></XRD></XRDS>", endpoint)));
|
||||
MvcResult mvcResult = this.mvc
|
||||
.perform(get("/login/openid").param(OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD,
|
||||
"https://www.google.com/1"))
|
||||
.andExpect(status().isFound())
|
||||
.andReturn();
|
||||
Object attributeObject = mvcResult.getRequest()
|
||||
.getSession()
|
||||
.getAttribute("SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST");
|
||||
assertThat(attributeObject).isInstanceOf(List.class);
|
||||
List<OpenIDAttribute> attributeList = (List<OpenIDAttribute>) attributeObject;
|
||||
assertThat(attributeList.stream().anyMatch((attribute) -> "firstname".equals(attribute.getName())
|
||||
&& "https://axschema.org/namePerson/first".equals(attribute.getType()) && attribute.isRequired()))
|
||||
.isTrue();
|
||||
assertThat(attributeList.stream().anyMatch((attribute) -> "lastname".equals(attribute.getName())
|
||||
&& "https://axschema.org/namePerson/last".equals(attribute.getType()) && attribute.isRequired()))
|
||||
.isTrue();
|
||||
assertThat(attributeList.stream().anyMatch((attribute) -> "email".equals(attribute.getName())
|
||||
&& "https://axschema.org/contact/email".equals(attribute.getType()) && attribute.isRequired()))
|
||||
.isTrue();
|
||||
assertThat(attributeList.stream()
|
||||
.anyMatch((attribute) -> "firstname".equals(attribute.getName())
|
||||
&& "https://axschema.org/namePerson/first".equals(attribute.getType())
|
||||
&& attribute.isRequired()))
|
||||
.isTrue();
|
||||
assertThat(attributeList.stream()
|
||||
.anyMatch((attribute) -> "lastname".equals(attribute.getName())
|
||||
&& "https://axschema.org/namePerson/last".equals(attribute.getType())
|
||||
&& attribute.isRequired()))
|
||||
.isTrue();
|
||||
assertThat(attributeList.stream()
|
||||
.anyMatch((attribute) -> "email".equals(attribute.getName())
|
||||
&& "https://axschema.org/contact/email".equals(attribute.getType()) && attribute.isRequired()))
|
||||
.isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,7 +144,7 @@ public class NamespaceHttpOpenIDLoginTests {
|
||||
this.spring.register(OpenIDLoginCustomConfig.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"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -149,7 +158,7 @@ public class NamespaceHttpOpenIDLoginTests {
|
||||
OpenIDLoginCustomRefsConfig.CONSUMER = mock(OpenIDConsumer.class);
|
||||
this.spring.register(OpenIDLoginCustomRefsConfig.class, UserDetailsServiceConfig.class).autowire();
|
||||
given(OpenIDLoginCustomRefsConfig.CONSUMER.endConsumption(any(HttpServletRequest.class)))
|
||||
.willThrow(new AuthenticationServiceException("boom"));
|
||||
.willThrow(new AuthenticationServiceException("boom"));
|
||||
// @formatter:off
|
||||
MockHttpServletRequestBuilder login = post("/login/openid")
|
||||
.with(csrf())
|
||||
|
||||
@@ -52,7 +52,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"));
|
||||
}
|
||||
|
||||
|
||||
@@ -88,7 +88,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");
|
||||
|
||||
@@ -51,37 +51,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");
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
|
||||
@@ -77,16 +77,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()");
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
|
||||
@@ -112,13 +112,13 @@ public class RememberMeConfigurerTests {
|
||||
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("/")
|
||||
@@ -132,8 +132,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);
|
||||
@@ -146,8 +150,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);
|
||||
@@ -174,8 +182,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);
|
||||
@@ -284,10 +296,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
|
||||
@@ -315,8 +326,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
|
||||
|
||||
@@ -227,8 +227,9 @@ public class RequestCacheConfigurerTests {
|
||||
// gh-6102
|
||||
@Test
|
||||
public void getWhenRequestCacheIsDisabledThenExceptionTranslationFilterDoesNotStoreRequest() throws Exception {
|
||||
this.spring.register(RequestCacheDisabledConfig.class,
|
||||
ExceptionHandlingConfigurerTests.DefaultSecurityConfig.class).autowire();
|
||||
this.spring
|
||||
.register(RequestCacheDisabledConfig.class, ExceptionHandlingConfigurerTests.DefaultSecurityConfig.class)
|
||||
.autowire();
|
||||
// @formatter:off
|
||||
MockHttpSession session = (MockHttpSession) this.mvc.perform(get("/bob"))
|
||||
.andReturn()
|
||||
|
||||
@@ -82,7 +82,7 @@ public class SecurityContextConfigurerTests {
|
||||
public void securityContextWhenInvokedTwiceThenUsesOriginalSecurityContextRepository() throws Exception {
|
||||
this.spring.register(DuplicateDoesNotOverrideConfig.class).autowire();
|
||||
given(DuplicateDoesNotOverrideConfig.SCR.loadContext(any(HttpRequestResponseHolder.class)))
|
||||
.willReturn(mock(SecurityContext.class));
|
||||
.willReturn(mock(SecurityContext.class));
|
||||
this.mvc.perform(get("/"));
|
||||
verify(DuplicateDoesNotOverrideConfig.SCR).loadContext(any(HttpRequestResponseHolder.class));
|
||||
}
|
||||
@@ -135,7 +135,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();
|
||||
}
|
||||
|
||||
|
||||
@@ -92,7 +92,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
|
||||
@@ -153,7 +153,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());
|
||||
}
|
||||
|
||||
|
||||
@@ -55,8 +55,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));
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
|
||||
@@ -102,11 +102,11 @@ public class SessionManagementConfigurerTests {
|
||||
public void sessionManagementWhenConfiguredThenDoesNotOverrideSecurityContextRepository() throws Exception {
|
||||
SessionManagementSecurityContextRepositoryConfig.SECURITY_CONTEXT_REPO = mock(SecurityContextRepository.class);
|
||||
given(SessionManagementSecurityContextRepositoryConfig.SECURITY_CONTEXT_REPO
|
||||
.loadContext(any(HttpRequestResponseHolder.class))).willReturn(mock(SecurityContext.class));
|
||||
.loadContext(any(HttpRequestResponseHolder.class))).willReturn(mock(SecurityContext.class));
|
||||
this.spring.register(SessionManagementSecurityContextRepositoryConfig.class).autowire();
|
||||
this.mvc.perform(get("/"));
|
||||
verify(SessionManagementSecurityContextRepositoryConfig.SECURITY_CONTEXT_REPO)
|
||||
.saveContext(any(SecurityContext.class), any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
.saveContext(any(SecurityContext.class), any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -246,7 +246,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
|
||||
@@ -254,7 +254,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
|
||||
@@ -262,7 +262,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
|
||||
@@ -270,7 +270,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
|
||||
|
||||
@@ -287,8 +287,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);
|
||||
}
|
||||
|
||||
|
||||
@@ -156,7 +156,8 @@ public class UrlAuthorizationsTests {
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
ApplicationContext context = getApplicationContext();
|
||||
UrlAuthorizationConfigurer<HttpSecurity>.StandardInterceptUrlRegistry registry = http
|
||||
.apply(new UrlAuthorizationConfigurer(context)).getRegistry();
|
||||
.apply(new UrlAuthorizationConfigurer(context))
|
||||
.getRegistry();
|
||||
// @formatter:off
|
||||
registry
|
||||
.antMatchers("/a").hasRole("ADMIN")
|
||||
|
||||
@@ -107,7 +107,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));
|
||||
}
|
||||
|
||||
|
||||
@@ -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("ROLE_USER");
|
||||
assertThat(authentication.getAuthorities()).first()
|
||||
.isInstanceOf(OAuth2UserAuthority.class)
|
||||
.hasToString("ROLE_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("ROLE_USER");
|
||||
assertThat(authentication.getAuthorities()).first()
|
||||
.isInstanceOf(OAuth2UserAuthority.class)
|
||||
.hasToString("ROLE_USER");
|
||||
SecurityContextHolderStrategy strategy = this.context.getBean(SecurityContextHolderStrategy.class);
|
||||
verify(strategy, atLeastOnce()).getContext();
|
||||
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("ROLE_USER");
|
||||
assertThat(authentication.getAuthorities()).first()
|
||||
.isInstanceOf(OAuth2UserAuthority.class)
|
||||
.hasToString("ROLE_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("ROLE_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("ROLE_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("ROLE_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("ROLE_USER");
|
||||
assertThat(authentication.getAuthorities()).first()
|
||||
.isInstanceOf(OAuth2UserAuthority.class)
|
||||
.hasToString("ROLE_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("ROLE_USER");
|
||||
assertThat(authentication.getAuthorities()).first()
|
||||
.isInstanceOf(OidcUserAuthority.class)
|
||||
.hasToString("ROLE_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("ROLE_USER");
|
||||
assertThat(authentication.getAuthorities()).first()
|
||||
.isInstanceOf(OidcUserAuthority.class)
|
||||
.hasToString("ROLE_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("ROLE_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("ROLE_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();
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1057,7 +1076,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());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -227,8 +227,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
|
||||
@@ -241,8 +243,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
|
||||
@@ -640,7 +644,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
|
||||
@@ -655,7 +659,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
|
||||
@@ -672,8 +676,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
|
||||
@@ -690,7 +694,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
|
||||
@@ -709,8 +713,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
|
||||
@@ -739,9 +743,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
|
||||
@@ -766,11 +770,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());
|
||||
}
|
||||
|
||||
@@ -870,7 +875,7 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
this.spring.context(context).autowire();
|
||||
OAuth2ResourceServerConfigurer.JwtConfigurer jwtConfigurer = new OAuth2ResourceServerConfigurer(context).jwt();
|
||||
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class)
|
||||
.isThrownBy(() -> jwtConfigurer.getJwtDecoder());
|
||||
.isThrownBy(() -> jwtConfigurer.getJwtDecoder());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -916,8 +921,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
|
||||
@@ -930,7 +936,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
|
||||
@@ -942,7 +948,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
|
||||
@@ -954,10 +960,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);
|
||||
@@ -972,7 +980,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
|
||||
@@ -1018,14 +1026,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())
|
||||
@@ -1038,11 +1046,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")))
|
||||
@@ -1066,7 +1074,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")))
|
||||
@@ -1101,7 +1109,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())
|
||||
@@ -1114,11 +1122,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")))
|
||||
@@ -1132,7 +1140,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())
|
||||
@@ -1144,14 +1152,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);
|
||||
@@ -1170,7 +1179,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();
|
||||
@@ -1227,8 +1236,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
|
||||
@@ -1244,7 +1253,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
|
||||
@@ -1266,8 +1275,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));
|
||||
}
|
||||
@@ -1311,29 +1321,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
|
||||
@@ -1387,16 +1397,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")))
|
||||
@@ -1451,7 +1462,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) {
|
||||
@@ -2231,7 +2243,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();
|
||||
}
|
||||
|
||||
@@ -2514,8 +2526,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")
|
||||
@@ -2546,7 +2561,7 @@ public class OAuth2ResourceServerConfigurerTests {
|
||||
public void setEnvironment(Environment environment) {
|
||||
if (environment instanceof ConfigurableEnvironment) {
|
||||
((ConfigurableEnvironment) environment).getPropertySources()
|
||||
.addFirst(new MockWebServerPropertySource());
|
||||
.addFirst(new MockWebServerPropertySource());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2587,8 +2602,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
|
||||
|
||||
@@ -111,29 +111,34 @@ public class OpenIDLoginConfigurerTests {
|
||||
given(mockAuthRequest.getDestinationUrl(anyBoolean())).willReturn("mockUrl");
|
||||
given(OpenIdAttributesInLambdaConfig.CONSUMER_MANAGER.associate(any())).willReturn(mockDiscoveryInformation);
|
||||
given(OpenIdAttributesInLambdaConfig.CONSUMER_MANAGER.authenticate(any(DiscoveryInformation.class), any(),
|
||||
any())).willReturn(mockAuthRequest);
|
||||
any()))
|
||||
.willReturn(mockAuthRequest);
|
||||
this.spring.register(OpenIdAttributesInLambdaConfig.class).autowire();
|
||||
try (MockWebServer server = new MockWebServer()) {
|
||||
String endpoint = server.url("/").toString();
|
||||
server.enqueue(new MockResponse().addHeader(YadisResolver.YADIS_XRDS_LOCATION, endpoint));
|
||||
server.enqueue(new MockResponse()
|
||||
.setBody(String.format("<XRDS><XRD><Service><URI>%s</URI></Service></XRD></XRDS>", endpoint)));
|
||||
MvcResult mvcResult = this.mvc.perform(
|
||||
get("/login/openid").param(OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD, endpoint))
|
||||
.andExpect(status().isFound()).andReturn();
|
||||
Object attributeObject = mvcResult.getRequest().getSession()
|
||||
.getAttribute("SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST");
|
||||
.setBody(String.format("<XRDS><XRD><Service><URI>%s</URI></Service></XRD></XRDS>", endpoint)));
|
||||
MvcResult mvcResult = this.mvc
|
||||
.perform(
|
||||
get("/login/openid").param(OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD, endpoint))
|
||||
.andExpect(status().isFound())
|
||||
.andReturn();
|
||||
Object attributeObject = mvcResult.getRequest()
|
||||
.getSession()
|
||||
.getAttribute("SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST");
|
||||
assertThat(attributeObject).isInstanceOf(List.class);
|
||||
List<OpenIDAttribute> attributeList = (List<OpenIDAttribute>) attributeObject;
|
||||
assertThat(
|
||||
attributeList.stream()
|
||||
.anyMatch((attribute) -> "nickname".equals(attribute.getName())
|
||||
&& "https://schema.openid.net/namePerson/friendly".equals(attribute.getType())))
|
||||
.isTrue();
|
||||
.anyMatch((attribute) -> "nickname".equals(attribute.getName())
|
||||
&& "https://schema.openid.net/namePerson/friendly".equals(attribute.getType())))
|
||||
.isTrue();
|
||||
assertThat(attributeList.stream()
|
||||
.anyMatch((attribute) -> "email".equals(attribute.getName())
|
||||
&& "https://schema.openid.net/contact/email".equals(attribute.getType())
|
||||
&& attribute.isRequired() && attribute.getCount() == 2)).isTrue();
|
||||
.anyMatch((attribute) -> "email".equals(attribute.getName())
|
||||
&& "https://schema.openid.net/contact/email".equals(attribute.getType())
|
||||
&& attribute.isRequired() && attribute.getCount() == 2))
|
||||
.isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,13 +150,14 @@ public class OpenIDLoginConfigurerTests {
|
||||
given(mockAuthRequest.getDestinationUrl(anyBoolean())).willReturn("mockUrl");
|
||||
given(OpenIdAttributesNullNameConfig.CONSUMER_MANAGER.associate(any())).willReturn(mockDiscoveryInformation);
|
||||
given(OpenIdAttributesNullNameConfig.CONSUMER_MANAGER.authenticate(any(DiscoveryInformation.class), any(),
|
||||
any())).willReturn(mockAuthRequest);
|
||||
any()))
|
||||
.willReturn(mockAuthRequest);
|
||||
this.spring.register(OpenIdAttributesNullNameConfig.class).autowire();
|
||||
try (MockWebServer server = new MockWebServer()) {
|
||||
String endpoint = server.url("/").toString();
|
||||
server.enqueue(new MockResponse().addHeader(YadisResolver.YADIS_XRDS_LOCATION, endpoint));
|
||||
server.enqueue(new MockResponse()
|
||||
.setBody(String.format("<XRDS><XRD><Service><URI>%s</URI></Service></XRD></XRDS>", endpoint)));
|
||||
.setBody(String.format("<XRDS><XRD><Service><URI>%s</URI></Service></XRD></XRDS>", endpoint)));
|
||||
// @formatter:off
|
||||
MockHttpServletRequestBuilder request = get("/login/openid")
|
||||
.param(OpenIDAuthenticationFilter.DEFAULT_CLAIMED_IDENTITY_FIELD, endpoint);
|
||||
|
||||
@@ -140,7 +140,7 @@ public class Saml2LoginConfigurerTests {
|
||||
a) -> Collections.singletonList(new SimpleGrantedAuthority("TEST"));
|
||||
|
||||
private static final GrantedAuthoritiesMapper AUTHORITIES_MAPPER = (authorities) -> Collections
|
||||
.singletonList(new SimpleGrantedAuthority("TEST CONVERTED"));
|
||||
.singletonList(new SimpleGrantedAuthority("TEST CONVERTED"));
|
||||
|
||||
private static final Duration RESPONSE_TIME_VALIDATION_SKEW = Duration.ZERO;
|
||||
|
||||
@@ -202,8 +202,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")
|
||||
@@ -215,7 +215,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));
|
||||
}
|
||||
|
||||
@@ -244,9 +244,10 @@ public class Saml2LoginConfigurerTests {
|
||||
public void saml2LoginWhenCustomAuthenticationRequestContextResolverThenUses() throws Exception {
|
||||
this.spring.register(CustomAuthenticationRequestContextResolver.class).autowire();
|
||||
Saml2AuthenticationRequestContext context = TestSaml2AuthenticationRequestContexts
|
||||
.authenticationRequestContext().build();
|
||||
.authenticationRequestContext()
|
||||
.build();
|
||||
Saml2AuthenticationRequestContextResolver resolver = this.spring.getContext()
|
||||
.getBean(Saml2AuthenticationRequestContextResolver.class);
|
||||
.getBean(Saml2AuthenticationRequestContextResolver.class);
|
||||
given(resolver.resolve(any(HttpServletRequest.class))).willReturn(context);
|
||||
this.mvc.perform(get("/saml2/authenticate/registration-id")).andExpect(status().isFound());
|
||||
verify(resolver).resolve(any(HttpServletRequest.class));
|
||||
@@ -305,7 +306,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);
|
||||
@@ -318,11 +319,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);
|
||||
@@ -340,9 +341,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");
|
||||
@@ -355,7 +356,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));
|
||||
}
|
||||
@@ -366,7 +367,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));
|
||||
@@ -375,10 +376,11 @@ public class Saml2LoginConfigurerTests {
|
||||
@Test
|
||||
public void saml2LoginWhenLoginProcessingUrlWithoutRegistrationIdAndDefaultAuthenticationConverterThenValidates() {
|
||||
assertThatExceptionOfType(BeanCreationException.class)
|
||||
.isThrownBy(() -> this.spring.register(CustomLoginProcessingUrlDefaultAuthenticationConverter.class)
|
||||
.autowire())
|
||||
.havingRootCause().isInstanceOf(IllegalStateException.class)
|
||||
.withMessage("loginProcessingUrl must contain {registrationId} path variable");
|
||||
.isThrownBy(
|
||||
() -> this.spring.register(CustomLoginProcessingUrlDefaultAuthenticationConverter.class).autowire())
|
||||
.havingRootCause()
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.withMessage("loginProcessingUrl must contain {registrationId} path variable");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -388,7 +390,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
|
||||
@@ -401,11 +403,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
|
||||
@@ -417,10 +419,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"));
|
||||
}
|
||||
|
||||
private void validateSaml2WebSsoAuthenticationFilterConfiguration() {
|
||||
@@ -429,14 +433,20 @@ public class Saml2LoginConfigurerTests {
|
||||
AuthenticationManager manager = (AuthenticationManager) ReflectionTestUtils.getField(filter,
|
||||
"authenticationManager");
|
||||
ProviderManager pm = (ProviderManager) manager;
|
||||
AuthenticationProvider provider = pm.getProviders().stream()
|
||||
.filter((p) -> p instanceof OpenSaml4AuthenticationProvider).findFirst().get();
|
||||
AuthenticationProvider provider = pm.getProviders()
|
||||
.stream()
|
||||
.filter((p) -> p instanceof OpenSaml4AuthenticationProvider)
|
||||
.findFirst()
|
||||
.get();
|
||||
assertThat(provider).isNotNull();
|
||||
}
|
||||
|
||||
private Saml2WebSsoAuthenticationFilter getSaml2SsoFilter(FilterChainProxy chain) {
|
||||
return (Saml2WebSsoAuthenticationFilter) chain.getFilters("/login/saml2/sso/test").stream()
|
||||
.filter((f) -> f instanceof Saml2WebSsoAuthenticationFilter).findFirst().get();
|
||||
return (Saml2WebSsoAuthenticationFilter) chain.getFilters("/login/saml2/sso/test")
|
||||
.stream()
|
||||
.filter((f) -> f instanceof Saml2WebSsoAuthenticationFilter)
|
||||
.findFirst()
|
||||
.get();
|
||||
}
|
||||
|
||||
private void performSaml2Login(String expected) throws IOException, ServletException {
|
||||
@@ -449,11 +459,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();
|
||||
Assertions.assertNotNull(authentication, "Expected a valid authentication object.");
|
||||
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) {
|
||||
@@ -481,7 +493,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();
|
||||
}
|
||||
@@ -549,7 +561,7 @@ public class Saml2LoginConfigurerTests {
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.authorizeRequests((authz) -> authz.anyRequest().authenticated())
|
||||
.saml2Login((saml2) -> saml2.failureHandler(authenticationFailureHandler));
|
||||
.saml2Login((saml2) -> saml2.failureHandler(authenticationFailureHandler));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -715,7 +727,7 @@ public class Saml2LoginConfigurerTests {
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.authorizeRequests((authz) -> authz.anyRequest().authenticated())
|
||||
.saml2Login((saml2) -> saml2.authenticationConverter(authenticationConverter));
|
||||
.saml2Login((saml2) -> saml2.authenticationConverter(authenticationConverter));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -730,7 +742,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();
|
||||
}
|
||||
|
||||
@@ -831,10 +843,10 @@ public class Saml2LoginConfigurerTests {
|
||||
@Bean
|
||||
RelyingPartyRegistrationRepository relyingPartyRegistrationRepository() {
|
||||
RelyingPartyRegistration registration = TestRelyingPartyRegistrations.noCredentials()
|
||||
.signingX509Credentials((c) -> c.add(TestSaml2X509Credentials.relyingPartySigningCredential()))
|
||||
.assertingPartyDetails((party) -> party.verificationX509Credentials(
|
||||
(c) -> c.add(TestSaml2X509Credentials.relyingPartyVerifyingCredential())))
|
||||
.build();
|
||||
.signingX509Credentials((c) -> c.add(TestSaml2X509Credentials.relyingPartySigningCredential()))
|
||||
.assertingPartyDetails((party) -> party.verificationX509Credentials(
|
||||
(c) -> c.add(TestSaml2X509Credentials.relyingPartyVerifyingCredential())))
|
||||
.build();
|
||||
return spy(new InMemoryRelyingPartyRegistrationRepository(registration));
|
||||
}
|
||||
|
||||
|
||||
@@ -174,7 +174,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");
|
||||
@@ -185,7 +186,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");
|
||||
@@ -195,8 +197,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
|
||||
@@ -209,8 +212,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));
|
||||
}
|
||||
@@ -220,7 +224,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));
|
||||
}
|
||||
|
||||
@@ -233,7 +237,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
|
||||
@@ -249,8 +253,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());
|
||||
@@ -264,10 +271,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());
|
||||
@@ -281,10 +293,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());
|
||||
@@ -308,11 +325,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());
|
||||
@@ -336,11 +356,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());
|
||||
@@ -354,19 +377,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));
|
||||
}
|
||||
|
||||
@@ -377,11 +406,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());
|
||||
}
|
||||
@@ -391,15 +420,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();
|
||||
}
|
||||
@@ -409,16 +446,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));
|
||||
}
|
||||
|
||||
@@ -427,11 +471,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());
|
||||
}
|
||||
@@ -441,8 +488,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());
|
||||
@@ -452,7 +502,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");
|
||||
@@ -465,7 +516,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));
|
||||
|
||||
}
|
||||
|
||||
@@ -475,7 +526,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));
|
||||
|
||||
}
|
||||
|
||||
@@ -485,7 +536,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));
|
||||
|
||||
}
|
||||
|
||||
@@ -672,16 +723,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,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
|
||||
@@ -365,8 +367,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();
|
||||
}
|
||||
|
||||
|
||||
@@ -78,7 +78,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));
|
||||
@@ -107,14 +108,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>
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -111,8 +111,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
|
||||
@@ -137,7 +137,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
|
||||
@@ -147,7 +147,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
|
||||
@@ -157,7 +157,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
|
||||
@@ -167,7 +167,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
|
||||
@@ -225,8 +225,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
|
||||
@@ -234,8 +234,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
|
||||
@@ -243,8 +243,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
|
||||
@@ -253,8 +253,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
|
||||
@@ -262,7 +262,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);
|
||||
}
|
||||
|
||||
@@ -271,9 +271,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
|
||||
@@ -288,7 +288,7 @@ public class AbstractSecurityWebSocketMessageBrokerConfigurerTests {
|
||||
TestHandshakeHandler handshakeHandler = this.context.getBean(TestHandshakeHandler.class);
|
||||
assertThatCsrfToken(handshakeHandler.attributes.get(CsrfToken.class.getName())).isEqualTo(this.token);
|
||||
assertThat(handshakeHandler.attributes.get(this.sessionAttr))
|
||||
.isEqualTo(request.getSession().getAttribute(this.sessionAttr));
|
||||
.isEqualTo(request.getSession().getAttribute(this.sessionAttr));
|
||||
}
|
||||
|
||||
private HttpRequestHandler handler(HttpServletRequest request) throws Exception {
|
||||
@@ -547,7 +547,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();
|
||||
}
|
||||
|
||||
|
||||
@@ -124,8 +124,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
|
||||
@@ -150,7 +150,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
|
||||
@@ -160,7 +160,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
|
||||
@@ -170,7 +170,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
|
||||
@@ -180,7 +180,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
|
||||
@@ -198,7 +198,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(CsrfChannelInterceptor.class);
|
||||
}
|
||||
|
||||
@@ -252,8 +254,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
|
||||
@@ -261,8 +263,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
|
||||
@@ -270,8 +272,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
|
||||
@@ -280,8 +282,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
|
||||
@@ -292,7 +294,7 @@ public class WebSocketMessageBrokerSecurityConfigurationTests {
|
||||
for (ChannelInterceptor interceptor : messageChannel.getInterceptors()) {
|
||||
if (interceptor instanceof AuthorizationChannelInterceptor) {
|
||||
assertThat(ReflectionTestUtils.getField(interceptor, "preSendAuthorizationManager"))
|
||||
.isSameAs(authorizationManager);
|
||||
.isSameAs(authorizationManager);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -304,7 +306,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);
|
||||
}
|
||||
|
||||
@@ -313,7 +317,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);
|
||||
}
|
||||
|
||||
@@ -323,8 +329,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
|
||||
@@ -338,8 +344,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
|
||||
@@ -362,8 +368,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);
|
||||
|
||||
}
|
||||
|
||||
@@ -371,7 +377,7 @@ public class WebSocketMessageBrokerSecurityConfigurationTests {
|
||||
TestHandshakeHandler handshakeHandler = this.context.getBean(TestHandshakeHandler.class);
|
||||
assertThatCsrfToken(handshakeHandler.attributes.get(CsrfToken.class.getName())).isEqualTo(this.token);
|
||||
assertThat(handshakeHandler.attributes.get(this.sessionAttr))
|
||||
.isEqualTo(request.getSession().getAttribute(this.sessionAttr));
|
||||
.isEqualTo(request.getSession().getAttribute(this.sessionAttr));
|
||||
}
|
||||
|
||||
private HttpRequestHandler handler(HttpServletRequest request) throws Exception {
|
||||
@@ -630,7 +636,7 @@ public class WebSocketMessageBrokerSecurityConfigurationTests {
|
||||
// work around SPR-12716
|
||||
SockJsWebSocketHandler sockJs = (SockJsWebSocketHandler) wsHandler;
|
||||
WebSocketServerSockJsSession session = (WebSocketServerSockJsSession) ReflectionTestUtils
|
||||
.getField(sockJs, "sockJsSession");
|
||||
.getField(sockJs, "sockJsSession");
|
||||
this.attributes = session.getAttributes();
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -72,7 +72,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();
|
||||
}
|
||||
|
||||
@@ -161,7 +161,7 @@ public class AuthenticationProviderBeanDefinitionParserTests {
|
||||
|
||||
private AuthenticationProvider getProvider() {
|
||||
List<AuthenticationProvider> providers = ((ProviderManager) this.appContext
|
||||
.getBean(BeanIds.AUTHENTICATION_MANAGER)).getProviders();
|
||||
.getBean(BeanIds.AUTHENTICATION_MANAGER)).getProviders();
|
||||
return providers.get(0);
|
||||
}
|
||||
|
||||
|
||||
@@ -65,7 +65,7 @@ public class JdbcUserServiceBeanDefinitionParserTests {
|
||||
@Test
|
||||
public void beanNameIsCorrect() {
|
||||
assertThat(JdbcUserDetailsManager.class.getName())
|
||||
.isEqualTo(new JdbcUserServiceBeanDefinitionParser().getBeanClassName(mock(Element.class)));
|
||||
.isEqualTo(new JdbcUserServiceBeanDefinitionParser().getBeanClassName(mock(Element.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -112,7 +112,7 @@ public class JdbcUserServiceBeanDefinitionParserTests {
|
||||
setContext("<jdbc-user-service id='myUserService' cache-ref='userCache' data-source-ref='dataSource'/>"
|
||||
+ DATA_SOURCE + USER_CACHE_XML);
|
||||
CachingUserDetailsService cachingUserService = (CachingUserDetailsService) this.appContext
|
||||
.getBean("myUserService" + AbstractUserDetailsServiceBeanDefinitionParser.CACHING_SUFFIX);
|
||||
.getBean("myUserService" + AbstractUserDetailsServiceBeanDefinitionParser.CACHING_SUFFIX);
|
||||
assertThat(this.appContext.getBean("userCache")).isSameAs(cachingUserService.getUserCache());
|
||||
assertThat(cachingUserService.loadUserByUsername("rod")).isNotNull();
|
||||
assertThat(cachingUserService.loadUserByUsername("rod")).isNotNull();
|
||||
@@ -148,7 +148,7 @@ public class JdbcUserServiceBeanDefinitionParserTests {
|
||||
assertThat(this.appContext.getBean("userCache")).isSameAs(provider.getUserCache());
|
||||
provider.authenticate(UsernamePasswordAuthenticationToken.unauthenticated("rod", "koala"));
|
||||
assertThat(provider.getUserCache().getUserFromCache("rod")).isNotNull()
|
||||
.withFailMessage("Cache should contain user after authentication");
|
||||
.withFailMessage("Cache should contain user after authentication");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -44,7 +44,8 @@ public class PasswordEncoderParserTests {
|
||||
public void passwordEncoderDefaultsToDelegatingPasswordEncoder() throws Exception {
|
||||
this.spring.configLocations(
|
||||
"classpath:org/springframework/security/config/authentication/PasswordEncoderParserTests-default.xml")
|
||||
.mockMvcAfterSpringSecurityOk().autowire();
|
||||
.mockMvcAfterSpringSecurityOk()
|
||||
.autowire();
|
||||
// @formatter:off
|
||||
this.mockMvc.perform(get("/").with(httpBasic("user", "password")))
|
||||
.andExpect(status().isOk());
|
||||
@@ -53,9 +54,11 @@ public class PasswordEncoderParserTests {
|
||||
|
||||
@Test
|
||||
public void passwordEncoderDefaultsToPasswordEncoderBean() throws Exception {
|
||||
this.spring.configLocations(
|
||||
"classpath:org/springframework/security/config/authentication/PasswordEncoderParserTests-bean.xml")
|
||||
.mockMvcAfterSpringSecurityOk().autowire();
|
||||
this.spring
|
||||
.configLocations(
|
||||
"classpath:org/springframework/security/config/authentication/PasswordEncoderParserTests-bean.xml")
|
||||
.mockMvcAfterSpringSecurityOk()
|
||||
.autowire();
|
||||
// @formatter:off
|
||||
this.mockMvc.perform(get("/").with(httpBasic("user", "password")))
|
||||
.andExpect(status().isOk());
|
||||
|
||||
@@ -102,9 +102,9 @@ public class UserServiceBeanDefinitionParserTests {
|
||||
// @formatter:on
|
||||
UserDetailsService userService = (UserDetailsService) this.appContext.getBean("service");
|
||||
assertThat(userService.loadUserByUsername("https://joe.myopenid.com/").getUsername())
|
||||
.isEqualTo("https://joe.myopenid.com/");
|
||||
.isEqualTo("https://joe.myopenid.com/");
|
||||
assertThat(userService.loadUserByUsername("https://www.google.com/accounts/o8/id?id=MPtOaenBIk5yzW9n7n9")
|
||||
.getUsername()).isEqualTo("https://www.google.com/accounts/o8/id?id=MPtOaenBIk5yzW9n7n9");
|
||||
.getUsername()).isEqualTo("https://www.google.com/accounts/o8/id?id=MPtOaenBIk5yzW9n7n9");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -143,8 +143,8 @@ public class UserServiceBeanDefinitionParserTests {
|
||||
|
||||
@Test
|
||||
public void userServiceWithMissingPropertiesFileThrowsException() {
|
||||
assertThatExceptionOfType(FatalBeanException.class).isThrownBy(
|
||||
() -> setContext("<user-service id='service' properties='classpath:doesntexist.properties'/>"));
|
||||
assertThatExceptionOfType(FatalBeanException.class)
|
||||
.isThrownBy(() -> setContext("<user-service id='service' properties='classpath:doesntexist.properties'/>"));
|
||||
}
|
||||
|
||||
private void setContext(String context) {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user