Remove blank lines from all tests

Remove all blank lines from test code so that test methods are
visually grouped together. This generally helps to make the test
classes easer to scan, however, the "given" / "when" / "then"
blocks used by some tests are now not as easy to discern.

Issue gh-8945
This commit is contained in:
Phillip Webb
2020-08-01 19:33:21 -07:00
committed by Rob Winch
parent 5bdd757108
commit a5aa6b3d7f
787 changed files with 9 additions and 10241 deletions

View File

@@ -34,13 +34,11 @@ public class DataSourcePopulator implements InitializingBean {
@Override
public void afterPropertiesSet() {
Assert.notNull(this.template, "dataSource required");
this.template.execute(
"CREATE TABLE USERS(USERNAME VARCHAR_IGNORECASE(50) NOT NULL PRIMARY KEY,PASSWORD VARCHAR_IGNORECASE(500) NOT NULL,ENABLED BOOLEAN NOT NULL);");
this.template.execute(
"CREATE TABLE AUTHORITIES(USERNAME VARCHAR_IGNORECASE(50) NOT NULL,AUTHORITY VARCHAR_IGNORECASE(50) NOT NULL,CONSTRAINT FK_AUTHORITIES_USERS FOREIGN KEY(USERNAME) REFERENCES USERS(USERNAME));");
this.template.execute("CREATE UNIQUE INDEX IX_AUTH_USERNAME ON AUTHORITIES(USERNAME,AUTHORITY);");
/*
* Passwords encoded using MD5, NOT in Base64 format, with null as salt Encoded
* password for rod is "koala" Encoded password for dianne is "emu" Encoded

View File

@@ -111,7 +111,6 @@ public class FilterChainProxyConfigTests {
@Test
public void mixingPatternsAndPlaceholdersDoesntCauseOrderingIssues() {
FilterChainProxy fcp = this.appCtx.getBean("sec1235FilterChainProxy", FilterChainProxy.class);
List<SecurityFilterChain> chains = fcp.getFilterChains();
assertThat(getPattern(chains.get(0))).isEqualTo("/login*");
assertThat(getPattern(chains.get(1))).isEqualTo("/logout");
@@ -127,17 +126,14 @@ public class FilterChainProxyConfigTests {
List<Filter> filters = filterChainProxy.getFilters("/foo/blah;x=1");
assertThat(filters).hasSize(1);
assertThat(filters.get(0) instanceof SecurityContextHolderAwareRequestFilter).isTrue();
filters = filterChainProxy.getFilters("/some;x=2,y=3/other/path;z=4/blah");
assertThat(filters).isNotNull();
assertThat(filters).hasSize(3);
assertThat(filters.get(0) instanceof SecurityContextPersistenceFilter).isTrue();
assertThat(filters.get(1) instanceof SecurityContextHolderAwareRequestFilter).isTrue();
assertThat(filters.get(2) instanceof SecurityContextHolderAwareRequestFilter).isTrue();
filters = filterChainProxy.getFilters("/do/not/filter;x=7");
assertThat(filters).isEmpty();
filters = filterChainProxy.getFilters("/another/nonspecificmatch");
assertThat(filters).hasSize(3);
assertThat(filters.get(0) instanceof SecurityContextPersistenceFilter).isTrue();
@@ -148,13 +144,10 @@ public class FilterChainProxyConfigTests {
private void doNormalOperation(FilterChainProxy filterChainProxy) throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "");
request.setServletPath("/foo/secure/super/somefile.html");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
filterChainProxy.doFilter(request, response, chain);
verify(chain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
request.setServletPath("/a/path/which/doesnt/match/any/filter.html");
chain = mock(FilterChain.class);
filterChainProxy.doFilter(request, response, chain);

View File

@@ -37,7 +37,6 @@ public class MockUserServiceBeanPostProcessor implements BeanPostProcessor {
if (bean instanceof PostProcessedMockUserDetailsService) {
((PostProcessedMockUserDetailsService) bean).setPostProcessorWasHere("Hello from the post processor!");
}
return bean;
}

View File

@@ -90,13 +90,10 @@ public class SecurityNamespaceHandlerTests {
PowerMockito.spy(ClassUtils.class);
PowerMockito.doThrow(new NoClassDefFoundError(className)).when(ClassUtils.class, "forName",
eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class));
Log logger = mock(Log.class);
SecurityNamespaceHandler handler = new SecurityNamespaceHandler();
ReflectionTestUtils.setField(handler, "logger", logger);
handler.init();
PowerMockito.verifyStatic(ClassUtils.class);
ClassUtils.forName(eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class));
verifyZeroInteractions(logger);

View File

@@ -43,10 +43,8 @@ public class SecurityConfigurerAdapterClosureTests {
return l;
}
});
this.conf.init(builder);
this.conf.configure(builder);
assertThat(this.conf.list).contains("a");
}

View File

@@ -36,7 +36,6 @@ public class SecurityConfigurerAdapterTests {
public void postProcessObjectPostProcessorsAreSorted() {
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);
}

View File

@@ -76,11 +76,9 @@ public class AuthenticationManagerBuilderTests {
public void buildWhenAddAuthenticationProviderThenDoesNotPerformRegistration() throws Exception {
ObjectPostProcessor<Object> opp = mock(ObjectPostProcessor.class);
AuthenticationProvider provider = mock(AuthenticationProvider.class);
AuthenticationManagerBuilder builder = new AuthenticationManagerBuilder(opp);
builder.authenticationProvider(provider);
builder.build();
verify(opp, never()).postProcess(provider);
}
@@ -92,13 +90,11 @@ public class AuthenticationManagerBuilderTests {
given(opp.postProcess(any())).willAnswer((a) -> a.getArgument(0));
AuthenticationManager am = new AuthenticationManagerBuilder(opp).authenticationEventPublisher(aep)
.inMemoryAuthentication().and().build();
try {
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
}
catch (AuthenticationException success) {
}
verify(aep).publishAuthenticationFailure(any(), any());
}
@@ -107,9 +103,7 @@ public class AuthenticationManagerBuilderTests {
this.spring.register(PasswordEncoderGlobalConfig.class).autowire();
AuthenticationManager manager = this.spring.getContext().getBean(AuthenticationConfiguration.class)
.getAuthenticationManager();
Authentication auth = manager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
assertThat(auth.getName()).isEqualTo("user");
assertThat(auth.getAuthorities()).extracting(GrantedAuthority::getAuthority).containsOnly("ROLE_USER");
}
@@ -119,9 +113,7 @@ public class AuthenticationManagerBuilderTests {
this.spring.register(PasswordEncoderGlobalConfig.class).autowire();
AuthenticationManager manager = this.spring.getContext().getBean(AuthenticationConfiguration.class)
.getAuthenticationManager();
Authentication auth = manager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
assertThat(auth.getName()).isEqualTo("user");
assertThat(auth.getAuthorities()).extracting(GrantedAuthority::getAuthority).containsOnly("ROLE_USER");
}
@@ -129,9 +121,7 @@ public class AuthenticationManagerBuilderTests {
@Test
public void authenticationManagerWhenMultipleProvidersThenWorks() throws Exception {
this.spring.register(MultiAuthenticationProvidersConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(authenticated().withUsername("user").withRoles("USER"));
this.mockMvc.perform(formLogin().user("admin"))
.andExpect(authenticated().withUsername("admin").withRoles("USER", "ADMIN"));
}
@@ -140,11 +130,9 @@ public class AuthenticationManagerBuilderTests {
public void buildWhenAuthenticationProviderThenIsConfigured() throws Exception {
ObjectPostProcessor<Object> opp = mock(ObjectPostProcessor.class);
AuthenticationProvider provider = mock(AuthenticationProvider.class);
AuthenticationManagerBuilder builder = new AuthenticationManagerBuilder(opp);
builder.authenticationProvider(provider);
builder.build();
assertThat(builder.isConfigured()).isTrue();
}
@@ -152,27 +140,22 @@ public class AuthenticationManagerBuilderTests {
public void buildWhenParentThenIsConfigured() throws Exception {
ObjectPostProcessor<Object> opp = mock(ObjectPostProcessor.class);
AuthenticationManager parent = mock(AuthenticationManager.class);
AuthenticationManagerBuilder builder = new AuthenticationManagerBuilder(opp);
builder.parentAuthenticationManager(parent);
builder.build();
assertThat(builder.isConfigured()).isTrue();
}
@Test
public void buildWhenNotConfiguredThenIsConfiguredFalse() throws Exception {
ObjectPostProcessor<Object> opp = mock(ObjectPostProcessor.class);
AuthenticationManagerBuilder builder = new AuthenticationManagerBuilder(opp);
builder.build();
assertThat(builder.isConfigured()).isFalse();
}
public void buildWhenUserFromProperties() throws Exception {
this.spring.register(UserFromPropertiesConfig.class).autowire();
this.mockMvc.perform(formLogin().user("joe", "joespassword"))
.andExpect(authenticated().withUsername("joe").withRoles("USER"));
}

View File

@@ -47,10 +47,8 @@ public class NamespaceAuthenticationManagerTests {
@Test
public void authenticationMangerWhenDefaultThenEraseCredentialsIsTrue() throws Exception {
this.spring.register(EraseCredentialsTrueDefaultConfig.class).autowire();
this.mockMvc.perform(formLogin())
.andExpect(authenticated().withAuthentication((a) -> assertThat(a.getCredentials()).isNull()));
this.mockMvc.perform(formLogin())
.andExpect(authenticated().withAuthentication((a) -> assertThat(a.getCredentials()).isNull()));
// no exception due to username being cleared out
@@ -59,10 +57,8 @@ public class NamespaceAuthenticationManagerTests {
@Test
public void authenticationMangerWhenEraseCredentialsIsFalseThenCredentialsNotNull() throws Exception {
this.spring.register(EraseCredentialsFalseConfig.class).autowire();
this.mockMvc.perform(formLogin())
.andExpect(authenticated().withAuthentication((a) -> assertThat(a.getCredentials()).isNotNull()));
this.mockMvc.perform(formLogin())
.andExpect(authenticated().withAuthentication((a) -> assertThat(a.getCredentials()).isNotNull()));
// no exception due to username being cleared out
@@ -72,7 +68,6 @@ public class NamespaceAuthenticationManagerTests {
// SEC-2533
public void authenticationManagerWhenGlobalAndEraseCredentialsIsFalseThenCredentialsNotNull() throws Exception {
this.spring.register(GlobalEraseCredentialsFalseConfig.class).autowire();
this.mockMvc.perform(SecurityMockMvcRequestBuilders.formLogin()).andExpect(SecurityMockMvcResultMatchers
.authenticated().withAuthentication((a) -> assertThat(a.getCredentials()).isNotNull()));
}

View File

@@ -49,7 +49,6 @@ public class NamespaceAuthenticationProviderTests {
// authentication-provider@ref
public void authenticationProviderRef() throws Exception {
this.spring.register(AuthenticationProviderRefConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(authenticated().withUsername("user"));
}
@@ -57,7 +56,6 @@ public class NamespaceAuthenticationProviderTests {
// authentication-provider@user-service-ref
public void authenticationProviderUserServiceRef() throws Exception {
this.spring.register(AuthenticationProviderRefConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(authenticated().withUsername("user"));
}

View File

@@ -53,14 +53,12 @@ public class NamespaceJdbcUserServiceTests {
@Test
public void jdbcUserService() throws Exception {
this.spring.register(DataSourceConfig.class, JdbcUserServiceConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(authenticated().withUsername("user"));
}
@Test
public void jdbcUserServiceCustom() throws Exception {
this.spring.register(CustomDataSourceConfig.class, CustomJdbcUserServiceSampleConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(authenticated().withUsername("user").withRoles("DBA", "USER"));
}
@@ -118,7 +116,6 @@ public class NamespaceJdbcUserServiceTests {
// jdbc-user-service@role-prefix
.rolePrefix("ROLE_");
// @formatter:on
}
static class CustomUserCache implements UserCache {

View File

@@ -52,21 +52,18 @@ public class NamespacePasswordEncoderTests {
@Test
public void passwordEncoderRefWithInMemory() throws Exception {
this.spring.register(PasswordEncoderWithInMemoryConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(authenticated());
}
@Test
public void passwordEncoderRefWithJdbc() throws Exception {
this.spring.register(PasswordEncoderWithJdbcConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(authenticated());
}
@Test
public void passwordEncoderRefWithUserDetailsService() throws Exception {
this.spring.register(PasswordEncoderWithUserDetailsServiceConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(authenticated());
}
@@ -91,7 +88,6 @@ public class NamespacePasswordEncoderTests {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
// @formatter:off
auth

View File

@@ -51,7 +51,6 @@ public class PasswordEncoderConfigurerTests {
@Test
public void passwordEncoderRefWhenAuthenticationManagerBuilderThenAuthenticationSuccess() throws Exception {
this.spring.register(PasswordEncoderNoAuthManagerLoadsConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(authenticated());
}

View File

@@ -48,7 +48,6 @@ public class AuthenticationConfigurationPublishTests {
@Test
public void authenticationEventPublisherBeanUsedByDefault() {
this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
assertThat(this.listener.getEvents()).hasSize(1);
}

View File

@@ -88,7 +88,6 @@ public class AuthenticationConfigurationTests {
public void orderingAutowiredOnEnableGlobalMethodSecurity() {
this.spring.register(AuthenticationTestConfiguration.class, GlobalMethodSecurityAutowiredConfig.class,
ServicesConfig.class).autowire();
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
this.service.run();
@@ -98,7 +97,6 @@ public class AuthenticationConfigurationTests {
public void orderingAutowiredOnEnableWebSecurity() {
this.spring.register(AuthenticationTestConfiguration.class, WebSecurityConfig.class,
GlobalMethodSecurityAutowiredConfig.class, ServicesConfig.class).autowire();
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
this.service.run();
@@ -108,7 +106,6 @@ public class AuthenticationConfigurationTests {
public void orderingAutowiredOnEnableWebMvcSecurity() {
this.spring.register(AuthenticationTestConfiguration.class, WebMvcSecurityConfig.class,
GlobalMethodSecurityAutowiredConfig.class, ServicesConfig.class).autowire();
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"));
this.service.run();
@@ -117,7 +114,6 @@ public class AuthenticationConfigurationTests {
@Test
public void getAuthenticationManagerWhenNoAuthenticationThenNull() throws Exception {
this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class).autowire();
assertThat(this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager())
.isNull();
}
@@ -126,7 +122,6 @@ public class AuthenticationConfigurationTests {
public void getAuthenticationManagerWhenNoOpGlobalAuthenticationConfigurerAdapterThenNull() throws Exception {
this.spring.register(AuthenticationConfiguration.class, ObjectPostProcessorConfiguration.class,
NoOpGlobalAuthenticationConfigurerAdapter.class).autowire();
assertThat(this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager())
.isNull();
}
@@ -136,10 +131,8 @@ public class AuthenticationConfigurationTests {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password");
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());
}
@@ -148,11 +141,9 @@ public class AuthenticationConfigurationTests {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("user", "password");
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());
}
@@ -173,13 +164,10 @@ public class AuthenticationConfigurationTests {
config.setGlobalAuthenticationConfigurers(Arrays.asList(new ConfiguresInMemoryConfigurerAdapter(),
new BootGlobalAuthenticationConfigurerAdapter()));
AuthenticationManager authenticationManager = config.getAuthenticationManager();
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
assertThatThrownBy(
() -> authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("boot", "password")))
.isInstanceOf(AuthenticationException.class);
}
@Test
@@ -188,7 +176,6 @@ public class AuthenticationConfigurationTests {
AuthenticationConfiguration config = this.spring.getContext().getBean(AuthenticationConfiguration.class);
config.setGlobalAuthenticationConfigurers(Arrays.asList(new BootGlobalAuthenticationConfigurerAdapter()));
AuthenticationManager authenticationManager = config.getAuthenticationManager();
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("boot", "password"));
}
@@ -198,17 +185,14 @@ public class AuthenticationConfigurationTests {
this.spring.register(Sec2531Config.class).autowire();
ObjectPostProcessor<Object> opp = this.spring.getContext().getBean(ObjectPostProcessor.class);
given(opp.postProcess(any())).willAnswer((a) -> a.getArgument(0));
AuthenticationConfiguration config = this.spring.getContext().getBean(AuthenticationConfiguration.class);
config.getAuthenticationManager();
verify(opp).postProcess(any(ProxyFactoryBean.class));
}
@Test
public void getAuthenticationManagerWhenSec2822ThenCannotForceAuthenticationAlreadyBuilt() throws Exception {
this.spring.register(Sec2822WebSecurity.class, Sec2822UseAuth.class, Sec2822Config.class).autowire();
this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager();
// no exception
}
@@ -222,9 +206,7 @@ public class AuthenticationConfigurationTests {
AuthenticationManager am = this.spring.getContext().getBean(AuthenticationConfiguration.class)
.getAuthenticationManager();
given(uds.loadUserByUsername("user")).willReturn(PasswordEncodedUser.user(), PasswordEncodedUser.user());
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
assertThatThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "invalid")))
.isInstanceOf(AuthenticationException.class);
}
@@ -239,9 +221,7 @@ public class AuthenticationConfigurationTests {
.getAuthenticationManager();
given(uds.loadUserByUsername("user")).willReturn(User.withUserDetails(user).build(),
User.withUserDetails(user).build());
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
assertThatThrownBy(() -> am.authenticate(new UsernamePasswordAuthenticationToken("user", "invalid")))
.isInstanceOf(AuthenticationException.class);
}
@@ -257,9 +237,7 @@ public class AuthenticationConfigurationTests {
given(manager.loadUserByUsername("user")).willReturn(User.withUserDetails(user).build(),
User.withUserDetails(user).build());
given(manager.updatePassword(any(), any())).willReturn(user);
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
verify(manager).updatePassword(eq(user), startsWith("{bcrypt}"));
}
@@ -272,7 +250,6 @@ public class AuthenticationConfigurationTests {
.getAuthenticationManager();
given(ap.supports(any())).willReturn(true);
given(ap.authenticate(any())).willReturn(TestAuthentication.authenticatedUser());
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
}
@@ -285,7 +262,6 @@ public class AuthenticationConfigurationTests {
.getAuthenticationManager();
given(ap.supports(any())).willReturn(true);
given(ap.authenticate(any())).willReturn(TestAuthentication.authenticatedUser());
am.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
}
@@ -314,9 +290,7 @@ public class AuthenticationConfigurationTests {
throws Exception {
this.spring.register(AuthenticationConfigurationSubclass.class).autowire();
AuthenticationManagerBuilder ap = this.spring.getContext().getBean(AuthenticationManagerBuilder.class);
this.spring.getContext().getBean(AuthenticationConfiguration.class).getAuthenticationManager();
assertThatThrownBy(ap::build).isInstanceOf(AlreadyBuiltException.class);
}
@@ -447,15 +421,11 @@ public class AuthenticationConfigurationTests {
if (auth.isConfigured()) {
return;
}
UserDetails user = User.withUserDetails(PasswordEncodedUser.user()).username("boot").build();
List<UserDetails> users = Arrays.asList(user);
InMemoryUserDetailsManager inMemory = new InMemoryUserDetailsManager(users);
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setUserDetailsService(inMemory);
auth.authenticationProvider(provider);
}

View File

@@ -40,29 +40,23 @@ public class EnableGlobalAuthenticationTests {
@Test
public void authenticationConfigurationWhenGetAuthenticationManagerThenNotNull() throws Exception {
this.spring.register(Config.class).autowire();
AuthenticationConfiguration auth = this.spring.getContext().getBean(AuthenticationConfiguration.class);
assertThat(auth.getAuthenticationManager()).isNotNull();
}
@Test
public void enableGlobalAuthenticationWhenNoConfigurationAnnotationThenBeanProxyingEnabled() {
this.spring.register(BeanProxyEnabledByDefaultConfig.class).autowire();
Child childBean = this.spring.getContext().getBean(Child.class);
Parent parentBean = this.spring.getContext().getBean(Parent.class);
assertThat(parentBean.getChild()).isSameAs(childBean);
}
@Test
public void enableGlobalAuthenticationWhenProxyBeanMethodsFalseThenBeanProxyingDisabled() {
this.spring.register(BeanProxyDisabledConfig.class).autowire();
Child childBean = this.spring.getContext().getBean(Child.class);
Parent parentBean = this.spring.getContext().getBean(Parent.class);
assertThat(parentBean.getChild()).isNotSameAs(childBean);
}

View File

@@ -40,7 +40,6 @@ public class LdapAuthenticationProviderConfigurerTests {
assertThat(this.configurer.getAuthoritiesMapper()).isInstanceOf(SimpleAuthorityMapper.class);
this.configurer.authoritiesMapper(new NullAuthoritiesMapper());
assertThat(this.configurer.getAuthoritiesMapper()).isInstanceOf(NullAuthoritiesMapper.class);
}
}

View File

@@ -46,7 +46,6 @@ public class UserDetailsManagerConfigurerTests {
UserDetails userDetails = new UserDetailsManagerConfigurer<AuthenticationManagerBuilder, InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder>>(
this.userDetailsManager).withUser("user").password("password").roles("USER").disabled(true)
.accountExpired(true).accountLocked(true).credentialsExpired(true).build();
assertThat(userDetails.getUsername()).isEqualTo("user");
assertThat(userDetails.getPassword()).isEqualTo("password");
assertThat(userDetails.getAuthorities().stream().findFirst().get().getAuthority()).isEqualTo("ROLE_USER");
@@ -59,31 +58,25 @@ public class UserDetailsManagerConfigurerTests {
@Test
public void authoritiesWithGrantedAuthorityWorks() {
SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER");
UserDetails userDetails = new UserDetailsManagerConfigurer<AuthenticationManagerBuilder, InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder>>(
this.userDetailsManager).withUser("user").password("password").authorities(authority).build();
assertThat(userDetails.getAuthorities().stream().findFirst().get()).isEqualTo(authority);
}
@Test
public void authoritiesWithStringAuthorityWorks() {
String authority = "ROLE_USER";
UserDetails userDetails = new UserDetailsManagerConfigurer<AuthenticationManagerBuilder, InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder>>(
this.userDetailsManager).withUser("user").password("password").authorities(authority).build();
assertThat(userDetails.getAuthorities().stream().findFirst().get().getAuthority()).isEqualTo(authority);
}
@Test
public void authoritiesWithAListOfGrantedAuthorityWorks() {
SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER");
UserDetails userDetails = new UserDetailsManagerConfigurer<AuthenticationManagerBuilder, InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder>>(
this.userDetailsManager).withUser("user").password("password").authorities(Arrays.asList(authority))
.build();
assertThat(userDetails.getAuthorities().stream().findFirst().get()).isEqualTo(authority);
}

View File

@@ -54,7 +54,6 @@ public class AutowireBeanFactoryObjectPostProcessorTests {
@Test
public void postProcessWhenApplicationContextAwareThenAwareInvoked() {
this.spring.register(Config.class).autowire();
ApplicationContextAware toPostProcess = mock(ApplicationContextAware.class);
this.objectObjectPostProcessor.postProcess(toPostProcess);
verify(toPostProcess).setApplicationContext(isNotNull());
@@ -63,17 +62,14 @@ public class AutowireBeanFactoryObjectPostProcessorTests {
@Test
public void postProcessWhenApplicationEventPublisherAwareThenAwareInvoked() {
this.spring.register(Config.class).autowire();
ApplicationEventPublisherAware toPostProcess = mock(ApplicationEventPublisherAware.class);
this.objectObjectPostProcessor.postProcess(toPostProcess);
verify(toPostProcess).setApplicationEventPublisher(isNotNull());
}
@Test
public void postProcessWhenBeanClassLoaderAwareThenAwareInvoked() {
this.spring.register(Config.class).autowire();
BeanClassLoaderAware toPostProcess = mock(BeanClassLoaderAware.class);
this.objectObjectPostProcessor.postProcess(toPostProcess);
verify(toPostProcess).setBeanClassLoader(isNotNull());
@@ -82,7 +78,6 @@ public class AutowireBeanFactoryObjectPostProcessorTests {
@Test
public void postProcessWhenBeanFactoryAwareThenAwareInvoked() {
this.spring.register(Config.class).autowire();
BeanFactoryAware toPostProcess = mock(BeanFactoryAware.class);
this.objectObjectPostProcessor.postProcess(toPostProcess);
verify(toPostProcess).setBeanFactory(isNotNull());
@@ -91,7 +86,6 @@ public class AutowireBeanFactoryObjectPostProcessorTests {
@Test
public void postProcessWhenEnvironmentAwareThenAwareInvoked() {
this.spring.register(Config.class).autowire();
EnvironmentAware toPostProcess = mock(EnvironmentAware.class);
this.objectObjectPostProcessor.postProcess(toPostProcess);
verify(toPostProcess).setEnvironment(isNotNull());
@@ -100,7 +94,6 @@ public class AutowireBeanFactoryObjectPostProcessorTests {
@Test
public void postProcessWhenMessageSourceAwareThenAwareInvoked() {
this.spring.register(Config.class).autowire();
MessageSourceAware toPostProcess = mock(MessageSourceAware.class);
this.objectObjectPostProcessor.postProcess(toPostProcess);
verify(toPostProcess).setMessageSource(isNotNull());
@@ -109,7 +102,6 @@ public class AutowireBeanFactoryObjectPostProcessorTests {
@Test
public void postProcessWhenServletContextAwareThenAwareInvoked() {
this.spring.register(Config.class).autowire();
ServletContextAware toPostProcess = mock(ServletContextAware.class);
this.objectObjectPostProcessor.postProcess(toPostProcess);
verify(toPostProcess).setServletContext(isNotNull());
@@ -118,21 +110,16 @@ public class AutowireBeanFactoryObjectPostProcessorTests {
@Test
public void postProcessWhenDisposableBeanThenAwareInvoked() throws Exception {
this.spring.register(Config.class).autowire();
DisposableBean toPostProcess = mock(DisposableBean.class);
this.objectObjectPostProcessor.postProcess(toPostProcess);
this.spring.getContext().close();
verify(toPostProcess).destroy();
}
@Test
public void postProcessWhenSmartInitializingSingletonThenAwareInvoked() {
this.spring.register(Config.class, SmartConfig.class).autowire();
SmartConfig config = this.spring.getContext().getBean(SmartConfig.class);
verify(config.toTest).afterSingletonsInstantiated();
}
@@ -140,9 +127,7 @@ public class AutowireBeanFactoryObjectPostProcessorTests {
// SEC-2382
public void autowireBeanFactoryWhenBeanNameAutoProxyCreatorThenWorks() {
this.spring.testConfigLocations("AutowireBeanFactoryObjectPostProcessorTests-aopconfig.xml").autowire();
MyAdvisedBean bean = this.spring.getContext().getBean(MyAdvisedBean.class);
assertThat(bean.doStuff()).isEqualTo("null");
}

View File

@@ -52,12 +52,10 @@ public class ApplicationConfig {
vendorAdapter.setDatabase(Database.HSQL);
vendorAdapter.setGenerateDdl(true);
vendorAdapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan(User.class.getPackage().getName());
factory.setDataSource(dataSource());
return factory;
}

View File

@@ -81,23 +81,19 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoWhenPermitAllThenAopDoesNotSubscribe() {
given(this.delegate.monoFindById(1L)).willReturn(Mono.from(this.result));
this.delegate.monoFindById(1L);
this.result.assertNoSubscribers();
}
@Test
public void monoWhenPermitAllThenSuccess() {
given(this.delegate.monoFindById(1L)).willReturn(Mono.just("success"));
StepVerifier.create(this.delegate.monoFindById(1L)).expectNext("success").verifyComplete();
}
@Test
public void monoPreAuthorizeHasRoleWhenGrantedThenSuccess() {
given(this.delegate.monoPreAuthorizeHasRoleFindById(1L)).willReturn(Mono.just("result"));
Mono<String> findById = this.messageService.monoPreAuthorizeHasRoleFindById(1L)
.subscriberContext(this.withAdmin);
StepVerifier.create(findById).expectNext("result").verifyComplete();
@@ -106,28 +102,23 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPreAuthorizeHasRoleWhenNoAuthenticationThenDenied() {
given(this.delegate.monoPreAuthorizeHasRoleFindById(1L)).willReturn(Mono.from(this.result));
Mono<String> findById = this.messageService.monoPreAuthorizeHasRoleFindById(1L);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
this.result.assertNoSubscribers();
}
@Test
public void monoPreAuthorizeHasRoleWhenNotAuthorizedThenDenied() {
given(this.delegate.monoPreAuthorizeHasRoleFindById(1L)).willReturn(Mono.from(this.result));
Mono<String> findById = this.messageService.monoPreAuthorizeHasRoleFindById(1L)
.subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
this.result.assertNoSubscribers();
}
@Test
public void monoPreAuthorizeBeanWhenGrantedThenSuccess() {
given(this.delegate.monoPreAuthorizeBeanFindById(2L)).willReturn(Mono.just("result"));
Mono<String> findById = this.messageService.monoPreAuthorizeBeanFindById(2L).subscriberContext(this.withAdmin);
StepVerifier.create(findById).expectNext("result").verifyComplete();
}
@@ -135,7 +126,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPreAuthorizeBeanWhenNotAuthenticatedAndGrantedThenSuccess() {
given(this.delegate.monoPreAuthorizeBeanFindById(2L)).willReturn(Mono.just("result"));
Mono<String> findById = this.messageService.monoPreAuthorizeBeanFindById(2L);
StepVerifier.create(findById).expectNext("result").verifyComplete();
}
@@ -143,27 +133,22 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPreAuthorizeBeanWhenNoAuthenticationThenDenied() {
given(this.delegate.monoPreAuthorizeBeanFindById(1L)).willReturn(Mono.from(this.result));
Mono<String> findById = this.messageService.monoPreAuthorizeBeanFindById(1L);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
this.result.assertNoSubscribers();
}
@Test
public void monoPreAuthorizeBeanWhenNotAuthorizedThenDenied() {
given(this.delegate.monoPreAuthorizeBeanFindById(1L)).willReturn(Mono.from(this.result));
Mono<String> findById = this.messageService.monoPreAuthorizeBeanFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
this.result.assertNoSubscribers();
}
@Test
public void monoPostAuthorizeWhenAuthorizedThenSuccess() {
given(this.delegate.monoPostAuthorizeFindById(1L)).willReturn(Mono.just("user"));
Mono<String> findById = this.messageService.monoPostAuthorizeFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectNext("user").verifyComplete();
}
@@ -171,7 +156,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPostAuthorizeWhenNotAuthorizedThenDenied() {
given(this.delegate.monoPostAuthorizeBeanFindById(1L)).willReturn(Mono.just("not-authorized"));
Mono<String> findById = this.messageService.monoPostAuthorizeBeanFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
}
@@ -179,7 +163,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPostAuthorizeWhenBeanAndAuthorizedThenSuccess() {
given(this.delegate.monoPostAuthorizeBeanFindById(2L)).willReturn(Mono.just("user"));
Mono<String> findById = this.messageService.monoPostAuthorizeBeanFindById(2L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectNext("user").verifyComplete();
}
@@ -187,7 +170,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPostAuthorizeWhenBeanAndNotAuthenticatedAndAuthorizedThenSuccess() {
given(this.delegate.monoPostAuthorizeBeanFindById(2L)).willReturn(Mono.just("anonymous"));
Mono<String> findById = this.messageService.monoPostAuthorizeBeanFindById(2L);
StepVerifier.create(findById).expectNext("anonymous").verifyComplete();
}
@@ -195,33 +177,27 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void monoPostAuthorizeWhenBeanAndNotAuthorizedThenDenied() {
given(this.delegate.monoPostAuthorizeBeanFindById(1L)).willReturn(Mono.just("not-authorized"));
Mono<String> findById = this.messageService.monoPostAuthorizeBeanFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
}
// Flux tests
@Test
public void fluxWhenPermitAllThenAopDoesNotSubscribe() {
given(this.delegate.fluxFindById(1L)).willReturn(Flux.from(this.result));
this.delegate.fluxFindById(1L);
this.result.assertNoSubscribers();
}
@Test
public void fluxWhenPermitAllThenSuccess() {
given(this.delegate.fluxFindById(1L)).willReturn(Flux.just("success"));
StepVerifier.create(this.delegate.fluxFindById(1L)).expectNext("success").verifyComplete();
}
@Test
public void fluxPreAuthorizeHasRoleWhenGrantedThenSuccess() {
given(this.delegate.fluxPreAuthorizeHasRoleFindById(1L)).willReturn(Flux.just("result"));
Flux<String> findById = this.messageService.fluxPreAuthorizeHasRoleFindById(1L)
.subscriberContext(this.withAdmin);
StepVerifier.create(findById).consumeNextWith((s) -> AssertionsForClassTypes.assertThat(s).isEqualTo("result"))
@@ -231,28 +207,23 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPreAuthorizeHasRoleWhenNoAuthenticationThenDenied() {
given(this.delegate.fluxPreAuthorizeHasRoleFindById(1L)).willReturn(Flux.from(this.result));
Flux<String> findById = this.messageService.fluxPreAuthorizeHasRoleFindById(1L);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
this.result.assertNoSubscribers();
}
@Test
public void fluxPreAuthorizeHasRoleWhenNotAuthorizedThenDenied() {
given(this.delegate.fluxPreAuthorizeHasRoleFindById(1L)).willReturn(Flux.from(this.result));
Flux<String> findById = this.messageService.fluxPreAuthorizeHasRoleFindById(1L)
.subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
this.result.assertNoSubscribers();
}
@Test
public void fluxPreAuthorizeBeanWhenGrantedThenSuccess() {
given(this.delegate.fluxPreAuthorizeBeanFindById(2L)).willReturn(Flux.just("result"));
Flux<String> findById = this.messageService.fluxPreAuthorizeBeanFindById(2L).subscriberContext(this.withAdmin);
StepVerifier.create(findById).expectNext("result").verifyComplete();
}
@@ -260,7 +231,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPreAuthorizeBeanWhenNotAuthenticatedAndGrantedThenSuccess() {
given(this.delegate.fluxPreAuthorizeBeanFindById(2L)).willReturn(Flux.just("result"));
Flux<String> findById = this.messageService.fluxPreAuthorizeBeanFindById(2L);
StepVerifier.create(findById).expectNext("result").verifyComplete();
}
@@ -268,27 +238,22 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPreAuthorizeBeanWhenNoAuthenticationThenDenied() {
given(this.delegate.fluxPreAuthorizeBeanFindById(1L)).willReturn(Flux.from(this.result));
Flux<String> findById = this.messageService.fluxPreAuthorizeBeanFindById(1L);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
this.result.assertNoSubscribers();
}
@Test
public void fluxPreAuthorizeBeanWhenNotAuthorizedThenDenied() {
given(this.delegate.fluxPreAuthorizeBeanFindById(1L)).willReturn(Flux.from(this.result));
Flux<String> findById = this.messageService.fluxPreAuthorizeBeanFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
this.result.assertNoSubscribers();
}
@Test
public void fluxPostAuthorizeWhenAuthorizedThenSuccess() {
given(this.delegate.fluxPostAuthorizeFindById(1L)).willReturn(Flux.just("user"));
Flux<String> findById = this.messageService.fluxPostAuthorizeFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectNext("user").verifyComplete();
}
@@ -296,7 +261,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPostAuthorizeWhenNotAuthorizedThenDenied() {
given(this.delegate.fluxPostAuthorizeBeanFindById(1L)).willReturn(Flux.just("not-authorized"));
Flux<String> findById = this.messageService.fluxPostAuthorizeBeanFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
}
@@ -304,7 +268,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPostAuthorizeWhenBeanAndAuthorizedThenSuccess() {
given(this.delegate.fluxPostAuthorizeBeanFindById(2L)).willReturn(Flux.just("user"));
Flux<String> findById = this.messageService.fluxPostAuthorizeBeanFindById(2L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectNext("user").verifyComplete();
}
@@ -312,7 +275,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPostAuthorizeWhenBeanAndNotAuthenticatedAndAuthorizedThenSuccess() {
given(this.delegate.fluxPostAuthorizeBeanFindById(2L)).willReturn(Flux.just("anonymous"));
Flux<String> findById = this.messageService.fluxPostAuthorizeBeanFindById(2L);
StepVerifier.create(findById).expectNext("anonymous").verifyComplete();
}
@@ -320,33 +282,27 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void fluxPostAuthorizeWhenBeanAndNotAuthorizedThenDenied() {
given(this.delegate.fluxPostAuthorizeBeanFindById(1L)).willReturn(Flux.just("not-authorized"));
Flux<String> findById = this.messageService.fluxPostAuthorizeBeanFindById(1L).subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
}
// Publisher tests
@Test
public void publisherWhenPermitAllThenAopDoesNotSubscribe() {
given(this.delegate.publisherFindById(1L)).willReturn(this.result);
this.delegate.publisherFindById(1L);
this.result.assertNoSubscribers();
}
@Test
public void publisherWhenPermitAllThenSuccess() {
given(this.delegate.publisherFindById(1L)).willReturn(publisherJust("success"));
StepVerifier.create(this.delegate.publisherFindById(1L)).expectNext("success").verifyComplete();
}
@Test
public void publisherPreAuthorizeHasRoleWhenGrantedThenSuccess() {
given(this.delegate.publisherPreAuthorizeHasRoleFindById(1L)).willReturn(publisherJust("result"));
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeHasRoleFindById(1L))
.subscriberContext(this.withAdmin);
StepVerifier.create(findById).consumeNextWith((s) -> AssertionsForClassTypes.assertThat(s).isEqualTo("result"))
@@ -356,28 +312,23 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPreAuthorizeHasRoleWhenNoAuthenticationThenDenied() {
given(this.delegate.publisherPreAuthorizeHasRoleFindById(1L)).willReturn(this.result);
Publisher<String> findById = this.messageService.publisherPreAuthorizeHasRoleFindById(1L);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
this.result.assertNoSubscribers();
}
@Test
public void publisherPreAuthorizeHasRoleWhenNotAuthorizedThenDenied() {
given(this.delegate.publisherPreAuthorizeHasRoleFindById(1L)).willReturn(this.result);
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeHasRoleFindById(1L))
.subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
this.result.assertNoSubscribers();
}
@Test
public void publisherPreAuthorizeBeanWhenGrantedThenSuccess() {
given(this.delegate.publisherPreAuthorizeBeanFindById(2L)).willReturn(publisherJust("result"));
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeBeanFindById(2L))
.subscriberContext(this.withAdmin);
StepVerifier.create(findById).expectNext("result").verifyComplete();
@@ -386,7 +337,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPreAuthorizeBeanWhenNotAuthenticatedAndGrantedThenSuccess() {
given(this.delegate.publisherPreAuthorizeBeanFindById(2L)).willReturn(publisherJust("result"));
Publisher<String> findById = this.messageService.publisherPreAuthorizeBeanFindById(2L);
StepVerifier.create(findById).expectNext("result").verifyComplete();
}
@@ -394,28 +344,23 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPreAuthorizeBeanWhenNoAuthenticationThenDenied() {
given(this.delegate.publisherPreAuthorizeBeanFindById(1L)).willReturn(this.result);
Publisher<String> findById = this.messageService.publisherPreAuthorizeBeanFindById(1L);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
this.result.assertNoSubscribers();
}
@Test
public void publisherPreAuthorizeBeanWhenNotAuthorizedThenDenied() {
given(this.delegate.publisherPreAuthorizeBeanFindById(1L)).willReturn(this.result);
Publisher<String> findById = Flux.from(this.messageService.publisherPreAuthorizeBeanFindById(1L))
.subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
this.result.assertNoSubscribers();
}
@Test
public void publisherPostAuthorizeWhenAuthorizedThenSuccess() {
given(this.delegate.publisherPostAuthorizeFindById(1L)).willReturn(publisherJust("user"));
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeFindById(1L))
.subscriberContext(this.withUser);
StepVerifier.create(findById).expectNext("user").verifyComplete();
@@ -424,7 +369,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPostAuthorizeWhenNotAuthorizedThenDenied() {
given(this.delegate.publisherPostAuthorizeBeanFindById(1L)).willReturn(publisherJust("not-authorized"));
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeBeanFindById(1L))
.subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();
@@ -433,7 +377,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPostAuthorizeWhenBeanAndAuthorizedThenSuccess() {
given(this.delegate.publisherPostAuthorizeBeanFindById(2L)).willReturn(publisherJust("user"));
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeBeanFindById(2L))
.subscriberContext(this.withUser);
StepVerifier.create(findById).expectNext("user").verifyComplete();
@@ -442,7 +385,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPostAuthorizeWhenBeanAndNotAuthenticatedAndAuthorizedThenSuccess() {
given(this.delegate.publisherPostAuthorizeBeanFindById(2L)).willReturn(publisherJust("anonymous"));
Publisher<String> findById = this.messageService.publisherPostAuthorizeBeanFindById(2L);
StepVerifier.create(findById).expectNext("anonymous").verifyComplete();
}
@@ -450,7 +392,6 @@ public class EnableReactiveMethodSecurityTests {
@Test
public void publisherPostAuthorizeWhenBeanAndNotAuthorizedThenDenied() {
given(this.delegate.publisherPostAuthorizeBeanFindById(1L)).willReturn(publisherJust("not-authorized"));
Publisher<String> findById = Flux.from(this.messageService.publisherPostAuthorizeBeanFindById(1L))
.subscriberContext(this.withUser);
StepVerifier.create(findById).expectError(AccessDeniedException.class).verify();

View File

@@ -110,13 +110,11 @@ public class GlobalMethodSecurityConfigurationTests {
@Test
public void methodSecurityAuthenticationManagerPublishesEvent() {
this.spring.register(InMemoryAuthWithGlobalMethodSecurityConfig.class).autowire();
try {
this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("foo", "bar"));
}
catch (AuthenticationException ex) {
}
assertThat(this.events.getEvents()).extracting(Object::getClass)
.containsOnly((Class) AuthenticationFailureBadCredentialsEvent.class);
}
@@ -125,14 +123,10 @@ public class GlobalMethodSecurityConfigurationTests {
@WithMockUser
public void methodSecurityWhenAuthenticationTrustResolverIsBeanThenAutowires() {
this.spring.register(CustomTrustResolverConfig.class).autowire();
AuthenticationTrustResolver trustResolver = this.spring.getContext().getBean(AuthenticationTrustResolver.class);
given(trustResolver.isAnonymous(any())).willReturn(true, false);
assertThatThrownBy(() -> this.service.preAuthorizeNotAnonymous()).isInstanceOf(AccessDeniedException.class);
this.service.preAuthorizeNotAnonymous();
verify(trustResolver, atLeastOnce()).isAnonymous(any());
}
@@ -142,9 +136,7 @@ public class GlobalMethodSecurityConfigurationTests {
public void defaultWebSecurityExpressionHandlerHasBeanResolverSet() {
this.spring.register(ExpressionHandlerHasBeanResolverSetConfig.class).autowire();
Authz authz = this.spring.getContext().getBean(Authz.class);
assertThatThrownBy(() -> this.service.preAuthorizeBean(false)).isInstanceOf(AccessDeniedException.class);
this.service.preAuthorizeBean(true);
}
@@ -152,9 +144,7 @@ public class GlobalMethodSecurityConfigurationTests {
@WithMockUser
public void methodSecuritySupportsAnnotaitonsOnInterfaceParamerNames() {
this.spring.register(MethodSecurityServiceConfig.class).autowire();
assertThatThrownBy(() -> this.service.postAnnotation("deny")).isInstanceOf(AccessDeniedException.class);
this.service.postAnnotation("grant");
// no exception
}
@@ -165,17 +155,14 @@ public class GlobalMethodSecurityConfigurationTests {
this.spring.register(AutowirePermissionEvaluatorConfig.class).autowire();
PermissionEvaluator permission = this.spring.getContext().getBean(PermissionEvaluator.class);
given(permission.hasPermission(any(), eq("something"), eq("read"))).willReturn(true, false);
this.service.hasPermission("something");
// no exception
assertThatThrownBy(() -> this.service.hasPermission("something")).isInstanceOf(AccessDeniedException.class);
}
@Test
public void multiPermissionEvaluatorConfig() {
this.spring.register(MultiPermissionEvaluatorConfig.class).autowire();
// no exception
}
@@ -184,7 +171,6 @@ public class GlobalMethodSecurityConfigurationTests {
@WithMockUser
public void enableGlobalMethodSecurityWorksOnSuperclass() {
this.spring.register(ChildConfig.class).autowire();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
}
@@ -200,7 +186,6 @@ public class GlobalMethodSecurityConfigurationTests {
child.register(Sec2479ChildConfig.class);
child.refresh();
this.spring.context(child).autowire();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
}
}
@@ -209,9 +194,7 @@ public class GlobalMethodSecurityConfigurationTests {
@Test
public void enableGlobalMethodSecurityDoesNotTriggerEagerInitializationOfBeansInGlobalAuthenticationConfigurer() {
this.spring.register(Sec2815Config.class).autowire();
MockBeanPostProcessor pp = this.spring.getContext().getBean(MockBeanPostProcessor.class);
assertThat(pp.beforeInit).containsKeys("dataSource");
assertThat(pp.afterInit).containsKeys("dataSource");
}
@@ -220,9 +203,9 @@ public class GlobalMethodSecurityConfigurationTests {
@Test
public void globalSecurityProxiesSecurity() {
this.spring.register(Sec3005Config.class).autowire();
assertThat(this.service.getClass()).matches((c) -> !Proxy.isProxyClass(c), "is not proxy class");
}
//
// // gh-3797
// def preAuthorizeBeanSpel() {
@@ -241,14 +224,11 @@ public class GlobalMethodSecurityConfigurationTests {
// thrown(AccessDeniedException)
// }
//
@Test
@WithMockUser
public void preAuthorizeBeanSpel() {
this.spring.register(PreAuthorizeBeanSpelConfig.class).autowire();
assertThatThrownBy(() -> this.service.preAuthorizeBean(false)).isInstanceOf(AccessDeniedException.class);
this.service.preAuthorizeBean(true);
}
@@ -257,7 +237,6 @@ public class GlobalMethodSecurityConfigurationTests {
@WithMockUser
public void roleHierarchy() {
this.spring.register(RoleHierarchyConfig.class).autowire();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
this.service.preAuthorizeAdmin();
}
@@ -266,12 +245,9 @@ public class GlobalMethodSecurityConfigurationTests {
@WithMockUser(authorities = "ROLE:USER")
public void grantedAuthorityDefaultsAutowires() {
this.spring.register(CustomGrantedAuthorityConfig.class).autowire();
CustomGrantedAuthorityConfig.CustomAuthorityService customService = this.spring.getContext()
.getBean(CustomGrantedAuthorityConfig.CustomAuthorityService.class);
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
customService.customPrefixRoleUser();
// no exception
}
@@ -280,12 +256,9 @@ public class GlobalMethodSecurityConfigurationTests {
@WithMockUser(authorities = "USER")
public void grantedAuthorityDefaultsWithEmptyRolePrefix() {
this.spring.register(EmptyRolePrefixGrantedAuthorityConfig.class).autowire();
EmptyRolePrefixGrantedAuthorityConfig.CustomAuthorityService customService = this.spring.getContext()
.getBean(EmptyRolePrefixGrantedAuthorityConfig.CustomAuthorityService.class);
assertThatThrownBy(() -> this.service.securedUser()).isInstanceOf(AccessDeniedException.class);
customService.emptyPrefixRoleUser();
// no exception
}
@@ -297,7 +270,6 @@ public class GlobalMethodSecurityConfigurationTests {
.getBean(MethodInterceptor.class);
MethodSecurityMetadataSource methodSecurityMetadataSource = this.spring.getContext()
.getBean(MethodSecurityMetadataSource.class);
assertThat(methodInterceptor.getSecurityMetadataSource()).isSameAs(methodSecurityMetadataSource);
}

View File

@@ -54,9 +54,7 @@ public class NamespaceGlobalMethodSecurityExpressionHandlerTests {
@WithMockUser
public void methodSecurityWhenUsingCustomPermissionEvaluatorThenPreAuthorizesAccordingly() {
this.spring.register(CustomAccessDecisionManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatCode(() -> this.service.hasPermission("granted")).doesNotThrowAnyException();
assertThatThrownBy(() -> this.service.hasPermission("denied")).isInstanceOf(AccessDeniedException.class);
}
@@ -64,9 +62,7 @@ public class NamespaceGlobalMethodSecurityExpressionHandlerTests {
@WithMockUser
public void methodSecurityWhenUsingCustomPermissionEvaluatorThenPostAuthorizesAccordingly() {
this.spring.register(CustomAccessDecisionManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatCode(() -> this.service.postHasPermission("granted")).doesNotThrowAnyException();
assertThatThrownBy(() -> this.service.postHasPermission("denied")).isInstanceOf(AccessDeniedException.class);
}
@@ -76,7 +72,6 @@ public class NamespaceGlobalMethodSecurityExpressionHandlerTests {
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
expressionHandler.setPermissionEvaluator(new PermissionEvaluator() {
@Override
public boolean hasPermission(Authentication authentication, Object targetDomainObject,
@@ -90,7 +85,6 @@ public class NamespaceGlobalMethodSecurityExpressionHandlerTests {
throw new UnsupportedOperationException();
}
});
return expressionHandler;
}

View File

@@ -78,18 +78,14 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser
public void methodSecurityWhenCustomAccessDecisionManagerThenAuthorizes() {
this.spring.register(CustomAccessDecisionManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
assertThatThrownBy(() -> this.service.secured()).isInstanceOf(AccessDeniedException.class);
}
@Test
@WithMockUser
public void methodSecurityWhenCustomAfterInvocationManagerThenAuthorizes() {
this.spring.register(CustomAfterInvocationManagerConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatThrownBy(() -> this.service.preAuthorizePermitAll()).isInstanceOf(AccessDeniedException.class);
}
@@ -97,7 +93,6 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser
public void methodSecurityWhenCustomAuthenticationManagerThenAuthorizes() {
this.spring.register(CustomAuthenticationConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(UnsupportedOperationException.class);
}
@@ -105,15 +100,10 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser
public void methodSecurityWhenJsr250EnabledThenAuthorizes() {
this.spring.register(Jsr250Config.class, MethodSecurityServiceConfig.class).autowire();
assertThatCode(() -> this.service.preAuthorize()).doesNotThrowAnyException();
assertThatCode(() -> this.service.secured()).doesNotThrowAnyException();
assertThatThrownBy(() -> this.service.jsr250()).isInstanceOf(AccessDeniedException.class);
assertThatCode(() -> this.service.jsr250PermitAll()).doesNotThrowAnyException();
}
@Test
@@ -121,11 +111,8 @@ public class NamespaceGlobalMethodSecurityTests {
public void methodSecurityWhenCustomMethodSecurityMetadataSourceThenAuthorizes() {
this.spring.register(CustomMethodSecurityMetadataSourceConfig.class, MethodSecurityServiceConfig.class)
.autowire();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
assertThatThrownBy(() -> this.service.secured()).isInstanceOf(AccessDeniedException.class);
assertThatThrownBy(() -> this.service.jsr250()).isInstanceOf(AccessDeniedException.class);
}
@@ -133,12 +120,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(AspectJMethodSecurityInterceptor.class)).isNotNull();
// TODO diagnose why aspectj isn't weaving method security advice around
// MethodSecurityServiceImpl
}
@@ -146,24 +131,19 @@ public class NamespaceGlobalMethodSecurityTests {
@Test
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(AspectJMethodSecurityInterceptor.class)).isNotNull();
}
@Test
@WithMockUser
public void methodSecurityWhenOrderSpecifiedThenConfigured() {
this.spring.register(CustomOrderConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThat(this.spring.getContext().getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class)
.getOrder()).isEqualTo(-135);
assertThatThrownBy(() -> this.service.jsr250()).isInstanceOf(AccessDeniedException.class);
}
@@ -171,10 +151,8 @@ 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);
assertThatThrownBy(() -> this.service.jsr250()).isInstanceOf(UnsupportedOperationException.class);
}
@@ -183,10 +161,8 @@ public class NamespaceGlobalMethodSecurityTests {
public void methodSecurityWhenOrderUnspecifiedAndCustomGlobalMethodSecurityConfigurationThenConfiguredToLowestPrecedence() {
this.spring.register(DefaultOrderExtendsMethodSecurityConfig.class, MethodSecurityServiceConfig.class)
.autowire();
assertThat(this.spring.getContext().getBean("metaDataSourceAdvisor", MethodSecurityMetadataSourceAdvisor.class)
.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE);
assertThatThrownBy(() -> this.service.jsr250()).isInstanceOf(UnsupportedOperationException.class);
}
@@ -194,11 +170,8 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser
public void methodSecurityWhenPrePostEnabledThenPreAuthorizes() {
this.spring.register(PreAuthorizeConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatCode(() -> this.service.secured()).doesNotThrowAnyException();
assertThatCode(() -> this.service.jsr250()).doesNotThrowAnyException();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
}
@@ -206,11 +179,8 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser
public void methodSecurityWhenPrePostEnabledAndCustomGlobalMethodSecurityConfigurationThenPreAuthorizes() {
this.spring.register(PreAuthorizeExtendsGMSCConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatCode(() -> this.service.secured()).doesNotThrowAnyException();
assertThatCode(() -> this.service.jsr250()).doesNotThrowAnyException();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
}
@@ -218,10 +188,8 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser
public void methodSecurityWhenProxyTargetClassThenDoesNotWireToInterface() {
this.spring.register(ProxyTargetClassConfig.class, MethodSecurityServiceConfig.class).autowire();
// make sure service was actually proxied
assertThat(this.service.getClass().getInterfaces()).doesNotContain(MethodSecurityService.class);
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
}
@@ -229,9 +197,7 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser
public void methodSecurityWhenDefaultProxyThenWiresToInterface() {
this.spring.register(DefaultProxyConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThat(this.service.getClass().getInterfaces()).contains(MethodSecurityService.class);
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
}
@@ -239,7 +205,6 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser
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()));
}
@@ -248,13 +213,9 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser
public void methodSecurityWhenSecuredEnabledThenSecures() {
this.spring.register(SecuredConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatThrownBy(() -> this.service.secured()).isInstanceOf(AccessDeniedException.class);
assertThatCode(() -> this.service.securedUser()).doesNotThrowAnyException();
assertThatCode(() -> this.service.preAuthorize()).doesNotThrowAnyException();
assertThatCode(() -> this.service.jsr250()).doesNotThrowAnyException();
}
@@ -269,11 +230,8 @@ public class NamespaceGlobalMethodSecurityTests {
@WithMockUser
public void methodSecurityWhenImportingGlobalMethodSecurityConfigurationSubclassThenAuthorizes() {
this.spring.register(ImportSubclassGMSCConfig.class, MethodSecurityServiceConfig.class).autowire();
assertThatCode(() -> this.service.secured()).doesNotThrowAnyException();
assertThatCode(() -> this.service.jsr250()).doesNotThrowAnyException();
assertThatThrownBy(() -> this.service.preAuthorize()).isInstanceOf(AccessDeniedException.class);
}
@@ -320,7 +278,6 @@ public class NamespaceGlobalMethodSecurityTests {
@Override
public Object decide(Authentication authentication, Object object, Collection<ConfigAttribute> attributes,
Object returnedObject) throws AccessDeniedException {
throw new AccessDeniedException("custom AfterInvocationManager");
}
@@ -403,7 +360,6 @@ public class NamespaceGlobalMethodSecurityTests {
BeanDefinitionRegistry registry) {
BeanDefinitionBuilder advice = BeanDefinitionBuilder.rootBeanDefinition(ExceptingInterceptor.class);
registry.registerBeanDefinition("exceptingInterceptor", advice.getBeanDefinition());
BeanDefinitionBuilder advisor = BeanDefinitionBuilder
.rootBeanDefinition(MethodSecurityMetadataSourceAdvisor.class);
advisor.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);

View File

@@ -46,15 +46,12 @@ public class ReactiveMethodSecurityConfigurationTests {
@Test
public void rolePrefixWithGrantedAuthorityDefaults() throws NoSuchMethodException {
this.spring.register(WithRolePrefixConfiguration.class).autowire();
TestingAuthenticationToken authentication = new TestingAuthenticationToken("principal", "credential",
"CUSTOM_ABC");
MockMethodInvocation methodInvocation = new MockMethodInvocation(new Foo(), Foo.class, "bar", String.class);
EvaluationContext context = this.methodSecurityExpressionHandler.createEvaluationContext(authentication,
methodInvocation);
SecurityExpressionRoot root = (SecurityExpressionRoot) context.getRootObject().getValue();
assertThat(root.hasRole("ROLE_ABC")).isFalse();
assertThat(root.hasRole("ROLE_CUSTOM_ABC")).isFalse();
assertThat(root.hasRole("CUSTOM_ABC")).isTrue();
@@ -64,15 +61,12 @@ public class ReactiveMethodSecurityConfigurationTests {
@Test
public void rolePrefixWithDefaultConfig() throws NoSuchMethodException {
this.spring.register(ReactiveMethodSecurityConfiguration.class).autowire();
TestingAuthenticationToken authentication = new TestingAuthenticationToken("principal", "credential",
"ROLE_ABC");
MockMethodInvocation methodInvocation = new MockMethodInvocation(new Foo(), Foo.class, "bar", String.class);
EvaluationContext context = this.methodSecurityExpressionHandler.createEvaluationContext(authentication,
methodInvocation);
SecurityExpressionRoot root = (SecurityExpressionRoot) context.getRootObject().getValue();
assertThat(root.hasRole("ROLE_ABC")).isTrue();
assertThat(root.hasRole("ABC")).isTrue();
}
@@ -80,15 +74,12 @@ public class ReactiveMethodSecurityConfigurationTests {
@Test
public void rolePrefixWithGrantedAuthorityDefaultsAndSubclassWithProxyingEnabled() throws NoSuchMethodException {
this.spring.register(SubclassConfig.class).autowire();
TestingAuthenticationToken authentication = new TestingAuthenticationToken("principal", "credential",
"ROLE_ABC");
MockMethodInvocation methodInvocation = new MockMethodInvocation(new Foo(), Foo.class, "bar", String.class);
EvaluationContext context = this.methodSecurityExpressionHandler.createEvaluationContext(authentication,
methodInvocation);
SecurityExpressionRoot root = (SecurityExpressionRoot) context.getRootObject().getValue();
assertThat(root.hasRole("ROLE_ABC")).isTrue();
assertThat(root.hasRole("ABC")).isTrue();
}

View File

@@ -60,19 +60,15 @@ public class SampleEnableGlobalMethodSecurityTests {
@Test
public void preAuthorize() {
this.spring.register(SampleWebSecurityConfig.class).autowire();
assertThat(this.methodSecurityService.secured()).isNull();
assertThat(this.methodSecurityService.jsr250()).isNull();
assertThatThrownBy(() -> this.methodSecurityService.preAuthorize()).isInstanceOf(AccessDeniedException.class);
}
@Test
public void customPermissionHandler() {
this.spring.register(CustomPermissionEvaluatorWebSecurityConfig.class).autowire();
assertThat(this.methodSecurityService.hasPermission("allowed")).isNull();
assertThatThrownBy(() -> this.methodSecurityService.hasPermission("denied"))
.isInstanceOf(AccessDeniedException.class);
}

View File

@@ -68,20 +68,15 @@ public class Sec2758Tests {
@WithMockUser(authorities = "CUSTOM")
@Test
public void requestWhenNullifyingRolePrefixThenPassivityRestored() throws Exception {
this.spring.register(SecurityConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isOk());
}
@WithMockUser(authorities = "CUSTOM")
@Test
public void methodSecurityWhenNullifyingRolePrefixThenPassivityRestored() {
this.spring.register(SecurityConfig.class).autowire();
assertThatCode(() -> this.service.doJsr250()).doesNotThrowAnyException();
assertThatCode(() -> this.service.doPreAuthorize()).doesNotThrowAnyException();
}

View File

@@ -77,7 +77,6 @@ public class AbstractRequestMatcherRegistryAnyMatcherTests {
.anyRequest().authenticated()
.antMatchers("/demo/**").permitAll();
// @formatter:on
}
}
@@ -93,7 +92,6 @@ public class AbstractRequestMatcherRegistryAnyMatcherTests {
.anyRequest().authenticated()
.mvcMatchers("/demo/**").permitAll();
// @formatter:on
}
}
@@ -109,7 +107,6 @@ public class AbstractRequestMatcherRegistryAnyMatcherTests {
.anyRequest().authenticated()
.regexMatchers(".*").permitAll();
// @formatter:on
}
}
@@ -125,7 +122,6 @@ public class AbstractRequestMatcherRegistryAnyMatcherTests {
.anyRequest().authenticated()
.anyRequest().permitAll();
// @formatter:on
}
}
@@ -141,7 +137,6 @@ public class AbstractRequestMatcherRegistryAnyMatcherTests {
.anyRequest().authenticated()
.requestMatchers(new AntPathRequestMatcher("/**")).permitAll();
// @formatter:on
}
}

View File

@@ -69,7 +69,6 @@ public class SampleWebSecurityConfigurerAdapterTests {
this.request = new MockHttpServletRequest("GET", "");
this.response = new MockHttpServletResponse();
this.chain = new MockFilterChain();
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "CSRF-TOKEN-TEST");
new HttpSessionCsrfTokenRepository().saveToken(csrfToken, this.request, this.response);
this.request.setParameter(csrfToken.getParameterName(), csrfToken.getToken());
@@ -78,136 +77,112 @@ public class SampleWebSecurityConfigurerAdapterTests {
@Test
public void helloWorldSampleWhenRequestSecureResourceThenRedirectToLogin() throws Exception {
this.spring.register(HelloWorldWebSecurityConfigurerAdapter.class).autowire();
this.request.addHeader("Accept", "text/html");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("http://localhost/login");
}
@Test
public void helloWorldSampleWhenRequestLoginWithoutCredentialsThenRedirectToLogin() throws Exception {
this.spring.register(HelloWorldWebSecurityConfigurerAdapter.class).autowire();
this.request.setServletPath("/login");
this.request.setMethod("POST");
this.request.addHeader("Accept", "text/html");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("/login?error");
}
@Test
public void helloWorldSampleWhenRequestLoginWithValidCredentialsThenRedirectToIndex() throws Exception {
this.spring.register(HelloWorldWebSecurityConfigurerAdapter.class).autowire();
this.request.setServletPath("/login");
this.request.setMethod("POST");
this.request.addHeader("Accept", "text/html");
this.request.addParameter("username", "user");
this.request.addParameter("password", "password");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("/");
}
@Test
public void readmeSampleWhenRequestSecureResourceThenRedirectToLogin() throws Exception {
this.spring.register(SampleWebSecurityConfigurerAdapter.class).autowire();
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("http://localhost/login");
}
@Test
public void readmeSampleWhenRequestLoginWithoutCredentialsThenRedirectToLogin() throws Exception {
this.spring.register(SampleWebSecurityConfigurerAdapter.class).autowire();
this.request.setServletPath("/login");
this.request.setMethod("POST");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("/login?error");
}
@Test
public void readmeSampleWhenRequestLoginWithValidCredentialsThenRedirectToIndex() throws Exception {
this.spring.register(SampleWebSecurityConfigurerAdapter.class).autowire();
this.request.setServletPath("/login");
this.request.setMethod("POST");
this.request.addParameter("username", "user");
this.request.addParameter("password", "password");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("/");
}
@Test
public void multiHttpSampleWhenRequestSecureResourceThenRedirectToLogin() throws Exception {
this.spring.register(SampleMultiHttpSecurityConfig.class).autowire();
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("http://localhost/login");
}
@Test
public void multiHttpSampleWhenRequestLoginWithoutCredentialsThenRedirectToLogin() throws Exception {
this.spring.register(SampleMultiHttpSecurityConfig.class).autowire();
this.request.setServletPath("/login");
this.request.setMethod("POST");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("/login?error");
}
@Test
public void multiHttpSampleWhenRequestLoginWithValidCredentialsThenRedirectToIndex() throws Exception {
this.spring.register(SampleMultiHttpSecurityConfig.class).autowire();
this.request.setServletPath("/login");
this.request.setMethod("POST");
this.request.addParameter("username", "user");
this.request.addParameter("password", "password");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getRedirectedUrl()).isEqualTo("/");
}
@Test
public void multiHttpSampleWhenRequestProtectedResourceThenStatusUnauthorized() throws Exception {
this.spring.register(SampleMultiHttpSecurityConfig.class).autowire();
this.request.setServletPath("/api/admin/test");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
}
@Test
public void multiHttpSampleWhenRequestAdminResourceWithRegularUserThenStatusForbidden() throws Exception {
this.spring.register(SampleMultiHttpSecurityConfig.class).autowire();
this.request.setServletPath("/api/admin/test");
this.request.addHeader("Authorization",
"Basic " + Base64.getEncoder().encodeToString("user:password".getBytes()));
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
@Test
public void multiHttpSampleWhenRequestAdminResourceWithAdminUserThenStatusOk() throws Exception {
this.spring.register(SampleMultiHttpSecurityConfig.class).autowire();
this.request.setServletPath("/api/admin/test");
this.request.addHeader("Authorization",
"Basic " + Base64.getEncoder().encodeToString("admin:password".getBytes()));
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
}

View File

@@ -84,9 +84,7 @@ public class WebSecurityConfigurerAdapterPowermockTests {
PowerMockito
.when(SpringFactoriesLoader.loadFactories(AbstractHttpConfigurer.class, getClass().getClassLoader()))
.thenReturn(Arrays.<AbstractHttpConfigurer>asList(configurer));
loadConfig(Config.class);
assertThat(configurer.init).isTrue();
assertThat(configurer.configure).isTrue();
}
@@ -94,21 +92,16 @@ public class WebSecurityConfigurerAdapterPowermockTests {
@Test
public void loadConfigWhenDefaultConfigThenWebAsyncManagerIntegrationFilterAdded() throws Exception {
this.spring.register(WebAsyncPopulatedByDefaultConfig.class).autowire();
WebAsyncManager webAsyncManager = mock(WebAsyncManager.class);
this.mockMvc.perform(get("/").requestAttr(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE, webAsyncManager));
ArgumentCaptor<CallableProcessingInterceptor> callableProcessingInterceptorArgCaptor = ArgumentCaptor
.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);
assertThat(callableProcessingInterceptor).isNotNull();
}

View File

@@ -84,7 +84,6 @@ public class WebSecurityConfigurerAdapterTests {
@Test
public void loadConfigWhenRequestSecureThenDefaultSecurityHeadersReturned() throws Exception {
this.spring.register(HeadersArePopulatedByDefaultConfig.class).autowire();
this.mockMvc.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"))
@@ -96,9 +95,7 @@ public class WebSecurityConfigurerAdapterTests {
@Test
public void loadConfigWhenRequestAuthenticateThenAuthenticationEventPublished() throws Exception {
this.spring.register(InMemoryAuthWithWebSecurityConfigurerAdapter.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(status().is3xxRedirection());
assertThat(InMemoryAuthWithWebSecurityConfigurerAdapter.EVENTS).isNotEmpty();
assertThat(InMemoryAuthWithWebSecurityConfigurerAdapter.EVENTS).hasSize(1);
}
@@ -106,9 +103,7 @@ public class WebSecurityConfigurerAdapterTests {
@Test
public void loadConfigWhenInMemoryConfigureProtectedThenPasswordUpgraded() throws Exception {
this.spring.register(InMemoryConfigureProtectedConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(status().is3xxRedirection());
UserDetailsService uds = this.spring.getContext().getBean(UserDetailsService.class);
assertThat(uds.loadUserByUsername("user").getPassword()).startsWith("{bcrypt}");
}
@@ -116,9 +111,7 @@ public class WebSecurityConfigurerAdapterTests {
@Test
public void loadConfigWhenInMemoryConfigureGlobalThenPasswordUpgraded() throws Exception {
this.spring.register(InMemoryConfigureGlobalConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(status().is3xxRedirection());
UserDetailsService uds = this.spring.getContext().getBean(UserDetailsService.class);
assertThat(uds.loadUserByUsername("user").getPassword()).startsWith("{bcrypt}");
}
@@ -128,10 +121,8 @@ public class WebSecurityConfigurerAdapterTests {
OverrideContentNegotiationStrategySharedObjectConfig.CONTENT_NEGOTIATION_STRATEGY_BEAN = mock(
ContentNegotiationStrategy.class);
this.spring.register(OverrideContentNegotiationStrategySharedObjectConfig.class).autowire();
OverrideContentNegotiationStrategySharedObjectConfig securityConfig = this.spring.getContext()
.getBean(OverrideContentNegotiationStrategySharedObjectConfig.class);
assertThat(securityConfig.contentNegotiationStrategySharedObject).isNotNull();
assertThat(securityConfig.contentNegotiationStrategySharedObject)
.isSameAs(OverrideContentNegotiationStrategySharedObjectConfig.CONTENT_NEGOTIATION_STRATEGY_BEAN);
@@ -140,10 +131,8 @@ public class WebSecurityConfigurerAdapterTests {
@Test
public void loadConfigWhenDefaultContentNegotiationStrategyThenHeaderContentNegotiationStrategy() {
this.spring.register(ContentNegotiationStrategyDefaultSharedObjectConfig.class).autowire();
ContentNegotiationStrategyDefaultSharedObjectConfig securityConfig = this.spring.getContext()
.getBean(ContentNegotiationStrategyDefaultSharedObjectConfig.class);
assertThat(securityConfig.contentNegotiationStrategySharedObject).isNotNull();
assertThat(securityConfig.contentNegotiationStrategySharedObject)
.isInstanceOf(HeaderContentNegotiationStrategy.class);
@@ -152,9 +141,7 @@ public class WebSecurityConfigurerAdapterTests {
@Test
public void loadConfigWhenUserDetailsServiceHasCircularReferenceThenStillLoads() {
this.spring.register(RequiresUserDetailsServiceConfig.class, UserDetailsServiceConfig.class).autowire();
MyFilter myFilter = this.spring.getContext().getBean(MyFilter.class);
assertThatCode(() -> myFilter.userDetailsService.loadUserByUsername("user")).doesNotThrowAnyException();
assertThatExceptionOfType(UsernameNotFoundException.class)
.isThrownBy(() -> myFilter.userDetailsService.loadUserByUsername("admin"));
@@ -164,10 +151,8 @@ public class WebSecurityConfigurerAdapterTests {
@Test
public void loadConfigWhenSharedObjectsCreatedThenApplicationContextAdded() {
this.spring.register(ApplicationContextSharedObjectConfig.class).autowire();
ApplicationContextSharedObjectConfig securityConfig = this.spring.getContext()
.getBean(ApplicationContextSharedObjectConfig.class);
assertThat(securityConfig.applicationContextSharedObject).isNotNull();
assertThat(securityConfig.applicationContextSharedObject).isSameAs(this.spring.getContext());
}
@@ -176,9 +161,7 @@ public class WebSecurityConfigurerAdapterTests {
public void loadConfigWhenCustomAuthenticationTrustResolverBeanThenOverridesDefault() {
CustomTrustResolverConfig.AUTHENTICATION_TRUST_RESOLVER_BEAN = mock(AuthenticationTrustResolver.class);
this.spring.register(CustomTrustResolverConfig.class).autowire();
CustomTrustResolverConfig securityConfig = this.spring.getContext().getBean(CustomTrustResolverConfig.class);
assertThat(securityConfig.authenticationTrustResolverSharedObject).isNotNull();
assertThat(securityConfig.authenticationTrustResolverSharedObject)
.isSameAs(CustomTrustResolverConfig.AUTHENTICATION_TRUST_RESOLVER_BEAN);
@@ -195,12 +178,9 @@ public class WebSecurityConfigurerAdapterTests {
@Test
public void performWhenUsingAuthenticationEventPublisherBeanThenUses() throws Exception {
this.spring.register(CustomAuthenticationEventPublisherBean.class).autowire();
AuthenticationEventPublisher authenticationEventPublisher = this.spring.getContext()
.getBean(AuthenticationEventPublisher.class);
this.mockMvc.perform(get("/").with(httpBasic("user", "password")));
verify(authenticationEventPublisher).publishAuthenticationSuccess(any(Authentication.class));
}
@@ -208,14 +188,11 @@ public class WebSecurityConfigurerAdapterTests {
@Test
public void performWhenUsingAuthenticationEventPublisherInDslThenUses() throws Exception {
this.spring.register(CustomAuthenticationEventPublisherDsl.class).autowire();
AuthenticationEventPublisher authenticationEventPublisher = CustomAuthenticationEventPublisherDsl.EVENT_PUBLISHER;
this.mockMvc.perform(get("/").with(httpBasic("user", "password"))); // fails since
// no
// providers
// configured
verify(authenticationEventPublisher).publishAuthenticationFailure(any(AuthenticationException.class),
any(Authentication.class));
}

View File

@@ -74,9 +74,7 @@ public class HttpConfigurationTests {
public void configureWhenAddFilterCasAuthenticationFilterThenFilterAdded() throws Exception {
CasAuthenticationFilterConfig.CAS_AUTHENTICATION_FILTER = spy(new CasAuthenticationFilter());
this.spring.register(CasAuthenticationFilterConfig.class).autowire();
this.mockMvc.perform(get("/"));
verify(CasAuthenticationFilterConfig.CAS_AUTHENTICATION_FILTER).doFilter(any(ServletRequest.class),
any(ServletResponse.class), any(FilterChain.class));
}
@@ -84,7 +82,6 @@ public class HttpConfigurationTests {
@Test
public void configureWhenConfigIsRequestMatchersJavadocThenAuthorizationApplied() throws Exception {
this.spring.register(RequestMatcherRegistryConfigs.class).autowire();
this.mockMvc.perform(get("/oauth/a")).andExpect(status().isUnauthorized());
this.mockMvc.perform(get("/oauth/b")).andExpect(status().isUnauthorized());
this.mockMvc.perform(get("/api/a")).andExpect(status().isUnauthorized());

View File

@@ -93,11 +93,8 @@ public class NamespaceHttpTests {
given(AccessDecisionManagerRefConfig.ACCESS_DECISION_MANAGER.supports(FilterInvocation.class)).willReturn(true);
given(AccessDecisionManagerRefConfig.ACCESS_DECISION_MANAGER.supports(any(ConfigAttribute.class)))
.willReturn(true);
this.spring.register(AccessDecisionManagerRefConfig.class).autowire();
this.mockMvc.perform(get("/"));
verify(AccessDecisionManagerRefConfig.ACCESS_DECISION_MANAGER, times(1)).decide(any(Authentication.class),
any(), anyCollection());
}
@@ -105,7 +102,6 @@ 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"));
}
@@ -114,19 +110,15 @@ public class NamespaceHttpTests {
public void configureWhenAuthenticationManagerProvidedThenVerifyUse() throws Exception {
AuthenticationManagerRefConfig.AUTHENTICATION_MANAGER = mock(AuthenticationManager.class);
this.spring.register(AuthenticationManagerRefConfig.class).autowire();
this.mockMvc.perform(formLogin());
verify(AuthenticationManagerRefConfig.AUTHENTICATION_MANAGER, times(1)).authenticate(any(Authentication.class));
}
@Test // http@create-session=always
public void configureWhenSessionCreationPolicyAlwaysThenSessionCreatedOnRequest() throws Exception {
this.spring.register(CreateSessionAlwaysConfig.class).autowire();
MvcResult mvcResult = this.mockMvc.perform(get("/")).andReturn();
HttpSession session = mvcResult.getRequest().getSession(false);
assertThat(session).isNotNull();
assertThat(session.isNew()).isTrue();
}
@@ -134,25 +126,19 @@ public class NamespaceHttpTests {
@Test // http@create-session=stateless
public void configureWhenSessionCreationPolicyStatelessThenSessionNotCreatedOnRequest() throws Exception {
this.spring.register(CreateSessionStatelessConfig.class).autowire();
MvcResult mvcResult = this.mockMvc.perform(get("/")).andReturn();
HttpSession session = mvcResult.getRequest().getSession(false);
assertThat(session).isNull();
}
@Test // http@create-session=ifRequired
public void configureWhenSessionCreationPolicyIfRequiredThenSessionCreatedWhenRequiredOnRequest() throws Exception {
this.spring.register(IfRequiredConfig.class).autowire();
MvcResult mvcResult = this.mockMvc.perform(get("/unsecure")).andReturn();
HttpSession session = mvcResult.getRequest().getSession(false);
assertThat(session).isNull();
mvcResult = this.mockMvc.perform(formLogin()).andReturn();
session = mvcResult.getRequest().getSession(false);
assertThat(session).isNotNull();
assertThat(session.isNew()).isTrue();
}
@@ -160,10 +146,8 @@ public class NamespaceHttpTests {
@Test // http@create-session=never
public void configureWhenSessionCreationPolicyNeverThenSessionNotCreatedOnRequest() throws Exception {
this.spring.register(CreateSessionNeverConfig.class).autowire();
MvcResult mvcResult = this.mockMvc.perform(get("/")).andReturn();
HttpSession session = mvcResult.getRequest().getSession(false);
assertThat(session).isNull();
}
@@ -171,7 +155,6 @@ public class NamespaceHttpTests {
public void configureWhenAuthenticationEntryPointSetAndRequestUnauthorizedThenRedirectedToAuthenticationEntryPoint()
throws Exception {
this.spring.register(EntryPointRefConfig.class).autowire();
this.mockMvc.perform(get("/")).andExpect(status().is3xxRedirection())
.andExpect(redirectedUrlPattern("**/entry-point"));
}
@@ -180,22 +163,17 @@ public class NamespaceHttpTests {
public void configureWhenJaasApiIntegrationFilterAddedThenJaasSubjectObtained() throws Exception {
LoginContext loginContext = mock(LoginContext.class);
given(loginContext.getSubject()).willReturn(new Subject());
JaasAuthenticationToken authenticationToken = mock(JaasAuthenticationToken.class);
given(authenticationToken.isAuthenticated()).willReturn(true);
given(authenticationToken.getLoginContext()).willReturn(loginContext);
this.spring.register(JaasApiProvisionConfig.class).autowire();
this.mockMvc.perform(get("/").with(authentication(authenticationToken)));
verify(loginContext, times(1)).getSubject();
}
@Test // http@realm
public void configureWhenHttpBasicAndRequestUnauthorizedThenReturnWWWAuthenticateWithRealm() throws Exception {
this.spring.register(RealmConfig.class).autowire();
this.mockMvc.perform(get("/")).andExpect(status().isUnauthorized())
.andExpect(header().string("WWW-Authenticate", "Basic realm=\"RealmConfig\""));
}
@@ -203,9 +181,7 @@ public class NamespaceHttpTests {
@Test // http@request-matcher-ref ant
public void configureWhenAntPatternMatchingThenAntPathRequestMatcherUsed() {
this.spring.register(RequestMatcherAntConfig.class).autowire();
FilterChainProxy filterChainProxy = this.spring.getContext().getBean(FilterChainProxy.class);
assertThat(filterChainProxy.getFilterChains().get(0)).isInstanceOf(DefaultSecurityFilterChain.class);
DefaultSecurityFilterChain securityFilterChain = (DefaultSecurityFilterChain) filterChainProxy.getFilterChains()
.get(0);
@@ -215,9 +191,7 @@ public class NamespaceHttpTests {
@Test // http@request-matcher-ref regex
public void configureWhenRegexPatternMatchingThenRegexRequestMatcherUsed() {
this.spring.register(RequestMatcherRegexConfig.class).autowire();
FilterChainProxy filterChainProxy = this.spring.getContext().getBean(FilterChainProxy.class);
assertThat(filterChainProxy.getFilterChains().get(0)).isInstanceOf(DefaultSecurityFilterChain.class);
DefaultSecurityFilterChain securityFilterChain = (DefaultSecurityFilterChain) filterChainProxy.getFilterChains()
.get(0);
@@ -227,9 +201,7 @@ public class NamespaceHttpTests {
@Test // http@request-matcher-ref
public void configureWhenRequestMatcherProvidedThenRequestMatcherUsed() {
this.spring.register(RequestMatcherRefConfig.class).autowire();
FilterChainProxy filterChainProxy = this.spring.getContext().getBean(FilterChainProxy.class);
assertThat(filterChainProxy.getFilterChains().get(0)).isInstanceOf(DefaultSecurityFilterChain.class);
DefaultSecurityFilterChain securityFilterChain = (DefaultSecurityFilterChain) filterChainProxy.getFilterChains()
.get(0);
@@ -240,9 +212,7 @@ public class NamespaceHttpTests {
@Test // http@security=none
public void configureWhenIgnoredAntPatternsThenAntPathRequestMatcherUsedWithNoFilters() {
this.spring.register(SecurityNoneConfig.class).autowire();
FilterChainProxy filterChainProxy = this.spring.getContext().getBean(FilterChainProxy.class);
assertThat(filterChainProxy.getFilterChains().get(0)).isInstanceOf(DefaultSecurityFilterChain.class);
DefaultSecurityFilterChain securityFilterChain = (DefaultSecurityFilterChain) filterChainProxy.getFilterChains()
.get(0);
@@ -250,7 +220,6 @@ public class NamespaceHttpTests {
assertThat(((AntPathRequestMatcher) securityFilterChain.getRequestMatcher()).getPattern())
.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);
@@ -262,7 +231,6 @@ public class NamespaceHttpTests {
@Test // http@security-context-repository-ref
public void configureWhenNullSecurityContextRepositoryThenSecurityContextNotSavedInSession() throws Exception {
this.spring.register(SecurityContextRepoConfig.class).autowire();
MvcResult mvcResult = this.mockMvc.perform(formLogin()).andReturn();
HttpSession session = mvcResult.getRequest().getSession(false);
assertThat(session).isNull();
@@ -271,9 +239,7 @@ public class NamespaceHttpTests {
@Test // http@servlet-api-provision=false
public void configureWhenServletApiDisabledThenRequestNotServletApiWrapper() throws Exception {
this.spring.register(ServletApiProvisionConfig.class, MainController.class).autowire();
this.mockMvc.perform(get("/"));
assertThat(MainController.HTTP_SERVLET_REQUEST_TYPE)
.isNotInstanceOf(SecurityContextHolderAwareRequestWrapper.class);
}
@@ -281,9 +247,7 @@ public class NamespaceHttpTests {
@Test // http@servlet-api-provision defaults to true
public void configureWhenServletApiDefaultThenRequestIsServletApiWrapper() throws Exception {
this.spring.register(ServletApiProvisionDefaultsConfig.class, MainController.class).autowire();
this.mockMvc.perform(get("/"));
assertThat(SecurityContextHolderAwareRequestWrapper.class)
.isAssignableFrom(MainController.HTTP_SERVLET_REQUEST_TYPE);
}
@@ -291,9 +255,7 @@ public class NamespaceHttpTests {
@Test // http@use-expressions=true
public void configureWhenUseExpressionsEnabledThenExpressionBasedSecurityMetadataSource() {
this.spring.register(UseExpressionsConfig.class).autowire();
UseExpressionsConfig config = this.spring.getContext().getBean(UseExpressionsConfig.class);
assertThat(ExpressionBasedFilterInvocationSecurityMetadataSource.class)
.isAssignableFrom(config.filterInvocationSecurityMetadataSourceType);
}
@@ -301,9 +263,7 @@ public class NamespaceHttpTests {
@Test // http@use-expressions=false
public void configureWhenUseExpressionsDisabledThenDefaultSecurityMetadataSource() {
this.spring.register(DisableUseExpressionsConfig.class).autowire();
DisableUseExpressionsConfig config = this.spring.getContext().getBean(DisableUseExpressionsConfig.class);
assertThat(DefaultFilterInvocationSecurityMetadataSource.class)
.isAssignableFrom(config.filterInvocationSecurityMetadataSourceType);
}

View File

@@ -75,66 +75,44 @@ public class WebSecurityTests {
@Test
public void ignoringMvcMatcher() throws Exception {
loadConfig(MvcMatcherConfig.class, LegacyMvcMatchingConfig.class);
this.request.setRequestURI("/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
setup();
this.request.setRequestURI("/path.html");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
setup();
this.request.setRequestURI("/path/");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
setup();
this.request.setRequestURI("/other");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
}
@Test
public void ignoringMvcMatcherServletPath() throws Exception {
loadConfig(MvcMatcherServletPathConfig.class, LegacyMvcMatchingConfig.class);
this.request.setServletPath("/spring");
this.request.setRequestURI("/spring/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
setup();
this.request.setServletPath("/spring");
this.request.setRequestURI("/spring/path.html");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
setup();
this.request.setServletPath("/spring");
this.request.setRequestURI("/spring/path/");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
setup();
this.request.setServletPath("/other");
this.request.setRequestURI("/other/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
}
@@ -143,7 +121,6 @@ public class WebSecurityTests {
this.context.register(configs);
this.context.setServletContext(new MockServletContext());
this.context.refresh();
this.context.getAutowireCapableBeanFactory().autowireBean(this);
}

View File

@@ -67,9 +67,7 @@ public class AuthenticationPrincipalArgumentResolverTests {
context.setAuthentication(
new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities()));
SecurityContextHolder.setContext(context);
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
mockMvc.perform(get("/users/self")).andExpect(status().isOk()).andExpect(content().string("extracted-user"));
}
@@ -84,12 +82,10 @@ public class AuthenticationPrincipalArgumentResolverTests {
.inMemoryAuthentication();
// @formatter:off
}
@Bean
public UsernameExtractor usernameExtractor() {
return new UsernameExtractor();
}
@RestController
static class UserController {
@GetMapping("/users/self")
@@ -98,7 +94,6 @@ public class AuthenticationPrincipalArgumentResolverTests {
}
}
}
static class UsernameExtractor {
public String extract(User u) {
return "extracted-" + u.getUsername();

View File

@@ -57,7 +57,6 @@ public class EnableWebSecurityTests {
@Test
public void configureWhenOverrideAuthenticationManagerBeanThenAuthenticationManagerBeanRegistered() {
this.spring.register(SecurityConfig.class).autowire();
AuthenticationManager authenticationManager = this.spring.getContext().getBean(AuthenticationManager.class);
Authentication authentication = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken("user", "password"));
@@ -73,7 +72,6 @@ public class EnableWebSecurityTests {
@Test
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"));
}
@@ -81,7 +79,6 @@ public class EnableWebSecurityTests {
@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"));
}
@@ -89,20 +86,16 @@ public class EnableWebSecurityTests {
@Test
public void enableWebSecurityWhenNoConfigurationAnnotationThenBeanProxyingEnabled() {
this.spring.register(BeanProxyEnabledByDefaultConfig.class).autowire();
Child childBean = this.spring.getContext().getBean(Child.class);
Parent parentBean = this.spring.getContext().getBean(Parent.class);
assertThat(parentBean.getChild()).isSameAs(childBean);
}
@Test
public void enableWebSecurityWhenProxyBeanMethodsFalseThenBeanProxyingDisabled() {
this.spring.register(BeanProxyDisabledConfig.class).autowire();
Child childBean = this.spring.getContext().getBean(Child.class);
Parent parentBean = this.spring.getContext().getBean(Parent.class);
assertThat(parentBean.getChild()).isNotSameAs(childBean);
}

View File

@@ -81,7 +81,6 @@ public class HttpSecurityConfigurationTests {
@Test
public void getWhenDefaultFilterChainBeanThenDefaultHeadersInResponse() throws Exception {
this.spring.register(DefaultWithFilterChainConfig.class).autowire();
MvcResult mvcResult = this.mockMvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff"))
.andExpect(header().string(HttpHeaders.X_FRAME_OPTIONS,
@@ -100,48 +99,39 @@ public class HttpSecurityConfigurationTests {
@Test
public void logoutWhenDefaultFilterChainBeanThenCreatesDefaultLogoutEndpoint() throws Exception {
this.spring.register(DefaultWithFilterChainConfig.class).autowire();
this.mockMvc.perform(post("/logout").with(csrf())).andExpect(redirectedUrl("/login?logout"));
}
@Test
public void loadConfigWhenDefaultConfigThenWebAsyncManagerIntegrationFilterAdded() throws Exception {
this.spring.register(DefaultWithFilterChainConfig.class, NameController.class).autowire();
MvcResult mvcResult = this.mockMvc.perform(get("/name").with(user("Bob"))).andExpect(request().asyncStarted())
.andReturn();
this.mockMvc.perform(asyncDispatch(mvcResult)).andExpect(status().isOk()).andExpect(content().string("Bob"));
}
@Test
public void getWhenDefaultFilterChainBeanThenAnonymousPermitted() throws Exception {
this.spring.register(AuthorizeRequestsConfig.class, UserDetailsConfig.class, BaseController.class).autowire();
this.mockMvc.perform(get("/")).andExpect(status().isOk());
}
@Test
public void authenticateWhenDefaultFilterChainBeanThenSessionIdChanges() throws Exception {
this.spring.register(SecurityEnabledConfig.class, UserDetailsConfig.class).autowire();
MockHttpSession session = new MockHttpSession();
String sessionId = session.getId();
MvcResult result = this.mockMvc.perform(
post("/login").param("username", "user").param("password", "password").session(session).with(csrf()))
.andReturn();
assertThat(result.getRequest().getSession(false).getId()).isNotEqualTo(sessionId);
}
@Test
public void authenticateWhenDefaultFilterChainBeanThenRedirectsToSavedRequest() throws Exception {
this.spring.register(SecurityEnabledConfig.class, UserDetailsConfig.class).autowire();
MockHttpSession session = (MockHttpSession) this.mockMvc.perform(get("/messages")).andReturn().getRequest()
.getSession();
this.mockMvc.perform(
post("/login").param("username", "user").param("password", "password").session(session).with(csrf()))
.andExpect(redirectedUrl("http://localhost/messages"));
@@ -150,7 +140,6 @@ public class HttpSecurityConfigurationTests {
@Test
public void authenticateWhenDefaultFilterChainBeanThenRolePrefixIsSet() throws Exception {
this.spring.register(SecurityEnabledConfig.class, UserDetailsConfig.class, UserController.class).autowire();
this.mockMvc
.perform(get("/user")
.with(authentication(new TestingAuthenticationToken("user", "password", "ROLE_USER"))))
@@ -160,7 +149,6 @@ public class HttpSecurityConfigurationTests {
@Test
public void loginWhenUsingDefaultsThenDefaultLoginPageGenerated() throws Exception {
this.spring.register(SecurityEnabledConfig.class).autowire();
this.mockMvc.perform(get("/login")).andExpect(status().isOk());
}

View File

@@ -77,29 +77,23 @@ public class OAuth2ClientConfigurationTests {
String clientRegistrationId = "client1";
String principalName = "user1";
TestingAuthenticationToken authentication = new TestingAuthenticationToken(principalName, "password");
ClientRegistrationRepository clientRegistrationRepository = mock(ClientRegistrationRepository.class);
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
.registrationId(clientRegistrationId).build();
given(clientRegistrationRepository.findByRegistrationId(eq(clientRegistrationId)))
.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);
OAuth2AccessToken accessToken = mock(OAuth2AccessToken.class);
given(authorizedClient.getAccessToken()).willReturn(accessToken);
OAuth2AccessTokenResponseClient accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
OAuth2AuthorizedClientArgumentResolverConfig.CLIENT_REGISTRATION_REPOSITORY = clientRegistrationRepository;
OAuth2AuthorizedClientArgumentResolverConfig.AUTHORIZED_CLIENT_REPOSITORY = authorizedClientRepository;
OAuth2AuthorizedClientArgumentResolverConfig.ACCESS_TOKEN_RESPONSE_CLIENT = accessTokenResponseClient;
this.spring.register(OAuth2AuthorizedClientArgumentResolverConfig.class).autowire();
this.mockMvc
.perform(get("/authorized-client")
.with(SecurityMockMvcRequestPostProcessors.authentication(authentication)))
@@ -113,25 +107,20 @@ public class OAuth2ClientConfigurationTests {
String clientRegistrationId = "client1";
String principalName = "user1";
TestingAuthenticationToken authentication = new TestingAuthenticationToken(principalName, "password");
ClientRegistrationRepository clientRegistrationRepository = mock(ClientRegistrationRepository.class);
OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
OAuth2AccessTokenResponseClient accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials()
.registrationId(clientRegistrationId).build();
given(clientRegistrationRepository.findByRegistrationId(clientRegistrationId)).willReturn(clientRegistration);
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234")
.tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(300).build();
given(accessTokenResponseClient.getTokenResponse(any(OAuth2ClientCredentialsGrantRequest.class)))
.willReturn(accessTokenResponse);
OAuth2AuthorizedClientArgumentResolverConfig.CLIENT_REGISTRATION_REPOSITORY = clientRegistrationRepository;
OAuth2AuthorizedClientArgumentResolverConfig.AUTHORIZED_CLIENT_REPOSITORY = authorizedClientRepository;
OAuth2AuthorizedClientArgumentResolverConfig.ACCESS_TOKEN_RESPONSE_CLIENT = accessTokenResponseClient;
this.spring.register(OAuth2AuthorizedClientArgumentResolverConfig.class).autowire();
this.mockMvc
.perform(get("/authorized-client")
.with(SecurityMockMvcRequestPostProcessors.authentication(authentication)))
@@ -177,28 +166,22 @@ public class OAuth2ClientConfigurationTests {
String clientRegistrationId = "client1";
String principalName = "user1";
TestingAuthenticationToken authentication = new TestingAuthenticationToken(principalName, "password");
ClientRegistrationRepository clientRegistrationRepository = mock(ClientRegistrationRepository.class);
OAuth2AuthorizedClientRepository authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
OAuth2AuthorizedClientManager authorizedClientManager = mock(OAuth2AuthorizedClientManager.class);
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
.registrationId(clientRegistrationId).build();
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, principalName,
TestOAuth2AccessTokens.noScopes());
given(authorizedClientManager.authorize(any())).willReturn(authorizedClient);
OAuth2AuthorizedClientManagerRegisteredConfig.CLIENT_REGISTRATION_REPOSITORY = clientRegistrationRepository;
OAuth2AuthorizedClientManagerRegisteredConfig.AUTHORIZED_CLIENT_REPOSITORY = authorizedClientRepository;
OAuth2AuthorizedClientManagerRegisteredConfig.AUTHORIZED_CLIENT_MANAGER = authorizedClientManager;
this.spring.register(OAuth2AuthorizedClientManagerRegisteredConfig.class).autowire();
this.mockMvc
.perform(get("/authorized-client")
.with(SecurityMockMvcRequestPostProcessors.authentication(authentication)))
.andExpect(status().isOk()).andExpect(content().string("resolved"));
verify(authorizedClientManager).authorize(any());
verifyNoInteractions(clientRegistrationRepository);
verifyNoInteractions(authorizedClientRepository);

View File

@@ -60,7 +60,6 @@ public class Sec2515Tests {
.getContext();
context.setClassLoader(new URLClassLoader(new URL[0], context.getClassLoader()));
this.spring.autowire();
assertThat(this.spring.getContext().getBean(AuthenticationManager.class)).isNotNull();
} // SEC-2515

View File

@@ -63,7 +63,6 @@ public class SecurityReactorContextConfigurationResourceServerTests {
public void requestWhenUsingFilterThenBearerTokenPropagated() throws Exception {
BearerTokenAuthentication authentication = TestBearerTokenAuthentications.bearer();
this.spring.register(BearerFilterConfig.class, WebServerConfig.class, Controller.class).autowire();
this.mockMvc.perform(get("/token").with(SecurityMockMvcRequestPostProcessors.authentication(authentication)))
.andExpect(status().isOk()).andExpect(content().string("Bearer token"));
}
@@ -73,7 +72,6 @@ public class SecurityReactorContextConfigurationResourceServerTests {
public void requestWhenNotUsingFilterThenBearerTokenNotPropagated() throws Exception {
BearerTokenAuthentication authentication = TestBearerTokenAuthentications.bearer();
this.spring.register(BearerFilterlessConfig.class, WebServerConfig.class, Controller.class).autowire();
this.mockMvc.perform(get("/token").with(SecurityMockMvcRequestPostProcessors.authentication(authentication)))
.andExpect(status().isOk()).andExpect(content().string(""));
}
@@ -155,7 +153,6 @@ public class SecurityReactorContextConfigurationResourceServerTests {
String header = request.getHeader("Authorization");
if (StringUtils.isBlank(header)) {
return response;
}
return response.setBody(header);
}

View File

@@ -106,10 +106,8 @@ public class SecurityReactorContextConfigurationTests {
RequestContextHolder
.setRequestAttributes(new ServletRequestAttributes(this.servletRequest, this.servletResponse));
SecurityContextHolder.getContext().setAuthentication(this.authentication);
String testKey = "test_key";
String testValue = "test_value";
BaseSubscriber<Object> parent = new BaseSubscriber<Object>() {
@Override
public Context currentContext() {
@@ -117,9 +115,7 @@ public class SecurityReactorContextConfigurationTests {
}
};
CoreSubscriber<Object> subscriber = this.subscriberRegistrar.createSubscriberIfNecessary(parent);
Context resultContext = subscriber.currentContext();
assertThat(resultContext.getOrEmpty(testKey)).hasValue(testValue);
Map<Object, Object> securityContextAttributes = resultContext
.getOrDefault(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES, null);
@@ -134,7 +130,6 @@ public class SecurityReactorContextConfigurationTests {
RequestContextHolder
.setRequestAttributes(new ServletRequestAttributes(this.servletRequest, this.servletResponse));
SecurityContextHolder.getContext().setAuthentication(this.authentication);
Context parentContext = Context.of(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES,
new HashMap<>());
BaseSubscriber<Object> parent = new BaseSubscriber<Object>() {
@@ -144,7 +139,6 @@ public class SecurityReactorContextConfigurationTests {
}
};
CoreSubscriber<Object> subscriber = this.subscriberRegistrar.createSubscriberIfNecessary(parent);
Context resultContext = subscriber.currentContext();
assertThat(resultContext).isSameAs(parentContext);
}
@@ -189,7 +183,6 @@ public class SecurityReactorContextConfigurationTests {
return null;
}
});
CoreSubscriber<Object> subscriber = this.subscriberRegistrar
.createSubscriberIfNecessary(Operators.emptySubscriber());
assertThat(subscriber).isInstanceOf(SecurityReactorContextConfiguration.SecurityReactorContextSubscriber.class);
@@ -200,14 +193,11 @@ public class SecurityReactorContextConfigurationTests {
// Trigger the importing of SecurityReactorContextConfiguration via
// OAuth2ImportSelector
this.spring.register(SecurityConfig.class).autowire();
// Setup for SecurityReactorContextSubscriberRegistrar
RequestContextHolder
.setRequestAttributes(new ServletRequestAttributes(this.servletRequest, this.servletResponse));
SecurityContextHolder.getContext().setAuthentication(this.authentication);
ClientResponse clientResponseOk = ClientResponse.create(HttpStatus.OK).build();
ExchangeFilterFunction filter = (req, next) -> Mono.subscriberContext()
.filter((ctx) -> ctx.hasKey(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES))
.map((ctx) -> ctx.get(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES)).cast(Map.class)
@@ -221,18 +211,14 @@ public class SecurityReactorContextConfigurationTests {
return ClientResponse.create(HttpStatus.NOT_FOUND).build();
}
});
ClientRequest clientRequest = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
MockExchangeFunction exchange = new MockExchangeFunction();
Map<Object, Object> expectedContextAttributes = new HashMap<>();
expectedContextAttributes.put(HttpServletRequest.class, this.servletRequest);
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));
StepVerifier.create(clientResponseMono).expectAccessibleContext()
.contains(SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES, expectedContextAttributes)
.then().expectNext(clientResponseOk).verifyComplete();

View File

@@ -94,7 +94,6 @@ public class WebMvcSecurityConfigurationTests {
public void csrfToken() throws Exception {
CsrfToken csrfToken = new DefaultCsrfToken("headerName", "paramName", "token");
MockHttpServletRequestBuilder request = get("/csrf").requestAttr(CsrfToken.class.getName(), csrfToken);
this.mockMvc.perform(request).andExpect(assertResult(csrfToken));
}

View File

@@ -89,30 +89,22 @@ public class WebSecurityConfigurationTests {
@Test
public void loadConfigWhenWebSecurityConfigurersHaveOrderThenFilterChainsOrdered() {
this.spring.register(SortedWebSecurityConfigurerAdaptersConfig.class).autowire();
FilterChainProxy filterChainProxy = this.spring.getContext().getBean(FilterChainProxy.class);
List<SecurityFilterChain> filterChains = filterChainProxy.getFilterChains();
assertThat(filterChains).hasSize(6);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "");
request.setServletPath("/ignore1");
assertThat(filterChains.get(0).matches(request)).isTrue();
assertThat(filterChains.get(0).getFilters()).isEmpty();
request.setServletPath("/ignore2");
assertThat(filterChains.get(1).matches(request)).isTrue();
assertThat(filterChains.get(1).getFilters()).isEmpty();
request.setServletPath("/role1/**");
assertThat(filterChains.get(2).matches(request)).isTrue();
request.setServletPath("/role2/**");
assertThat(filterChains.get(3).matches(request)).isTrue();
request.setServletPath("/role3/**");
assertThat(filterChains.get(4).matches(request)).isTrue();
request.setServletPath("/**");
assertThat(filterChains.get(5).matches(request)).isTrue();
}
@@ -120,22 +112,16 @@ public class WebSecurityConfigurationTests {
@Test
public void loadConfigWhenSecurityFilterChainsHaveOrderThenFilterChainsOrdered() {
this.spring.register(SortedSecurityFilterChainConfig.class).autowire();
FilterChainProxy filterChainProxy = this.spring.getContext().getBean(FilterChainProxy.class);
List<SecurityFilterChain> filterChains = filterChainProxy.getFilterChains();
assertThat(filterChains).hasSize(4);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "");
request.setServletPath("/role1/**");
assertThat(filterChains.get(0).matches(request)).isTrue();
request.setServletPath("/role2/**");
assertThat(filterChains.get(1).matches(request)).isTrue();
request.setServletPath("/role3/**");
assertThat(filterChains.get(2).matches(request)).isTrue();
request.setServletPath("/**");
assertThat(filterChains.get(3).matches(request)).isTrue();
}
@@ -143,7 +129,6 @@ public class WebSecurityConfigurationTests {
@Test
public void loadConfigWhenWebSecurityConfigurersHaveSameOrderThenThrowBeanCreationException() {
Throwable thrown = catchThrowable(() -> this.spring.register(DuplicateOrderConfig.class).autowire());
assertThat(thrown).isInstanceOf(BeanCreationException.class)
.hasMessageContaining("@Order on WebSecurityConfigurers must be unique")
.hasMessageContaining(DuplicateOrderConfig.WebConfigurer1.class.getName())
@@ -153,9 +138,7 @@ public class WebSecurityConfigurationTests {
@Test
public void loadConfigWhenWebInvocationPrivilegeEvaluatorSetThenIsRegistered() {
PrivilegeEvaluatorConfigurerAdapterConfig.PRIVILEGE_EVALUATOR = mock(WebInvocationPrivilegeEvaluator.class);
this.spring.register(PrivilegeEvaluatorConfigurerAdapterConfig.class).autowire();
assertThat(this.spring.getContext().getBean(WebInvocationPrivilegeEvaluator.class))
.isSameAs(PrivilegeEvaluatorConfigurerAdapterConfig.PRIVILEGE_EVALUATOR);
}
@@ -165,9 +148,7 @@ public class WebSecurityConfigurationTests {
WebSecurityExpressionHandlerConfig.EXPRESSION_HANDLER = mock(SecurityExpressionHandler.class);
given(WebSecurityExpressionHandlerConfig.EXPRESSION_HANDLER.getExpressionParser())
.willReturn(mock(ExpressionParser.class));
this.spring.register(WebSecurityExpressionHandlerConfig.class).autowire();
assertThat(this.spring.getContext().getBean(SecurityExpressionHandler.class))
.isSameAs(WebSecurityExpressionHandlerConfig.EXPRESSION_HANDLER);
}
@@ -176,7 +157,6 @@ public class WebSecurityConfigurationTests {
public void loadConfigWhenSecurityExpressionHandlerIsNullThenException() {
Throwable thrown = catchThrowable(
() -> this.spring.register(NullWebSecurityExpressionHandlerConfig.class).autowire());
assertThat(thrown).isInstanceOf(BeanCreationException.class);
assertThat(thrown).hasRootCauseExactlyInstanceOf(IllegalArgumentException.class);
}
@@ -184,7 +164,6 @@ public class WebSecurityConfigurationTests {
@Test
public void loadConfigWhenDefaultSecurityExpressionHandlerThenDefaultIsRegistered() {
this.spring.register(WebSecurityExpressionHandlerDefaultsConfig.class).autowire();
assertThat(this.spring.getContext().getBean(SecurityExpressionHandler.class))
.isInstanceOf(DefaultWebSecurityExpressionHandler.class);
}
@@ -195,7 +174,6 @@ public class WebSecurityConfigurationTests {
TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "notused", "ROLE_ADMIN");
FilterInvocation invocation = new FilterInvocation(new MockHttpServletRequest("GET", ""),
new MockHttpServletResponse(), new MockFilterChain());
AbstractSecurityExpressionHandler handler = this.spring.getContext()
.getBean(AbstractSecurityExpressionHandler.class);
EvaluationContext evaluationContext = handler.createEvaluationContext(authentication, invocation);
@@ -210,7 +188,6 @@ public class WebSecurityConfigurationTests {
TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "notused");
FilterInvocation invocation = new FilterInvocation(new MockHttpServletRequest("GET", ""),
new MockHttpServletResponse(), new MockFilterChain());
AbstractSecurityExpressionHandler handler = this.spring.getContext()
.getBean(AbstractSecurityExpressionHandler.class);
EvaluationContext evaluationContext = handler.createEvaluationContext(authentication, invocation);
@@ -222,7 +199,6 @@ public class WebSecurityConfigurationTests {
@Test
public void loadConfigWhenDefaultWebInvocationPrivilegeEvaluatorThenDefaultIsRegistered() {
this.spring.register(WebInvocationPrivilegeEvaluatorDefaultsConfig.class).autowire();
assertThat(this.spring.getContext().getBean(WebInvocationPrivilegeEvaluator.class))
.isInstanceOf(DefaultWebInvocationPrivilegeEvaluator.class);
}
@@ -239,7 +215,6 @@ public class WebSecurityConfigurationTests {
@Test
public void loadConfigWhenDefaultSecurityExpressionHandlerThenBeanResolverSet() throws Exception {
this.spring.register(DefaultExpressionHandlerSetsBeanResolverConfig.class).autowire();
this.mockMvc.perform(get("/")).andExpect(status().isOk());
this.mockMvc.perform(post("/")).andExpect(status().isForbidden());
}
@@ -248,14 +223,11 @@ public class WebSecurityConfigurationTests {
@Test
public void loadConfigWhenMultipleWebSecurityConfigurationThenContextLoads() {
this.spring.register(ParentConfig.class).autowire();
this.child.register(ChildConfig.class);
this.child.getContext().setParent(this.spring.getContext());
this.child.autowire();
assertThat(this.spring.getContext().getBean("springSecurityFilterChain")).isNotNull();
assertThat(this.child.getContext().getBean("springSecurityFilterChain")).isNotNull();
assertThat(this.spring.getContext().containsBean("springSecurityFilterChain")).isTrue();
assertThat(this.child.getContext().containsBean("springSecurityFilterChain")).isTrue();
}
@@ -271,17 +243,14 @@ public class WebSecurityConfigurationTests {
public void loadConfigWhenBeanProxyingEnabledAndSubclassThenFilterChainsCreated() {
this.spring.register(GlobalAuthenticationWebSecurityConfigurerAdaptersConfig.class, SubclassConfig.class)
.autowire();
FilterChainProxy filterChainProxy = this.spring.getContext().getBean(FilterChainProxy.class);
List<SecurityFilterChain> filterChains = filterChainProxy.getFilterChains();
assertThat(filterChains).hasSize(4);
}
@Test
public void loadConfigWhenBothAdapterAndFilterChainConfiguredThenException() {
Throwable thrown = catchThrowable(() -> this.spring.register(AdapterAndFilterChainConfig.class).autowire());
assertThat(thrown).isInstanceOf(BeanCreationException.class)
.hasRootCauseExactlyInstanceOf(IllegalStateException.class)
.hasMessageContaining("Found WebSecurityConfigurerAdapter as well as SecurityFilterChain.");

View File

@@ -39,10 +39,8 @@ public class Sec2377Tests {
@Test
public void refreshContextWhenParentAndChildRegisteredThenNoException() {
this.parent.register(Sec2377AConfig.class).autowire();
ConfigurableApplicationContext context = this.child.register(Sec2377BConfig.class).getContext();
context.setParent(this.parent.getContext());
this.child.autowire();
}

View File

@@ -41,7 +41,6 @@ public class AbstractConfigAttributeRequestMatcherRegistryTests {
@Test
public void testGetRequestMatcherIsTypeRegexMatcher() {
List<RequestMatcher> requestMatchers = this.registry.regexMatchers(HttpMethod.GET, "/a.*");
for (RequestMatcher requestMatcher : requestMatchers) {
assertThat(requestMatcher).isInstanceOf(RegexRequestMatcher.class);
}
@@ -50,7 +49,6 @@ public class AbstractConfigAttributeRequestMatcherRegistryTests {
@Test
public void testRequestMatcherIsTypeRegexMatcher() {
List<RequestMatcher> requestMatchers = this.registry.regexMatchers("/a.*");
for (RequestMatcher requestMatcher : requestMatchers) {
assertThat(requestMatcher).isInstanceOf(RegexRequestMatcher.class);
}
@@ -59,7 +57,6 @@ public class AbstractConfigAttributeRequestMatcherRegistryTests {
@Test
public void testGetRequestMatcherIsTypeAntPathRequestMatcher() {
List<RequestMatcher> requestMatchers = this.registry.antMatchers(HttpMethod.GET, "/a.*");
for (RequestMatcher requestMatcher : requestMatchers) {
assertThat(requestMatcher).isInstanceOf(AntPathRequestMatcher.class);
}
@@ -68,7 +65,6 @@ public class AbstractConfigAttributeRequestMatcherRegistryTests {
@Test
public void testRequestMatcherIsTypeAntPathRequestMatcher() {
List<RequestMatcher> requestMatchers = this.registry.antMatchers("/a.*");
for (RequestMatcher requestMatcher : requestMatchers) {
assertThat(requestMatcher).isInstanceOf(AntPathRequestMatcher.class);
}

View File

@@ -52,28 +52,24 @@ public class AnonymousConfigurerTests {
@Test
public void requestWhenAnonymousTwiceInvokedThenDoesNotOverride() throws Exception {
this.spring.register(InvokeTwiceDoesNotOverride.class, PrincipalController.class).autowire();
this.mockMvc.perform(get("/")).andExpect(content().string("principal"));
}
@Test
public void requestWhenAnonymousPrincipalInLambdaThenPrincipalUsed() throws Exception {
this.spring.register(AnonymousPrincipalInLambdaConfig.class, PrincipalController.class).autowire();
this.mockMvc.perform(get("/")).andExpect(content().string("principal"));
}
@Test
public void requestWhenAnonymousDisabledInLambdaThenRespondsWithForbidden() throws Exception {
this.spring.register(AnonymousDisabledInLambdaConfig.class, PrincipalController.class).autowire();
this.mockMvc.perform(get("/")).andExpect(status().isForbidden());
}
@Test
public void requestWhenAnonymousWithDefaultsInLambdaThenRespondsWithOk() throws Exception {
this.spring.register(AnonymousWithDefaultsInLambdaConfig.class, PrincipalController.class).autowire();
this.mockMvc.perform(get("/")).andExpect(status().isOk());
}

View File

@@ -94,9 +94,7 @@ public class AuthorizeRequestsTests {
public void antMatchersMethodAndNoPatterns() throws Exception {
loadConfig(AntMatchersNoPatternsConfig.class);
this.request.setMethod("POST");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
@@ -104,9 +102,7 @@ public class AuthorizeRequestsTests {
public void postWhenPostDenyAllInLambdaThenRespondsWithForbidden() throws Exception {
loadConfig(AntMatchersNoPatternsInLambdaConfig.class);
this.request.setMethod("POST");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
@@ -114,18 +110,12 @@ public class AuthorizeRequestsTests {
@Test
public void antMatchersPathVariables() throws Exception {
loadConfig(AntPatchersPathVariables.class);
this.request.setServletPath("/user/user");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
this.setup();
this.request.setServletPath("/user/deny");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
@@ -133,18 +123,12 @@ public class AuthorizeRequestsTests {
@Test
public void antMatchersPathVariablesCaseInsensitive() throws Exception {
loadConfig(AntPatchersPathVariables.class);
this.request.setServletPath("/USER/user");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
this.setup();
this.request.setServletPath("/USER/deny");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
@@ -152,18 +136,12 @@ public class AuthorizeRequestsTests {
@Test
public void antMatchersPathVariablesCaseInsensitiveCamelCaseVariables() throws Exception {
loadConfig(AntMatchersPathVariablesCamelCaseVariables.class);
this.request.setServletPath("/USER/user");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
this.setup();
this.request.setServletPath("/USER/deny");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
@@ -171,185 +149,126 @@ public class AuthorizeRequestsTests {
@Test
public void roleHiearchy() throws Exception {
loadConfig(RoleHiearchyConfig.class);
SecurityContext securityContext = new SecurityContextImpl();
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("test", "notused",
AuthorityUtils.createAuthorityList("ROLE_USER")));
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);
}
@Test
public void mvcMatcher() throws Exception {
loadConfig(MvcMatcherConfig.class, LegacyMvcMatchingConfig.class);
this.request.setRequestURI("/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setRequestURI("/path.html");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/path/");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
}
@Test
public void requestWhenMvcMatcherDenyAllThenRespondsWithUnauthorized() throws Exception {
loadConfig(MvcMatcherInLambdaConfig.class, LegacyMvcMatchingConfig.class);
this.request.setRequestURI("/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setRequestURI("/path.html");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/path/");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
}
@Test
public void requestWhenMvcMatcherServletPathDenyAllThenMatchesOnServletPath() throws Exception {
loadConfig(MvcMatcherServletPathInLambdaConfig.class, LegacyMvcMatchingConfig.class);
this.request.setServletPath("/spring");
this.request.setRequestURI("/spring/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/spring");
this.request.setRequestURI("/spring/path.html");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/spring");
this.request.setRequestURI("/spring/path/");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/foo");
this.request.setRequestURI("/foo/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
setup();
this.request.setServletPath("/");
this.request.setRequestURI("/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
}
@Test
public void mvcMatcherPathVariables() throws Exception {
loadConfig(MvcMatcherPathVariablesConfig.class);
this.request.setRequestURI("/user/user");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
this.setup();
this.request.setRequestURI("/user/deny");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
}
@Test
public void requestWhenMvcMatcherPathVariablesThenMatchesOnPathVariables() throws Exception {
loadConfig(MvcMatcherPathVariablesInLambdaConfig.class);
this.request.setRequestURI("/user/user");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
this.setup();
this.request.setRequestURI("/user/deny");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
}
@Test
public void mvcMatcherServletPath() throws Exception {
loadConfig(MvcMatcherServletPathConfig.class, LegacyMvcMatchingConfig.class);
this.request.setServletPath("/spring");
this.request.setRequestURI("/spring/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/spring");
this.request.setRequestURI("/spring/path.html");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/spring");
this.request.setRequestURI("/spring/path/");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/foo");
this.request.setRequestURI("/foo/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
setup();
this.request.setServletPath("/");
this.request.setRequestURI("/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
}
@@ -358,7 +277,6 @@ public class AuthorizeRequestsTests {
this.context.register(configs);
this.context.setServletContext(this.servletContext);
this.context.refresh();
this.context.getAutowireCapableBeanFactory().autowireBean(this);
}

View File

@@ -56,7 +56,6 @@ public class ChannelSecurityConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnInsecureChannelProcessor() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(InsecureChannelProcessor.class));
}
@@ -64,7 +63,6 @@ public class ChannelSecurityConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnSecureChannelProcessor() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(SecureChannelProcessor.class));
}
@@ -72,7 +70,6 @@ public class ChannelSecurityConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnChannelDecisionManagerImpl() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(ChannelDecisionManagerImpl.class));
}
@@ -80,21 +77,18 @@ public class ChannelSecurityConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnChannelProcessingFilter() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(ChannelProcessingFilter.class));
}
@Test
public void requiresChannelWhenInvokesTwiceThenUsesOriginalRequiresSecure() throws Exception {
this.spring.register(DuplicateInvocationsDoesNotOverrideConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(redirectedUrl("https://localhost/"));
}
@Test
public void requestWhenRequiresChannelConfiguredInLambdaThenRedirectsToHttps() throws Exception {
this.spring.register(RequiresChannelInLambdaConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(redirectedUrl("https://localhost/"));
}

View File

@@ -73,7 +73,6 @@ public class CorsConfigurerTests {
@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"));
@@ -82,7 +81,6 @@ public class CorsConfigurerTests {
@Test
public void optionsWhenCrossOriginAnnotationThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(MvcCorsConfig.class).autowire();
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())
@@ -93,7 +91,6 @@ public class CorsConfigurerTests {
@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"));
@@ -102,7 +99,6 @@ public class CorsConfigurerTests {
@Test
public void optionsWhenDefaultsInLambdaAndCrossOriginAnnotationThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(MvcCorsInLambdaConfig.class).autowire();
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())
@@ -113,7 +109,6 @@ public class CorsConfigurerTests {
@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"));
@@ -122,7 +117,6 @@ public class CorsConfigurerTests {
@Test
public void optionsWhenCorsConfigurationSourceBeanThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(ConfigSourceConfig.class).autowire();
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())
@@ -134,7 +128,6 @@ public class CorsConfigurerTests {
public void getWhenMvcCorsInLambdaConfigAndCorsConfigurationSourceBeanThenRespondsWithCorsHeaders()
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"));
@@ -144,7 +137,6 @@ public class CorsConfigurerTests {
public void optionsWhenMvcCorsInLambdaConfigAndCorsConfigurationSourceBeanThenRespondsWithCorsHeaders()
throws Exception {
this.spring.register(ConfigSourceInLambdaConfig.class).autowire();
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())
@@ -155,7 +147,6 @@ public class CorsConfigurerTests {
@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"));
@@ -164,7 +155,6 @@ public class CorsConfigurerTests {
@Test
public void optionsWhenCorsFilterBeanThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(CorsFilterConfig.class).autowire();
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())
@@ -175,7 +165,6 @@ public class CorsConfigurerTests {
@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"));
@@ -184,7 +173,6 @@ public class CorsConfigurerTests {
@Test
public void optionsWhenConfigSourceInLambdaConfigAndCorsFilterBeanThenRespondsWithCorsHeaders() throws Exception {
this.spring.register(CorsFilterInLambdaConfig.class).autowire();
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())

View File

@@ -50,43 +50,31 @@ public class CsrfConfigurerIgnoringRequestMatchersTests {
@Test
public void requestWhenIgnoringRequestMatchersThenAugmentedByConfiguredRequestMatcher() throws Exception {
this.spring.register(IgnoringRequestMatchers.class, BasicController.class).autowire();
this.mvc.perform(get("/path")).andExpect(status().isForbidden());
this.mvc.perform(post("/path")).andExpect(status().isOk());
}
@Test
public void requestWhenIgnoringRequestMatchersInLambdaThenAugmentedByConfiguredRequestMatcher() throws Exception {
this.spring.register(IgnoringRequestInLambdaMatchers.class, BasicController.class).autowire();
this.mvc.perform(get("/path")).andExpect(status().isForbidden());
this.mvc.perform(post("/path")).andExpect(status().isOk());
}
@Test
public void requestWhenIgnoringRequestMatcherThenUnionsWithConfiguredIgnoringAntMatchers() throws Exception {
this.spring.register(IgnoringPathsAndMatchers.class, BasicController.class).autowire();
this.mvc.perform(put("/csrf")).andExpect(status().isForbidden());
this.mvc.perform(post("/csrf")).andExpect(status().isOk());
this.mvc.perform(put("/no-csrf")).andExpect(status().isOk());
}
@Test
public void requestWhenIgnoringRequestMatcherInLambdaThenUnionsWithConfiguredIgnoringAntMatchers()
throws Exception {
this.spring.register(IgnoringPathsAndMatchersInLambdaConfig.class, BasicController.class).autowire();
this.mvc.perform(put("/csrf")).andExpect(status().isForbidden());
this.mvc.perform(post("/csrf")).andExpect(status().isOk());
this.mvc.perform(put("/no-csrf")).andExpect(status().isOk());
}

View File

@@ -50,21 +50,18 @@ public class CsrfConfigurerNoWebMvcTests {
@Test
public void missingDispatcherServletPreventsCsrfRequestDataValueProcessor() {
loadContext(EnableWebConfig.class);
assertThat(this.context.containsBeanDefinition("requestDataValueProcessor")).isTrue();
}
@Test
public void findDispatcherServletPreventsCsrfRequestDataValueProcessor() {
loadContext(EnableWebMvcConfig.class);
assertThat(this.context.containsBeanDefinition("requestDataValueProcessor")).isTrue();
}
@Test
public void overrideCsrfRequestDataValueProcessor() {
loadContext(EnableWebOverrideRequestDataConfig.class);
assertThat(this.context.getBean(RequestDataValueProcessor.class).getClass())
.isNotEqualTo(CsrfRequestDataValueProcessor.class);
}

View File

@@ -96,7 +96,6 @@ public class CsrfConfigurerTests {
this.spring
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
.autowire();
this.mvc.perform(post("/")).andExpect(status().isForbidden());
}
@@ -105,7 +104,6 @@ public class CsrfConfigurerTests {
this.spring
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
.autowire();
this.mvc.perform(put("/")).andExpect(status().isForbidden());
}
@@ -114,7 +112,6 @@ public class CsrfConfigurerTests {
this.spring
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
.autowire();
this.mvc.perform(patch("/")).andExpect(status().isForbidden());
}
@@ -123,7 +120,6 @@ public class CsrfConfigurerTests {
this.spring
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
.autowire();
this.mvc.perform(delete("/")).andExpect(status().isForbidden());
}
@@ -132,7 +128,6 @@ public class CsrfConfigurerTests {
this.spring
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
.autowire();
this.mvc.perform(request("INVALID", URI.create("/"))).andExpect(status().isForbidden());
}
@@ -141,7 +136,6 @@ public class CsrfConfigurerTests {
this.spring
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
.autowire();
this.mvc.perform(get("/")).andExpect(status().isOk());
}
@@ -150,7 +144,6 @@ public class CsrfConfigurerTests {
this.spring
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
.autowire();
this.mvc.perform(head("/")).andExpect(status().isOk());
}
@@ -159,7 +152,6 @@ public class CsrfConfigurerTests {
this.spring
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
.autowire();
this.mvc.perform(request(HttpMethod.TRACE, "/")).andExpect(status().isOk());
}
@@ -168,28 +160,24 @@ public class CsrfConfigurerTests {
this.spring
.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
.autowire();
this.mvc.perform(options("/")).andExpect(status().isOk());
}
@Test
public void enableWebSecurityWhenDefaultConfigurationThenCreatesRequestDataValueProcessor() {
this.spring.register(CsrfAppliedDefaultConfig.class, AllowHttpMethodsFirewallConfig.class).autowire();
assertThat(this.spring.getContext().getBean(RequestDataValueProcessor.class)).isNotNull();
}
@Test
public void postWhenCsrfDisabledThenRespondsWithOk() throws Exception {
this.spring.register(DisableCsrfConfig.class, BasicController.class).autowire();
this.mvc.perform(post("/")).andExpect(status().isOk());
}
@Test
public void postWhenCsrfDisabledInLambdaThenRespondsWithOk() throws Exception {
this.spring.register(DisableCsrfInLambdaConfig.class, BasicController.class).autowire();
this.mvc.perform(post("/")).andExpect(status().isOk());
}
@@ -197,9 +185,7 @@ public class CsrfConfigurerTests {
@Test
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"));
@@ -212,12 +198,10 @@ public class CsrfConfigurerTests {
given(CsrfDisablesPostRequestFromRequestCacheConfig.REPO.loadToken(any())).willReturn(csrfToken);
given(CsrfDisablesPostRequestFromRequestCacheConfig.REPO.generateToken(any())).willReturn(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("/"));
verify(CsrfDisablesPostRequestFromRequestCacheConfig.REPO, atLeastOnce())
.loadToken(any(HttpServletRequest.class));
}
@@ -229,12 +213,10 @@ public class CsrfConfigurerTests {
given(CsrfDisablesPostRequestFromRequestCacheConfig.REPO.loadToken(any())).willReturn(csrfToken);
given(CsrfDisablesPostRequestFromRequestCacheConfig.REPO.generateToken(any())).willReturn(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"));
verify(CsrfDisablesPostRequestFromRequestCacheConfig.REPO, atLeastOnce())
.loadToken(any(HttpServletRequest.class));
}
@@ -243,10 +225,8 @@ public class CsrfConfigurerTests {
@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();
this.mvc.perform(post("/").session((MockHttpSession) mvcResult.getRequest().getSession()))
.andExpect(status().isForbidden());
}
@@ -255,7 +235,6 @@ public class CsrfConfigurerTests {
public void requireCsrfProtectionMatcherWhenRequestDoesNotMatchThenRespondsWithOk() throws Exception {
this.spring.register(RequireCsrfProtectionMatcherConfig.class, BasicController.class).autowire();
given(RequireCsrfProtectionMatcherConfig.MATCHER.matches(any())).willReturn(false);
this.mvc.perform(get("/")).andExpect(status().isOk());
}
@@ -264,7 +243,6 @@ public class CsrfConfigurerTests {
RequireCsrfProtectionMatcherConfig.MATCHER = mock(RequestMatcher.class);
given(RequireCsrfProtectionMatcherConfig.MATCHER.matches(any())).willReturn(true);
this.spring.register(RequireCsrfProtectionMatcherConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isForbidden());
}
@@ -273,7 +251,6 @@ public class CsrfConfigurerTests {
RequireCsrfProtectionMatcherInLambdaConfig.MATCHER = mock(RequestMatcher.class);
this.spring.register(RequireCsrfProtectionMatcherInLambdaConfig.class, BasicController.class).autowire();
given(RequireCsrfProtectionMatcherInLambdaConfig.MATCHER.matches(any())).willReturn(false);
this.mvc.perform(get("/")).andExpect(status().isOk());
}
@@ -282,7 +259,6 @@ public class CsrfConfigurerTests {
RequireCsrfProtectionMatcherInLambdaConfig.MATCHER = mock(RequestMatcher.class);
given(RequireCsrfProtectionMatcherInLambdaConfig.MATCHER.matches(any())).willReturn(true);
this.spring.register(RequireCsrfProtectionMatcherInLambdaConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isForbidden());
}
@@ -292,7 +268,6 @@ public class CsrfConfigurerTests {
given(CsrfTokenRepositoryConfig.REPO.loadToken(any()))
.willReturn(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).loadToken(any(HttpServletRequest.class));
}
@@ -301,9 +276,7 @@ public class CsrfConfigurerTests {
public void logoutWhenCustomCsrfTokenRepositoryThenCsrfTokenIsCleared() throws Exception {
CsrfTokenRepositoryConfig.REPO = mock(CsrfTokenRepository.class);
this.spring.register(CsrfTokenRepositoryConfig.class, BasicController.class).autowire();
this.mvc.perform(post("/logout").with(csrf()).with(user("user")));
verify(CsrfTokenRepositoryConfig.REPO).saveToken(isNull(), any(HttpServletRequest.class),
any(HttpServletResponse.class));
}
@@ -315,10 +288,8 @@ public class CsrfConfigurerTests {
given(CsrfTokenRepositoryConfig.REPO.loadToken(any())).willReturn(csrfToken);
given(CsrfTokenRepositoryConfig.REPO.generateToken(any())).willReturn(csrfToken);
this.spring.register(CsrfTokenRepositoryConfig.class, BasicController.class).autowire();
this.mvc.perform(post("/login").with(csrf()).param("username", "user").param("password", "password"))
.andExpect(redirectedUrl("/"));
verify(CsrfTokenRepositoryConfig.REPO).saveToken(isNull(), any(HttpServletRequest.class),
any(HttpServletResponse.class));
}
@@ -329,7 +300,6 @@ public class CsrfConfigurerTests {
given(CsrfTokenRepositoryInLambdaConfig.REPO.loadToken(any()))
.willReturn(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).loadToken(any(HttpServletRequest.class));
}
@@ -338,9 +308,7 @@ public class CsrfConfigurerTests {
public void getWhenCustomAccessDeniedHandlerThenHandlerIsUsed() throws Exception {
AccessDeniedHandlerConfig.DENIED_HANDLER = mock(AccessDeniedHandler.class);
this.spring.register(AccessDeniedHandlerConfig.class, BasicController.class).autowire();
this.mvc.perform(post("/")).andExpect(status().isOk());
verify(AccessDeniedHandlerConfig.DENIED_HANDLER).handle(any(HttpServletRequest.class),
any(HttpServletResponse.class), any());
}
@@ -348,7 +316,6 @@ public class CsrfConfigurerTests {
@Test
public void loginWhenNoCsrfTokenThenRespondsWithForbidden() throws Exception {
this.spring.register(FormLoginConfig.class).autowire();
this.mvc.perform(post("/login").param("username", "user").param("password", "password"))
.andExpect(status().isForbidden()).andExpect(unauthenticated());
}
@@ -356,7 +323,6 @@ public class CsrfConfigurerTests {
@Test
public void logoutWhenNoCsrfTokenThenRespondsWithForbidden() throws Exception {
this.spring.register(FormLoginConfig.class).autowire();
this.mvc.perform(post("/logout").with(user("username"))).andExpect(status().isForbidden())
.andExpect(authenticated());
}
@@ -365,14 +331,12 @@ public class CsrfConfigurerTests {
@Test
public void logoutWhenCsrfEnabledAndGetRequestThenDoesNotLogout() throws Exception {
this.spring.register(FormLoginConfig.class).autowire();
this.mvc.perform(get("/logout").with(user("username"))).andExpect(authenticated());
}
@Test
public void logoutWhenGetRequestAndGetEnabledForLogoutThenLogsOut() throws Exception {
this.spring.register(LogoutAllowsGetConfig.class).autowire();
this.mvc.perform(get("/logout").with(user("username"))).andExpect(unauthenticated());
}
@@ -386,9 +350,7 @@ public class CsrfConfigurerTests {
@Test
public void getWhenDefaultCsrfTokenRepositoryThenDoesNotCreateSession() throws Exception {
this.spring.register(DefaultDoesNotCreateSession.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/")).andReturn();
assertThat(mvcResult.getRequest().getSession(false)).isNull();
}
@@ -401,12 +363,9 @@ public class CsrfConfigurerTests {
@Test
public void csrfAuthenticationStrategyConfiguredThenStrategyUsed() throws Exception {
CsrfAuthenticationStrategyConfig.STRATEGY = mock(SessionAuthenticationStrategy.class);
this.spring.register(CsrfAuthenticationStrategyConfig.class).autowire();
this.mvc.perform(post("/login").with(csrf()).param("username", "user").param("password", "password"))
.andExpect(redirectedUrl("/"));
verify(CsrfAuthenticationStrategyConfig.STRATEGY, atLeastOnce()).onAuthentication(any(Authentication.class),
any(HttpServletRequest.class), any(HttpServletResponse.class));
}

View File

@@ -100,10 +100,8 @@ public class DefaultFiltersTests {
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());
assertThat(classes.contains(WebAsyncManagerIntegrationFilter.class)).isTrue();
@@ -125,11 +123,9 @@ public class DefaultFiltersTests {
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest("POST", "");
request.setServletPath("/logout");
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());
assertThat(response.getRedirectedUrl()).isEqualTo("/login?logout");

View File

@@ -68,7 +68,6 @@ public class DefaultLoginPageConfigurerTests {
@Test
public void getWhenFormLoginEnabledThenRedirectsToLoginPage() throws Exception {
this.spring.register(DefaultLoginPageConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(redirectedUrl("http://localhost/login"));
}
@@ -77,7 +76,6 @@ public class DefaultLoginPageConfigurerTests {
this.spring.register(DefaultLoginPageConfig.class).autowire();
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "BaseSpringSpec_CSRFTOKEN");
String csrfAttributeName = HttpSessionCsrfTokenRepository.class.getName().concat(".CSRF_TOKEN");
this.mvc.perform(get("/login").sessionAttr(csrfAttributeName, csrfToken))
.andExpect(content().string("<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + " <head>\n"
+ " <meta charset=\"utf-8\">\n"
@@ -103,7 +101,6 @@ public class DefaultLoginPageConfigurerTests {
@Test
public void loginWhenNoCredentialsThenRedirectedToLoginPageWithError() throws Exception {
this.spring.register(DefaultLoginPageConfig.class).autowire();
this.mvc.perform(post("/login").with(csrf())).andExpect(redirectedUrl("/login?error"));
}
@@ -112,9 +109,7 @@ public class DefaultLoginPageConfigurerTests {
this.spring.register(DefaultLoginPageConfig.class).autowire();
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "BaseSpringSpec_CSRFTOKEN");
String csrfAttributeName = HttpSessionCsrfTokenRepository.class.getName().concat(".CSRF_TOKEN");
MvcResult mvcResult = this.mvc.perform(post("/login").with(csrf())).andReturn();
this.mvc.perform(get("/login?error").session((MockHttpSession) mvcResult.getRequest().getSession())
.sessionAttr(csrfAttributeName, csrfToken))
.andExpect(content().string("<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + " <head>\n"
@@ -142,7 +137,6 @@ public class DefaultLoginPageConfigurerTests {
@Test
public void loginWhenValidCredentialsThenRedirectsToDefaultSuccessPage() throws Exception {
this.spring.register(DefaultLoginPageConfig.class).autowire();
this.mvc.perform(post("/login").with(csrf()).param("username", "user").param("password", "password"))
.andExpect(redirectedUrl("/"));
}
@@ -152,7 +146,6 @@ public class DefaultLoginPageConfigurerTests {
this.spring.register(DefaultLoginPageConfig.class).autowire();
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "BaseSpringSpec_CSRFTOKEN");
String csrfAttributeName = HttpSessionCsrfTokenRepository.class.getName().concat(".CSRF_TOKEN");
this.mvc.perform(get("/login?logout").sessionAttr(csrfAttributeName, csrfToken))
.andExpect(content().string("<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + " <head>\n"
+ " <meta charset=\"utf-8\">\n"
@@ -179,14 +172,12 @@ public class DefaultLoginPageConfigurerTests {
@Test
public void loginPageWhenLoggedOutAndCustomLogoutSuccessHandlerThenDoesNotRenderLoginPage() throws Exception {
this.spring.register(DefaultLoginPageCustomLogoutSuccessHandlerConfig.class).autowire();
this.mvc.perform(get("/login?logout")).andExpect(content().string(""));
}
@Test
public void loginPageWhenLoggedOutAndCustomLogoutSuccessUrlThenDoesNotRenderLoginPage() throws Exception {
this.spring.register(DefaultLoginPageCustomLogoutSuccessUrlConfig.class).autowire();
this.mvc.perform(get("/login?logout")).andExpect(content().string(""));
}
@@ -195,7 +186,6 @@ public class DefaultLoginPageConfigurerTests {
this.spring.register(DefaultLoginPageWithRememberMeConfig.class).autowire();
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "BaseSpringSpec_CSRFTOKEN");
String csrfAttributeName = HttpSessionCsrfTokenRepository.class.getName().concat(".CSRF_TOKEN");
this.mvc.perform(get("/login").sessionAttr(csrfAttributeName, csrfToken))
.andExpect(content().string("<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + " <head>\n"
+ " <meta charset=\"utf-8\">\n"
@@ -223,10 +213,8 @@ public class DefaultLoginPageConfigurerTests {
@Test
public void loginPageWhenOpenIdLoginConfiguredThenOpedIdLoginPage() throws Exception {
this.spring.register(DefaultLoginPageWithOpenIDConfig.class).autowire();
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "BaseSpringSpec_CSRFTOKEN");
String csrfAttributeName = HttpSessionCsrfTokenRepository.class.getName().concat(".CSRF_TOKEN");
this.mvc.perform(get("/login").sessionAttr(csrfAttributeName, csrfToken))
.andExpect(content().string("<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + " <head>\n"
+ " <meta charset=\"utf-8\">\n"
@@ -251,7 +239,6 @@ public class DefaultLoginPageConfigurerTests {
this.spring.register(DefaultLoginPageWithFormLoginOpenIDRememberMeConfig.class).autowire();
CsrfToken csrfToken = new DefaultCsrfToken("X-CSRF-TOKEN", "_csrf", "BaseSpringSpec_CSRFTOKEN");
String csrfAttributeName = HttpSessionCsrfTokenRepository.class.getName().concat(".CSRF_TOKEN");
this.mvc.perform(get("/login").sessionAttr(csrfAttributeName, csrfToken))
.andExpect(content().string("<!DOCTYPE html>\n" + "<html lang=\"en\">\n" + " <head>\n"
+ " <meta charset=\"utf-8\">\n"
@@ -290,7 +277,6 @@ public class DefaultLoginPageConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnDefaultLoginPageGeneratingFilter() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(DefaultLoginPageGeneratingFilter.class));
}
@@ -298,7 +284,6 @@ public class DefaultLoginPageConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnUsernamePasswordAuthenticationFilter() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor)
.postProcess(any(UsernamePasswordAuthenticationFilter.class));
}
@@ -307,7 +292,6 @@ public class DefaultLoginPageConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnLoginUrlAuthenticationEntryPoint() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(LoginUrlAuthenticationEntryPoint.class));
}
@@ -315,14 +299,12 @@ public class DefaultLoginPageConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnExceptionTranslationFilter() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(ExceptionTranslationFilter.class));
}
@Test
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())

View File

@@ -55,9 +55,7 @@ public class ExceptionHandlingConfigurerAccessDeniedHandlerTests {
@WithMockUser(roles = "ANYTHING")
public void getWhenAccessDeniedOverriddenThenCustomizesResponseByRequest() throws Exception {
this.spring.register(RequestMatcherBasedAccessDeniedHandlerConfig.class).autowire();
this.mvc.perform(get("/hello")).andExpect(status().isIAmATeapot());
this.mvc.perform(get("/goodbye")).andExpect(status().isForbidden());
}
@@ -65,9 +63,7 @@ public class ExceptionHandlingConfigurerAccessDeniedHandlerTests {
@WithMockUser(roles = "ANYTHING")
public void getWhenAccessDeniedOverriddenInLambdaThenCustomizesResponseByRequest() throws Exception {
this.spring.register(RequestMatcherBasedAccessDeniedHandlerInLambdaConfig.class).autowire();
this.mvc.perform(get("/hello")).andExpect(status().isIAmATeapot());
this.mvc.perform(get("/goodbye")).andExpect(status().isForbidden());
}
@@ -75,9 +71,7 @@ public class ExceptionHandlingConfigurerAccessDeniedHandlerTests {
@WithMockUser(roles = "ANYTHING")
public void getWhenAccessDeniedOverriddenByOnlyOneHandlerThenAllRequestsUseThatHandler() throws Exception {
this.spring.register(SingleRequestMatcherAccessDeniedHandlerConfig.class).autowire();
this.mvc.perform(get("/hello")).andExpect(status().isIAmATeapot());
this.mvc.perform(get("/goodbye")).andExpect(status().isIAmATeapot());
}

View File

@@ -67,7 +67,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnExceptionTranslationFilter() {
this.spring.register(ObjectPostProcessorConfig.class, DefaultSecurityConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(ExceptionTranslationFilter.class));
}
@@ -75,7 +74,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
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());
}
@@ -84,7 +82,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenAcceptHeaderIsImageGifThenRespondsWith302() throws Exception {
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.IMAGE_GIF)).andExpect(status().isFound());
}
@@ -92,7 +89,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenAcceptHeaderIsImageJpgThenRespondsWith302() throws Exception {
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.IMAGE_JPEG)).andExpect(status().isFound());
}
@@ -100,7 +96,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenAcceptHeaderIsImagePngThenRespondsWith302() throws Exception {
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.IMAGE_PNG)).andExpect(status().isFound());
}
@@ -108,7 +103,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenAcceptHeaderIsTextHtmlThenRespondsWith302() throws Exception {
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.TEXT_HTML)).andExpect(status().isFound());
}
@@ -116,7 +110,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenAcceptHeaderIsTextPlainThenRespondsWith302() throws Exception {
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.TEXT_PLAIN)).andExpect(status().isFound());
}
@@ -124,7 +117,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
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());
}
@@ -133,7 +125,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
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());
}
@@ -142,7 +133,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenAcceptHeaderIsApplicationJsonThenRespondsWith401() throws Exception {
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON))
.andExpect(status().isUnauthorized());
}
@@ -151,7 +141,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
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());
}
@@ -160,7 +149,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
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());
}
@@ -169,7 +157,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenAcceptHeaderIsTextXmlThenRespondsWith401() throws Exception {
this.spring.register(HttpBasicAndFormLoginEntryPointsConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.TEXT_XML)).andExpect(status().isUnauthorized());
}
@@ -177,14 +164,12 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenAcceptIsAnyThenRespondsWith401() throws Exception {
this.spring.register(DefaultSecurityConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, MediaType.ALL)).andExpect(status().isUnauthorized());
}
@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());
@@ -193,7 +178,6 @@ public class ExceptionHandlingConfigurerTests {
@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());
}
@@ -202,9 +186,7 @@ public class ExceptionHandlingConfigurerTests {
public void getWhenCustomContentNegotiationStrategyThenStrategyIsUsed() throws Exception {
this.spring.register(OverrideContentNegotiationStrategySharedObjectConfig.class, DefaultSecurityConfig.class)
.autowire();
this.mvc.perform(get("/"));
verify(OverrideContentNegotiationStrategySharedObjectConfig.CNS, atLeastOnce())
.resolveMediaTypes(any(NativeWebRequest.class));
}
@@ -212,7 +194,6 @@ public class ExceptionHandlingConfigurerTests {
@Test
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"));
}
@@ -220,16 +201,13 @@ public class ExceptionHandlingConfigurerTests {
@Test
public void getWhenDeclaringHttpBasicBeforeFormLoginThenRespondsWith401() throws Exception {
this.spring.register(BasicAuthenticationEntryPointBeforeFormLoginConfig.class).autowire();
this.mvc.perform(get("/").header(HttpHeaders.ACCEPT, "bogus/type")).andExpect(status().isUnauthorized());
}
@Test
public void getWhenInvokingExceptionHandlingTwiceThenOriginalEntryPointUsed() throws Exception {
this.spring.register(InvokeTwiceDoesNotOverrideConfig.class).autowire();
this.mvc.perform(get("/"));
verify(InvokeTwiceDoesNotOverrideConfig.AEP).commence(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(AuthenticationException.class));
}
@@ -278,17 +256,14 @@ public class ExceptionHandlingConfigurerTests {
// @formatter:off
}
}
@EnableWebSecurity
static class HttpBasicAndFormLoginEntryPointsConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off

View File

@@ -93,7 +93,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void configureWhenNoCustomAccessDecisionManagerThenUsesAffirmativeBased() {
this.spring.register(NoSpecificAccessDecisionManagerConfig.class).autowire();
verify(NoSpecificAccessDecisionManagerConfig.objectPostProcessor).postProcess(any(AffirmativeBased.class));
}
@@ -113,7 +112,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void getWhenHasAnyAuthorityRoleUserConfiguredAndAuthorityIsRoleUserThenRespondsWithOk() throws Exception {
this.spring.register(RoleUserAnyAuthorityConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").authorities(new SimpleGrantedAuthority("ROLE_USER"))))
.andExpect(status().isOk());
}
@@ -122,7 +120,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
public void getWhenHasAnyAuthorityRoleUserConfiguredAndAuthorityIsRoleAdminThenRespondsWithForbidden()
throws Exception {
this.spring.register(RoleUserAnyAuthorityConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").authorities(new SimpleGrantedAuthority("ROLE_ADMIN"))))
.andExpect(status().isForbidden());
}
@@ -130,14 +127,12 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void getWhenHasAnyAuthorityRoleUserConfiguredAndNoAuthorityThenRespondsWithUnauthorized() throws Exception {
this.spring.register(RoleUserAnyAuthorityConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isUnauthorized());
}
@Test
public void getWhenHasAuthorityRoleUserConfiguredAndAuthorityIsRoleUserThenRespondsWithOk() throws Exception {
this.spring.register(RoleUserAuthorityConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").authorities(new SimpleGrantedAuthority("ROLE_USER"))))
.andExpect(status().isOk());
}
@@ -146,7 +141,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
public void getWhenHasAuthorityRoleUserConfiguredAndAuthorityIsRoleAdminThenRespondsWithForbidden()
throws Exception {
this.spring.register(RoleUserAuthorityConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").authorities(new SimpleGrantedAuthority("ROLE_ADMIN"))))
.andExpect(status().isForbidden());
}
@@ -154,14 +148,12 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void getWhenHasAuthorityRoleUserConfiguredAndNoAuthorityThenRespondsWithUnauthorized() throws Exception {
this.spring.register(RoleUserAuthorityConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isUnauthorized());
}
@Test
public void getWhenAuthorityRoleUserOrAdminRequiredAndAuthorityIsRoleUserThenRespondsWithOk() throws Exception {
this.spring.register(RoleUserOrRoleAdminAuthorityConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").authorities(new SimpleGrantedAuthority("ROLE_USER"))))
.andExpect(status().isOk());
}
@@ -169,7 +161,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void getWhenAuthorityRoleUserOrAdminRequiredAndAuthorityIsRoleAdminThenRespondsWithOk() throws Exception {
this.spring.register(RoleUserOrRoleAdminAuthorityConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").authorities(new SimpleGrantedAuthority("ROLE_ADMIN"))))
.andExpect(status().isOk());
}
@@ -178,7 +169,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
public void getWhenAuthorityRoleUserOrAdminRequiredAndAuthorityIsRoleOtherThenRespondsWithForbidden()
throws Exception {
this.spring.register(RoleUserOrRoleAdminAuthorityConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").authorities(new SimpleGrantedAuthority("ROLE_OTHER"))))
.andExpect(status().isForbidden());
}
@@ -186,49 +176,42 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void getWhenAuthorityRoleUserOrAdminAuthRequiredAndNoUserThenRespondsWithUnauthorized() throws Exception {
this.spring.register(RoleUserOrRoleAdminAuthorityConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isUnauthorized());
}
@Test
public void getWhenHasAnyRoleUserConfiguredAndRoleIsUserThenRespondsWithOk() throws Exception {
this.spring.register(RoleUserConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").roles("USER"))).andExpect(status().isOk());
}
@Test
public void getWhenHasAnyRoleUserConfiguredAndRoleIsAdminThenRespondsWithForbidden() throws Exception {
this.spring.register(RoleUserConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").roles("ADMIN"))).andExpect(status().isForbidden());
}
@Test
public void getWhenRoleUserOrAdminConfiguredAndRoleIsUserThenRespondsWithOk() throws Exception {
this.spring.register(RoleUserOrAdminConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").roles("USER"))).andExpect(status().isOk());
}
@Test
public void getWhenRoleUserOrAdminConfiguredAndRoleIsAdminThenRespondsWithOk() throws Exception {
this.spring.register(RoleUserOrAdminConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").roles("ADMIN"))).andExpect(status().isOk());
}
@Test
public void getWhenRoleUserOrAdminConfiguredAndRoleIsOtherThenRespondsWithForbidden() throws Exception {
this.spring.register(RoleUserOrAdminConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").roles("OTHER"))).andExpect(status().isForbidden());
}
@Test
public void getWhenHasIpAddressConfiguredAndIpAddressMatchesThenRespondsWithOk() throws Exception {
this.spring.register(HasIpAddressConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with((request) -> {
request.setRemoteAddr("192.168.1.0");
return request;
@@ -238,7 +221,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void getWhenHasIpAddressConfiguredAndIpAddressDoesNotMatchThenRespondsWithUnauthorized() throws Exception {
this.spring.register(HasIpAddressConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with((request) -> {
request.setRemoteAddr("192.168.1.1");
return request;
@@ -248,28 +230,24 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void getWhenAnonymousConfiguredAndAnonymousUserThenRespondsWithOk() throws Exception {
this.spring.register(AnonymousConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isOk());
}
@Test
public void getWhenAnonymousConfiguredAndLoggedInUserThenRespondsWithForbidden() throws Exception {
this.spring.register(AnonymousConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user"))).andExpect(status().isForbidden());
}
@Test
public void getWhenRememberMeConfiguredAndNoUserThenRespondsWithUnauthorized() throws Exception {
this.spring.register(RememberMeConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isUnauthorized());
}
@Test
public void getWhenRememberMeConfiguredAndRememberMeTokenThenRespondsWithOk() throws Exception {
this.spring.register(RememberMeConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(authentication(
new RememberMeAuthenticationToken("key", "user", AuthorityUtils.createAuthorityList("ROLE_USER")))))
.andExpect(status().isOk());
@@ -278,28 +256,24 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void getWhenDenyAllConfiguredAndNoUserThenRespondsWithUnauthorized() throws Exception {
this.spring.register(DenyAllConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isUnauthorized());
}
@Test
public void getWheDenyAllConfiguredAndUserLoggedInThenRespondsWithForbidden() throws Exception {
this.spring.register(DenyAllConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").roles("USER"))).andExpect(status().isForbidden());
}
@Test
public void getWhenNotDenyAllConfiguredAndNoUserThenRespondsWithOk() throws Exception {
this.spring.register(NotDenyAllConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isOk());
}
@Test
public void getWhenNotDenyAllConfiguredAndRememberMeTokenThenRespondsWithOk() throws Exception {
this.spring.register(NotDenyAllConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(authentication(
new RememberMeAuthenticationToken("key", "user", AuthorityUtils.createAuthorityList("ROLE_USER")))))
.andExpect(status().isOk());
@@ -308,7 +282,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void getWhenFullyAuthenticatedConfiguredAndRememberMeTokenThenRespondsWithUnauthorized() throws Exception {
this.spring.register(FullyAuthenticatedConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(authentication(
new RememberMeAuthenticationToken("key", "user", AuthorityUtils.createAuthorityList("ROLE_USER")))))
.andExpect(status().isUnauthorized());
@@ -317,35 +290,30 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void getWhenFullyAuthenticatedConfiguredAndUserThenRespondsWithOk() throws Exception {
this.spring.register(FullyAuthenticatedConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/").with(user("user").roles("USER"))).andExpect(status().isOk());
}
@Test
public void getWhenAccessRoleUserOrGetRequestConfiguredThenRespondsWithOk() throws Exception {
this.spring.register(AccessConfig.class, BasicController.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isOk());
}
@Test
public void postWhenAccessRoleUserOrGetRequestConfiguredAndRoleUserThenRespondsWithOk() throws Exception {
this.spring.register(AccessConfig.class, BasicController.class).autowire();
this.mvc.perform(post("/").with(csrf()).with(user("user").roles("USER"))).andExpect(status().isOk());
}
@Test
public void postWhenAccessRoleUserOrGetRequestConfiguredThenRespondsWithUnauthorized() throws Exception {
this.spring.register(AccessConfig.class, BasicController.class).autowire();
this.mvc.perform(post("/").with(csrf())).andExpect(status().isUnauthorized());
}
@Test
public void authorizeRequestsWhenInvokedTwiceThenUsesOriginalConfiguration() throws Exception {
this.spring.register(InvokeTwiceDoesNotResetConfig.class, BasicController.class).autowire();
this.mvc.perform(post("/").with(csrf())).andExpect(status().isUnauthorized());
}
@@ -358,58 +326,49 @@ public class ExpressionUrlAuthorizationConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenApplicationListenerInvokedOnAuthorizedEvent()
throws Exception {
this.spring.register(AuthorizedRequestsWithPostProcessorConfig.class).autowire();
this.mvc.perform(get("/"));
verify(AuthorizedRequestsWithPostProcessorConfig.AL).onApplicationEvent(any(AuthorizedEvent.class));
}
@Test
public void getWhenPermissionCheckAndRoleDoesNotMatchThenRespondsWithForbidden() throws Exception {
this.spring.register(UseBeansInExpressions.class, WildcardController.class).autowire();
this.mvc.perform(get("/admin").with(user("user").roles("USER"))).andExpect(status().isForbidden());
}
@Test
public void getWhenPermissionCheckAndRoleMatchesThenRespondsWithOk() throws Exception {
this.spring.register(UseBeansInExpressions.class, WildcardController.class).autowire();
this.mvc.perform(get("/user").with(user("user").roles("USER"))).andExpect(status().isOk());
}
@Test
public void getWhenPermissionCheckAndAuthenticationNameMatchesThenRespondsWithOk() throws Exception {
this.spring.register(UseBeansInExpressions.class, WildcardController.class).autowire();
this.mvc.perform(get("/allow").with(user("user").roles("USER"))).andExpect(status().isOk());
}
@Test
public void getWhenPermissionCheckAndAuthenticationNameDoesNotMatchThenRespondsWithForbidden() throws Exception {
this.spring.register(UseBeansInExpressions.class, WildcardController.class).autowire();
this.mvc.perform(get("/deny").with(user("user").roles("USER"))).andExpect(status().isForbidden());
}
@Test
public void getWhenCustomExpressionHandlerAndRoleDoesNotMatchThenRespondsWithForbidden() throws Exception {
this.spring.register(CustomExpressionRootConfig.class, WildcardController.class).autowire();
this.mvc.perform(get("/admin").with(user("user").roles("USER"))).andExpect(status().isForbidden());
}
@Test
public void getWhenCustomExpressionHandlerAndRoleMatchesThenRespondsWithOk() throws Exception {
this.spring.register(CustomExpressionRootConfig.class, WildcardController.class).autowire();
this.mvc.perform(get("/user").with(user("user").roles("USER"))).andExpect(status().isOk());
}
@Test
public void getWhenCustomExpressionHandlerAndAuthenticationNameMatchesThenRespondsWithOk() throws Exception {
this.spring.register(CustomExpressionRootConfig.class, WildcardController.class).autowire();
this.mvc.perform(get("/allow").with(user("user").roles("USER"))).andExpect(status().isOk());
}
@@ -417,7 +376,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
public void getWhenCustomExpressionHandlerAndAuthenticationNameDoesNotMatchThenRespondsWithForbidden()
throws Exception {
this.spring.register(CustomExpressionRootConfig.class, WildcardController.class).autowire();
this.mvc.perform(get("/deny").with(user("user").roles("USER"))).andExpect(status().isForbidden());
}
@@ -425,7 +383,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Test
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnAccessDecisionManager() {
this.spring.register(Sec3011Config.class).autowire();
verify(Sec3011Config.objectPostProcessor).postProcess(any(AccessDecisionManager.class));
}
@@ -433,7 +390,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
public void getWhenRegisteringPermissionEvaluatorAndPermissionWithIdAndTypeMatchesThenRespondsWithOk()
throws Exception {
this.spring.register(PermissionEvaluatorConfig.class, WildcardController.class).autowire();
this.mvc.perform(get("/allow")).andExpect(status().isOk());
}
@@ -441,7 +397,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
public void getWhenRegisteringPermissionEvaluatorAndPermissionWithIdAndTypeDoesNotMatchThenRespondsWithForbidden()
throws Exception {
this.spring.register(PermissionEvaluatorConfig.class, WildcardController.class).autowire();
this.mvc.perform(get("/deny")).andExpect(status().isForbidden());
}
@@ -449,7 +404,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
public void getWhenRegisteringPermissionEvaluatorAndPermissionWithObjectMatchesThenRespondsWithOk()
throws Exception {
this.spring.register(PermissionEvaluatorConfig.class, WildcardController.class).autowire();
this.mvc.perform(get("/allowObject")).andExpect(status().isOk());
}
@@ -457,21 +411,18 @@ public class ExpressionUrlAuthorizationConfigurerTests {
public void getWhenRegisteringPermissionEvaluatorAndPermissionWithObjectDoesNotMatchThenRespondsWithForbidden()
throws Exception {
this.spring.register(PermissionEvaluatorConfig.class, WildcardController.class).autowire();
this.mvc.perform(get("/denyObject")).andExpect(status().isForbidden());
}
@Test
public void getWhenRegisteringRoleHierarchyAndRelatedRoleAllowedThenRespondsWithOk() throws Exception {
this.spring.register(RoleHierarchyConfig.class, WildcardController.class).autowire();
this.mvc.perform(get("/allow").with(user("user").roles("USER"))).andExpect(status().isOk());
}
@Test
public void getWhenRegisteringRoleHierarchyAndNoRelatedRolesAllowedThenRespondsWithForbidden() throws Exception {
this.spring.register(RoleHierarchyConfig.class, WildcardController.class).autowire();
this.mvc.perform(get("/deny").with(user("user").roles("USER"))).andExpect(status().isForbidden());
}
@@ -939,7 +890,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
@Bean
PermissionEvaluator permissionEvaluator() {
return new PermissionEvaluator() {
@Override
public boolean hasPermission(Authentication authentication, Object targetDomainObject,
Object permission) {
@@ -951,7 +901,6 @@ public class ExpressionUrlAuthorizationConfigurerTests {
Object permission) {
return "ID".equals(targetId) && "TYPE".equals(targetType) && "PERMISSION".equals(permission);
}
};
}

View File

@@ -69,29 +69,22 @@ public class FormLoginConfigurerTests {
@Test
public void requestCache() throws Exception {
this.spring.register(RequestCacheConfig.class, AuthenticationTestConfiguration.class).autowire();
RequestCacheConfig config = this.spring.getContext().getBean(RequestCacheConfig.class);
this.mockMvc.perform(formLogin()).andExpect(authenticated());
verify(config.requestCache).getRequest(any(), any());
}
@Test
public void requestCacheAsBean() throws Exception {
this.spring.register(RequestCacheBeanConfig.class, AuthenticationTestConfiguration.class).autowire();
RequestCache requestCache = this.spring.getContext().getBean(RequestCache.class);
this.mockMvc.perform(formLogin()).andExpect(authenticated());
verify(requestCache).getRequest(any(), any());
}
@Test
public void loginWhenFormLoginConfiguredThenHasDefaultUsernameAndPasswordParameterNames() throws Exception {
this.spring.register(FormLoginConfig.class).autowire();
this.mockMvc.perform(formLogin().user("username", "user").password("password", "password"))
.andExpect(status().isFound()).andExpect(redirectedUrl("/"));
}
@@ -99,7 +92,6 @@ public class FormLoginConfigurerTests {
@Test
public void loginWhenFormLoginConfiguredThenHasDefaultFailureUrl() throws Exception {
this.spring.register(FormLoginConfig.class).autowire();
this.mockMvc.perform(formLogin().user("invalid")).andExpect(status().isFound())
.andExpect(redirectedUrl("/login?error"));
}
@@ -107,28 +99,24 @@ public class FormLoginConfigurerTests {
@Test
public void loginWhenFormLoginConfiguredThenHasDefaultSuccessUrl() throws Exception {
this.spring.register(FormLoginConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(status().isFound()).andExpect(redirectedUrl("/"));
}
@Test
public void getLoginPageWhenFormLoginConfiguredThenNotSecured() throws Exception {
this.spring.register(FormLoginConfig.class).autowire();
this.mockMvc.perform(get("/login")).andExpect(status().isFound());
}
@Test
public void loginWhenFormLoginConfiguredThenSecured() throws Exception {
this.spring.register(FormLoginConfig.class).autowire();
this.mockMvc.perform(post("/login")).andExpect(status().isForbidden());
}
@Test
public void requestProtectedWhenFormLoginConfiguredThenRedirectsToLogin() throws Exception {
this.spring.register(FormLoginConfig.class).autowire();
this.mockMvc.perform(get("/private")).andExpect(status().isFound())
.andExpect(redirectedUrl("http://localhost/login"));
}
@@ -136,7 +124,6 @@ public class FormLoginConfigurerTests {
@Test
public void loginWhenFormLoginDefaultsInLambdaThenHasDefaultUsernameAndPasswordParameterNames() throws Exception {
this.spring.register(FormLoginInLambdaConfig.class).autowire();
this.mockMvc.perform(formLogin().user("username", "user").password("password", "password"))
.andExpect(status().isFound()).andExpect(redirectedUrl("/"));
}
@@ -144,7 +131,6 @@ public class FormLoginConfigurerTests {
@Test
public void loginWhenFormLoginDefaultsInLambdaThenHasDefaultFailureUrl() throws Exception {
this.spring.register(FormLoginInLambdaConfig.class).autowire();
this.mockMvc.perform(formLogin().user("invalid")).andExpect(status().isFound())
.andExpect(redirectedUrl("/login?error"));
}
@@ -152,28 +138,24 @@ public class FormLoginConfigurerTests {
@Test
public void loginWhenFormLoginDefaultsInLambdaThenHasDefaultSuccessUrl() throws Exception {
this.spring.register(FormLoginInLambdaConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(status().isFound()).andExpect(redirectedUrl("/"));
}
@Test
public void getLoginPageWhenFormLoginDefaultsInLambdaThenNotSecured() throws Exception {
this.spring.register(FormLoginInLambdaConfig.class).autowire();
this.mockMvc.perform(get("/login")).andExpect(status().isOk());
}
@Test
public void loginWhenFormLoginDefaultsInLambdaThenSecured() throws Exception {
this.spring.register(FormLoginInLambdaConfig.class).autowire();
this.mockMvc.perform(post("/login")).andExpect(status().isForbidden());
}
@Test
public void requestProtectedWhenFormLoginDefaultsInLambdaThenRedirectsToLogin() throws Exception {
this.spring.register(FormLoginInLambdaConfig.class).autowire();
this.mockMvc.perform(get("/private")).andExpect(status().isFound())
.andExpect(redirectedUrl("http://localhost/login"));
}
@@ -181,21 +163,18 @@ public class FormLoginConfigurerTests {
@Test
public void getLoginPageWhenFormLoginPermitAllThenPermittedAndNoRedirect() throws Exception {
this.spring.register(FormLoginConfigPermitAll.class).autowire();
this.mockMvc.perform(get("/login")).andExpect(status().isOk()).andExpect(redirectedUrl(null));
}
@Test
public void getLoginPageWithErrorQueryWhenFormLoginPermitAllThenPermittedAndNoRedirect() throws Exception {
this.spring.register(FormLoginConfigPermitAll.class).autowire();
this.mockMvc.perform(get("/login?error")).andExpect(status().isOk()).andExpect(redirectedUrl(null));
}
@Test
public void loginWhenFormLoginPermitAllAndInvalidUserThenRedirectsToLoginPageWithError() throws Exception {
this.spring.register(FormLoginConfigPermitAll.class).autowire();
this.mockMvc.perform(formLogin().user("invalid")).andExpect(status().isFound())
.andExpect(redirectedUrl("/login?error"));
}
@@ -203,21 +182,18 @@ public class FormLoginConfigurerTests {
@Test
public void getLoginPageWhenCustomLoginPageThenPermittedAndNoRedirect() throws Exception {
this.spring.register(FormLoginDefaultsConfig.class).autowire();
this.mockMvc.perform(get("/authenticate")).andExpect(redirectedUrl(null));
}
@Test
public void getLoginPageWithErrorQueryWhenCustomLoginPageThenPermittedAndNoRedirect() throws Exception {
this.spring.register(FormLoginDefaultsConfig.class).autowire();
this.mockMvc.perform(get("/authenticate?error")).andExpect(redirectedUrl(null));
}
@Test
public void loginWhenCustomLoginPageAndInvalidUserThenRedirectsToCustomLoginPageWithError() throws Exception {
this.spring.register(FormLoginDefaultsConfig.class).autowire();
this.mockMvc.perform(formLogin("/authenticate").user("invalid")).andExpect(status().isFound())
.andExpect(redirectedUrl("/authenticate?error"));
}
@@ -225,35 +201,30 @@ public class FormLoginConfigurerTests {
@Test
public void logoutWhenCustomLoginPageThenRedirectsToCustomLoginPage() throws Exception {
this.spring.register(FormLoginDefaultsConfig.class).autowire();
this.mockMvc.perform(logout()).andExpect(redirectedUrl("/authenticate?logout"));
}
@Test
public void getLoginPageWithLogoutQueryWhenCustomLoginPageThenPermittedAndNoRedirect() throws Exception {
this.spring.register(FormLoginDefaultsConfig.class).autowire();
this.mockMvc.perform(get("/authenticate?logout")).andExpect(redirectedUrl(null));
}
@Test
public void getLoginPageWhenCustomLoginPageInLambdaThenPermittedAndNoRedirect() throws Exception {
this.spring.register(FormLoginDefaultsInLambdaConfig.class).autowire();
this.mockMvc.perform(get("/authenticate")).andExpect(redirectedUrl(null));
}
@Test
public void loginWhenCustomLoginProcessingUrlThenRedirectsToHome() throws Exception {
this.spring.register(FormLoginLoginProcessingUrlConfig.class).autowire();
this.mockMvc.perform(formLogin("/loginCheck")).andExpect(status().isFound()).andExpect(redirectedUrl("/"));
}
@Test
public void loginWhenCustomLoginProcessingUrlInLambdaThenRedirectsToHome() throws Exception {
this.spring.register(FormLoginLoginProcessingUrlInLambdaConfig.class).autowire();
this.mockMvc.perform(formLogin("/loginCheck")).andExpect(status().isFound()).andExpect(redirectedUrl("/"));
}
@@ -262,17 +233,14 @@ public class FormLoginConfigurerTests {
FormLoginUsesPortMapperConfig.PORT_MAPPER = mock(PortMapper.class);
given(FormLoginUsesPortMapperConfig.PORT_MAPPER.lookupHttpsPort(any())).willReturn(9443);
this.spring.register(FormLoginUsesPortMapperConfig.class).autowire();
this.mockMvc.perform(get("http://localhost:9090")).andExpect(status().isFound())
.andExpect(redirectedUrl("https://localhost:9443/login"));
verify(FormLoginUsesPortMapperConfig.PORT_MAPPER).lookupHttpsPort(any());
}
@Test
public void failureUrlWhenPermitAllAndFailureHandlerThenSecured() throws Exception {
this.spring.register(PermitAllIgnoresFailureHandlerConfig.class).autowire();
this.mockMvc.perform(get("/login?error")).andExpect(status().isFound())
.andExpect(redirectedUrl("http://localhost/login"));
}
@@ -280,21 +248,18 @@ public class FormLoginConfigurerTests {
@Test
public void formLoginWhenInvokedTwiceThenUsesOriginalUsernameParameter() throws Exception {
this.spring.register(DuplicateInvocationsDoesNotOverrideConfig.class).autowire();
this.mockMvc.perform(formLogin().user("custom-username", "user")).andExpect(authenticated());
}
@Test
public void loginWhenInvalidLoginAndFailureForwardUrlThenForwardsToFailureForwardUrl() throws Exception {
this.spring.register(FormLoginUserForwardAuthenticationSuccessAndFailureConfig.class).autowire();
this.mockMvc.perform(formLogin().user("invalid")).andExpect(forwardedUrl("/failure_forward_url"));
}
@Test
public void loginWhenSuccessForwardUrlThenForwardsToSuccessForwardUrl() throws Exception {
this.spring.register(FormLoginUserForwardAuthenticationSuccessAndFailureConfig.class).autowire();
this.mockMvc.perform(formLogin()).andExpect(forwardedUrl("/success_forward_url"));
}
@@ -302,7 +267,6 @@ public class FormLoginConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnUsernamePasswordAuthenticationFilter() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor)
.postProcess(any(UsernamePasswordAuthenticationFilter.class));
}
@@ -311,7 +275,6 @@ public class FormLoginConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnLoginUrlAuthenticationEntryPoint() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(LoginUrlAuthenticationEntryPoint.class));
}
@@ -319,7 +282,6 @@ public class FormLoginConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnExceptionTranslationFilter() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(ExceptionTranslationFilter.class));
}

View File

@@ -48,7 +48,6 @@ 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"))

View File

@@ -62,7 +62,6 @@ public class HeadersConfigurerTests {
@Test
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()))
@@ -80,7 +79,6 @@ public class HeadersConfigurerTests {
@Test
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()))
@@ -99,7 +97,6 @@ public class HeadersConfigurerTests {
public void getWhenHeaderDefaultsDisabledAndContentTypeConfiguredThenOnlyContentTypeHeaderInResponse()
throws Exception {
this.spring.register(ContentTypeOptionsConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/"))
.andExpect(header().string(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff")).andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_CONTENT_TYPE_OPTIONS);
@@ -108,7 +105,6 @@ public class HeadersConfigurerTests {
@Test
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();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_CONTENT_TYPE_OPTIONS);
@@ -118,7 +114,6 @@ public class HeadersConfigurerTests {
public void getWhenHeaderDefaultsDisabledAndFrameOptionsConfiguredThenOnlyFrameOptionsHeaderInResponse()
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();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_FRAME_OPTIONS);
@@ -128,7 +123,6 @@ public class HeadersConfigurerTests {
public void getWhenHeaderDefaultsDisabledAndHstsConfiguredThenOnlyStrictTransportSecurityHeaderInResponse()
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"))
@@ -140,7 +134,6 @@ public class HeadersConfigurerTests {
public void getWhenHeaderDefaultsDisabledAndCacheControlConfiguredThenCacheControlAndExpiresAndPragmaHeadersInResponse()
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"))
@@ -153,7 +146,6 @@ public class HeadersConfigurerTests {
public void getWhenOnlyCacheControlConfiguredInLambdaThenCacheControlAndExpiresAndPragmaHeadersInResponse()
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"))
@@ -166,7 +158,6 @@ public class HeadersConfigurerTests {
public void getWhenHeaderDefaultsDisabledAndXssProtectionConfiguredThenOnlyXssProtectionHeaderInResponse()
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();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_XSS_PROTECTION);
@@ -175,7 +166,6 @@ public class HeadersConfigurerTests {
@Test
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();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.X_XSS_PROTECTION);
@@ -184,7 +174,6 @@ public class HeadersConfigurerTests {
@Test
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();
@@ -194,7 +183,6 @@ public class HeadersConfigurerTests {
public void getWhenFrameOptionsSameOriginConfiguredInLambdaThenFrameOptionsHeaderHasValueSameOrigin()
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();
@@ -203,7 +191,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenHeaderDefaultsDisabledAndPublicHpkpWithNoPinThenNoHeadersInResponse() throws Exception {
this.spring.register(HpkpConfigNoPins.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/")).andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).isEmpty();
}
@@ -211,7 +198,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenSecureRequestAndHpkpWithPinThenPublicKeyPinsReportOnlyHeaderInResponse() throws Exception {
this.spring.register(HpkpConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.PUBLIC_KEY_PINS_REPORT_ONLY,
"max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\""))
@@ -222,7 +208,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenInsecureRequestHeaderDefaultsDisabledAndHpkpWithPinThenNoHeadersInResponse() throws Exception {
this.spring.register(HpkpConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/")).andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).isEmpty();
}
@@ -231,7 +216,6 @@ public class HeadersConfigurerTests {
public void getWhenHpkpWithMultiplePinsThenPublicKeyPinsReportOnlyHeaderWithMultiplePinsInResponse()
throws Exception {
this.spring.register(HpkpConfigWithPins.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true)).andExpect(header().string(
HttpHeaders.PUBLIC_KEY_PINS_REPORT_ONLY,
"max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\" ; pin-sha256=\"E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=\""))
@@ -242,7 +226,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenHpkpWithCustomAgeThenPublicKeyPinsReportOnlyHeaderWithCustomAgeInResponse() throws Exception {
this.spring.register(HpkpConfigCustomAge.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.PUBLIC_KEY_PINS_REPORT_ONLY,
"max-age=604800 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\""))
@@ -253,7 +236,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenHpkpWithReportOnlyFalseThenPublicKeyPinsHeaderInResponse() throws Exception {
this.spring.register(HpkpConfigTerminateConnection.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.PUBLIC_KEY_PINS,
"max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\""))
@@ -265,7 +247,6 @@ public class HeadersConfigurerTests {
public void getWhenHpkpIncludeSubdomainThenPublicKeyPinsReportOnlyHeaderWithIncludeSubDomainsInResponse()
throws Exception {
this.spring.register(HpkpConfigIncludeSubDomains.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true)).andExpect(header().string(
HttpHeaders.PUBLIC_KEY_PINS_REPORT_ONLY,
"max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\" ; includeSubDomains"))
@@ -276,7 +257,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenHpkpWithReportUriThenPublicKeyPinsReportOnlyHeaderWithReportUriInResponse() throws Exception {
this.spring.register(HpkpConfigWithReportURI.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true)).andExpect(header().string(
HttpHeaders.PUBLIC_KEY_PINS_REPORT_ONLY,
"max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\" ; report-uri=\"https://example.net/pkp-report\""))
@@ -288,7 +268,6 @@ public class HeadersConfigurerTests {
public void getWhenHpkpWithReportUriAsStringThenPublicKeyPinsReportOnlyHeaderWithReportUriInResponse()
throws Exception {
this.spring.register(HpkpConfigWithReportURIAsString.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true)).andExpect(header().string(
HttpHeaders.PUBLIC_KEY_PINS_REPORT_ONLY,
"max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\" ; report-uri=\"https://example.net/pkp-report\""))
@@ -300,7 +279,6 @@ public class HeadersConfigurerTests {
public void getWhenHpkpWithReportUriInLambdaThenPublicKeyPinsReportOnlyHeaderWithReportUriInResponse()
throws Exception {
this.spring.register(HpkpWithReportUriInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true)).andExpect(header().string(
HttpHeaders.PUBLIC_KEY_PINS_REPORT_ONLY,
"max-age=5184000 ; pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\" ; report-uri=\"https://example.net/pkp-report\""))
@@ -311,7 +289,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenContentSecurityPolicyConfiguredThenContentSecurityPolicyHeaderInResponse() throws Exception {
this.spring.register(ContentSecurityPolicyDefaultConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.CONTENT_SECURITY_POLICY, "default-src 'self'")).andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.CONTENT_SECURITY_POLICY);
@@ -321,7 +298,6 @@ public class HeadersConfigurerTests {
public void getWhenContentSecurityPolicyWithReportOnlyThenContentSecurityPolicyReportOnlyHeaderInResponse()
throws Exception {
this.spring.register(ContentSecurityPolicyReportOnlyConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.CONTENT_SECURITY_POLICY_REPORT_ONLY,
"default-src 'self'; script-src trustedscripts.example.com"))
@@ -334,7 +310,6 @@ public class HeadersConfigurerTests {
public void getWhenContentSecurityPolicyWithReportOnlyInLambdaThenContentSecurityPolicyReportOnlyHeaderInResponse()
throws Exception {
this.spring.register(ContentSecurityPolicyReportOnlyInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.CONTENT_SECURITY_POLICY_REPORT_ONLY,
"default-src 'self'; script-src trustedscripts.example.com"))
@@ -358,7 +333,6 @@ public class HeadersConfigurerTests {
@Test
public void configureWhenContentSecurityPolicyNoPolicyDirectivesInLambdaThenDefaultHeaderValue() throws Exception {
this.spring.register(ContentSecurityPolicyNoDirectivesInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string(HttpHeaders.CONTENT_SECURITY_POLICY, "default-src 'self'")).andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly(HttpHeaders.CONTENT_SECURITY_POLICY);
@@ -367,7 +341,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenReferrerPolicyConfiguredThenReferrerPolicyHeaderInResponse() throws Exception {
this.spring.register(ReferrerPolicyDefaultConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string("Referrer-Policy", ReferrerPolicy.NO_REFERRER.getPolicy())).andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly("Referrer-Policy");
@@ -376,7 +349,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenReferrerPolicyInLambdaThenReferrerPolicyHeaderInResponse() throws Exception {
this.spring.register(ReferrerPolicyDefaultInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string("Referrer-Policy", ReferrerPolicy.NO_REFERRER.getPolicy())).andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly("Referrer-Policy");
@@ -386,7 +358,6 @@ public class HeadersConfigurerTests {
public void getWhenReferrerPolicyConfiguredWithCustomValueThenReferrerPolicyHeaderWithCustomValueInResponse()
throws Exception {
this.spring.register(ReferrerPolicyCustomConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string("Referrer-Policy", ReferrerPolicy.SAME_ORIGIN.getPolicy())).andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly("Referrer-Policy");
@@ -395,7 +366,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenReferrerPolicyConfiguredWithCustomValueInLambdaThenCustomValueInResponse() throws Exception {
this.spring.register(ReferrerPolicyCustomInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string("Referrer-Policy", ReferrerPolicy.SAME_ORIGIN.getPolicy())).andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly("Referrer-Policy");
@@ -404,7 +374,6 @@ public class HeadersConfigurerTests {
@Test
public void getWhenFeaturePolicyConfiguredThenFeaturePolicyHeaderInResponse() throws Exception {
this.spring.register(FeaturePolicyConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true))
.andExpect(header().string("Feature-Policy", "geolocation 'self'")).andReturn();
assertThat(mvcResult.getResponse().getHeaderNames()).containsExactly("Feature-Policy");
@@ -420,7 +389,6 @@ public class HeadersConfigurerTests {
public void getWhenHstsConfiguredWithPreloadThenStrictTransportSecurityHeaderWithPreloadInResponse()
throws Exception {
this.spring.register(HstsWithPreloadConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true)).andExpect(header()
.string(HttpHeaders.STRICT_TRANSPORT_SECURITY, "max-age=31536000 ; includeSubDomains ; preload"))
.andReturn();
@@ -431,7 +399,6 @@ public class HeadersConfigurerTests {
public void getWhenHstsConfiguredWithPreloadInLambdaThenStrictTransportSecurityHeaderWithPreloadInResponse()
throws Exception {
this.spring.register(HstsWithPreloadInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/").secure(true)).andExpect(header()
.string(HttpHeaders.STRICT_TRANSPORT_SECURITY, "max-age=31536000 ; includeSubDomains ; preload"))
.andReturn();
@@ -659,7 +626,6 @@ public class HeadersConfigurerTests {
Map<String, String> pins = new LinkedHashMap<>();
pins.put("d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=", "sha256");
pins.put("E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=", "sha256");
// @formatter:off
http
.headers()

View File

@@ -67,14 +67,12 @@ public class HttpBasicConfigurerTests {
@Test
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnBasicAuthenticationFilter() {
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(BasicAuthenticationFilter.class));
}
@Test
public void httpBasicWhenUsingDefaultsInLambdaThenResponseIncludesBasicChallenge() throws Exception {
this.spring.register(DefaultsLambdaEntryPointConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isUnauthorized())
.andExpect(header().string("WWW-Authenticate", "Basic realm=\"Realm\""));
}
@@ -83,7 +81,6 @@ public class HttpBasicConfigurerTests {
@Test
public void httpBasicWhenUsingDefaultsThenResponseIncludesBasicChallenge() throws Exception {
this.spring.register(DefaultsEntryPointConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isUnauthorized())
.andExpect(header().string("WWW-Authenticate", "Basic realm=\"Realm\""));
}
@@ -91,9 +88,7 @@ public class HttpBasicConfigurerTests {
@Test
public void httpBasicWhenUsingCustomAuthenticationEntryPointThenResponseIncludesBasicChallenge() throws Exception {
this.spring.register(CustomAuthenticationEntryPointConfig.class).autowire();
this.mvc.perform(get("/"));
verify(CustomAuthenticationEntryPointConfig.ENTRY_POINT).commence(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(AuthenticationException.class));
}
@@ -101,9 +96,7 @@ public class HttpBasicConfigurerTests {
@Test
public void httpBasicWhenInvokedTwiceThenUsesOriginalEntryPoint() throws Exception {
this.spring.register(DuplicateDoesNotOverrideConfig.class).autowire();
this.mvc.perform(get("/"));
verify(DuplicateDoesNotOverrideConfig.ENTRY_POINT).commence(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(AuthenticationException.class));
}
@@ -112,7 +105,6 @@ public class HttpBasicConfigurerTests {
@Test
public void httpBasicWhenRememberMeConfiguredThenSetsRememberMeCookie() throws Exception {
this.spring.register(BasicUsesRememberMeConfig.class).autowire();
this.mvc.perform(get("/").with(httpBasic("user", "password")).param("remember-me", "true"))
.andExpect(cookie().exists("remember-me"));
}

View File

@@ -73,9 +73,7 @@ public class HttpSecurityAntMatchersTests {
public void antMatchersMethodAndNoPatterns() throws Exception {
loadConfig(AntMatchersNoPatternsConfig.class);
this.request.setMethod("POST");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_FORBIDDEN);
}
@@ -84,9 +82,7 @@ public class HttpSecurityAntMatchersTests {
public void antMatchersMethodAndEmptyPatterns() throws Exception {
loadConfig(AntMatchersEmptyPatternsConfig.class);
this.request.setMethod("POST");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
}
@@ -94,7 +90,6 @@ public class HttpSecurityAntMatchersTests {
this.context = new AnnotationConfigWebApplicationContext();
this.context.register(configs);
this.context.refresh();
this.context.getAutowireCapableBeanFactory().autowireBean(this);
}

View File

@@ -73,17 +73,13 @@ public class HttpSecurityLogoutTests {
@Test
public void clearAuthenticationFalse() throws Exception {
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.setMethod("POST");
this.request.setServletPath("/logout");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(currentContext.getAuthentication()).isNotNull();
}
@@ -91,7 +87,6 @@ public class HttpSecurityLogoutTests {
this.context = new AnnotationConfigWebApplicationContext();
this.context.register(configs);
this.context.refresh();
this.context.getAutowireCapableBeanFactory().autowireBean(this);
}

View File

@@ -78,135 +78,92 @@ public class HttpSecurityRequestMatchersTests {
@Test
public void mvcMatcher() throws Exception {
loadConfig(MvcMatcherConfig.class, LegacyMvcMatchingConfig.class);
this.request.setServletPath("/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/path.html");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/path/");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
}
@Test
public void mvcMatcherGetFiltersNoUnsupportedMethodExceptionFromDummyRequest() {
loadConfig(MvcMatcherConfig.class);
assertThat(this.springSecurityFilterChain.getFilters("/path")).isNotEmpty();
}
@Test
public void requestMatchersMvcMatcher() throws Exception {
loadConfig(RequestMatchersMvcMatcherConfig.class, LegacyMvcMatchingConfig.class);
this.request.setServletPath("/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/path.html");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/path/");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
}
@Test
public void requestMatchersWhenMvcMatcherInLambdaThenPathIsSecured() throws Exception {
loadConfig(RequestMatchersMvcMatcherInLambdaConfig.class, LegacyMvcMatchingConfig.class);
this.request.setServletPath("/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/path.html");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/path/");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
}
@Test
public void requestMatchersMvcMatcherServletPath() throws Exception {
loadConfig(RequestMatchersMvcMatcherServeltPathConfig.class);
this.request.setServletPath("/spring");
this.request.setRequestURI("/spring/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("");
this.request.setRequestURI("/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
setup();
this.request.setServletPath("/other");
this.request.setRequestURI("/other/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
}
@Test
public void requestMatcherWhensMvcMatcherServletPathInLambdaThenPathIsSecured() throws Exception {
loadConfig(RequestMatchersMvcMatcherServletPathInLambdaConfig.class);
this.request.setServletPath("/spring");
this.request.setRequestURI("/spring/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("");
this.request.setRequestURI("/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
setup();
this.request.setServletPath("/other");
this.request.setRequestURI("/other/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
}
@@ -215,7 +172,6 @@ public class HttpSecurityRequestMatchersTests {
this.context.register(configs);
this.context.setServletContext(new MockServletContext());
this.context.refresh();
this.context.getAutowireCapableBeanFactory().autowireBean(this);
}

View File

@@ -56,7 +56,6 @@ public class Issue55Tests {
TestingAuthenticationToken token = new TestingAuthenticationToken("test", "this");
this.spring.register(WebSecurityConfigurerAdapterDefaultsAuthManagerConfig.class);
this.spring.getContext().getBean(FilterChainProxy.class);
FilterSecurityInterceptor filter = (FilterSecurityInterceptor) findFilter(FilterSecurityInterceptor.class, 0);
assertThat(filter.getAuthenticationManager().authenticate(token)).isEqualTo(CustomAuthenticationManager.RESULT);
}
@@ -67,10 +66,8 @@ public class Issue55Tests {
TestingAuthenticationToken token = new TestingAuthenticationToken("test", "this");
this.spring.register(MultiWebSecurityConfigurerAdapterDefaultsAuthManagerConfig.class);
this.spring.getContext().getBean(FilterChainProxy.class);
FilterSecurityInterceptor filter = (FilterSecurityInterceptor) findFilter(FilterSecurityInterceptor.class, 0);
assertThat(filter.getAuthenticationManager().authenticate(token)).isEqualTo(CustomAuthenticationManager.RESULT);
FilterSecurityInterceptor secondFilter = (FilterSecurityInterceptor) findFilter(FilterSecurityInterceptor.class,
1);
assertThat(secondFilter.getAuthenticationManager().authenticate(token))

View File

@@ -61,7 +61,6 @@ public class JeeConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnJ2eePreAuthenticatedProcessingFilter() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor)
.postProcess(any(J2eePreAuthenticatedProcessingFilter.class));
}
@@ -70,7 +69,6 @@ public class JeeConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnJ2eeBasedPreAuthenticatedWebAuthenticationDetailsSource() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor)
.postProcess(any(J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource.class));
}
@@ -80,7 +78,6 @@ public class JeeConfigurerTests {
this.spring.register(InvokeTwiceDoesNotOverride.class).autowire();
Principal user = mock(Principal.class);
given(user.getName()).willReturn("user");
this.mvc.perform(get("/").principal(user).with((request) -> {
request.addUserRole("ROLE_ADMIN");
request.addUserRole("ROLE_USER");
@@ -93,7 +90,6 @@ public class JeeConfigurerTests {
this.spring.register(JeeMappableRolesConfig.class).autowire();
Principal user = mock(Principal.class);
given(user.getName()).willReturn("user");
this.mvc.perform(get("/").principal(user).with((request) -> {
request.addUserRole("ROLE_ADMIN");
request.addUserRole("ROLE_USER");
@@ -106,7 +102,6 @@ public class JeeConfigurerTests {
this.spring.register(JeeMappableAuthoritiesConfig.class).autowire();
Principal user = mock(Principal.class);
given(user.getName()).willReturn("user");
this.mvc.perform(get("/").principal(user).with((request) -> {
request.addUserRole("ROLE_ADMIN");
request.addUserRole("ROLE_USER");
@@ -124,7 +119,6 @@ public class JeeConfigurerTests {
given(user.getName()).willReturn("user");
given(JeeCustomAuthenticatedUserDetailsServiceConfig.authenticationUserDetailsService.loadUserDetails(any()))
.willReturn(userDetails);
this.mvc.perform(get("/").principal(user).with((request) -> {
request.addUserRole("ROLE_ADMIN");
request.addUserRole("ROLE_USER");

View File

@@ -67,7 +67,6 @@ public class LogoutConfigurerClearSiteDataTests {
@WithMockUser
public void logoutWhenRequestTypeGetThenHeaderNotPresentt() throws Exception {
this.spring.register(HttpLogoutConfig.class).autowire();
this.mvc.perform(get("/logout").secure(true).with(SecurityMockMvcRequestPostProcessors.csrf()))
.andExpect(header().doesNotExist(CLEAR_SITE_DATA_HEADER));
}
@@ -76,7 +75,6 @@ public class LogoutConfigurerClearSiteDataTests {
@WithMockUser
public void logoutWhenRequestTypePostAndNotSecureThenHeaderNotPresent() throws Exception {
this.spring.register(HttpLogoutConfig.class).autowire();
this.mvc.perform(post("/logout").with(SecurityMockMvcRequestPostProcessors.csrf()))
.andExpect(header().doesNotExist(CLEAR_SITE_DATA_HEADER));
}
@@ -85,7 +83,6 @@ public class LogoutConfigurerClearSiteDataTests {
@WithMockUser
public void logoutWhenRequestTypePostAndSecureThenHeaderIsPresent() throws Exception {
this.spring.register(HttpLogoutConfig.class).autowire();
this.mvc.perform(post("/logout").secure(true).with(SecurityMockMvcRequestPostProcessors.csrf()))
.andExpect(header().stringValues(CLEAR_SITE_DATA_HEADER, HEADER_VALUE));
}

View File

@@ -91,14 +91,12 @@ public class LogoutConfigurerTests {
@Test
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnLogoutFilter() {
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(LogoutFilter.class));
}
@Test
public void logoutWhenInvokedTwiceThenUsesOriginalLogoutUrl() throws Exception {
this.spring.register(DuplicateDoesNotOverrideConfig.class).autowire();
this.mvc.perform(post("/custom/logout").with(csrf())).andExpect(status().isFound())
.andExpect(redirectedUrl("/login?logout"));
}
@@ -107,42 +105,36 @@ public class LogoutConfigurerTests {
@Test
public void logoutWhenGetRequestAndCsrfDisabledThenRedirectsToLogin() throws Exception {
this.spring.register(CsrfDisabledConfig.class).autowire();
this.mvc.perform(get("/logout")).andExpect(status().isFound()).andExpect(redirectedUrl("/login?logout"));
}
@Test
public void logoutWhenPostRequestAndCsrfDisabledThenRedirectsToLogin() throws Exception {
this.spring.register(CsrfDisabledConfig.class).autowire();
this.mvc.perform(post("/logout")).andExpect(status().isFound()).andExpect(redirectedUrl("/login?logout"));
}
@Test
public void logoutWhenPutRequestAndCsrfDisabledThenRedirectsToLogin() throws Exception {
this.spring.register(CsrfDisabledConfig.class).autowire();
this.mvc.perform(put("/logout")).andExpect(status().isFound()).andExpect(redirectedUrl("/login?logout"));
}
@Test
public void logoutWhenDeleteRequestAndCsrfDisabledThenRedirectsToLogin() throws Exception {
this.spring.register(CsrfDisabledConfig.class).autowire();
this.mvc.perform(delete("/logout")).andExpect(status().isFound()).andExpect(redirectedUrl("/login?logout"));
}
@Test
public void logoutWhenGetRequestAndCsrfDisabledAndCustomLogoutUrlThenRedirectsToLogin() throws Exception {
this.spring.register(CsrfDisabledAndCustomLogoutConfig.class).autowire();
this.mvc.perform(get("/custom/logout")).andExpect(status().isFound()).andExpect(redirectedUrl("/login?logout"));
}
@Test
public void logoutWhenPostRequestAndCsrfDisabledAndCustomLogoutUrlThenRedirectsToLogin() throws Exception {
this.spring.register(CsrfDisabledAndCustomLogoutConfig.class).autowire();
this.mvc.perform(post("/custom/logout")).andExpect(status().isFound())
.andExpect(redirectedUrl("/login?logout"));
}
@@ -150,14 +142,12 @@ public class LogoutConfigurerTests {
@Test
public void logoutWhenPutRequestAndCsrfDisabledAndCustomLogoutUrlThenRedirectsToLogin() throws Exception {
this.spring.register(CsrfDisabledAndCustomLogoutConfig.class).autowire();
this.mvc.perform(put("/custom/logout")).andExpect(status().isFound()).andExpect(redirectedUrl("/login?logout"));
}
@Test
public void logoutWhenDeleteRequestAndCsrfDisabledAndCustomLogoutUrlThenRedirectsToLogin() throws Exception {
this.spring.register(CsrfDisabledAndCustomLogoutConfig.class).autowire();
this.mvc.perform(delete("/custom/logout")).andExpect(status().isFound())
.andExpect(redirectedUrl("/login?logout"));
}
@@ -165,7 +155,6 @@ public class LogoutConfigurerTests {
@Test
public void logoutWhenCustomLogoutUrlInLambdaThenRedirectsToLogin() throws Exception {
this.spring.register(CsrfDisabledAndCustomLogoutInLambdaConfig.class).autowire();
this.mvc.perform(get("/custom/logout")).andExpect(status().isFound()).andExpect(redirectedUrl("/login?logout"));
}
@@ -186,7 +175,6 @@ public class LogoutConfigurerTests {
@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"));
}
@@ -194,7 +182,6 @@ public class LogoutConfigurerTests {
@Test
public void logoutWhenAcceptTextHtmlThenRedirectsToLogin() throws Exception {
this.spring.register(BasicSecurityConfig.class).autowire();
this.mvc.perform(
post("/logout").with(csrf()).with(user("user")).header(HttpHeaders.ACCEPT, MediaType.TEXT_HTML_VALUE))
.andExpect(status().isFound()).andExpect(redirectedUrl("/login?logout"));
@@ -204,7 +191,6 @@ public class LogoutConfigurerTests {
@Test
public void logoutWhenAcceptApplicationJsonThenReturnsStatusNoContent() throws Exception {
this.spring.register(BasicSecurityConfig.class).autowire();
this.mvc.perform(post("/logout").with(csrf()).with(user("user")).header(HttpHeaders.ACCEPT,
MediaType.APPLICATION_JSON_VALUE)).andExpect(status().isNoContent());
}
@@ -213,7 +199,6 @@ public class LogoutConfigurerTests {
@Test
public void logoutWhenAcceptAllThenReturnsStatusNoContent() throws Exception {
this.spring.register(BasicSecurityConfig.class).autowire();
this.mvc.perform(
post("/logout").with(csrf()).with(user("user")).header(HttpHeaders.ACCEPT, MediaType.ALL_VALUE))
.andExpect(status().isNoContent());
@@ -223,7 +208,6 @@ public class LogoutConfigurerTests {
@Test
public void logoutWhenAcceptFromChromeThenRedirectsToLogin() throws Exception {
this.spring.register(BasicSecurityConfig.class).autowire();
this.mvc.perform(post("/logout").with(csrf()).with(user("user")).header(HttpHeaders.ACCEPT,
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"))
.andExpect(status().isFound()).andExpect(redirectedUrl("/login?logout"));
@@ -233,7 +217,6 @@ public class LogoutConfigurerTests {
@Test
public void logoutWhenXMLHttpRequestThenReturnsStatusNoContent() throws Exception {
this.spring.register(BasicSecurityConfig.class).autowire();
this.mvc.perform(post("/logout").with(csrf()).with(user("user"))
.header(HttpHeaders.ACCEPT, "text/html,application/json").header("X-Requested-With", "XMLHttpRequest"))
.andExpect(status().isNoContent());
@@ -242,7 +225,6 @@ public class LogoutConfigurerTests {
@Test
public void logoutWhenDisabledThenLogoutUrlNotFound() throws Exception {
this.spring.register(LogoutDisabledConfig.class).autowire();
this.mvc.perform(post("/logout").with(csrf())).andExpect(status().isNotFound());
}

View File

@@ -65,24 +65,18 @@ public class NamespaceHttpBasicTests {
@Test
public void basicAuthenticationWhenUsingDefaultsThenMatchesNamespace() throws Exception {
this.spring.register(HttpBasicConfig.class, UserConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isUnauthorized());
this.mvc.perform(get("/").with(httpBasic("user", "invalid"))).andExpect(status().isUnauthorized())
.andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"Realm\""));
this.mvc.perform(get("/").with(httpBasic("user", "password"))).andExpect(status().isNotFound());
}
@Test
public void basicAuthenticationWhenUsingDefaultsInLambdaThenMatchesNamespace() throws Exception {
this.spring.register(HttpBasicLambdaConfig.class, UserConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isUnauthorized());
this.mvc.perform(get("/").with(httpBasic("user", "invalid"))).andExpect(status().isUnauthorized())
.andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"Realm\""));
this.mvc.perform(get("/").with(httpBasic("user", "password"))).andExpect(status().isNotFound());
}
@@ -92,7 +86,6 @@ public class NamespaceHttpBasicTests {
@Test
public void basicAuthenticationWhenUsingCustomRealmThenMatchesNamespace() throws Exception {
this.spring.register(CustomHttpBasicConfig.class, UserConfig.class).autowire();
this.mvc.perform(get("/").with(httpBasic("user", "invalid"))).andExpect(status().isUnauthorized())
.andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"Custom Realm\""));
}
@@ -100,7 +93,6 @@ public class NamespaceHttpBasicTests {
@Test
public void basicAuthenticationWhenUsingCustomRealmInLambdaThenMatchesNamespace() throws Exception {
this.spring.register(CustomHttpBasicLambdaConfig.class, UserConfig.class).autowire();
this.mvc.perform(get("/").with(httpBasic("user", "invalid"))).andExpect(status().isUnauthorized())
.andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"Custom Realm\""));
}
@@ -111,12 +103,9 @@ public class NamespaceHttpBasicTests {
@Test
public void basicAuthenticationWhenUsingAuthenticationDetailsSourceRefThenMatchesNamespace() throws Exception {
this.spring.register(AuthenticationDetailsSourceHttpBasicConfig.class, UserConfig.class).autowire();
AuthenticationDetailsSource<HttpServletRequest, ?> source = this.spring.getContext()
.getBean(AuthenticationDetailsSource.class);
this.mvc.perform(get("/").with(httpBasic("user", "password")));
verify(source).buildDetails(any(HttpServletRequest.class));
}
@@ -124,12 +113,9 @@ public class NamespaceHttpBasicTests {
public void basicAuthenticationWhenUsingAuthenticationDetailsSourceRefInLambdaThenMatchesNamespace()
throws Exception {
this.spring.register(AuthenticationDetailsSourceHttpBasicLambdaConfig.class, UserConfig.class).autowire();
AuthenticationDetailsSource<HttpServletRequest, ?> source = this.spring.getContext()
.getBean(AuthenticationDetailsSource.class);
this.mvc.perform(get("/").with(httpBasic("user", "password")));
verify(source).buildDetails(any(HttpServletRequest.class));
}
@@ -139,22 +125,16 @@ public class NamespaceHttpBasicTests {
@Test
public void basicAuthenticationWhenUsingEntryPointRefThenMatchesNamespace() throws Exception {
this.spring.register(EntryPointRefHttpBasicConfig.class, UserConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(status().is(999));
this.mvc.perform(get("/").with(httpBasic("user", "invalid"))).andExpect(status().is(999));
this.mvc.perform(get("/").with(httpBasic("user", "password"))).andExpect(status().isNotFound());
}
@Test
public void basicAuthenticationWhenUsingEntryPointRefInLambdaThenMatchesNamespace() throws Exception {
this.spring.register(EntryPointRefHttpBasicLambdaConfig.class, UserConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(status().is(999));
this.mvc.perform(get("/").with(httpBasic("user", "invalid"))).andExpect(status().is(999));
this.mvc.perform(get("/").with(httpBasic("user", "password"))).andExpect(status().isNotFound());
}

View File

@@ -63,11 +63,8 @@ public class NamespaceHttpFormLoginTests {
@Test
public void formLoginWhenDefaultConfigurationThenMatchesNamespace() throws Exception {
this.spring.register(FormLoginConfig.class, UserDetailsServiceConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(redirectedUrl("http://localhost/login"));
this.mvc.perform(post("/login").with(csrf())).andExpect(redirectedUrl("/login?error"));
this.mvc.perform(post("/login").param("username", "user").param("password", "password").with(csrf()))
.andExpect(redirectedUrl("/"));
}
@@ -75,12 +72,9 @@ public class NamespaceHttpFormLoginTests {
@Test
public void formLoginWithCustomEndpointsThenBehaviorMatchesNamespace() throws Exception {
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"));
this.mvc.perform(post("/authentication/login/process").param("username", "user").param("password", "password")
.with(csrf())).andExpect(redirectedUrl("/default"));
}
@@ -88,12 +82,9 @@ public class NamespaceHttpFormLoginTests {
@Test
public void formLoginWithCustomHandlersThenBehaviorMatchesNamespace() throws Exception {
this.spring.register(FormLoginCustomRefsConfig.class, UserDetailsServiceConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(redirectedUrl("http://localhost/login"));
this.mvc.perform(post("/login").with(csrf())).andExpect(redirectedUrl("/custom/failure"));
verifyBean(WebAuthenticationDetailsSource.class).buildDetails(any(HttpServletRequest.class));
this.mvc.perform(post("/login").param("username", "user").param("password", "password").with(csrf()))
.andExpect(redirectedUrl("/custom/targetUrl"));
}

View File

@@ -50,7 +50,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
public class NamespaceHttpHeadersTests {
static final Map<String, String> defaultHeaders = new LinkedHashMap<>();
static {
defaultHeaders.put("X-Content-Type-Options", "nosniff");
defaultHeaders.put("X-Frame-Options", "DENY");
@@ -60,7 +59,6 @@ public class NamespaceHttpHeadersTests {
defaultHeaders.put("Pragma", "no-cache");
defaultHeaders.put("X-XSS-Protection", "1; mode=block");
}
@Rule
public final SpringTestRule spring = new SpringTestRule();
@@ -70,28 +68,24 @@ public class NamespaceHttpHeadersTests {
@Test
public void secureRequestWhenDefaultConfigThenBehaviorMatchesNamespace() throws Exception {
this.spring.register(HeadersDefaultConfig.class).autowire();
this.mvc.perform(get("/").secure(true)).andExpect(includesDefaults());
}
@Test
public void secureRequestWhenCacheControlOnlyThenBehaviorMatchesNamespace() throws Exception {
this.spring.register(HeadersCacheControlConfig.class).autowire();
this.mvc.perform(get("/").secure(true)).andExpect(includes("Cache-Control", "Expires", "Pragma"));
}
@Test
public void secureRequestWhenHstsOnlyThenBehaviorMatchesNamespace() throws Exception {
this.spring.register(HstsConfig.class).autowire();
this.mvc.perform(get("/").secure(true)).andExpect(includes("Strict-Transport-Security"));
}
@Test
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")));
}
@@ -99,14 +93,12 @@ public class NamespaceHttpHeadersTests {
@Test
public void requestWhenFrameOptionsSameOriginThenBehaviorMatchesNamespace() throws Exception {
this.spring.register(FrameOptionsSameOriginConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(includes(Collections.singletonMap("X-Frame-Options", "SAMEORIGIN")));
}
@Test
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")));
}
@@ -114,28 +106,24 @@ public class NamespaceHttpHeadersTests {
@Test
public void requestWhenXssOnlyThenBehaviorMatchesNamespace() throws Exception {
this.spring.register(XssProtectionConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(includes("X-XSS-Protection"));
}
@Test
public void requestWhenXssCustomThenBehaviorMatchesNamespace() throws Exception {
this.spring.register(XssProtectionCustomConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(includes(Collections.singletonMap("X-XSS-Protection", "1")));
}
@Test
public void requestWhenXContentTypeOptionsOnlyThenBehaviorMatchesNamespace() throws Exception {
this.spring.register(ContentTypeOptionsConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(includes("X-Content-Type-Options"));
}
@Test
public void requestWhenCustomHeaderOnlyThenBehaviorMatchesNamespace() throws Exception {
this.spring.register(HeaderRefConfig.class).autowire();
this.mvc.perform(get("/"))
.andExpect(includes(Collections.singletonMap("customHeaderName", "customHeaderValue")));
}

View File

@@ -60,32 +60,26 @@ public class NamespaceHttpInterceptUrlTests {
@Test
public void unauthenticatedRequestWhenUrlRequiresAuthenticationThenBehaviorMatchesNamespace() throws Exception {
this.spring.register(HttpInterceptUrlConfig.class).autowire();
this.mvc.perform(get("/users")).andExpect(status().isForbidden());
}
@Test
public void authenticatedRequestWhenUrlRequiresElevatedPrivilegesThenBehaviorMatchesNamespace() throws Exception {
this.spring.register(HttpInterceptUrlConfig.class).autowire();
this.mvc.perform(get("/users").with(authentication(user("ROLE_USER")))).andExpect(status().isForbidden());
}
@Test
public void authenticatedRequestWhenAuthorizedThenBehaviorMatchesNamespace() throws Exception {
this.spring.register(HttpInterceptUrlConfig.class, BaseController.class).autowire();
this.mvc.perform(get("/users").with(authentication(user("ROLE_ADMIN")))).andExpect(status().isOk()).andReturn();
}
@Test
public void requestWhenMappedByPostInterceptUrlThenBehaviorMatchesNamespace() throws Exception {
this.spring.register(HttpInterceptUrlConfig.class, BaseController.class).autowire();
this.mvc.perform(get("/admin/post").with(authentication(user("ROLE_USER")))).andExpect(status().isOk());
this.mvc.perform(post("/admin/post").with(authentication(user("ROLE_USER")))).andExpect(status().isForbidden());
this.mvc.perform(post("/admin/post").with(csrf()).with(authentication(user("ROLE_ADMIN"))))
.andExpect(status().isOk());
}
@@ -93,11 +87,8 @@ public class NamespaceHttpInterceptUrlTests {
@Test
public void requestWhenRequiresChannelThenBehaviorMatchesNamespace() throws Exception {
this.spring.register(HttpInterceptUrlConfig.class).autowire();
this.mvc.perform(get("/login")).andExpect(redirectedUrl("https://localhost/login"));
this.mvc.perform(get("/secured/a")).andExpect(redirectedUrl("https://localhost/secured/a"));
this.mvc.perform(get("https://localhost/user")).andExpect(redirectedUrl("http://localhost/user"));
}

View File

@@ -62,10 +62,8 @@ public class NamespaceHttpJeeTests {
@Test
public void requestWhenJeeUserThenBehaviorDiffersFromNamespaceForRoleNames() throws Exception {
this.spring.register(JeeMappableRolesConfig.class, BaseController.class).autowire();
Principal user = mock(Principal.class);
given(user.getName()).willReturn("joe");
this.mvc.perform(get("/roles").principal(user).with((request) -> {
request.addUserRole("ROLE_admin");
request.addUserRole("ROLE_user");
@@ -77,18 +75,13 @@ public class NamespaceHttpJeeTests {
@Test
public void requestWhenCustomAuthenticatedUserDetailsServiceThenBehaviorMatchesNamespace() throws Exception {
this.spring.register(JeeUserServiceRefConfig.class, BaseController.class).autowire();
Principal user = mock(Principal.class);
given(user.getName()).willReturn("joe");
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"));
verifyBean(AuthenticationUserDetailsService.class).loadUserDetails(any());
}

View File

@@ -72,7 +72,6 @@ public class NamespaceHttpLogoutTests {
@WithMockUser
public void logoutWhenUsingDefaultsThenMatchesNamespace() throws Exception {
this.spring.register(HttpLogoutConfig.class).autowire();
this.mvc.perform(post("/logout").with(csrf())).andExpect(authenticated(false))
.andExpect(redirectedUrl("/login?logout")).andExpect(noCookies()).andExpect(session(Objects::isNull));
}
@@ -81,7 +80,6 @@ public class NamespaceHttpLogoutTests {
@WithMockUser
public void logoutWhenDisabledInLambdaThenRespondsWithNotFound() throws Exception {
this.spring.register(HttpLogoutDisabledInLambdaConfig.class).autowire();
this.mvc.perform(post("/logout").with(csrf()).with(user("user"))).andExpect(status().isNotFound());
}
@@ -92,7 +90,6 @@ public class NamespaceHttpLogoutTests {
@WithMockUser
public void logoutWhenUsingVariousCustomizationsMatchesNamespace() throws Exception {
this.spring.register(CustomHttpLogoutConfig.class).autowire();
this.mvc.perform(post("/custom-logout").with(csrf())).andExpect(authenticated(false))
.andExpect(redirectedUrl("/logout-success"))
.andExpect((result) -> assertThat(result.getResponse().getCookies()).hasSize(1))
@@ -103,7 +100,6 @@ public class NamespaceHttpLogoutTests {
@WithMockUser
public void logoutWhenUsingVariousCustomizationsInLambdaThenMatchesNamespace() throws Exception {
this.spring.register(CustomHttpLogoutInLambdaConfig.class).autowire();
this.mvc.perform(post("/custom-logout").with(csrf())).andExpect(authenticated(false))
.andExpect(redirectedUrl("/logout-success"))
.andExpect((result) -> assertThat(result.getResponse().getCookies()).hasSize(1))
@@ -117,7 +113,6 @@ public class NamespaceHttpLogoutTests {
@WithMockUser
public void logoutWhenUsingSuccessHandlerRefThenMatchesNamespace() throws Exception {
this.spring.register(SuccessHandlerRefHttpLogoutConfig.class).autowire();
this.mvc.perform(post("/logout").with(csrf())).andExpect(authenticated(false))
.andExpect(redirectedUrl("/SuccessHandlerRefHttpLogoutConfig")).andExpect(noCookies())
.andExpect(session(Objects::isNull));
@@ -127,7 +122,6 @@ public class NamespaceHttpLogoutTests {
@WithMockUser
public void logoutWhenUsingSuccessHandlerRefInLambdaThenMatchesNamespace() throws Exception {
this.spring.register(SuccessHandlerRefHttpLogoutInLambdaConfig.class).autowire();
this.mvc.perform(post("/logout").with(csrf())).andExpect(authenticated(false))
.andExpect(redirectedUrl("/SuccessHandlerRefHttpLogoutConfig")).andExpect(noCookies())
.andExpect(session(Objects::isNull));
@@ -224,7 +218,6 @@ public class NamespaceHttpLogoutTests {
protected void configure(HttpSecurity http) throws Exception {
SimpleUrlLogoutSuccessHandler logoutSuccessHandler = new SimpleUrlLogoutSuccessHandler();
logoutSuccessHandler.setDefaultTargetUrl("/SuccessHandlerRefHttpLogoutConfig");
// @formatter:off
http
.logout((logout) -> logout.logoutSuccessHandler(logoutSuccessHandler));

View File

@@ -104,18 +104,14 @@ public class NamespaceHttpOpenIDLoginTests {
given(OpenIDLoginAttributeExchangeConfig.CONSUMER_MANAGER.authenticate(any(DiscoveryInformation.class), any(),
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");
assertThat(attributeObject).isInstanceOf(List.class);
@@ -144,25 +140,20 @@ public class NamespaceHttpOpenIDLoginTests {
public void openidLoginWithCustomHandlersThenBehaviorMatchesNamespace() throws Exception {
OpenIDAuthenticationToken token = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.SUCCESS,
"identityUrl", "message", Arrays.asList(new OpenIDAttribute("name", "type")));
OpenIDLoginCustomRefsConfig.AUDS = mock(AuthenticationUserDetailsService.class);
given(OpenIDLoginCustomRefsConfig.AUDS.loadUserDetails(any(Authentication.class)))
.willReturn(new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER")));
OpenIDLoginCustomRefsConfig.ADS = spy(new WebAuthenticationDetailsSource());
OpenIDLoginCustomRefsConfig.CONSUMER = mock(OpenIDConsumer.class);
this.spring.register(OpenIDLoginCustomRefsConfig.class, UserDetailsServiceConfig.class).autowire();
given(OpenIDLoginCustomRefsConfig.CONSUMER.endConsumption(any(HttpServletRequest.class)))
.willThrow(new AuthenticationServiceException("boom"));
this.mvc.perform(post("/login/openid").with(csrf()).param("openid.identity", "identity"))
.andExpect(redirectedUrl("/custom/failure"));
reset(OpenIDLoginCustomRefsConfig.CONSUMER);
given(OpenIDLoginCustomRefsConfig.CONSUMER.endConsumption(any(HttpServletRequest.class))).willReturn(token);
this.mvc.perform(post("/login/openid").with(csrf()).param("openid.identity", "identity"))
.andExpect(redirectedUrl("/custom/targetUrl"));
verify(OpenIDLoginCustomRefsConfig.AUDS).loadUserDetails(any(Authentication.class));
verify(OpenIDLoginCustomRefsConfig.ADS).buildDetails(any(Object.class));
}

View File

@@ -49,12 +49,9 @@ public class NamespaceHttpPortMappingsTests {
@Test
public void portMappingWhenRequestRequiresChannelThenBehaviorMatchesNamespace() throws Exception {
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"));
this.mvc.perform(get("https://localhost:9443/user")).andExpect(redirectedUrl("http://localhost:9080/user"));
}

View File

@@ -68,9 +68,7 @@ public class NamespaceHttpRequestCacheTests {
@Test
public void requestWhenDefaultConfigurationThenUsesHttpSessionRequestCache() throws Exception {
this.spring.register(DefaultRequestCacheRefConfig.class).autowire();
MvcResult result = this.mvc.perform(get("/")).andExpect(status().isForbidden()).andReturn();
HttpSession session = result.getRequest().getSession(false);
assertThat(session).isNotNull();
assertThat(session.getAttribute("SPRING_SECURITY_SAVED_REQUEST")).isNotNull();

View File

@@ -69,7 +69,6 @@ public class NamespaceHttpServerAccessDeniedHandlerTests {
@Test
public void requestWhenCustomAccessDeniedPageInLambdaThenForwardedToCustomPage() throws Exception {
this.spring.register(AccessDeniedPageInLambdaConfig.class).autowire();
this.mvc.perform(get("/").with(authentication(user()))).andExpect(status().isForbidden())
.andExpect(forwardedUrl("/AccessDeniedPageConfig"));
}
@@ -85,9 +84,7 @@ public class NamespaceHttpServerAccessDeniedHandlerTests {
@Test
public void requestWhenCustomAccessDeniedHandlerInLambdaThenBehaviorMatchesNamespace() throws Exception {
this.spring.register(AccessDeniedHandlerRefInLambdaConfig.class).autowire();
this.mvc.perform(get("/").with(authentication(user())));
verify(AccessDeniedHandlerRefInLambdaConfig.accessDeniedHandler).handle(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(AccessDeniedException.class));
}

View File

@@ -81,10 +81,8 @@ public class NamespaceHttpX509Tests {
@Test
public void x509AuthenticationWhenHasCustomAuthenticationDetailsSourceThenMatchesNamespace() throws Exception {
this.spring.register(AuthenticationDetailsSourceRefConfig.class, X509Controller.class).autowire();
X509Certificate certificate = loadCert("rod.cer");
this.mvc.perform(get("/whoami").with(x509(certificate))).andExpect(content().string("rod"));
verifyBean(AuthenticationDetailsSource.class).buildDetails(any());
}
@@ -183,7 +181,6 @@ public class NamespaceHttpX509Tests {
@Bean
AuthenticationDetailsSource<HttpServletRequest, PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails> authenticationDetailsSource() {
return mock(AuthenticationDetailsSource.class);
}

View File

@@ -82,19 +82,15 @@ public class NamespaceRememberMeTests {
public void rememberMeLoginWhenUsingDefaultsThenMatchesNamespace() throws Exception {
this.spring.register(RememberMeConfig.class, SecurityController.class).autowire();
MvcResult result = this.mvc.perform(post("/login").with(rememberMeLogin())).andReturn();
MockHttpSession session = (MockHttpSession) result.getRequest().getSession();
Cookie rememberMe = result.getResponse().getCookie("remember-me");
assertThat(rememberMe).isNotNull();
this.mvc.perform(get("/authentication-class").cookie(rememberMe))
.andExpect(content().string(RememberMeAuthenticationToken.class.getName()));
result = this.mvc.perform(post("/logout").with(csrf()).session(session).cookie(rememberMe))
.andExpect(redirectedUrl("/login?logout")).andReturn();
rememberMe = result.getResponse().getCookie("remember-me");
assertThat(rememberMe).isNotNull().extracting(Cookie::getMaxAge).isEqualTo(0);
this.mvc.perform(post("/authentication-class").with(csrf()).cookie(rememberMe))
.andExpect(redirectedUrl("http://localhost/login")).andReturn();
}
@@ -105,11 +101,9 @@ public class NamespaceRememberMeTests {
public void logoutWhenCustomRememberMeServicesDeclaredThenUses() throws Exception {
RememberMeServicesRefConfig.REMEMBER_ME_SERVICES = mock(RememberMeServicesWithoutLogoutHandler.class);
this.spring.register(RememberMeServicesRefConfig.class).autowire();
this.mvc.perform(get("/"));
verify(RememberMeServicesRefConfig.REMEMBER_ME_SERVICES).autoLogin(any(HttpServletRequest.class),
any(HttpServletResponse.class));
this.mvc.perform(post("/login").with(csrf()));
verify(RememberMeServicesRefConfig.REMEMBER_ME_SERVICES).loginFail(any(HttpServletRequest.class),
any(HttpServletResponse.class));
@@ -119,15 +113,11 @@ public class NamespaceRememberMeTests {
public void rememberMeLoginWhenAuthenticationSuccessHandlerDeclaredThenUses() throws Exception {
AuthSuccessConfig.SUCCESS_HANDLER = mock(AuthenticationSuccessHandler.class);
this.spring.register(AuthSuccessConfig.class).autowire();
MvcResult result = this.mvc.perform(post("/login").with(rememberMeLogin())).andReturn();
verifyZeroInteractions(AuthSuccessConfig.SUCCESS_HANDLER);
Cookie rememberMe = result.getResponse().getCookie("remember-me");
assertThat(rememberMe).isNotNull();
this.mvc.perform(get("/somewhere").cookie(rememberMe));
verify(AuthSuccessConfig.SUCCESS_HANDLER).onAuthenticationSuccess(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(Authentication.class));
}
@@ -137,10 +127,8 @@ public class NamespaceRememberMeTests {
this.spring.register(WithoutKeyConfig.class, KeyConfig.class, SecurityController.class).autowire();
Cookie withoutKey = this.mvc.perform(post("/without-key/login").with(rememberMeLogin()))
.andExpect(redirectedUrl("/")).andReturn().getResponse().getCookie("remember-me");
this.mvc.perform(get("/somewhere").cookie(withoutKey)).andExpect(status().isFound())
.andExpect(redirectedUrl("http://localhost/login"));
Cookie withKey = this.mvc.perform(post("/login").with(rememberMeLogin())).andReturn().getResponse()
.getCookie("remember-me");
this.mvc.perform(get("/somewhere").cookie(withKey)).andExpect(status().isNotFound());
@@ -148,16 +136,13 @@ public class NamespaceRememberMeTests {
// http/remember-me@services-alias is not supported use standard aliasing instead
// (i.e. @Bean("alias"))
// http/remember-me@data-source-ref is not supported directly. Instead use
// http/remember-me@token-repository-ref example
@Test
public void rememberMeLoginWhenDeclaredTokenRepositoryThenMatchesNamespace() throws Exception {
TokenRepositoryRefConfig.TOKEN_REPOSITORY = mock(PersistentTokenRepository.class);
this.spring.register(TokenRepositoryRefConfig.class).autowire();
this.mvc.perform(post("/login").with(rememberMeLogin()));
verify(TokenRepositoryRefConfig.TOKEN_REPOSITORY).createNewToken(any(PersistentRememberMeToken.class));
}
@@ -166,7 +151,6 @@ public class NamespaceRememberMeTests {
this.spring.register(TokenValiditySecondsConfig.class).autowire();
Cookie expiredRememberMe = this.mvc.perform(post("/login").with(rememberMeLogin())).andReturn().getResponse()
.getCookie("remember-me");
assertThat(expiredRememberMe).extracting(Cookie::getMaxAge).isEqualTo(314);
}
@@ -175,7 +159,6 @@ public class NamespaceRememberMeTests {
this.spring.register(RememberMeConfig.class).autowire();
Cookie expiredRememberMe = this.mvc.perform(post("/login").with(rememberMeLogin())).andReturn().getResponse()
.getCookie("remember-me");
assertThat(expiredRememberMe).extracting(Cookie::getMaxAge).isEqualTo(AbstractRememberMeServices.TWO_WEEKS_S);
}
@@ -184,7 +167,6 @@ public class NamespaceRememberMeTests {
this.spring.register(UseSecureCookieConfig.class).autowire();
Cookie secureCookie = this.mvc.perform(post("/login").with(rememberMeLogin())).andReturn().getResponse()
.getCookie("remember-me");
assertThat(secureCookie).extracting(Cookie::getSecure).isEqualTo(true);
}
@@ -193,7 +175,6 @@ public class NamespaceRememberMeTests {
this.spring.register(RememberMeConfig.class).autowire();
Cookie secureCookie = this.mvc.perform(post("/login").with(rememberMeLogin()).secure(true)).andReturn()
.getResponse().getCookie("remember-me");
assertThat(secureCookie).extracting(Cookie::getSecure).isEqualTo(true);
}
@@ -202,7 +183,6 @@ public class NamespaceRememberMeTests {
this.spring.register(RememberMeParameterConfig.class).autowire();
Cookie rememberMe = this.mvc.perform(post("/login").with(rememberMeLogin("rememberMe", true))).andReturn()
.getResponse().getCookie("remember-me");
assertThat(rememberMe).isNotNull();
}
@@ -212,7 +192,6 @@ public class NamespaceRememberMeTests {
this.spring.register(RememberMeCookieNameConfig.class).autowire();
Cookie rememberMe = this.mvc.perform(post("/login").with(rememberMeLogin())).andReturn().getResponse()
.getCookie("rememberMe");
assertThat(rememberMe).isNotNull();
}
@@ -220,9 +199,7 @@ public class NamespaceRememberMeTests {
public void rememberMeLoginWhenGlobalUserDetailsServiceDeclaredThenMatchesNamespace() throws Exception {
DefaultsUserDetailsServiceWithDaoConfig.USERDETAILS_SERVICE = mock(UserDetailsService.class);
this.spring.register(DefaultsUserDetailsServiceWithDaoConfig.class).autowire();
this.mvc.perform(post("/login").with(rememberMeLogin()));
verify(DefaultsUserDetailsServiceWithDaoConfig.USERDETAILS_SERVICE).loadUserByUsername("user");
}
@@ -230,12 +207,9 @@ public class NamespaceRememberMeTests {
public void rememberMeLoginWhenUserDetailsServiceDeclaredThenMatchesNamespace() throws Exception {
UserServiceRefConfig.USERDETAILS_SERVICE = mock(UserDetailsService.class);
this.spring.register(UserServiceRefConfig.class).autowire();
given(UserServiceRefConfig.USERDETAILS_SERVICE.loadUserByUsername("user"))
.willReturn(new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER")));
this.mvc.perform(post("/login").with(rememberMeLogin()));
verify(UserServiceRefConfig.USERDETAILS_SERVICE).loadUserByUsername("user");
}
@@ -363,7 +337,6 @@ public class NamespaceRememberMeTests {
protected void configure(HttpSecurity http) throws Exception {
// JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl()
// tokenRepository.setDataSource(dataSource);
// @formatter:off
http
.formLogin()

View File

@@ -82,20 +82,16 @@ public class NamespaceSessionManagementTests {
public void authenticateWhenDefaultSessionManagementThenMatchesNamespace() throws Exception {
this.spring.register(SessionManagementConfig.class, BasicController.class, UserDetailsServiceConfig.class)
.autowire();
MockHttpSession session = new MockHttpSession();
String sessionId = session.getId();
MvcResult result = this.mvc.perform(get("/auth").session(session).with(httpBasic("user", "password")))
.andExpect(session()).andReturn();
assertThat(result.getRequest().getSession(false).getId()).isNotEqualTo(sessionId);
}
@Test
public void authenticateWhenUsingInvalidSessionUrlThenMatchesNamespace() throws Exception {
this.spring.register(CustomSessionManagementConfig.class).autowire();
this.mvc.perform(get("/auth").with((request) -> {
request.setRequestedSessionIdValid(false);
request.setRequestedSessionId("id");
@@ -106,13 +102,11 @@ public class NamespaceSessionManagementTests {
@Test
public void authenticateWhenUsingExpiredUrlThenMatchesNamespace() throws Exception {
this.spring.register(CustomSessionManagementConfig.class).autowire();
MockHttpSession session = new MockHttpSession();
SessionInformation sessionInformation = new SessionInformation(new Object(), session.getId(), new Date(0));
sessionInformation.expireNow();
SessionRegistry sessionRegistry = this.spring.getContext().getBean(SessionRegistry.class);
given(sessionRegistry.getSessionInformation(session.getId())).willReturn(sessionInformation);
this.mvc.perform(get("/auth").session(session)).andExpect(redirectedUrl("/expired-session"));
}
@@ -120,9 +114,7 @@ public class NamespaceSessionManagementTests {
public void authenticateWhenUsingMaxSessionsThenMatchesNamespace() throws Exception {
this.spring.register(CustomSessionManagementConfig.class, BasicController.class, UserDetailsServiceConfig.class)
.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"));
}
@@ -131,12 +123,10 @@ public class NamespaceSessionManagementTests {
public void authenticateWhenUsingFailureUrlThenMatchesNamespace() throws Exception {
this.spring.register(CustomSessionManagementConfig.class, BasicController.class, UserDetailsServiceConfig.class)
.autowire();
MockHttpServletRequest mock = spy(MockHttpServletRequest.class);
mock.setSession(new MockHttpSession());
given(mock.changeSessionId()).willThrow(SessionAuthenticationException.class);
mock.setMethod("GET");
this.mvc.perform(get("/auth").with((request) -> mock).with(httpBasic("user", "password")))
.andExpect(redirectedUrl("/session-auth-error"));
}
@@ -145,11 +135,8 @@ public class NamespaceSessionManagementTests {
public void authenticateWhenUsingSessionRegistryThenMatchesNamespace() throws Exception {
this.spring.register(CustomSessionManagementConfig.class, BasicController.class, UserDetailsServiceConfig.class)
.autowire();
SessionRegistry sessionRegistry = this.spring.getContext().getBean(SessionRegistry.class);
this.mvc.perform(get("/auth").with(httpBasic("user", "password"))).andExpect(status().isOk());
verify(sessionRegistry).registerNewSession(any(String.class), any(Object.class));
}
@@ -157,13 +144,11 @@ public class NamespaceSessionManagementTests {
@Test
public void authenticateWhenUsingCustomInvalidSessionStrategyThenMatchesNamespace() throws Exception {
this.spring.register(InvalidSessionStrategyConfig.class).autowire();
this.mvc.perform(get("/auth").with((request) -> {
request.setRequestedSessionIdValid(false);
request.setRequestedSessionId("id");
return request;
})).andExpect(status().isOk());
verifyBean(InvalidSessionStrategy.class).onInvalidSessionDetected(any(HttpServletRequest.class),
any(HttpServletResponse.class));
}
@@ -172,9 +157,7 @@ public class NamespaceSessionManagementTests {
public void authenticateWhenUsingCustomSessionAuthenticationStrategyThenMatchesNamespace() throws Exception {
this.spring.register(RefsSessionManagementConfig.class, BasicController.class, UserDetailsServiceConfig.class)
.autowire();
this.mvc.perform(get("/auth").with(httpBasic("user", "password"))).andExpect(status().isOk());
verifyBean(SessionAuthenticationStrategy.class).onAuthentication(any(Authentication.class),
any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@@ -184,13 +167,11 @@ public class NamespaceSessionManagementTests {
this.spring
.register(SFPNoneSessionManagementConfig.class, BasicController.class, UserDetailsServiceConfig.class)
.autowire();
MockHttpSession givenSession = new MockHttpSession();
String givenSessionId = givenSession.getId();
MockHttpSession resultingSession = (MockHttpSession) this.mvc
.perform(get("/auth").session(givenSession).with(httpBasic("user", "password")))
.andExpect(status().isOk()).andReturn().getRequest().getSession(false);
assertThat(givenSessionId).isEqualTo(resultingSession.getId());
}
@@ -198,15 +179,12 @@ public class NamespaceSessionManagementTests {
public void authenticateWhenMigrateSessionFixationProtectionThenMatchesNamespace() throws Exception {
this.spring.register(SFPMigrateSessionManagementConfig.class, BasicController.class,
UserDetailsServiceConfig.class).autowire();
MockHttpSession givenSession = new MockHttpSession();
String givenSessionId = givenSession.getId();
givenSession.setAttribute("name", "value");
MockHttpSession resultingSession = (MockHttpSession) this.mvc
.perform(get("/auth").session(givenSession).with(httpBasic("user", "password")))
.andExpect(status().isOk()).andReturn().getRequest().getSession(false);
assertThat(givenSessionId).isNotEqualTo(resultingSession.getId());
assertThat(resultingSession.getAttribute("name")).isEqualTo("value");
}
@@ -215,25 +193,20 @@ public class NamespaceSessionManagementTests {
@Test
public void authenticateWhenUsingSessionFixationProtectionThenUsesNonNullEventPublisher() throws Exception {
this.spring.register(SFPPostProcessedConfig.class, UserDetailsServiceConfig.class).autowire();
this.mvc.perform(get("/auth").session(new MockHttpSession()).with(httpBasic("user", "password")))
.andExpect(status().isNotFound());
verifyBean(MockEventListener.class).onApplicationEvent(any(SessionFixationProtectionEvent.class));
}
@Test
public void authenticateWhenNewSessionFixationProtectionThenMatchesNamespace() throws Exception {
this.spring.register(SFPNewSessionSessionManagementConfig.class, UserDetailsServiceConfig.class).autowire();
MockHttpSession givenSession = new MockHttpSession();
String givenSessionId = givenSession.getId();
givenSession.setAttribute("name", "value");
MockHttpSession resultingSession = (MockHttpSession) this.mvc
.perform(get("/auth").session(givenSession).with(httpBasic("user", "password")))
.andExpect(status().isNotFound()).andReturn().getRequest().getSession(false);
assertThat(givenSessionId).isNotEqualTo(resultingSession.getId());
assertThat(resultingSession.getAttribute("name")).isNull();
}
@@ -465,11 +438,8 @@ public class NamespaceSessionManagementTests {
assertThat(result.getRequest().getSession(false)).isNull();
return;
}
assertThat(result.getRequest().getSession(false)).isNotNull();
MockHttpSession session = (MockHttpSession) result.getRequest().getSession(false);
if (this.valid != null) {
if (this.valid) {
assertThat(session.isInvalid()).isFalse();
@@ -478,7 +448,6 @@ public class NamespaceSessionManagementTests {
assertThat(session.isInvalid()).isTrue();
}
}
if (this.id != null) {
assertThat(session.getId()).isEqualTo(this.id);
}

View File

@@ -49,7 +49,6 @@ public class PermitAllSupportTests {
@Test
public void performWhenUsingPermitAllExactUrlRequestMatcherThenMatchesExactUrl() throws Exception {
this.spring.register(PermitAllConfig.class).autowire();
this.mvc.perform(get("/app/xyz").contextPath("/app")).andExpect(status().isNotFound());
this.mvc.perform(get("/app/xyz?def").contextPath("/app")).andExpect(status().isFound());
this.mvc.perform(post("/app/abc?def").with(csrf()).contextPath("/app")).andExpect(status().isNotFound());

View File

@@ -47,21 +47,18 @@ public class PortMapperConfigurerTests {
@Test
public void requestWhenPortMapperTwiceInvokedThenDoesNotOverride() throws Exception {
this.spring.register(InvokeTwiceDoesNotOverride.class).autowire();
this.mockMvc.perform(get("http://localhost:543")).andExpect(redirectedUrl("https://localhost:123"));
}
@Test
public void requestWhenPortMapperHttpMapsToInLambdaThenRedirectsToHttpsPort() throws Exception {
this.spring.register(HttpMapsToInLambdaConfig.class).autowire();
this.mockMvc.perform(get("http://localhost:543")).andExpect(redirectedUrl("https://localhost:123"));
}
@Test
public void requestWhenCustomPortMapperInLambdaThenRedirectsToHttpsPort() throws Exception {
this.spring.register(CustomPortMapperInLambdaConfig.class).autowire();
this.mockMvc.perform(get("http://localhost:543")).andExpect(redirectedUrl("https://localhost:123"));
}

View File

@@ -81,7 +81,6 @@ public class RememberMeConfigurerTests {
@Test
public void postWhenNoUserDetailsServiceThenException() {
this.spring.register(NullUserDetailsConfig.class).autowire();
assertThatThrownBy(() -> this.mvc.perform(post("/login").param("username", "user").param("password", "password")
.param("remember-me", "true").with(csrf()))).hasMessageContaining("UserDetailsService is required");
}
@@ -89,7 +88,6 @@ public class RememberMeConfigurerTests {
@Test
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnRememberMeAuthenticationFilter() {
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(RememberMeAuthenticationFilter.class));
}
@@ -98,16 +96,13 @@ public class RememberMeConfigurerTests {
given(DuplicateDoesNotOverrideConfig.userDetailsService.loadUserByUsername(anyString()))
.willReturn(new User("user", "password", Collections.emptyList()));
this.spring.register(DuplicateDoesNotOverrideConfig.class).autowire();
this.mvc.perform(get("/").with(httpBasic("user", "password")).param("remember-me", "true"));
verify(DuplicateDoesNotOverrideConfig.userDetailsService).loadUserByUsername("user");
}
@Test
public void loginWhenRememberMeTrueThenRespondsWithRememberMeCookie() throws Exception {
this.spring.register(RememberMeConfig.class).autowire();
this.mvc.perform(post("/login").with(csrf()).param("username", "user").param("password", "password")
.param("remember-me", "true")).andExpect(cookie().exists("remember-me"));
}
@@ -115,11 +110,9 @@ 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();
Cookie rememberMeCookie = mvcResult.getResponse().getCookie("remember-me");
this.mvc.perform(get("/abc").cookie(rememberMeCookie)).andExpect(authenticated()
.withAuthentication((auth) -> assertThat(auth).isInstanceOf(RememberMeAuthenticationToken.class)));
}
@@ -127,12 +120,10 @@ public class RememberMeConfigurerTests {
@Test
public void logoutWhenRememberMeCookieThenAuthenticationIsRememberMeCookieExpired() 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();
Cookie rememberMeCookie = mvcResult.getResponse().getCookie("remember-me");
HttpSession session = mvcResult.getRequest().getSession();
this.mvc.perform(post("/logout").with(csrf()).cookie(rememberMeCookie).session((MockHttpSession) session))
.andExpect(redirectedUrl("/login?logout")).andExpect(cookie().maxAge("remember-me", 0));
}
@@ -140,7 +131,6 @@ public class RememberMeConfigurerTests {
@Test
public void getWhenRememberMeCookieAndLoggedOutThenRedirectsToLogin() throws Exception {
this.spring.register(RememberMeConfig.class).autowire();
MvcResult loginMvcResult = this.mvc.perform(post("/login").with(csrf()).param("username", "user")
.param("password", "password").param("remember-me", "true")).andReturn();
Cookie rememberMeCookie = loginMvcResult.getResponse().getCookie("remember-me");
@@ -149,7 +139,6 @@ public class RememberMeConfigurerTests {
.perform(post("/logout").with(csrf()).cookie(rememberMeCookie).session((MockHttpSession) session))
.andReturn();
Cookie expiredRememberMeCookie = logoutMvcResult.getResponse().getCookie("remember-me");
this.mvc.perform(get("/abc").with(csrf()).cookie(expiredRememberMeCookie))
.andExpect(redirectedUrl("http://localhost/login"));
}
@@ -157,7 +146,6 @@ public class RememberMeConfigurerTests {
@Test
public void loginWhenRememberMeConfiguredInLambdaThenRespondsWithRememberMeCookie() throws Exception {
this.spring.register(RememberMeInLambdaConfig.class).autowire();
this.mvc.perform(post("/login").with(csrf()).param("username", "user").param("password", "password")
.param("remember-me", "true")).andExpect(cookie().exists("remember-me"));
}
@@ -165,7 +153,6 @@ public class RememberMeConfigurerTests {
@Test
public void loginWhenRememberMeTrueAndCookieDomainThenRememberMeCookieHasDomain() throws Exception {
this.spring.register(RememberMeCookieDomainConfig.class).autowire();
this.mvc.perform(post("/login").with(csrf()).param("username", "user").param("password", "password")
.param("remember-me", "true")).andExpect(cookie().exists("remember-me"))
.andExpect(cookie().domain("remember-me", "spring.io"));
@@ -174,7 +161,6 @@ public class RememberMeConfigurerTests {
@Test
public void loginWhenRememberMeTrueAndCookieDomainInLambdaThenRememberMeCookieHasDomain() throws Exception {
this.spring.register(RememberMeCookieDomainInLambdaConfig.class).autowire();
this.mvc.perform(post("/login").with(csrf()).param("username", "user").param("password", "password")
.param("remember-me", "true")).andExpect(cookie().exists("remember-me"))
.andExpect(cookie().domain("remember-me", "spring.io"));
@@ -190,11 +176,9 @@ public class RememberMeConfigurerTests {
@Test
public void getWhenRememberMeCookieAndNoKeyConfiguredThenKeyFromRememberMeServicesIsUsed() throws Exception {
this.spring.register(FallbackRememberMeKeyConfig.class).autowire();
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");
this.mvc.perform(get("/abc").cookie(rememberMeCookie)).andExpect(authenticated()
.withAuthentication((auth) -> assertThat(auth).isInstanceOf(RememberMeAuthenticationToken.class)));
}

View File

@@ -69,16 +69,13 @@ public class RequestCacheConfigurerTests {
@Test
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnExceptionTranslationFilter() {
this.spring.register(ObjectPostProcessorConfig.class, DefaultSecurityConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(RequestCacheAwareFilter.class));
}
@Test
public void getWhenInvokingExceptionHandlingTwiceThenOriginalEntryPointUsed() throws Exception {
this.spring.register(InvokeTwiceDoesNotOverrideConfig.class).autowire();
this.mvc.perform(get("/"));
verify(InvokeTwiceDoesNotOverrideConfig.requestCache).getMatchingRequest(any(HttpServletRequest.class),
any(HttpServletResponse.class));
}
@@ -86,10 +83,8 @@ public class RequestCacheConfigurerTests {
@Test
public void getWhenBookmarkedUrlIsFaviconIcoThenPostAuthenticationRedirectsToRoot() throws Exception {
this.spring.register(RequestCacheDefaultsConfig.class, DefaultSecurityConfig.class).autowire();
MockHttpSession session = (MockHttpSession) this.mvc.perform(get("/favicon.ico"))
.andExpect(redirectedUrl("http://localhost/login")).andReturn().getRequest().getSession();
this.mvc.perform(formLogin(session)).andExpect(redirectedUrl("/")); // ignores
// favicon.ico
}
@@ -97,10 +92,8 @@ public class RequestCacheConfigurerTests {
@Test
public void getWhenBookmarkedUrlIsFaviconPngThenPostAuthenticationRedirectsToRoot() throws Exception {
this.spring.register(RequestCacheDefaultsConfig.class, DefaultSecurityConfig.class).autowire();
MockHttpSession session = (MockHttpSession) this.mvc.perform(get("/favicon.png"))
.andExpect(redirectedUrl("http://localhost/login")).andReturn().getRequest().getSession();
this.mvc.perform(formLogin(session)).andExpect(redirectedUrl("/")); // ignores
// favicon.png
}
@@ -109,14 +102,11 @@ public class RequestCacheConfigurerTests {
@Test
public void getWhenBookmarkedRequestIsApplicationJsonThenPostAuthenticationRedirectsToRoot() throws Exception {
this.spring.register(RequestCacheDefaultsConfig.class, DefaultSecurityConfig.class).autowire();
MockHttpSession session = (MockHttpSession) this.mvc
.perform(get("/messages").header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON))
.andExpect(redirectedUrl("http://localhost/login")).andReturn().getRequest().getSession();
this.mvc.perform(formLogin(session)).andExpect(redirectedUrl("/")); // ignores
// application/json
// This is desirable since JSON requests are typically not invoked directly from
// the browser and we don't want the browser to replay them
}
@@ -125,13 +115,10 @@ public class RequestCacheConfigurerTests {
@Test
public void getWhenBookmarkedRequestIsXRequestedWithThenPostAuthenticationRedirectsToRoot() throws Exception {
this.spring.register(RequestCacheDefaultsConfig.class, DefaultSecurityConfig.class).autowire();
MockHttpSession session = (MockHttpSession) this.mvc
.perform(get("/messages").header("X-Requested-With", "XMLHttpRequest"))
.andExpect(redirectedUrl("http://localhost/login")).andReturn().getRequest().getSession();
this.mvc.perform(formLogin(session)).andExpect(redirectedUrl("/"));
// This is desirable since XHR requests are typically not invoked directly from
// the browser and we don't want the browser to replay them
}
@@ -139,14 +126,11 @@ public class RequestCacheConfigurerTests {
@Test
public void getWhenBookmarkedRequestIsTextEventStreamThenPostAuthenticationRedirectsToRoot() throws Exception {
this.spring.register(RequestCacheDefaultsConfig.class, DefaultSecurityConfig.class).autowire();
MockHttpSession session = (MockHttpSession) this.mvc
.perform(get("/messages").header(HttpHeaders.ACCEPT, MediaType.TEXT_EVENT_STREAM))
.andExpect(redirectedUrl("http://localhost/login")).andReturn().getRequest().getSession();
this.mvc.perform(formLogin(session)).andExpect(redirectedUrl("/")); // ignores
// text/event-stream
// This is desirable since event-stream requests are typically not invoked
// directly from the browser and we don't want the browser to replay them
}
@@ -154,45 +138,37 @@ public class RequestCacheConfigurerTests {
@Test
public void getWhenBookmarkedRequestIsAllMediaTypeThenPostAuthenticationRemembers() throws Exception {
this.spring.register(RequestCacheDefaultsConfig.class, DefaultSecurityConfig.class).autowire();
MockHttpSession session = (MockHttpSession) this.mvc
.perform(get("/messages").header(HttpHeaders.ACCEPT, MediaType.ALL))
.andExpect(redirectedUrl("http://localhost/login")).andReturn().getRequest().getSession();
this.mvc.perform(formLogin(session)).andExpect(redirectedUrl("http://localhost/messages"));
}
@Test
public void getWhenBookmarkedRequestIsTextHtmlThenPostAuthenticationRemembers() throws Exception {
this.spring.register(RequestCacheDefaultsConfig.class, DefaultSecurityConfig.class).autowire();
MockHttpSession session = (MockHttpSession) this.mvc
.perform(get("/messages").header(HttpHeaders.ACCEPT, MediaType.TEXT_HTML))
.andExpect(redirectedUrl("http://localhost/login")).andReturn().getRequest().getSession();
this.mvc.perform(formLogin(session)).andExpect(redirectedUrl("http://localhost/messages"));
}
@Test
public void getWhenBookmarkedRequestIsChromeThenPostAuthenticationRemembers() throws Exception {
this.spring.register(RequestCacheDefaultsConfig.class, DefaultSecurityConfig.class).autowire();
MockHttpSession session = (MockHttpSession) this.mvc
.perform(get("/messages").header(HttpHeaders.ACCEPT,
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"))
.andExpect(redirectedUrl("http://localhost/login")).andReturn().getRequest().getSession();
this.mvc.perform(formLogin(session)).andExpect(redirectedUrl("http://localhost/messages"));
}
@Test
public void getWhenBookmarkedRequestIsRequestedWithAndroidThenPostAuthenticationRemembers() throws Exception {
this.spring.register(RequestCacheDefaultsConfig.class, DefaultSecurityConfig.class).autowire();
MockHttpSession session = (MockHttpSession) this.mvc
.perform(get("/messages").header("X-Requested-With", "com.android"))
.andExpect(redirectedUrl("http://localhost/login")).andReturn().getRequest().getSession();
this.mvc.perform(formLogin(session)).andExpect(redirectedUrl("http://localhost/messages"));
}
@@ -201,9 +177,7 @@ public class RequestCacheConfigurerTests {
public void getWhenRequestCacheIsDisabledThenExceptionTranslationFilterDoesNotStoreRequest() throws Exception {
this.spring.register(RequestCacheDisabledConfig.class,
ExceptionHandlingConfigurerTests.DefaultSecurityConfig.class).autowire();
MockHttpSession session = (MockHttpSession) this.mvc.perform(get("/bob")).andReturn().getRequest().getSession();
this.mvc.perform(formLogin(session)).andExpect(redirectedUrl("/"));
}
@@ -211,12 +185,9 @@ public class RequestCacheConfigurerTests {
@Test
public void postWhenRequestIsMultipartThenPostAuthenticationRedirectsToRoot() throws Exception {
this.spring.register(RequestCacheDefaultsConfig.class, DefaultSecurityConfig.class).autowire();
MockMultipartFile aFile = new MockMultipartFile("aFile", "A_FILE".getBytes());
MockHttpSession session = (MockHttpSession) this.mvc.perform(multipart("/upload").file(aFile)).andReturn()
.getRequest().getSession();
this.mvc.perform(formLogin(session)).andExpect(redirectedUrl("/"));
}
@@ -224,27 +195,21 @@ public class RequestCacheConfigurerTests {
public void getWhenRequestCacheIsDisabledInLambdaThenExceptionTranslationFilterDoesNotStoreRequest()
throws Exception {
this.spring.register(RequestCacheDisabledInLambdaConfig.class, DefaultSecurityConfig.class).autowire();
MockHttpSession session = (MockHttpSession) this.mvc.perform(get("/bob")).andReturn().getRequest().getSession();
this.mvc.perform(formLogin(session)).andExpect(redirectedUrl("/"));
}
@Test
public void getWhenRequestCacheInLambdaThenRedirectedToCachedPage() throws Exception {
this.spring.register(RequestCacheInLambdaConfig.class, DefaultSecurityConfig.class).autowire();
MockHttpSession session = (MockHttpSession) this.mvc.perform(get("/bob")).andReturn().getRequest().getSession();
this.mvc.perform(formLogin(session)).andExpect(redirectedUrl("http://localhost/bob"));
}
@Test
public void getWhenCustomRequestCacheInLambdaThenCustomRequestCacheUsed() throws Exception {
this.spring.register(CustomRequestCacheInLambdaConfig.class, DefaultSecurityConfig.class).autowire();
MockHttpSession session = (MockHttpSession) this.mvc.perform(get("/bob")).andReturn().getRequest().getSession();
this.mvc.perform(formLogin(session)).andExpect(redirectedUrl("/"));
}

View File

@@ -47,7 +47,6 @@ public class RequestMatcherConfigurerTests {
@Test
public void authorizeRequestsWhenInvokedMultipleTimesThenChainsPaths() throws Exception {
this.spring.register(Sec2908Config.class).autowire();
this.mvc.perform(get("/oauth/abc")).andExpect(status().isForbidden());
this.mvc.perform(get("/api/abc")).andExpect(status().isForbidden());
}
@@ -55,7 +54,6 @@ public class RequestMatcherConfigurerTests {
@Test
public void authorizeRequestsWhenInvokedMultipleTimesInLambdaThenChainsPaths() throws Exception {
this.spring.register(AuthorizeRequestInLambdaConfig.class).autowire();
this.mvc.perform(get("/oauth/abc")).andExpect(status().isForbidden());
this.mvc.perform(get("/api/abc")).andExpect(status().isForbidden());
}

View File

@@ -67,7 +67,6 @@ public class SecurityContextConfigurerTests {
@Test
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnSecurityContextPersistenceFilter() {
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(SecurityContextPersistenceFilter.class));
}
@@ -75,9 +74,7 @@ public class SecurityContextConfigurerTests {
public void securityContextWhenInvokedTwiceThenUsesOriginalSecurityContextRepository() throws Exception {
this.spring.register(DuplicateDoesNotOverrideConfig.class).autowire();
given(DuplicateDoesNotOverrideConfig.SCR.loadContext(any())).willReturn(mock(SecurityContext.class));
this.mvc.perform(get("/"));
verify(DuplicateDoesNotOverrideConfig.SCR).loadContext(any(HttpRequestResponseHolder.class));
}
@@ -85,14 +82,12 @@ public class SecurityContextConfigurerTests {
@Test
public void securityContextWhenSecurityContextRepositoryNotConfiguredThenDoesNotThrowException() throws Exception {
this.spring.register(SecurityContextRepositoryDefaultsSecurityContextRepositoryConfig.class).autowire();
this.mvc.perform(get("/"));
}
@Test
public void requestWhenSecurityContextWithDefaultsInLambdaThenSessionIsCreated() throws Exception {
this.spring.register(SecurityContextWithDefaultsInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(formLogin()).andReturn();
HttpSession session = mvcResult.getRequest().getSession(false);
assertThat(session).isNotNull();
@@ -101,7 +96,6 @@ public class SecurityContextConfigurerTests {
@Test
public void requestWhenSecurityContextDisabledInLambdaThenContextNotSavedInSession() throws Exception {
this.spring.register(SecurityContextDisabledInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(formLogin()).andReturn();
HttpSession session = mvcResult.getRequest().getSession(false);
assertThat(session).isNull();
@@ -110,7 +104,6 @@ public class SecurityContextConfigurerTests {
@Test
public void requestWhenNullSecurityContextRepositoryInLambdaThenContextNotSavedInSession() throws Exception {
this.spring.register(NullSecurityContextRepositoryInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(formLogin()).andReturn();
HttpSession session = mvcResult.getRequest().getSession(false);
assertThat(session).isNull();

View File

@@ -88,7 +88,6 @@ public class ServletApiConfigurerTests {
@Test
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnSecurityContextHolderAwareRequestFilter() {
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor)
.postProcess(any(SecurityContextHolderAwareRequestFilter.class));
}
@@ -97,14 +96,12 @@ public class ServletApiConfigurerTests {
@Test
public void configureWhenUsingDefaultsThenAuthenticationManagerIsNotNull() {
this.spring.register(ServletApiConfig.class).autowire();
assertThat(this.spring.getContext().getBean("customAuthenticationManager")).isNotNull();
}
@Test
public void configureWhenUsingDefaultsThenAuthenticationEntryPointIsLogin() throws Exception {
this.spring.register(ServletApiConfig.class).autowire();
this.mvc.perform(formLogin()).andExpect(status().isFound());
}
@@ -112,7 +109,6 @@ public class ServletApiConfigurerTests {
@Test
public void configureWhenUsingDefaultsThenRolePrefixIsSet() throws Exception {
this.spring.register(ServletApiConfig.class, AdminController.class).autowire();
this.mvc.perform(
get("/admin").with(authentication(new TestingAuthenticationToken("user", "pass", "ROLE_ADMIN"))))
.andExpect(status().isOk());
@@ -121,9 +117,7 @@ public class ServletApiConfigurerTests {
@Test
public void requestWhenCustomAuthenticationEntryPointThenEntryPointUsed() throws Exception {
this.spring.register(CustomEntryPointConfig.class).autowire();
this.mvc.perform(get("/"));
verify(CustomEntryPointConfig.ENTRYPOINT).commence(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(AuthenticationException.class));
}
@@ -131,11 +125,9 @@ public class ServletApiConfigurerTests {
@Test
public void servletApiWhenInvokedTwiceThenUsesOriginalRole() throws Exception {
this.spring.register(DuplicateInvocationsDoesNotOverrideConfig.class, AdminController.class).autowire();
this.mvc.perform(
get("/admin").with(user("user").authorities(AuthorityUtils.createAuthorityList("PERMISSION_ADMIN"))))
.andExpect(status().isOk());
this.mvc.perform(get("/admin").with(user("user").authorities(AuthorityUtils.createAuthorityList("ROLE_ADMIN"))))
.andExpect(status().isForbidden());
}
@@ -143,16 +135,13 @@ public class ServletApiConfigurerTests {
@Test
public void configureWhenSharedObjectTrustResolverThenTrustResolverUsed() throws Exception {
this.spring.register(SharedTrustResolverConfig.class).autowire();
this.mvc.perform(get("/"));
verify(SharedTrustResolverConfig.TR, atLeastOnce()).isAnonymous(any());
}
@Test
public void requestWhenServletApiWithDefaultsInLambdaThenUsesDefaultRolePrefix() throws Exception {
this.spring.register(ServletApiWithDefaultsInLambdaConfig.class, AdminController.class).autowire();
this.mvc.perform(get("/admin").with(user("user").authorities(AuthorityUtils.createAuthorityList("ROLE_ADMIN"))))
.andExpect(status().isOk());
}
@@ -160,11 +149,9 @@ public class ServletApiConfigurerTests {
@Test
public void requestWhenRolePrefixInLambdaThenUsesCustomRolePrefix() throws Exception {
this.spring.register(RolePrefixInLambdaConfig.class, AdminController.class).autowire();
this.mvc.perform(
get("/admin").with(user("user").authorities(AuthorityUtils.createAuthorityList("PERMISSION_ADMIN"))))
.andExpect(status().isOk());
this.mvc.perform(get("/admin").with(user("user").authorities(AuthorityUtils.createAuthorityList("ROLE_ADMIN"))))
.andExpect(status().isForbidden());
}
@@ -172,18 +159,13 @@ public class ServletApiConfigurerTests {
@Test
public void checkSecurityContextAwareAndLogoutFilterHasSameSizeAndHasLogoutSuccessEventPublishingLogoutHandler() {
this.spring.register(ServletApiWithLogoutConfig.class);
SecurityContextHolderAwareRequestFilter scaFilter = getFilter(SecurityContextHolderAwareRequestFilter.class);
LogoutFilter logoutFilter = getFilter(LogoutFilter.class);
LogoutHandler lfLogoutHandler = getFieldValue(logoutFilter, "handler");
assertThat(lfLogoutHandler).isInstanceOf(CompositeLogoutHandler.class);
List<LogoutHandler> scaLogoutHandlers = getFieldValue(scaFilter, "logoutHandlers");
List<LogoutHandler> lfLogoutHandlers = getFieldValue(lfLogoutHandler, "logoutHandlers");
assertThat(scaLogoutHandlers).hasSameSizeAs(lfLogoutHandlers);
assertThat(scaLogoutHandlers).hasAtLeastOneElementOfType(LogoutSuccessEventPublishingLogoutHandler.class);
assertThat(lfLogoutHandlers).hasAtLeastOneElementOfType(LogoutSuccessEventPublishingLogoutHandler.class);
}

View File

@@ -95,11 +95,8 @@ public class SessionManagementConfigurerServlet31Tests {
repository.saveToken(token, request, this.response);
request.setParameter(token.getParameterName(), token.getToken());
request.getSession().setAttribute("attribute1", "value1");
loadConfig(SessionManagementDefaultSessionFixationServlet31Config.class);
this.springSecurityFilterChain.doFilter(request, this.response, this.chain);
assertThat(request.getSession().getId()).isNotEqualTo(id);
assertThat(request.getSession().getAttribute("attribute1")).isEqualTo("value1");
}
@@ -116,7 +113,6 @@ public class SessionManagementConfigurerServlet31Tests {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(this.request, this.response);
repo.loadContext(requestResponseHolder);
SecurityContextImpl securityContextImpl = new SecurityContextImpl();
securityContextImpl.setAuthentication(auth);
repo.saveContext(securityContextImpl, requestResponseHolder.getRequest(), requestResponseHolder.getResponse());

View File

@@ -47,31 +47,22 @@ public class SessionManagementConfigurerSessionCreationPolicyTests {
@Test
public void getWhenSharedObjectSessionCreationPolicyConfigurationThenOverrides() throws Exception {
this.spring.register(StatelessCreateSessionSharedObjectConfig.class).autowire();
MvcResult result = this.mvc.perform(get("/")).andReturn();
assertThat(result.getRequest().getSession(false)).isNull();
}
@Test
public void getWhenUserSessionCreationPolicyConfigurationThenOverrides() throws Exception {
this.spring.register(StatelessCreateSessionUserConfig.class).autowire();
MvcResult result = this.mvc.perform(get("/")).andReturn();
assertThat(result.getRequest().getSession(false)).isNull();
}
@Test
public void getWhenDefaultsThenLoginChallengeCreatesSession() throws Exception {
this.spring.register(DefaultConfig.class, BasicController.class).autowire();
MvcResult result = this.mvc.perform(get("/")).andExpect(status().isUnauthorized()).andReturn();
assertThat(result.getRequest().getSession(false)).isNotNull();
}
@@ -96,7 +87,6 @@ public class SessionManagementConfigurerSessionCreationPolicyTests {
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// @formatter:on
http.setSharedObject(SessionCreationPolicy.class, SessionCreationPolicy.ALWAYS);
}

View File

@@ -83,9 +83,7 @@ public class SessionManagementConfigurerTests {
public void sessionManagementWhenConfiguredThenDoesNotOverrideRequestCache() throws Exception {
SessionManagementRequestCacheConfig.REQUEST_CACHE = mock(RequestCache.class);
this.spring.register(SessionManagementRequestCacheConfig.class).autowire();
this.mvc.perform(get("/"));
verify(SessionManagementRequestCacheConfig.REQUEST_CACHE).getMatchingRequest(any(HttpServletRequest.class),
any(HttpServletResponse.class));
}
@@ -96,9 +94,7 @@ public class SessionManagementConfigurerTests {
given(SessionManagementSecurityContextRepositoryConfig.SECURITY_CONTEXT_REPO
.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));
}
@@ -106,10 +102,8 @@ public class SessionManagementConfigurerTests {
@Test
public void sessionManagementWhenInvokedTwiceThenUsesOriginalSessionCreationPolicy() throws Exception {
this.spring.register(InvokeTwiceDoesNotOverride.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/")).andReturn();
HttpSession session = mvcResult.getRequest().getSession(false);
assertThat(session).isNull();
}
@@ -120,25 +114,20 @@ public class SessionManagementConfigurerTests {
this.spring.register(DisableSessionFixationEnableConcurrencyControlConfig.class).autowire();
MockHttpSession session = new MockHttpSession();
String sessionId = session.getId();
MvcResult mvcResult = this.mvc.perform(get("/").with(httpBasic("user", "password")).session(session))
.andExpect(status().isNotFound()).andReturn();
assertThat(mvcResult.getRequest().getSession().getId()).isEqualTo(sessionId);
}
@Test
public void authenticateWhenNewSessionFixationProtectionInLambdaThenCreatesNewSession() throws Exception {
this.spring.register(SFPNewSessionInLambdaConfig.class).autowire();
MockHttpSession givenSession = new MockHttpSession();
String givenSessionId = givenSession.getId();
givenSession.setAttribute("name", "value");
MockHttpSession resultingSession = (MockHttpSession) this.mvc
.perform(get("/auth").session(givenSession).with(httpBasic("user", "password")))
.andExpect(status().isNotFound()).andReturn().getRequest().getSession(false);
assertThat(givenSessionId).isNotEqualTo(resultingSession.getId());
assertThat(resultingSession.getAttribute("name")).isNull();
}
@@ -146,9 +135,7 @@ public class SessionManagementConfigurerTests {
@Test
public void loginWhenUserLoggedInAndMaxSessionsIsOneThenLoginPrevented() throws Exception {
this.spring.register(ConcurrencyControlConfig.class).autowire();
this.mvc.perform(post("/login").with(csrf()).param("username", "user").param("password", "password"));
this.mvc.perform(post("/login").with(csrf()).param("username", "user").param("password", "password"))
.andExpect(status().isFound()).andExpect(redirectedUrl("/login?error"));
}
@@ -156,13 +143,11 @@ public class SessionManagementConfigurerTests {
@Test
public void loginWhenUserSessionExpiredAndMaxSessionsIsOneThenLoggedIn() throws Exception {
this.spring.register(ConcurrencyControlConfig.class).autowire();
MvcResult mvcResult = this.mvc
.perform(post("/login").with(csrf()).param("username", "user").param("password", "password"))
.andReturn();
HttpSession authenticatedSession = mvcResult.getRequest().getSession();
this.spring.getContext().publishEvent(new HttpSessionDestroyedEvent(authenticatedSession));
this.mvc.perform(post("/login").with(csrf()).param("username", "user").param("password", "password"))
.andExpect(status().isFound()).andExpect(redirectedUrl("/"));
}
@@ -170,9 +155,7 @@ public class SessionManagementConfigurerTests {
@Test
public void loginWhenUserLoggedInAndMaxSessionsOneInLambdaThenLoginPrevented() throws Exception {
this.spring.register(ConcurrencyControlInLambdaConfig.class).autowire();
this.mvc.perform(post("/login").with(csrf()).param("username", "user").param("password", "password"));
this.mvc.perform(post("/login").with(csrf()).param("username", "user").param("password", "password"))
.andExpect(status().isFound()).andExpect(redirectedUrl("/login?error"));
}
@@ -180,10 +163,8 @@ public class SessionManagementConfigurerTests {
@Test
public void requestWhenSessionCreationPolicyStateLessInLambdaThenNoSessionCreated() throws Exception {
this.spring.register(SessionCreationPolicyStateLessInLambdaConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/")).andReturn();
HttpSession session = mvcResult.getRequest().getSession(false);
assertThat(session).isNull();
}
@@ -191,7 +172,6 @@ public class SessionManagementConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnSessionManagementFilter() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(SessionManagementFilter.class));
}
@@ -199,7 +179,6 @@ public class SessionManagementConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnConcurrentSessionFilter() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(ConcurrentSessionFilter.class));
}
@@ -207,7 +186,6 @@ public class SessionManagementConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnConcurrentSessionControlAuthenticationStrategy() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor)
.postProcess(any(ConcurrentSessionControlAuthenticationStrategy.class));
}
@@ -216,7 +194,6 @@ public class SessionManagementConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnCompositeSessionAuthenticationStrategy() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor)
.postProcess(any(CompositeSessionAuthenticationStrategy.class));
}
@@ -225,7 +202,6 @@ public class SessionManagementConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnRegisterSessionAuthenticationStrategy() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor)
.postProcess(any(RegisterSessionAuthenticationStrategy.class));
}
@@ -234,7 +210,6 @@ public class SessionManagementConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnChangeSessionIdAuthenticationStrategy() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor)
.postProcess(any(ChangeSessionIdAuthenticationStrategy.class));
}
@@ -245,9 +220,7 @@ public class SessionManagementConfigurerTests {
SharedTrustResolverConfig.TR = mock(AuthenticationTrustResolver.class);
given(SharedTrustResolverConfig.TR.isAnonymous(any())).willReturn(false);
this.spring.register(SharedTrustResolverConfig.class).autowire();
MvcResult mvcResult = this.mvc.perform(get("/")).andReturn();
assertThat(mvcResult.getRequest().getSession(false)).isNotNull();
}
@@ -255,10 +228,8 @@ public class SessionManagementConfigurerTests {
public void whenOneSessionRegistryBeanThenUseIt() throws Exception {
SessionRegistryOneBeanConfig.SESSION_REGISTRY = mock(SessionRegistry.class);
this.spring.register(SessionRegistryOneBeanConfig.class).autowire();
MockHttpSession session = new MockHttpSession(this.spring.getContext().getServletContext());
this.mvc.perform(get("/").session(session));
verify(SessionRegistryOneBeanConfig.SESSION_REGISTRY).getSessionInformation(session.getId());
}
@@ -267,10 +238,8 @@ public class SessionManagementConfigurerTests {
SessionRegistryTwoBeansConfig.SESSION_REGISTRY_ONE = mock(SessionRegistry.class);
SessionRegistryTwoBeansConfig.SESSION_REGISTRY_TWO = mock(SessionRegistry.class);
this.spring.register(SessionRegistryTwoBeansConfig.class).autowire();
MockHttpSession session = new MockHttpSession(this.spring.getContext().getServletContext());
this.mvc.perform(get("/").session(session));
verifyNoInteractions(SessionRegistryTwoBeansConfig.SESSION_REGISTRY_ONE);
verifyNoInteractions(SessionRegistryTwoBeansConfig.SESSION_REGISTRY_TWO);
}

View File

@@ -50,7 +50,6 @@ public class SessionManagementConfigurerTransientAuthenticationTests {
@Test
public void postWhenTransientAuthenticationThenNoSessionCreated() throws Exception {
this.spring.register(WithTransientAuthenticationConfig.class).autowire();
MvcResult result = this.mvc.perform(post("/login")).andReturn();
assertThat(result.getRequest().getSession(false)).isNull();
@@ -58,7 +57,6 @@ public class SessionManagementConfigurerTransientAuthenticationTests {
@Test
public void postWhenTransientAuthenticationThenAlwaysSessionOverrides() throws Exception {
this.spring.register(AlwaysCreateSessionConfig.class).autowire();
MvcResult result = this.mvc.perform(post("/login")).andReturn();
assertThat(result.getRequest().getSession(false)).isNotNull();

View File

@@ -78,67 +78,45 @@ public class UrlAuthorizationConfigurerTests {
@Test
public void mvcMatcher() throws Exception {
loadConfig(MvcMatcherConfig.class, LegacyMvcMatchingConfig.class);
this.request.setRequestURI("/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setRequestURI("/path.html");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/path/");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
}
@Test
public void mvcMatcherServletPath() throws Exception {
loadConfig(MvcMatcherServletPathConfig.class, LegacyMvcMatchingConfig.class);
this.request.setServletPath("/spring");
this.request.setRequestURI("/spring/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/spring");
this.request.setRequestURI("/spring/path.html");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/spring");
this.request.setRequestURI("/spring/path/");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_UNAUTHORIZED);
setup();
this.request.setServletPath("/foo");
this.request.setRequestURI("/foo/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
setup();
this.request.setServletPath("/");
this.request.setRequestURI("/path");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
}
@@ -152,7 +130,6 @@ public class UrlAuthorizationConfigurerTests {
this.context.register(configs);
this.context.setServletContext(new MockServletContext());
this.context.refresh();
this.context.getAutowireCapableBeanFactory().autowireBean(this);
}

View File

@@ -61,7 +61,6 @@ public class UrlAuthorizationsTests {
@WithMockUser(authorities = "ROLE_USER")
public void hasAnyAuthorityWhenAuthoritySpecifiedThenMatchesAuthority() throws Exception {
this.spring.register(RoleConfig.class).autowire();
this.mvc.perform(get("/role-user-authority")).andExpect(status().isNotFound());
this.mvc.perform(get("/role-user")).andExpect(status().isNotFound());
this.mvc.perform(get("/role-admin-authority")).andExpect(status().isForbidden());
@@ -71,7 +70,6 @@ public class UrlAuthorizationsTests {
@WithMockUser(authorities = "ROLE_ADMIN")
public void hasAnyAuthorityWhenAuthoritiesSpecifiedThenMatchesAuthority() throws Exception {
this.spring.register(RoleConfig.class).autowire();
this.mvc.perform(get("/role-user-admin-authority")).andExpect(status().isNotFound());
this.mvc.perform(get("/role-user-admin")).andExpect(status().isNotFound());
this.mvc.perform(get("/role-user-authority")).andExpect(status().isForbidden());
@@ -81,7 +79,6 @@ public class UrlAuthorizationsTests {
@WithMockUser(roles = "USER")
public void hasAnyRoleWhenRoleSpecifiedThenMatchesRole() throws Exception {
this.spring.register(RoleConfig.class).autowire();
this.mvc.perform(get("/role-user")).andExpect(status().isNotFound());
this.mvc.perform(get("/role-admin")).andExpect(status().isForbidden());
}
@@ -90,7 +87,6 @@ public class UrlAuthorizationsTests {
@WithMockUser(roles = "ADMIN")
public void hasAnyRoleWhenRolesSpecifiedThenMatchesRole() throws Exception {
this.spring.register(RoleConfig.class).autowire();
this.mvc.perform(get("/role-admin-user")).andExpect(status().isNotFound());
this.mvc.perform(get("/role-user")).andExpect(status().isForbidden());
}
@@ -99,7 +95,6 @@ public class UrlAuthorizationsTests {
@WithMockUser(authorities = "USER")
public void hasAnyRoleWhenRoleSpecifiedThenDoesNotMatchAuthority() throws Exception {
this.spring.register(RoleConfig.class).autowire();
this.mvc.perform(get("/role-user")).andExpect(status().isForbidden());
this.mvc.perform(get("/role-admin")).andExpect(status().isForbidden());
}
@@ -107,7 +102,6 @@ public class UrlAuthorizationsTests {
@Test
public void configureWhenNoAccessDecisionManagerThenDefaultsToAffirmativeBased() {
this.spring.register(NoSpecificAccessDecisionManagerConfig.class).autowire();
FilterSecurityInterceptor interceptor = getFilter(FilterSecurityInterceptor.class);
assertThat(interceptor).isNotNull();
assertThat(interceptor).extracting("accessDecisionManager").isInstanceOf(AffirmativeBased.class);
@@ -151,7 +145,6 @@ public class UrlAuthorizationsTests {
ApplicationContext context = getApplicationContext();
UrlAuthorizationConfigurer<HttpSecurity>.StandardInterceptUrlRegistry registry = http
.apply(new UrlAuthorizationConfigurer(context)).getRegistry();
registry.antMatchers("/a").hasRole("ADMIN").anyRequest().hasRole("USER");
}

View File

@@ -61,7 +61,6 @@ public class X509ConfigurerTests {
@Test
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnX509AuthenticationFilter() {
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(X509AuthenticationFilter.class));
}
@@ -69,7 +68,6 @@ public class X509ConfigurerTests {
public void x509WhenInvokedTwiceThenUsesOriginalSubjectPrincipalRegex() throws Exception {
this.spring.register(DuplicateDoesNotOverrideConfig.class).autowire();
X509Certificate certificate = loadCert("rodatexampledotcom.cer");
this.mvc.perform(get("/").with(x509(certificate))).andExpect(authenticated().withUsername("rod"));
}
@@ -77,7 +75,6 @@ public class X509ConfigurerTests {
public void x509WhenConfiguredInLambdaThenUsesDefaults() throws Exception {
this.spring.register(DefaultsInLambdaConfig.class).autowire();
X509Certificate certificate = loadCert("rod.cer");
this.mvc.perform(get("/").with(x509(certificate))).andExpect(authenticated().withUsername("rod"));
}
@@ -85,7 +82,6 @@ public class X509ConfigurerTests {
public void x509WhenSubjectPrincipalRegexInLambdaThenUsesRegexToExtractPrincipal() throws Exception {
this.spring.register(SubjectPrincipalRegexInLambdaConfig.class).autowire();
X509Certificate certificate = loadCert("rodatexampledotcom.cer");
this.mvc.perform(get("/").with(x509(certificate))).andExpect(authenticated().withUsername("rod"));
}

View File

@@ -120,7 +120,6 @@ public class OAuth2ClientConfigurerTests {
authorizedClientService);
authorizationRequestResolver = new DefaultOAuth2AuthorizationRequestResolver(clientRegistrationRepository,
"/oauth2/authorization");
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234")
.tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(300).build();
accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
@@ -132,7 +131,6 @@ public class OAuth2ClientConfigurerTests {
@Test
public void configureWhenAuthorizationCodeRequestThenRedirectForAuthorization() throws Exception {
this.spring.register(OAuth2ClientConfig.class).autowire();
MvcResult mvcResult = this.mockMvc.perform(get("/oauth2/authorization/registration-1"))
.andExpect(status().is3xxRedirection()).andReturn();
assertThat(mvcResult.getResponse().getRedirectedUrl())
@@ -143,7 +141,6 @@ public class OAuth2ClientConfigurerTests {
@Test
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();
assertThat(mvcResult.getResponse().getRedirectedUrl())
@@ -154,7 +151,6 @@ public class OAuth2ClientConfigurerTests {
@Test
public void configureWhenAuthorizationCodeResponseSuccessThenAuthorizedClientSaved() throws Exception {
this.spring.register(OAuth2ClientConfig.class).autowire();
// Setup the Authorization Request in the session
Map<String, Object> attributes = new HashMap<>();
attributes.put(OAuth2ParameterNames.REGISTRATION_ID, this.registration1.getRegistrationId());
@@ -162,21 +158,16 @@ public class OAuth2ClientConfigurerTests {
.authorizationUri(this.registration1.getProviderDetails().getAuthorizationUri())
.clientId(this.registration1.getClientId()).redirectUri("http://localhost/client-1").state("state")
.attributes(attributes).build();
AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = new HttpSessionOAuth2AuthorizationRequestRepository();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "");
MockHttpServletResponse response = new MockHttpServletResponse();
authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, request, response);
MockHttpSession session = (MockHttpSession) request.getSession();
String principalName = "user1";
TestingAuthenticationToken authentication = new TestingAuthenticationToken(principalName, "password");
this.mockMvc.perform(get("/client-1").param(OAuth2ParameterNames.CODE, "code")
.param(OAuth2ParameterNames.STATE, "state").with(authentication(authentication)).session(session))
.andExpect(status().is3xxRedirection()).andExpect(redirectedUrl("http://localhost/client-1"));
OAuth2AuthorizedClient authorizedClient = authorizedClientRepository
.loadAuthorizedClient(this.registration1.getRegistrationId(), authentication, request);
assertThat(authorizedClient).isNotNull();
@@ -186,20 +177,17 @@ public class OAuth2ClientConfigurerTests {
public void configureWhenRequestCacheProvidedAndClientAuthorizationRequiredExceptionThrownThenRequestCacheUsed()
throws Exception {
this.spring.register(OAuth2ClientConfig.class).autowire();
MvcResult mvcResult = this.mockMvc.perform(get("/resource1").with(user("user1")))
.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");
verify(requestCache).saveRequest(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@Test
public void configureWhenRequestCacheProvidedAndClientAuthorizationSucceedsThenRequestCacheUsed() throws Exception {
this.spring.register(OAuth2ClientConfig.class).autowire();
// Setup the Authorization Request in the session
Map<String, Object> attributes = new HashMap<>();
attributes.put(OAuth2ParameterNames.REGISTRATION_ID, this.registration1.getRegistrationId());
@@ -207,21 +195,16 @@ public class OAuth2ClientConfigurerTests {
.authorizationUri(this.registration1.getProviderDetails().getAuthorizationUri())
.clientId(this.registration1.getClientId()).redirectUri("http://localhost/client-1").state("state")
.attributes(attributes).build();
AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = new HttpSessionOAuth2AuthorizationRequestRepository();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "");
MockHttpServletResponse response = new MockHttpServletResponse();
authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, request, response);
MockHttpSession session = (MockHttpSession) request.getSession();
String principalName = "user1";
TestingAuthenticationToken authentication = new TestingAuthenticationToken(principalName, "password");
this.mockMvc.perform(get("/client-1").param(OAuth2ParameterNames.CODE, "code")
.param(OAuth2ParameterNames.STATE, "state").with(authentication(authentication)).session(session))
.andExpect(status().is3xxRedirection()).andExpect(redirectedUrl("http://localhost/client-1"));
verify(requestCache).getRequest(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@@ -234,12 +217,9 @@ public class OAuth2ClientConfigurerTests {
authorizationRequestResolver = mock(OAuth2AuthorizationRequestResolver.class);
given(authorizationRequestResolver.resolve(any()))
.willAnswer((invocation) -> defaultAuthorizationRequestResolver.resolve(invocation.getArgument(0)));
this.spring.register(OAuth2ClientConfig.class).autowire();
this.mockMvc.perform(get("/oauth2/authorization/registration-1")).andExpect(status().is3xxRedirection())
.andReturn();
verify(authorizationRequestResolver).resolve(any());
}

View File

@@ -157,18 +157,14 @@ public class OAuth2LoginConfigurerTests {
public void oauth2Login() throws Exception {
// setup application context
loadConfig(OAuth2LoginConfig.class);
// setup authorization request
OAuth2AuthorizationRequest authorizationRequest = createOAuth2AuthorizationRequest();
this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, this.request, this.response);
// setup authentication parameters
this.request.setParameter("code", "code123");
this.request.setParameter("state", authorizationRequest.getState());
// perform test
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
// assertions
Authentication authentication = this.securityContextRepository
.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
@@ -184,9 +180,7 @@ public class OAuth2LoginConfigurerTests {
this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, this.request, this.response);
this.request.setParameter("code", "code123");
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();
assertThat(authentication.getAuthorities()).hasSize(1);
@@ -199,18 +193,14 @@ public class OAuth2LoginConfigurerTests {
public void oauth2LoginWhenSuccessThenAuthenticationSuccessEventPublished() throws Exception {
// setup application context
loadConfig(OAuth2LoginConfig.class);
// setup authorization request
OAuth2AuthorizationRequest authorizationRequest = createOAuth2AuthorizationRequest();
this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, this.request, this.response);
// setup authentication parameters
this.request.setParameter("code", "code123");
this.request.setParameter("state", authorizationRequest.getState());
// perform test
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
// assertions
assertThat(OAuth2LoginConfig.EVENTS).isNotEmpty();
assertThat(OAuth2LoginConfig.EVENTS).hasSize(1);
@@ -221,18 +211,14 @@ public class OAuth2LoginConfigurerTests {
public void oauth2LoginCustomWithConfigurer() throws Exception {
// setup application context
loadConfig(OAuth2LoginConfigCustomWithConfigurer.class);
// setup authorization request
OAuth2AuthorizationRequest authorizationRequest = createOAuth2AuthorizationRequest();
this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, this.request, this.response);
// setup authentication parameters
this.request.setParameter("code", "code123");
this.request.setParameter("state", authorizationRequest.getState());
// perform test
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
// assertions
Authentication authentication = this.securityContextRepository
.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
@@ -245,18 +231,14 @@ public class OAuth2LoginConfigurerTests {
public void oauth2LoginCustomWithBeanRegistration() throws Exception {
// setup application context
loadConfig(OAuth2LoginConfigCustomWithBeanRegistration.class);
// setup authorization request
OAuth2AuthorizationRequest authorizationRequest = createOAuth2AuthorizationRequest();
this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, this.request, this.response);
// setup authentication parameters
this.request.setParameter("code", "code123");
this.request.setParameter("state", authorizationRequest.getState());
// perform test
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
// assertions
Authentication authentication = this.securityContextRepository
.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
@@ -269,18 +251,14 @@ public class OAuth2LoginConfigurerTests {
public void oauth2LoginCustomWithUserServiceBeanRegistration() throws Exception {
// setup application context
loadConfig(OAuth2LoginConfigCustomUserServiceBeanRegistration.class);
// setup authorization request
OAuth2AuthorizationRequest authorizationRequest = createOAuth2AuthorizationRequest();
this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, this.request, this.response);
// setup authentication parameters
this.request.setParameter("code", "code123");
this.request.setParameter("state", authorizationRequest.getState());
// perform test
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
// assertions
Authentication authentication = this.securityContextRepository
.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
@@ -294,19 +272,15 @@ public class OAuth2LoginConfigurerTests {
public void oauth2LoginConfigLoginProcessingUrl() throws Exception {
// setup application context
loadConfig(OAuth2LoginConfigLoginProcessingUrl.class);
// setup authorization request
OAuth2AuthorizationRequest authorizationRequest = createOAuth2AuthorizationRequest();
this.request.setServletPath("/login/oauth2/google");
this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, this.request, this.response);
// setup authentication parameters
this.request.setParameter("code", "code123");
this.request.setParameter("state", authorizationRequest.getState());
// perform test
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
// assertions
Authentication authentication = this.securityContextRepository
.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
@@ -327,13 +301,10 @@ public class OAuth2LoginConfigurerTests {
"https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=clientId&scope=openid+profile+email&state=state&redirect_uri=http%3A%2F%2Flocalhost%2Flogin%2Foauth2%2Fcode%2Fgoogle&custom-param1=custom-value1")
.build();
given(resolver.resolve(any())).willReturn(result);
String requestUri = "/oauth2/authorization/google";
this.request = new MockHttpServletRequest("GET", requestUri);
this.request.setServletPath(requestUri);
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
assertThat(this.response.getRedirectedUrl()).isEqualTo(
"https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=clientId&scope=openid+profile+email&state=state&redirect_uri=http%3A%2F%2Flocalhost%2Flogin%2Foauth2%2Fcode%2Fgoogle&custom-param1=custom-value1");
}
@@ -350,13 +321,10 @@ public class OAuth2LoginConfigurerTests {
"https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=clientId&scope=openid+profile+email&state=state&redirect_uri=http%3A%2F%2Flocalhost%2Flogin%2Foauth2%2Fcode%2Fgoogle&custom-param1=custom-value1")
.build();
given(resolver.resolve(any())).willReturn(result);
String requestUri = "/oauth2/authorization/google";
this.request = new MockHttpServletRequest("GET", requestUri);
this.request.setServletPath(requestUri);
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
assertThat(this.response.getRedirectedUrl()).isEqualTo(
"https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=clientId&scope=openid+profile+email&state=state&redirect_uri=http%3A%2F%2Flocalhost%2Flogin%2Foauth2%2Fcode%2Fgoogle&custom-param1=custom-value1");
}
@@ -365,13 +333,10 @@ public class OAuth2LoginConfigurerTests {
@Test
public void oauth2LoginWithOneClientConfiguredThenRedirectForAuthorization() throws Exception {
loadConfig(OAuth2LoginConfig.class);
String requestUri = "/";
this.request = new MockHttpServletRequest("GET", requestUri);
this.request.setServletPath(requestUri);
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
assertThat(this.response.getRedirectedUrl()).matches("http://localhost/oauth2/authorization/google");
}
@@ -380,14 +345,11 @@ public class OAuth2LoginConfigurerTests {
public void oauth2LoginWithOneClientConfiguredAndRequestFaviconNotAuthenticatedThenRedirectDefaultLoginPage()
throws Exception {
loadConfig(OAuth2LoginConfig.class);
String requestUri = "/favicon.ico";
this.request = new MockHttpServletRequest("GET", requestUri);
this.request.setServletPath(requestUri);
this.request.addHeader(HttpHeaders.ACCEPT, new MediaType("image", "*").toString());
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
assertThat(this.response.getRedirectedUrl()).matches("http://localhost/login");
}
@@ -395,13 +357,10 @@ public class OAuth2LoginConfigurerTests {
@Test
public void oauth2LoginWithMultipleClientsConfiguredThenRedirectDefaultLoginPage() throws Exception {
loadConfig(OAuth2LoginConfigMultipleClients.class);
String requestUri = "/";
this.request = new MockHttpServletRequest("GET", requestUri);
this.request.setServletPath(requestUri);
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
assertThat(this.response.getRedirectedUrl()).matches("http://localhost/login");
}
@@ -410,40 +369,31 @@ public class OAuth2LoginConfigurerTests {
public void oauth2LoginWithOneClientConfiguredAndRequestXHRNotAuthenticatedThenDoesNotRedirectForAuthorization()
throws Exception {
loadConfig(OAuth2LoginConfig.class);
String requestUri = "/";
this.request = new MockHttpServletRequest("GET", requestUri);
this.request.setServletPath(requestUri);
this.request.addHeader("X-Requested-With", "XMLHttpRequest");
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
assertThat(this.response.getRedirectedUrl()).doesNotMatch("http://localhost/oauth2/authorization/google");
}
@Test
public void oauth2LoginWithCustomLoginPageThenRedirectCustomLoginPage() throws Exception {
loadConfig(OAuth2LoginConfigCustomLoginPage.class);
String requestUri = "/";
this.request = new MockHttpServletRequest("GET", requestUri);
this.request.setServletPath(requestUri);
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
assertThat(this.response.getRedirectedUrl()).matches("http://localhost/custom-login");
}
@Test
public void requestWhenOauth2LoginWithCustomLoginPageInLambdaThenRedirectCustomLoginPage() throws Exception {
loadConfig(OAuth2LoginConfigCustomLoginPageInLambda.class);
String requestUri = "/";
this.request = new MockHttpServletRequest("GET", requestUri);
this.request.setServletPath(requestUri);
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
assertThat(this.response.getRedirectedUrl()).matches("http://localhost/custom-login");
}
@@ -451,18 +401,14 @@ public class OAuth2LoginConfigurerTests {
public void oidcLogin() throws Exception {
// setup application context
loadConfig(OAuth2LoginConfig.class, JwtDecoderFactoryConfig.class);
// setup authorization request
OAuth2AuthorizationRequest authorizationRequest = createOAuth2AuthorizationRequest("openid");
this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, this.request, this.response);
// setup authentication parameters
this.request.setParameter("code", "code123");
this.request.setParameter("state", authorizationRequest.getState());
// perform test
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
// assertions
Authentication authentication = this.securityContextRepository
.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
@@ -475,18 +421,14 @@ public class OAuth2LoginConfigurerTests {
public void requestWhenOauth2LoginInLambdaAndOidcThenAuthenticationContainsOidcUserAuthority() throws Exception {
// setup application context
loadConfig(OAuth2LoginInLambdaConfig.class, JwtDecoderFactoryConfig.class);
// setup authorization request
OAuth2AuthorizationRequest authorizationRequest = createOAuth2AuthorizationRequest("openid");
this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, this.request, this.response);
// setup authentication parameters
this.request.setParameter("code", "code123");
this.request.setParameter("state", authorizationRequest.getState());
// perform test
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
// assertions
Authentication authentication = this.securityContextRepository
.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
@@ -499,18 +441,14 @@ public class OAuth2LoginConfigurerTests {
public void oidcLoginCustomWithConfigurer() throws Exception {
// setup application context
loadConfig(OAuth2LoginConfigCustomWithConfigurer.class, JwtDecoderFactoryConfig.class);
// setup authorization request
OAuth2AuthorizationRequest authorizationRequest = createOAuth2AuthorizationRequest("openid");
this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, this.request, this.response);
// setup authentication parameters
this.request.setParameter("code", "code123");
this.request.setParameter("state", authorizationRequest.getState());
// perform test
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
// assertions
Authentication authentication = this.securityContextRepository
.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
@@ -523,18 +461,14 @@ public class OAuth2LoginConfigurerTests {
public void oidcLoginCustomWithBeanRegistration() throws Exception {
// setup application context
loadConfig(OAuth2LoginConfigCustomWithBeanRegistration.class, JwtDecoderFactoryConfig.class);
// setup authorization request
OAuth2AuthorizationRequest authorizationRequest = createOAuth2AuthorizationRequest("openid");
this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, this.request, this.response);
// setup authentication parameters
this.request.setParameter("code", "code123");
this.request.setParameter("state", authorizationRequest.getState());
// perform test
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
// assertions
Authentication authentication = this.securityContextRepository
.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
@@ -555,10 +489,8 @@ public class OAuth2LoginConfigurerTests {
@Test
public void logoutWhenUsingOidcLogoutHandlerThenRedirects() throws Exception {
this.spring.register(OAuth2LoginConfigWithOidcLogoutSuccessHandler.class).autowire();
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"));
}

View File

@@ -71,7 +71,6 @@ public class OpenIDLoginConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnOpenIDAuthenticationFilter() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(OpenIDAuthenticationFilter.class));
}
@@ -79,14 +78,12 @@ public class OpenIDLoginConfigurerTests {
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnOpenIDAuthenticationProvider() {
ObjectPostProcessorConfig.objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor).postProcess(any(OpenIDAuthenticationProvider.class));
}
@Test
public void openidLoginWhenInvokedTwiceThenUsesOriginalLoginPage() throws Exception {
this.spring.register(InvokeTwiceDoesNotOverrideConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isFound())
.andExpect(redirectedUrl("http://localhost/login/custom"));
}
@@ -94,7 +91,6 @@ public class OpenIDLoginConfigurerTests {
@Test
public void requestWhenOpenIdLoginPageInLambdaThenRedirectsToLoginPAge() throws Exception {
this.spring.register(OpenIdLoginPageInLambdaConfig.class).autowire();
this.mvc.perform(get("/")).andExpect(status().isFound())
.andExpect(redirectedUrl("http://localhost/login/custom"));
}
@@ -109,18 +105,14 @@ public class OpenIDLoginConfigurerTests {
given(OpenIdAttributesInLambdaConfig.CONSUMER_MANAGER.authenticate(any(DiscoveryInformation.class), any(),
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");
assertThat(attributeObject).isInstanceOf(List.class);
@@ -147,18 +139,14 @@ public class OpenIDLoginConfigurerTests {
given(OpenIdAttributesNullNameConfig.CONSUMER_MANAGER.authenticate(any(DiscoveryInformation.class), any(),
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)));
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);

View File

@@ -169,7 +169,6 @@ public class Saml2LoginConfigurerTests {
@Test
public void saml2LoginWhenCustomAuthenticationRequestContextResolverThenUses() throws Exception {
this.spring.register(CustomAuthenticationRequestContextResolver.class).autowire();
Saml2AuthenticationRequestContext context = TestSaml2AuthenticationRequestContexts
.authenticationRequestContext().build();
Saml2AuthenticationRequestContextResolver resolver = CustomAuthenticationRequestContextResolver.resolver;
@@ -181,7 +180,6 @@ public class Saml2LoginConfigurerTests {
@Test
public void authenticationRequestWhenAuthnRequestConsumerResolverThenUses() throws Exception {
this.spring.register(CustomAuthnRequestConsumerResolver.class).autowire();
MvcResult result = this.mvc.perform(get("/saml2/authenticate/registration-id")).andReturn();
UriComponents components = UriComponentsBuilder.fromHttpUrl(result.getResponse().getRedirectedUrl()).build();
String samlRequest = components.getQueryParams().getFirst("SAMLRequest");
@@ -228,10 +226,8 @@ public class Saml2LoginConfigurerTests {
// setup authentication parameters
this.request.setParameter("SAMLResponse",
Base64.getEncoder().encodeToString("saml2-xml-response-object".getBytes()));
// perform test
this.springSecurityFilterChain.doFilter(this.request, this.response, this.filterChain);
// assertions
Authentication authentication = this.securityContextRepository
.loadContext(new HttpRequestResponseHolder(this.request, this.response)).getAuthentication();
@@ -263,7 +259,6 @@ public class Saml2LoginConfigurerTests {
private static AuthenticationManager getAuthenticationManagerMock(String role) {
return new AuthenticationManager() {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (!supports(authentication.getClass())) {
@@ -306,7 +301,6 @@ public class Saml2LoginConfigurerTests {
return provider;
}
};
http.saml2Login().addObjectPostProcessor(processor);
super.configure(http);
}

View File

@@ -62,13 +62,10 @@ public class MessageSecurityMetadataSourceRegistryTests {
this.message = MessageBuilder.withPayload("Hi")
.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "price.stock.1.2").build();
this.messages.simpDestPathMatcher(new AntPathMatcher(".")).simpDestMatchers("price.stock.*").permitAll();
assertThat(getAttribute()).isNull();
this.message = MessageBuilder.withPayload("Hi")
.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "price.stock.1.2").build();
this.messages.simpDestPathMatcher(new AntPathMatcher(".")).simpDestMatchers("price.stock.**").permitAll();
assertThat(getAttribute()).isEqualTo("permitAll");
}
@@ -77,13 +74,10 @@ public class MessageSecurityMetadataSourceRegistryTests {
this.message = MessageBuilder.withPayload("Hi")
.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "price.stock.1.2").build();
this.messages.simpDestMatchers("price.stock.*").permitAll().simpDestPathMatcher(new AntPathMatcher("."));
assertThat(getAttribute()).isNull();
this.message = MessageBuilder.withPayload("Hi")
.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, "price.stock.1.2").build();
this.messages.simpDestMatchers("price.stock.**").permitAll().simpDestPathMatcher(new AntPathMatcher("."));
assertThat(getAttribute()).isEqualTo("permitAll");
}
@@ -95,7 +89,6 @@ public class MessageSecurityMetadataSourceRegistryTests {
@Test
public void matchersFalse() {
this.messages.matchers(this.matcher).permitAll();
assertThat(getAttribute()).isNull();
}
@@ -103,35 +96,30 @@ public class MessageSecurityMetadataSourceRegistryTests {
public void matchersTrue() {
given(this.matcher.matches(this.message)).willReturn(true);
this.messages.matchers(this.matcher).permitAll();
assertThat(getAttribute()).isEqualTo("permitAll");
}
@Test
public void simpDestMatchersExact() {
this.messages.simpDestMatchers("location").permitAll();
assertThat(getAttribute()).isEqualTo("permitAll");
}
@Test
public void simpDestMatchersMulti() {
this.messages.simpDestMatchers("admin/**", "api/**").hasRole("ADMIN").simpDestMatchers("location").permitAll();
assertThat(getAttribute()).isEqualTo("permitAll");
}
@Test
public void simpDestMatchersRole() {
this.messages.simpDestMatchers("admin/**", "location/**").hasRole("ADMIN").anyMessage().denyAll();
assertThat(getAttribute()).isEqualTo("hasRole('ROLE_ADMIN')");
}
@Test
public void simpDestMatchersAnyRole() {
this.messages.simpDestMatchers("admin/**", "location/**").hasAnyRole("ADMIN", "ROOT").anyMessage().denyAll();
assertThat(getAttribute()).isEqualTo("hasAnyRole('ROLE_ADMIN','ROLE_ROOT')");
}
@@ -139,7 +127,6 @@ public class MessageSecurityMetadataSourceRegistryTests {
public void simpDestMatchersAuthority() {
this.messages.simpDestMatchers("admin/**", "location/**").hasAuthority("ROLE_ADMIN").anyMessage()
.fullyAuthenticated();
assertThat(getAttribute()).isEqualTo("hasAuthority('ROLE_ADMIN')");
}
@@ -147,7 +134,6 @@ public class MessageSecurityMetadataSourceRegistryTests {
public void simpDestMatchersAccess() {
String expected = "hasRole('ROLE_ADMIN') and fullyAuthenticated";
this.messages.simpDestMatchers("admin/**", "location/**").access(expected).anyMessage().denyAll();
assertThat(getAttribute()).isEqualTo(expected);
}
@@ -155,56 +141,48 @@ public class MessageSecurityMetadataSourceRegistryTests {
public void simpDestMatchersAnyAuthority() {
this.messages.simpDestMatchers("admin/**", "location/**").hasAnyAuthority("ROLE_ADMIN", "ROLE_ROOT")
.anyMessage().denyAll();
assertThat(getAttribute()).isEqualTo("hasAnyAuthority('ROLE_ADMIN','ROLE_ROOT')");
}
@Test
public void simpDestMatchersRememberMe() {
this.messages.simpDestMatchers("admin/**", "location/**").rememberMe().anyMessage().denyAll();
assertThat(getAttribute()).isEqualTo("rememberMe");
}
@Test
public void simpDestMatchersAnonymous() {
this.messages.simpDestMatchers("admin/**", "location/**").anonymous().anyMessage().denyAll();
assertThat(getAttribute()).isEqualTo("anonymous");
}
@Test
public void simpDestMatchersFullyAuthenticated() {
this.messages.simpDestMatchers("admin/**", "location/**").fullyAuthenticated().anyMessage().denyAll();
assertThat(getAttribute()).isEqualTo("fullyAuthenticated");
}
@Test
public void simpDestMatchersDenyAll() {
this.messages.simpDestMatchers("admin/**", "location/**").denyAll().anyMessage().permitAll();
assertThat(getAttribute()).isEqualTo("denyAll");
}
@Test
public void simpDestMessageMatchersNotMatch() {
this.messages.simpMessageDestMatchers("admin/**").denyAll().anyMessage().permitAll();
assertThat(getAttribute()).isEqualTo("permitAll");
}
@Test
public void simpDestMessageMatchersMatch() {
this.messages.simpMessageDestMatchers("location/**").denyAll().anyMessage().permitAll();
assertThat(getAttribute()).isEqualTo("denyAll");
}
@Test
public void simpDestSubscribeMatchersNotMatch() {
this.messages.simpSubscribeDestMatchers("location/**").denyAll().anyMessage().permitAll();
assertThat(getAttribute()).isEqualTo("permitAll");
}
@@ -212,16 +190,13 @@ public class MessageSecurityMetadataSourceRegistryTests {
public void simpDestSubscribeMatchersMatch() {
this.message = MessageBuilder.fromMessage(this.message)
.setHeader(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER, SimpMessageType.SUBSCRIBE).build();
this.messages.simpSubscribeDestMatchers("location/**").denyAll().anyMessage().permitAll();
assertThat(getAttribute()).isEqualTo("denyAll");
}
@Test
public void nullDestMatcherNotMatches() {
this.messages.nullDestMatcher().denyAll().anyMessage().permitAll();
assertThat(getAttribute()).isEqualTo("permitAll");
}
@@ -229,16 +204,13 @@ public class MessageSecurityMetadataSourceRegistryTests {
public void nullDestMatcherMatch() {
this.message = MessageBuilder.withPayload("Hi")
.setHeader(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER, SimpMessageType.CONNECT).build();
this.messages.nullDestMatcher().denyAll().anyMessage().permitAll();
assertThat(getAttribute()).isEqualTo("denyAll");
}
@Test
public void simpTypeMatchersMatch() {
this.messages.simpTypeMatchers(SimpMessageType.MESSAGE).denyAll().anyMessage().permitAll();
assertThat(getAttribute()).isEqualTo("denyAll");
}
@@ -246,14 +218,12 @@ public class MessageSecurityMetadataSourceRegistryTests {
public void simpTypeMatchersMatchMulti() {
this.messages.simpTypeMatchers(SimpMessageType.CONNECT, SimpMessageType.MESSAGE).denyAll().anyMessage()
.permitAll();
assertThat(getAttribute()).isEqualTo("denyAll");
}
@Test
public void simpTypeMatchersNotMatch() {
this.messages.simpTypeMatchers(SimpMessageType.CONNECT).denyAll().anyMessage().permitAll();
assertThat(getAttribute()).isEqualTo("permitAll");
}
@@ -261,7 +231,6 @@ public class MessageSecurityMetadataSourceRegistryTests {
public void simpTypeMatchersNotMatchMulti() {
this.messages.simpTypeMatchers(SimpMessageType.CONNECT, SimpMessageType.DISCONNECT).denyAll().anyMessage()
.permitAll();
assertThat(getAttribute()).isEqualTo("permitAll");
}

Some files were not shown because too many files have changed in this diff Show More