filterChains = context.getBean(FilterChainProxy).filterChains
+ filterChains.size() == 2
+ filterChains[0].requestMatcher.pattern == '/resources/**'
+ filterChains[0].filters.empty
+ filterChains[1].requestMatcher instanceof AnyRequestMatcher
+ filterChains[1].filters.collect { it.class } ==
+ [WebAsyncManagerIntegrationFilter, SecurityContextPersistenceFilter, HeaderWriterFilter, CsrfFilter, LogoutFilter, RequestCacheAwareFilter,
+ SecurityContextHolderAwareRequestFilter, AnonymousAuthenticationFilter, SessionManagementFilter,
+ ExceptionTranslationFilter, FilterSecurityInterceptor ]
+ }
- @EnableWebSecurity
- static class FilterChainProxyBuilderIgnoringConfig extends BaseWebConfig {
- @Override
- public void configure(WebSecurity builder) throws Exception {
- builder
- .ignoring()
- .antMatchers("/resources/**");
- }
- @Override
- protected void configure(HttpSecurity http) {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER");
- }
- }
+ @EnableWebSecurity
+ static class FilterChainProxyBuilderIgnoringConfig extends BaseWebConfig {
+ @Override
+ public void configure(WebSecurity builder) throws Exception {
+ builder
+ .ignoring()
+ .antMatchers("/resources/**");
+ }
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER");
+ }
+ }
def "DefaultFilters.permitAll()"() {
- when:
- loadConfig(DefaultFiltersConfigPermitAll)
- MockHttpServletResponse response = new MockHttpServletResponse()
- request = new MockHttpServletRequest(servletPath : uri, queryString: query, method:"POST")
- setupCsrf()
- springSecurityFilterChain.doFilter(request, response, new MockFilterChain())
- then:
- response.redirectedUrl == "/login?logout"
- where:
- uri | query
- "/logout" | null
- }
+ when:
+ loadConfig(DefaultFiltersConfigPermitAll)
+ MockHttpServletResponse response = new MockHttpServletResponse()
+ request = new MockHttpServletRequest(servletPath : uri, queryString: query, method:"POST")
+ setupCsrf()
+ springSecurityFilterChain.doFilter(request, response, new MockFilterChain())
+ then:
+ response.redirectedUrl == "/login?logout"
+ where:
+ uri | query
+ "/logout" | null
+ }
- @EnableWebSecurity
- static class DefaultFiltersConfigPermitAll extends BaseWebConfig {
- protected void configure(HttpSecurity http) {
- }
- }
+ @EnableWebSecurity
+ static class DefaultFiltersConfigPermitAll extends BaseWebConfig {
+ protected void configure(HttpSecurity http) {
+ }
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/DefaultLoginPageConfigurerTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/DefaultLoginPageConfigurerTests.groovy
index e523a2d8ab..08b389ef0b 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/DefaultLoginPageConfigurerTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/DefaultLoginPageConfigurerTests.groovy
@@ -42,295 +42,295 @@ import org.springframework.security.web.authentication.ui.DefaultLoginPageGenera
*
*/
public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
- def "http/form-login default login generating page"() {
- setup:
- loadConfig(DefaultLoginPageConfig)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- findFilter(DefaultLoginPageGeneratingFilter)
- response.getRedirectedUrl() == "http://localhost/login"
- when: "request the login page"
- super.setup()
- request.requestURI = "/login"
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.getContentAsString() == """Login Page
+ def "http/form-login default login generating page"() {
+ setup:
+ loadConfig(DefaultLoginPageConfig)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ findFilter(DefaultLoginPageGeneratingFilter)
+ response.getRedirectedUrl() == "http://localhost/login"
+ when: "request the login page"
+ super.setup()
+ request.requestURI = "/login"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.getContentAsString() == """Login Page
Login with Username and Password
"""
- when: "fail to log in"
- super.setup()
- request.servletPath = "/login"
- request.method = "POST"
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "sent to login error page"
- response.getRedirectedUrl() == "/login?error"
- when: "request the error page"
- HttpSession session = request.session
- super.setup()
- request.session = session
- request.requestURI = "/login"
- request.queryString = "error"
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.getContentAsString() == """Login Page
+ when: "fail to log in"
+ super.setup()
+ request.servletPath = "/login"
+ request.method = "POST"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "sent to login error page"
+ response.getRedirectedUrl() == "/login?error"
+ when: "request the error page"
+ HttpSession session = request.session
+ super.setup()
+ request.session = session
+ request.requestURI = "/login"
+ request.queryString = "error"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.getContentAsString() == """Login Page
Your login attempt was not successful, try again.
Reason: Bad credentials
Login with Username and Password
"""
- when: "login success"
- super.setup()
- request.servletPath = "/login"
- request.method = "POST"
- request.parameters.username = ["user"] as String[]
- request.parameters.password = ["password"] as String[]
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "sent to default succes page"
- response.getRedirectedUrl() == "/"
- }
+ when: "login success"
+ super.setup()
+ request.servletPath = "/login"
+ request.method = "POST"
+ request.parameters.username = ["user"] as String[]
+ request.parameters.password = ["password"] as String[]
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "sent to default succes page"
+ response.getRedirectedUrl() == "/"
+ }
- def "logout success renders"() {
- setup:
- loadConfig(DefaultLoginPageConfig)
- when: "logout success"
- request.requestURI = "/login"
- request.queryString = "logout"
- request.method = "GET"
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "sent to default success page"
- response.getContentAsString() == """Login Page
+ def "logout success renders"() {
+ setup:
+ loadConfig(DefaultLoginPageConfig)
+ when: "logout success"
+ request.requestURI = "/login"
+ request.queryString = "logout"
+ request.method = "GET"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "sent to default success page"
+ response.getContentAsString() == """Login Page
You have been logged out
Login with Username and Password
"""
- }
+ }
- @Configuration
- static class DefaultLoginPageConfig extends BaseWebConfig {
- @Override
- protected void configure(HttpSecurity http) {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .formLogin()
- }
- }
+ @Configuration
+ static class DefaultLoginPageConfig extends BaseWebConfig {
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .formLogin()
+ }
+ }
- def "custom logout success handler prevents rendering"() {
- setup:
- loadConfig(DefaultLoginPageCustomLogoutSuccessHandlerConfig)
- when: "logout success"
- request.requestURI = "/login"
- request.queryString = "logout"
- request.method = "GET"
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "default success page is NOT rendered (application is in charge of it)"
- response.getContentAsString() == ""
- }
+ def "custom logout success handler prevents rendering"() {
+ setup:
+ loadConfig(DefaultLoginPageCustomLogoutSuccessHandlerConfig)
+ when: "logout success"
+ request.requestURI = "/login"
+ request.queryString = "logout"
+ request.method = "GET"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "default success page is NOT rendered (application is in charge of it)"
+ response.getContentAsString() == ""
+ }
- @Configuration
- static class DefaultLoginPageCustomLogoutSuccessHandlerConfig extends BaseWebConfig {
- @Override
- protected void configure(HttpSecurity http) {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .logout()
- .logoutSuccessHandler(new SimpleUrlLogoutSuccessHandler())
- .and()
- .formLogin()
- }
- }
+ @Configuration
+ static class DefaultLoginPageCustomLogoutSuccessHandlerConfig extends BaseWebConfig {
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .logout()
+ .logoutSuccessHandler(new SimpleUrlLogoutSuccessHandler())
+ .and()
+ .formLogin()
+ }
+ }
- def "custom logout success url prevents rendering"() {
- setup:
- loadConfig(DefaultLoginPageCustomLogoutConfig)
- when: "logout success"
- request.requestURI = "/login"
- request.queryString = "logout"
- request.method = "GET"
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "default success page is NOT rendered (application is in charge of it)"
- response.getContentAsString() == ""
- }
+ def "custom logout success url prevents rendering"() {
+ setup:
+ loadConfig(DefaultLoginPageCustomLogoutConfig)
+ when: "logout success"
+ request.requestURI = "/login"
+ request.queryString = "logout"
+ request.method = "GET"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "default success page is NOT rendered (application is in charge of it)"
+ response.getContentAsString() == ""
+ }
- @Configuration
- static class DefaultLoginPageCustomLogoutConfig extends BaseWebConfig {
- @Override
- protected void configure(HttpSecurity http) {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .logout()
- .logoutSuccessUrl("/login?logout")
- .and()
- .formLogin()
- }
- }
+ @Configuration
+ static class DefaultLoginPageCustomLogoutConfig extends BaseWebConfig {
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .logout()
+ .logoutSuccessUrl("/login?logout")
+ .and()
+ .formLogin()
+ }
+ }
- def "http/form-login default login with remember me"() {
- setup:
- loadConfig(DefaultLoginPageWithRememberMeConfig)
- when: "request the login page"
- super.setup()
- request.requestURI = "/login"
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.getContentAsString() == """Login Page
+ def "http/form-login default login with remember me"() {
+ setup:
+ loadConfig(DefaultLoginPageWithRememberMeConfig)
+ when: "request the login page"
+ super.setup()
+ request.requestURI = "/login"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.getContentAsString() == """Login Page
Login with Username and Password
"""
- }
+ }
- @Configuration
- static class DefaultLoginPageWithRememberMeConfig extends BaseWebConfig {
- @Override
- protected void configure(HttpSecurity http) {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .formLogin()
- .and()
- .rememberMe()
- }
- }
+ @Configuration
+ static class DefaultLoginPageWithRememberMeConfig extends BaseWebConfig {
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .formLogin()
+ .and()
+ .rememberMe()
+ }
+ }
- def "http/form-login default login with openid"() {
- setup:
- loadConfig(DefaultLoginPageWithOpenIDConfig)
- when: "request the login page"
- request.requestURI = "/login"
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.getContentAsString() == """Login PageLogin with OpenID Identity
"""
- }
+ }
- @Configuration
- static class DefaultLoginPageWithOpenIDConfig extends BaseWebConfig {
- @Override
- protected void configure(HttpSecurity http) {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .openidLogin()
- }
- }
+ @Configuration
+ static class DefaultLoginPageWithOpenIDConfig extends BaseWebConfig {
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .openidLogin()
+ }
+ }
- def "http/form-login default login with openid, form login, and rememberme"() {
- setup:
- loadConfig(DefaultLoginPageWithFormLoginOpenIDRememberMeConfig)
- when: "request the login page"
- request.requestURI = "/login"
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.getContentAsString() == """Login Page
+ def "http/form-login default login with openid, form login, and rememberme"() {
+ setup:
+ loadConfig(DefaultLoginPageWithFormLoginOpenIDRememberMeConfig)
+ when: "request the login page"
+ request.requestURI = "/login"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.getContentAsString() == """Login Page
Login with Username and Password
Login with OpenID Identity
"""
- }
+ }
- @Configuration
- static class DefaultLoginPageWithFormLoginOpenIDRememberMeConfig extends BaseWebConfig {
- @Override
- protected void configure(HttpSecurity http) {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .rememberMe()
- .and()
- .formLogin()
- .and()
- .openidLogin()
- }
- }
+ @Configuration
+ static class DefaultLoginPageWithFormLoginOpenIDRememberMeConfig extends BaseWebConfig {
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .rememberMe()
+ .and()
+ .formLogin()
+ .and()
+ .openidLogin()
+ }
+ }
- def "default login with custom AuthenticationEntryPoint"() {
- when:
- loadConfig(DefaultLoginWithCustomAuthenticationEntryPointConfig)
- then:
- !findFilter(DefaultLoginPageGeneratingFilter)
- }
+ def "default login with custom AuthenticationEntryPoint"() {
+ when:
+ loadConfig(DefaultLoginWithCustomAuthenticationEntryPointConfig)
+ then:
+ !findFilter(DefaultLoginPageGeneratingFilter)
+ }
- @Configuration
- static class DefaultLoginWithCustomAuthenticationEntryPointConfig extends BaseWebConfig {
- @Override
- protected void configure(HttpSecurity http) {
- http
- .exceptionHandling()
- .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"))
- .and()
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .formLogin()
- }
- }
+ @Configuration
+ static class DefaultLoginWithCustomAuthenticationEntryPointConfig extends BaseWebConfig {
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .exceptionHandling()
+ .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"))
+ .and()
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .formLogin()
+ }
+ }
- def "DefaultLoginPage ObjectPostProcessor"() {
- setup:
- AnyObjectPostProcessor objectPostProcessor = Mock()
- when:
- HttpSecurity http = new HttpSecurity(objectPostProcessor, authenticationBldr, [:])
- DefaultLoginPageConfigurer defaultLoginConfig = new DefaultLoginPageConfigurer([builder:http])
- defaultLoginConfig.addObjectPostProcessor(objectPostProcessor)
- http
- // must set builder manually due to groovy not selecting correct method
- .apply(defaultLoginConfig).and()
- .exceptionHandling()
- .and()
- .formLogin()
- .and()
- .build()
+ def "DefaultLoginPage ObjectPostProcessor"() {
+ setup:
+ AnyObjectPostProcessor objectPostProcessor = Mock()
+ when:
+ HttpSecurity http = new HttpSecurity(objectPostProcessor, authenticationBldr, [:])
+ DefaultLoginPageConfigurer defaultLoginConfig = new DefaultLoginPageConfigurer([builder:http])
+ defaultLoginConfig.addObjectPostProcessor(objectPostProcessor)
+ http
+ // must set builder manually due to groovy not selecting correct method
+ .apply(defaultLoginConfig).and()
+ .exceptionHandling()
+ .and()
+ .formLogin()
+ .and()
+ .build()
- then: "DefaultLoginPageGeneratingFilter is registered with LifecycleManager"
- 1 * objectPostProcessor.postProcess(_ as DefaultLoginPageGeneratingFilter) >> {DefaultLoginPageGeneratingFilter o -> o}
- 1 * objectPostProcessor.postProcess(_ as UsernamePasswordAuthenticationFilter) >> {UsernamePasswordAuthenticationFilter o -> o}
- 1 * objectPostProcessor.postProcess(_ as LoginUrlAuthenticationEntryPoint) >> {LoginUrlAuthenticationEntryPoint o -> o}
- 1 * objectPostProcessor.postProcess(_ as ExceptionTranslationFilter) >> {ExceptionTranslationFilter o -> o}
- }
+ then: "DefaultLoginPageGeneratingFilter is registered with LifecycleManager"
+ 1 * objectPostProcessor.postProcess(_ as DefaultLoginPageGeneratingFilter) >> {DefaultLoginPageGeneratingFilter o -> o}
+ 1 * objectPostProcessor.postProcess(_ as UsernamePasswordAuthenticationFilter) >> {UsernamePasswordAuthenticationFilter o -> o}
+ 1 * objectPostProcessor.postProcess(_ as LoginUrlAuthenticationEntryPoint) >> {LoginUrlAuthenticationEntryPoint o -> o}
+ 1 * objectPostProcessor.postProcess(_ as ExceptionTranslationFilter) >> {ExceptionTranslationFilter o -> o}
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/ExceptionHandlingConfigurerTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/ExceptionHandlingConfigurerTests.groovy
index a561a2c911..3051227e6c 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/ExceptionHandlingConfigurerTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/ExceptionHandlingConfigurerTests.groovy
@@ -46,153 +46,153 @@ import spock.lang.Unroll
*/
class ExceptionHandlingConfigurerTests extends BaseSpringSpec {
- def "exception ObjectPostProcessor"() {
- setup: "initialize the AUTH_FILTER as a mock"
- AnyObjectPostProcessor opp = Mock()
- when:
- HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
- http
- .exceptionHandling()
- .and()
- .build()
+ def "exception ObjectPostProcessor"() {
+ setup: "initialize the AUTH_FILTER as a mock"
+ AnyObjectPostProcessor opp = Mock()
+ when:
+ HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
+ http
+ .exceptionHandling()
+ .and()
+ .build()
- then: "ExceptionTranslationFilter is registered with LifecycleManager"
- 1 * opp.postProcess(_ as ExceptionTranslationFilter) >> {ExceptionTranslationFilter o -> o}
- }
+ then: "ExceptionTranslationFilter is registered with LifecycleManager"
+ 1 * opp.postProcess(_ as ExceptionTranslationFilter) >> {ExceptionTranslationFilter o -> o}
+ }
- @Unroll
- def "SEC-2199: defaultEntryPoint for httpBasic and formLogin"(String acceptHeader, int httpStatus) {
- setup:
- loadConfig(HttpBasicAndFormLoginEntryPointsConfig)
- when:
- request.addHeader("Accept", acceptHeader)
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == httpStatus
- where:
- acceptHeader | httpStatus
- MediaType.APPLICATION_XHTML_XML_VALUE | HttpServletResponse.SC_MOVED_TEMPORARILY
- MediaType.IMAGE_GIF_VALUE | HttpServletResponse.SC_MOVED_TEMPORARILY
- MediaType.IMAGE_JPEG_VALUE | HttpServletResponse.SC_MOVED_TEMPORARILY
- MediaType.IMAGE_PNG_VALUE | HttpServletResponse.SC_MOVED_TEMPORARILY
- MediaType.TEXT_HTML_VALUE | HttpServletResponse.SC_MOVED_TEMPORARILY
- MediaType.TEXT_PLAIN_VALUE | HttpServletResponse.SC_MOVED_TEMPORARILY
- MediaType.APPLICATION_ATOM_XML_VALUE | HttpServletResponse.SC_UNAUTHORIZED
- MediaType.APPLICATION_FORM_URLENCODED_VALUE | HttpServletResponse.SC_UNAUTHORIZED
- MediaType.APPLICATION_JSON_VALUE | HttpServletResponse.SC_UNAUTHORIZED
- MediaType.APPLICATION_OCTET_STREAM_VALUE | HttpServletResponse.SC_UNAUTHORIZED
- MediaType.APPLICATION_XML_VALUE | HttpServletResponse.SC_UNAUTHORIZED
- MediaType.MULTIPART_FORM_DATA_VALUE | HttpServletResponse.SC_UNAUTHORIZED
- MediaType.TEXT_XML_VALUE | HttpServletResponse.SC_UNAUTHORIZED
- }
+ @Unroll
+ def "SEC-2199: defaultEntryPoint for httpBasic and formLogin"(String acceptHeader, int httpStatus) {
+ setup:
+ loadConfig(HttpBasicAndFormLoginEntryPointsConfig)
+ when:
+ request.addHeader("Accept", acceptHeader)
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == httpStatus
+ where:
+ acceptHeader | httpStatus
+ MediaType.APPLICATION_XHTML_XML_VALUE | HttpServletResponse.SC_MOVED_TEMPORARILY
+ MediaType.IMAGE_GIF_VALUE | HttpServletResponse.SC_MOVED_TEMPORARILY
+ MediaType.IMAGE_JPEG_VALUE | HttpServletResponse.SC_MOVED_TEMPORARILY
+ MediaType.IMAGE_PNG_VALUE | HttpServletResponse.SC_MOVED_TEMPORARILY
+ MediaType.TEXT_HTML_VALUE | HttpServletResponse.SC_MOVED_TEMPORARILY
+ MediaType.TEXT_PLAIN_VALUE | HttpServletResponse.SC_MOVED_TEMPORARILY
+ MediaType.APPLICATION_ATOM_XML_VALUE | HttpServletResponse.SC_UNAUTHORIZED
+ MediaType.APPLICATION_FORM_URLENCODED_VALUE | HttpServletResponse.SC_UNAUTHORIZED
+ MediaType.APPLICATION_JSON_VALUE | HttpServletResponse.SC_UNAUTHORIZED
+ MediaType.APPLICATION_OCTET_STREAM_VALUE | HttpServletResponse.SC_UNAUTHORIZED
+ MediaType.APPLICATION_XML_VALUE | HttpServletResponse.SC_UNAUTHORIZED
+ MediaType.MULTIPART_FORM_DATA_VALUE | HttpServletResponse.SC_UNAUTHORIZED
+ MediaType.TEXT_XML_VALUE | HttpServletResponse.SC_UNAUTHORIZED
+ }
- def "ContentNegotiationStrategy defaults to HeaderContentNegotiationStrategy"() {
- when:
- loadConfig(HttpBasicAndFormLoginEntryPointsConfig)
- DelegatingAuthenticationEntryPoint delegateEntryPoint = findFilter(ExceptionTranslationFilter).authenticationEntryPoint
- then:
- delegateEntryPoint.entryPoints.keySet().collect {it.contentNegotiationStrategy.class} == [HeaderContentNegotiationStrategy,HeaderContentNegotiationStrategy]
- }
+ def "ContentNegotiationStrategy defaults to HeaderContentNegotiationStrategy"() {
+ when:
+ loadConfig(HttpBasicAndFormLoginEntryPointsConfig)
+ DelegatingAuthenticationEntryPoint delegateEntryPoint = findFilter(ExceptionTranslationFilter).authenticationEntryPoint
+ then:
+ delegateEntryPoint.entryPoints.keySet().collect {it.contentNegotiationStrategy.class} == [HeaderContentNegotiationStrategy,HeaderContentNegotiationStrategy]
+ }
- @EnableWebSecurity
- static class HttpBasicAndFormLoginEntryPointsConfig extends WebSecurityConfigurerAdapter {
+ @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(AuthenticationManagerBuilder auth) throws Exception {
+ auth
+ .inMemoryAuthentication()
+ .withUser("user").password("password").roles("USER")
+ }
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .anyRequest().authenticated()
- .and()
- .httpBasic()
- .and()
- .formLogin()
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .authorizeRequests()
+ .anyRequest().authenticated()
+ .and()
+ .httpBasic()
+ .and()
+ .formLogin()
+ }
+ }
- def "ContentNegotiationStrategy overrides with @Bean"() {
- setup:
- OverrideContentNegotiationStrategySharedObjectConfig.CNS = Mock(ContentNegotiationStrategy)
- when:
- loadConfig(OverrideContentNegotiationStrategySharedObjectConfig)
- DelegatingAuthenticationEntryPoint delegateEntryPoint = findFilter(ExceptionTranslationFilter).authenticationEntryPoint
- then:
- delegateEntryPoint.entryPoints.keySet().collect {it.contentNegotiationStrategy} == [OverrideContentNegotiationStrategySharedObjectConfig.CNS,OverrideContentNegotiationStrategySharedObjectConfig.CNS]
- }
+ def "ContentNegotiationStrategy overrides with @Bean"() {
+ setup:
+ OverrideContentNegotiationStrategySharedObjectConfig.CNS = Mock(ContentNegotiationStrategy)
+ when:
+ loadConfig(OverrideContentNegotiationStrategySharedObjectConfig)
+ DelegatingAuthenticationEntryPoint delegateEntryPoint = findFilter(ExceptionTranslationFilter).authenticationEntryPoint
+ then:
+ delegateEntryPoint.entryPoints.keySet().collect {it.contentNegotiationStrategy} == [OverrideContentNegotiationStrategySharedObjectConfig.CNS,OverrideContentNegotiationStrategySharedObjectConfig.CNS]
+ }
- def "Override ContentNegotiationStrategy with @Bean"() {
- setup:
- OverrideContentNegotiationStrategySharedObjectConfig.CNS = Mock(ContentNegotiationStrategy)
- when:
- loadConfig(OverrideContentNegotiationStrategySharedObjectConfig)
- then:
- context.getBean(OverrideContentNegotiationStrategySharedObjectConfig).http.getSharedObject(ContentNegotiationStrategy) == OverrideContentNegotiationStrategySharedObjectConfig.CNS
- }
+ def "Override ContentNegotiationStrategy with @Bean"() {
+ setup:
+ OverrideContentNegotiationStrategySharedObjectConfig.CNS = Mock(ContentNegotiationStrategy)
+ when:
+ loadConfig(OverrideContentNegotiationStrategySharedObjectConfig)
+ then:
+ context.getBean(OverrideContentNegotiationStrategySharedObjectConfig).http.getSharedObject(ContentNegotiationStrategy) == OverrideContentNegotiationStrategySharedObjectConfig.CNS
+ }
- @EnableWebSecurity
- static class OverrideContentNegotiationStrategySharedObjectConfig extends WebSecurityConfigurerAdapter {
- static ContentNegotiationStrategy CNS
+ @EnableWebSecurity
+ static class OverrideContentNegotiationStrategySharedObjectConfig extends WebSecurityConfigurerAdapter {
+ static ContentNegotiationStrategy CNS
- @Bean
- public ContentNegotiationStrategy cns() {
- return CNS
- }
- }
+ @Bean
+ public ContentNegotiationStrategy cns() {
+ return CNS
+ }
+ }
- def "delegatingAuthenticationEntryPoint.defaultEntryPoint is LoginUrlAuthenticationEntryPoint when using DefaultHttpConf"() {
- when:
- loadConfig(DefaultHttpConf)
- then:
- findFilter(ExceptionTranslationFilter).authenticationEntryPoint.defaultEntryPoint.class == LoginUrlAuthenticationEntryPoint
- }
+ def "delegatingAuthenticationEntryPoint.defaultEntryPoint is LoginUrlAuthenticationEntryPoint when using DefaultHttpConf"() {
+ when:
+ loadConfig(DefaultHttpConf)
+ then:
+ findFilter(ExceptionTranslationFilter).authenticationEntryPoint.defaultEntryPoint.class == LoginUrlAuthenticationEntryPoint
+ }
- @EnableWebSecurity
- static class DefaultHttpConf extends WebSecurityConfigurerAdapter {
- }
+ @EnableWebSecurity
+ static class DefaultHttpConf extends WebSecurityConfigurerAdapter {
+ }
- def "delegatingAuthenticationEntryPoint.defaultEntryPoint is BasicAuthenticationEntryPoint when httpBasic before formLogin"() {
- when:
- loadConfig(BasicAuthenticationEntryPointBeforeFormLoginConf)
- then:
- findFilter(ExceptionTranslationFilter).authenticationEntryPoint.defaultEntryPoint.defaultEntryPoint.class == BasicAuthenticationEntryPoint
- }
+ def "delegatingAuthenticationEntryPoint.defaultEntryPoint is BasicAuthenticationEntryPoint when httpBasic before formLogin"() {
+ when:
+ loadConfig(BasicAuthenticationEntryPointBeforeFormLoginConf)
+ then:
+ findFilter(ExceptionTranslationFilter).authenticationEntryPoint.defaultEntryPoint.defaultEntryPoint.class == BasicAuthenticationEntryPoint
+ }
- @EnableWebSecurity
- static class BasicAuthenticationEntryPointBeforeFormLoginConf extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .httpBasic()
- .and()
- .formLogin()
- }
- }
+ @EnableWebSecurity
+ static class BasicAuthenticationEntryPointBeforeFormLoginConf extends WebSecurityConfigurerAdapter {
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .httpBasic()
+ .and()
+ .formLogin()
+ }
+ }
- def "invoke exceptionHandling twice does not override"() {
- setup:
- InvokeTwiceDoesNotOverrideConfig.AEP = Mock(AuthenticationEntryPoint)
- when:
- loadConfig(InvokeTwiceDoesNotOverrideConfig)
- then:
- findFilter(ExceptionTranslationFilter).authenticationEntryPoint == InvokeTwiceDoesNotOverrideConfig.AEP
- }
+ def "invoke exceptionHandling twice does not override"() {
+ setup:
+ InvokeTwiceDoesNotOverrideConfig.AEP = Mock(AuthenticationEntryPoint)
+ when:
+ loadConfig(InvokeTwiceDoesNotOverrideConfig)
+ then:
+ findFilter(ExceptionTranslationFilter).authenticationEntryPoint == InvokeTwiceDoesNotOverrideConfig.AEP
+ }
- @EnableWebSecurity
- static class InvokeTwiceDoesNotOverrideConfig extends WebSecurityConfigurerAdapter {
- static AuthenticationEntryPoint AEP
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .exceptionHandling()
- .authenticationEntryPoint(AEP)
- .and()
- .exceptionHandling()
- }
- }
+ @EnableWebSecurity
+ static class InvokeTwiceDoesNotOverrideConfig extends WebSecurityConfigurerAdapter {
+ static AuthenticationEntryPoint AEP
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .exceptionHandling()
+ .authenticationEntryPoint(AEP)
+ .and()
+ .exceptionHandling()
+ }
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/ExpressionUrlAuthorizationsTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/ExpressionUrlAuthorizationsTests.groovy
index 8c8e802a17..ff05550693 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/ExpressionUrlAuthorizationsTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/ExpressionUrlAuthorizationsTests.groovy
@@ -37,494 +37,494 @@ import org.springframework.security.web.access.intercept.FilterSecurityIntercept
public class ExpressionUrlAuthorizationConfigurerTests extends BaseSpringSpec {
- def "hasAnyAuthority('ROLE_USER')"() {
- when:
- def expression = ExpressionUrlAuthorizationConfigurer.hasAnyAuthority("ROLE_USER")
- then:
- expression == "hasAnyAuthority('ROLE_USER')"
- }
+ def "hasAnyAuthority('ROLE_USER')"() {
+ when:
+ def expression = ExpressionUrlAuthorizationConfigurer.hasAnyAuthority("ROLE_USER")
+ then:
+ expression == "hasAnyAuthority('ROLE_USER')"
+ }
- def "hasAnyAuthority('ROLE_USER','ROLE_ADMIN')"() {
- when:
- def expression = ExpressionUrlAuthorizationConfigurer.hasAnyAuthority("ROLE_USER","ROLE_ADMIN")
- then:
- expression == "hasAnyAuthority('ROLE_USER','ROLE_ADMIN')"
- }
+ def "hasAnyAuthority('ROLE_USER','ROLE_ADMIN')"() {
+ when:
+ def expression = ExpressionUrlAuthorizationConfigurer.hasAnyAuthority("ROLE_USER","ROLE_ADMIN")
+ then:
+ expression == "hasAnyAuthority('ROLE_USER','ROLE_ADMIN')"
+ }
- def "hasAnyRole('USER')"() {
- when:
- def expression = ExpressionUrlAuthorizationConfigurer.hasAnyRole("USER")
- then:
- expression == "hasAnyRole('ROLE_USER')"
- }
+ def "hasAnyRole('USER')"() {
+ when:
+ def expression = ExpressionUrlAuthorizationConfigurer.hasAnyRole("USER")
+ then:
+ expression == "hasAnyRole('ROLE_USER')"
+ }
- def "hasAnyRole('USER','ADMIN')"() {
- when:
- def expression = ExpressionUrlAuthorizationConfigurer.hasAnyRole("USER","ADMIN")
- then:
- expression == "hasAnyRole('ROLE_USER','ROLE_ADMIN')"
- }
+ def "hasAnyRole('USER','ADMIN')"() {
+ when:
+ def expression = ExpressionUrlAuthorizationConfigurer.hasAnyRole("USER","ADMIN")
+ then:
+ expression == "hasAnyRole('ROLE_USER','ROLE_ADMIN')"
+ }
- def "hasRole('ROLE_USER') is rejected due to starting with ROLE_"() {
- when:
- def expression = ExpressionUrlAuthorizationConfigurer.hasRole("ROLE_USER")
- then:
- IllegalArgumentException e = thrown()
- e.message == "role should not start with 'ROLE_' since it is automatically inserted. Got 'ROLE_USER'"
- }
+ def "hasRole('ROLE_USER') is rejected due to starting with ROLE_"() {
+ when:
+ def expression = ExpressionUrlAuthorizationConfigurer.hasRole("ROLE_USER")
+ then:
+ IllegalArgumentException e = thrown()
+ e.message == "role should not start with 'ROLE_' since it is automatically inserted. Got 'ROLE_USER'"
+ }
- def "authorizeRequests() uses AffirmativeBased AccessDecisionManager"() {
- when: "Load Config with no specific AccessDecisionManager"
- loadConfig(NoSpecificAccessDecessionManagerConfig)
- then: "AccessDecessionManager matches the HttpSecurityBuilder's default"
- findFilter(FilterSecurityInterceptor).accessDecisionManager.class == AffirmativeBased
- }
+ def "authorizeRequests() uses AffirmativeBased AccessDecisionManager"() {
+ when: "Load Config with no specific AccessDecisionManager"
+ loadConfig(NoSpecificAccessDecessionManagerConfig)
+ then: "AccessDecessionManager matches the HttpSecurityBuilder's default"
+ findFilter(FilterSecurityInterceptor).accessDecisionManager.class == AffirmativeBased
+ }
- @EnableWebSecurity
- static class NoSpecificAccessDecessionManagerConfig extends WebSecurityConfigurerAdapter {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- }
- }
+ @EnableWebSecurity
+ static class NoSpecificAccessDecessionManagerConfig extends WebSecurityConfigurerAdapter {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ }
+ }
- def "authorizeRequests() no requests"() {
- when: "Load Config with no requests"
- loadConfig(NoRequestsConfig)
- then: "A meaningful exception is thrown"
- BeanCreationException success = thrown()
- success.message.contains "At least one mapping is required (i.e. authorizeRequests().anyRequest.authenticated())"
- }
+ def "authorizeRequests() no requests"() {
+ when: "Load Config with no requests"
+ loadConfig(NoRequestsConfig)
+ then: "A meaningful exception is thrown"
+ BeanCreationException success = thrown()
+ success.message.contains "At least one mapping is required (i.e. authorizeRequests().anyRequest.authenticated())"
+ }
- @EnableWebSecurity
- static class NoRequestsConfig extends WebSecurityConfigurerAdapter {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- }
- }
+ @EnableWebSecurity
+ static class NoRequestsConfig extends WebSecurityConfigurerAdapter {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .authorizeRequests()
+ }
+ }
- def "authorizeRequests() incomplete mapping"() {
- when: "Load Config with incomplete mapping"
- loadConfig(IncompleteMappingConfig)
- then: "A meaningful exception is thrown"
- BeanCreationException success = thrown()
- success.message.contains "An incomplete mapping was found for "
- }
+ def "authorizeRequests() incomplete mapping"() {
+ when: "Load Config with incomplete mapping"
+ loadConfig(IncompleteMappingConfig)
+ then: "A meaningful exception is thrown"
+ BeanCreationException success = thrown()
+ success.message.contains "An incomplete mapping was found for "
+ }
- @EnableWebSecurity
- static class IncompleteMappingConfig extends WebSecurityConfigurerAdapter {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .antMatchers("/a").authenticated()
- .anyRequest()
- }
- }
+ @EnableWebSecurity
+ static class IncompleteMappingConfig extends WebSecurityConfigurerAdapter {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .authorizeRequests()
+ .antMatchers("/a").authenticated()
+ .anyRequest()
+ }
+ }
- def "authorizeRequests() hasAuthority"() {
- setup:
- loadConfig(HasAuthorityConfig)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_UNAUTHORIZED
- when:
- super.setup()
- login()
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_OK
- when:
- super.setup()
- login("user","ROLE_INVALID")
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_FORBIDDEN
- }
+ def "authorizeRequests() hasAuthority"() {
+ setup:
+ loadConfig(HasAuthorityConfig)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_UNAUTHORIZED
+ when:
+ super.setup()
+ login()
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_OK
+ when:
+ super.setup()
+ login("user","ROLE_INVALID")
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_FORBIDDEN
+ }
- @EnableWebSecurity
- static class HasAuthorityConfig extends WebSecurityConfigurerAdapter {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .httpBasic()
- .and()
- .authorizeRequests()
- .anyRequest().hasAuthority("ROLE_USER")
- }
- }
+ @EnableWebSecurity
+ static class HasAuthorityConfig extends WebSecurityConfigurerAdapter {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .httpBasic()
+ .and()
+ .authorizeRequests()
+ .anyRequest().hasAuthority("ROLE_USER")
+ }
+ }
- def "authorizeRequests() hasAnyAuthority"() {
- setup:
- loadConfig(HasAnyAuthorityConfig)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_UNAUTHORIZED
- when:
- super.setup()
- login("user","ROLE_ADMIN")
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_OK
- when:
- super.setup()
- login("user","ROLE_DBA")
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_OK
- when:
- super.setup()
- login("user","ROLE_INVALID")
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_FORBIDDEN
- }
+ def "authorizeRequests() hasAnyAuthority"() {
+ setup:
+ loadConfig(HasAnyAuthorityConfig)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_UNAUTHORIZED
+ when:
+ super.setup()
+ login("user","ROLE_ADMIN")
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_OK
+ when:
+ super.setup()
+ login("user","ROLE_DBA")
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_OK
+ when:
+ super.setup()
+ login("user","ROLE_INVALID")
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_FORBIDDEN
+ }
- @EnableWebSecurity
- static class HasAnyAuthorityConfig extends WebSecurityConfigurerAdapter {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .httpBasic()
- .and()
- .authorizeRequests()
- .anyRequest().hasAnyAuthority("ROLE_ADMIN","ROLE_DBA")
- }
- }
+ @EnableWebSecurity
+ static class HasAnyAuthorityConfig extends WebSecurityConfigurerAdapter {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .httpBasic()
+ .and()
+ .authorizeRequests()
+ .anyRequest().hasAnyAuthority("ROLE_ADMIN","ROLE_DBA")
+ }
+ }
- def "authorizeRequests() hasIpAddress"() {
- setup:
- loadConfig(HasIpAddressConfig)
- when:
- request.remoteAddr = "192.168.1.1"
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_UNAUTHORIZED
- when:
- super.setup()
- request.remoteAddr = "192.168.1.0"
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_OK
- }
+ def "authorizeRequests() hasIpAddress"() {
+ setup:
+ loadConfig(HasIpAddressConfig)
+ when:
+ request.remoteAddr = "192.168.1.1"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_UNAUTHORIZED
+ when:
+ super.setup()
+ request.remoteAddr = "192.168.1.0"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_OK
+ }
- @EnableWebSecurity
- static class HasIpAddressConfig extends WebSecurityConfigurerAdapter {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .httpBasic()
- .and()
- .authorizeRequests()
- .anyRequest().hasIpAddress("192.168.1.0")
- }
- }
+ @EnableWebSecurity
+ static class HasIpAddressConfig extends WebSecurityConfigurerAdapter {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .httpBasic()
+ .and()
+ .authorizeRequests()
+ .anyRequest().hasIpAddress("192.168.1.0")
+ }
+ }
- def "authorizeRequests() anonymous"() {
- setup:
- loadConfig(AnonymousConfig)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_OK
- when:
- super.setup()
- login()
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_FORBIDDEN
- }
+ def "authorizeRequests() anonymous"() {
+ setup:
+ loadConfig(AnonymousConfig)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_OK
+ when:
+ super.setup()
+ login()
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_FORBIDDEN
+ }
- @EnableWebSecurity
- static class AnonymousConfig extends WebSecurityConfigurerAdapter {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .httpBasic()
- .and()
- .authorizeRequests()
- .anyRequest().anonymous()
- }
- }
+ @EnableWebSecurity
+ static class AnonymousConfig extends WebSecurityConfigurerAdapter {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .httpBasic()
+ .and()
+ .authorizeRequests()
+ .anyRequest().anonymous()
+ }
+ }
- def "authorizeRequests() rememberMe"() {
- setup:
- loadConfig(RememberMeConfig)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_UNAUTHORIZED
- when:
- super.setup()
- login(new RememberMeAuthenticationToken("key", "user", AuthorityUtils.createAuthorityList("ROLE_USER")))
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_OK
- }
+ def "authorizeRequests() rememberMe"() {
+ setup:
+ loadConfig(RememberMeConfig)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_UNAUTHORIZED
+ when:
+ super.setup()
+ login(new RememberMeAuthenticationToken("key", "user", AuthorityUtils.createAuthorityList("ROLE_USER")))
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_OK
+ }
- @EnableWebSecurity
- static class RememberMeConfig extends WebSecurityConfigurerAdapter {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .rememberMe()
- .and()
- .httpBasic()
- .and()
- .authorizeRequests()
- .anyRequest().rememberMe()
- }
+ @EnableWebSecurity
+ static class RememberMeConfig extends WebSecurityConfigurerAdapter {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .rememberMe()
+ .and()
+ .httpBasic()
+ .and()
+ .authorizeRequests()
+ .anyRequest().rememberMe()
+ }
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth
- .inMemoryAuthentication()
- .withUser("user").password("password").roles("USER")
- }
- }
+ @Override
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth
+ .inMemoryAuthentication()
+ .withUser("user").password("password").roles("USER")
+ }
+ }
- def "authorizeRequests() denyAll"() {
- setup:
- loadConfig(DenyAllConfig)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_UNAUTHORIZED
- when:
- super.setup()
- login(new RememberMeAuthenticationToken("key", "user", AuthorityUtils.createAuthorityList("ROLE_USER")))
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_FORBIDDEN
- }
+ def "authorizeRequests() denyAll"() {
+ setup:
+ loadConfig(DenyAllConfig)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_UNAUTHORIZED
+ when:
+ super.setup()
+ login(new RememberMeAuthenticationToken("key", "user", AuthorityUtils.createAuthorityList("ROLE_USER")))
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_FORBIDDEN
+ }
- @EnableWebSecurity
- static class DenyAllConfig extends WebSecurityConfigurerAdapter {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .httpBasic()
- .and()
- .authorizeRequests()
- .anyRequest().denyAll()
- }
- }
+ @EnableWebSecurity
+ static class DenyAllConfig extends WebSecurityConfigurerAdapter {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .httpBasic()
+ .and()
+ .authorizeRequests()
+ .anyRequest().denyAll()
+ }
+ }
- def "authorizeRequests() not denyAll"() {
- setup:
- loadConfig(NotDenyAllConfig)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_OK
- when:
- super.setup()
- login(new RememberMeAuthenticationToken("key", "user", AuthorityUtils.createAuthorityList("ROLE_USER")))
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_OK
- }
+ def "authorizeRequests() not denyAll"() {
+ setup:
+ loadConfig(NotDenyAllConfig)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_OK
+ when:
+ super.setup()
+ login(new RememberMeAuthenticationToken("key", "user", AuthorityUtils.createAuthorityList("ROLE_USER")))
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_OK
+ }
- @EnableWebSecurity
- static class NotDenyAllConfig extends WebSecurityConfigurerAdapter {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .httpBasic()
- .and()
- .authorizeRequests()
- .anyRequest().not().denyAll()
- }
- }
+ @EnableWebSecurity
+ static class NotDenyAllConfig extends WebSecurityConfigurerAdapter {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .httpBasic()
+ .and()
+ .authorizeRequests()
+ .anyRequest().not().denyAll()
+ }
+ }
- def "authorizeRequests() fullyAuthenticated"() {
- setup:
- loadConfig(FullyAuthenticatedConfig)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_UNAUTHORIZED
- when:
- super.setup()
- login(new RememberMeAuthenticationToken("key", "user", AuthorityUtils.createAuthorityList("ROLE_USER")))
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_FORBIDDEN
- when:
- super.setup()
- login()
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_OK
- }
+ def "authorizeRequests() fullyAuthenticated"() {
+ setup:
+ loadConfig(FullyAuthenticatedConfig)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_UNAUTHORIZED
+ when:
+ super.setup()
+ login(new RememberMeAuthenticationToken("key", "user", AuthorityUtils.createAuthorityList("ROLE_USER")))
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_FORBIDDEN
+ when:
+ super.setup()
+ login()
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_OK
+ }
- @EnableWebSecurity
- static class FullyAuthenticatedConfig extends WebSecurityConfigurerAdapter {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .rememberMe()
- .and()
- .httpBasic()
- .and()
- .authorizeRequests()
- .anyRequest().fullyAuthenticated()
- }
+ @EnableWebSecurity
+ static class FullyAuthenticatedConfig extends WebSecurityConfigurerAdapter {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .rememberMe()
+ .and()
+ .httpBasic()
+ .and()
+ .authorizeRequests()
+ .anyRequest().fullyAuthenticated()
+ }
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth
- .inMemoryAuthentication()
- .withUser("user").password("password").roles("USER")
- }
- }
+ @Override
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth
+ .inMemoryAuthentication()
+ .withUser("user").password("password").roles("USER")
+ }
+ }
- def "authorizeRequests() access"() {
- setup:
- loadConfig(AccessConfig)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "Access is granted due to GET"
- response.status == HttpServletResponse.SC_OK
- when:
- super.setup()
- login()
- request.method = "POST"
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "Access is granted due to role"
- response.status == HttpServletResponse.SC_OK
- when:
- super.setup()
- request.method = "POST"
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "Access is denied"
- response.status == HttpServletResponse.SC_UNAUTHORIZED
- }
+ def "authorizeRequests() access"() {
+ setup:
+ loadConfig(AccessConfig)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "Access is granted due to GET"
+ response.status == HttpServletResponse.SC_OK
+ when:
+ super.setup()
+ login()
+ request.method = "POST"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "Access is granted due to role"
+ response.status == HttpServletResponse.SC_OK
+ when:
+ super.setup()
+ request.method = "POST"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "Access is denied"
+ response.status == HttpServletResponse.SC_UNAUTHORIZED
+ }
- @EnableWebSecurity
- static class AccessConfig extends WebSecurityConfigurerAdapter {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .rememberMe()
- .and()
- .httpBasic()
- .and()
- .authorizeRequests()
- .anyRequest().access("hasRole('ROLE_USER') or request.method == 'GET'")
- }
+ @EnableWebSecurity
+ static class AccessConfig extends WebSecurityConfigurerAdapter {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .rememberMe()
+ .and()
+ .httpBasic()
+ .and()
+ .authorizeRequests()
+ .anyRequest().access("hasRole('ROLE_USER') or request.method == 'GET'")
+ }
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth
- .inMemoryAuthentication()
- .withUser("user").password("password").roles("USER")
- }
- }
+ @Override
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth
+ .inMemoryAuthentication()
+ .withUser("user").password("password").roles("USER")
+ }
+ }
- def "invoke authorizeUrls twice does not reset"() {
- setup:
- loadConfig(InvokeTwiceDoesNotResetConfig)
- when:
- request.method = "POST"
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "Access is denied"
- response.status == HttpServletResponse.SC_UNAUTHORIZED
- }
+ def "invoke authorizeUrls twice does not reset"() {
+ setup:
+ loadConfig(InvokeTwiceDoesNotResetConfig)
+ when:
+ request.method = "POST"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "Access is denied"
+ response.status == HttpServletResponse.SC_UNAUTHORIZED
+ }
- @EnableWebSecurity
- static class InvokeTwiceDoesNotResetConfig extends WebSecurityConfigurerAdapter {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .httpBasic()
- .and()
- .authorizeRequests()
- .anyRequest().authenticated()
- .and()
- .authorizeRequests()
- }
+ @EnableWebSecurity
+ static class InvokeTwiceDoesNotResetConfig extends WebSecurityConfigurerAdapter {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .httpBasic()
+ .and()
+ .authorizeRequests()
+ .anyRequest().authenticated()
+ .and()
+ .authorizeRequests()
+ }
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth
- .inMemoryAuthentication()
- }
- }
+ @Override
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth
+ .inMemoryAuthentication()
+ }
+ }
- def "All Properties are accessible and chain properly"() {
- when:
- loadConfig(AllPropertiesWorkConfig)
- then:
- noExceptionThrown()
- }
+ def "All Properties are accessible and chain properly"() {
+ when:
+ loadConfig(AllPropertiesWorkConfig)
+ then:
+ noExceptionThrown()
+ }
- def "AuthorizedRequests withPostProcessor"() {
- setup:
- ApplicationListener al = Mock()
- AuthorizedRequestsWithPostProcessorConfig.AL = al
- loadConfig(AuthorizedRequestsWithPostProcessorConfig)
- when:
- springSecurityFilterChain.doFilter(request, response, chain)
- then:
- 1 * al.onApplicationEvent(_ as AuthorizedEvent)
- }
+ def "AuthorizedRequests withPostProcessor"() {
+ setup:
+ ApplicationListener al = Mock()
+ AuthorizedRequestsWithPostProcessorConfig.AL = al
+ loadConfig(AuthorizedRequestsWithPostProcessorConfig)
+ when:
+ springSecurityFilterChain.doFilter(request, response, chain)
+ then:
+ 1 * al.onApplicationEvent(_ as AuthorizedEvent)
+ }
- def "Use @permission.check in access"() {
- setup:
- loadConfig(UseBeansInExpressions)
- when: "invoke standard expression that denies access"
- login()
- request.servletPath = "/admin/1"
- springSecurityFilterChain.doFilter(request, response, chain)
- then: "standard expression works - get forbidden"
- response.status == HttpServletResponse.SC_FORBIDDEN
- when: "invoke standard expression that allows access"
- super.setup()
- login()
- request.servletPath = "/user/1"
- springSecurityFilterChain.doFilter(request, response, chain)
- then: "standard expression works - get ok"
- response.status == HttpServletResponse.SC_OK
- when: "invoke custom bean as expression that allows access"
- super.setup()
- login()
- request.servletPath = "/allow/1"
- springSecurityFilterChain.doFilter(request, response, chain)
- then: "custom bean expression allows access"
- response.status == HttpServletResponse.SC_OK
- when: "invoke custom bean as expression that denies access"
- super.setup()
- login()
- request.servletPath = "/deny/1"
- springSecurityFilterChain.doFilter(request, response, chain)
- then: "custom bean expression denies access"
- response.status == HttpServletResponse.SC_FORBIDDEN
- }
+ def "Use @permission.check in access"() {
+ setup:
+ loadConfig(UseBeansInExpressions)
+ when: "invoke standard expression that denies access"
+ login()
+ request.servletPath = "/admin/1"
+ springSecurityFilterChain.doFilter(request, response, chain)
+ then: "standard expression works - get forbidden"
+ response.status == HttpServletResponse.SC_FORBIDDEN
+ when: "invoke standard expression that allows access"
+ super.setup()
+ login()
+ request.servletPath = "/user/1"
+ springSecurityFilterChain.doFilter(request, response, chain)
+ then: "standard expression works - get ok"
+ response.status == HttpServletResponse.SC_OK
+ when: "invoke custom bean as expression that allows access"
+ super.setup()
+ login()
+ request.servletPath = "/allow/1"
+ springSecurityFilterChain.doFilter(request, response, chain)
+ then: "custom bean expression allows access"
+ response.status == HttpServletResponse.SC_OK
+ when: "invoke custom bean as expression that denies access"
+ super.setup()
+ login()
+ request.servletPath = "/deny/1"
+ springSecurityFilterChain.doFilter(request, response, chain)
+ then: "custom bean expression denies access"
+ response.status == HttpServletResponse.SC_FORBIDDEN
+ }
- def "Use custom expressionroot in access"() {
- setup:
- loadConfig(CustomExpressionRootConfig)
- when: "invoke standard expression that denies access"
- login()
- request.servletPath = "/admin/1"
- springSecurityFilterChain.doFilter(request, response, chain)
- then: "standard expression works - get forbidden"
- response.status == HttpServletResponse.SC_FORBIDDEN
- when: "invoke standard expression that allows access"
- super.setup()
- login()
- request.servletPath = "/user/1"
- springSecurityFilterChain.doFilter(request, response, chain)
- then: "standard expression works - get ok"
- response.status == HttpServletResponse.SC_OK
- when: "invoke custom bean as expression that allows access"
- super.setup()
- login()
- request.servletPath = "/allow/1"
- springSecurityFilterChain.doFilter(request, response, chain)
- then: "custom bean expression allows access"
- response.status == HttpServletResponse.SC_OK
- when: "invoke custom bean as expression that denies access"
- super.setup()
- login()
- request.servletPath = "/deny/1"
- springSecurityFilterChain.doFilter(request, response, chain)
- then: "custom bean expression denies access"
- response.status == HttpServletResponse.SC_FORBIDDEN
- }
+ def "Use custom expressionroot in access"() {
+ setup:
+ loadConfig(CustomExpressionRootConfig)
+ when: "invoke standard expression that denies access"
+ login()
+ request.servletPath = "/admin/1"
+ springSecurityFilterChain.doFilter(request, response, chain)
+ then: "standard expression works - get forbidden"
+ response.status == HttpServletResponse.SC_FORBIDDEN
+ when: "invoke standard expression that allows access"
+ super.setup()
+ login()
+ request.servletPath = "/user/1"
+ springSecurityFilterChain.doFilter(request, response, chain)
+ then: "standard expression works - get ok"
+ response.status == HttpServletResponse.SC_OK
+ when: "invoke custom bean as expression that allows access"
+ super.setup()
+ login()
+ request.servletPath = "/allow/1"
+ springSecurityFilterChain.doFilter(request, response, chain)
+ then: "custom bean expression allows access"
+ response.status == HttpServletResponse.SC_OK
+ when: "invoke custom bean as expression that denies access"
+ super.setup()
+ login()
+ request.servletPath = "/deny/1"
+ springSecurityFilterChain.doFilter(request, response, chain)
+ then: "custom bean expression denies access"
+ response.status == HttpServletResponse.SC_FORBIDDEN
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/FormLoginConfigurerTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/FormLoginConfigurerTests.groovy
index 2c83f13c2f..4846355877 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/FormLoginConfigurerTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/FormLoginConfigurerTests.groovy
@@ -56,266 +56,266 @@ import spock.lang.Unroll
* @author Rob Winch
*/
class FormLoginConfigurerTests extends BaseSpringSpec {
- def "Form Login"() {
- when: "load formLogin()"
- context = new AnnotationConfigApplicationContext(FormLoginConfig)
+ def "Form Login"() {
+ when: "load formLogin()"
+ context = new AnnotationConfigApplicationContext(FormLoginConfig)
- then: "FilterChains configured correctly"
- def filterChains = filterChains()
- filterChains.size() == 2
- filterChains[0].requestMatcher.pattern == '/resources/**'
- filterChains[0].filters.empty
- filterChains[1].requestMatcher instanceof AnyRequestMatcher
- filterChains[1].filters.collect { it.class.name.contains('$') ? it.class.superclass : it.class } ==
- [WebAsyncManagerIntegrationFilter, SecurityContextPersistenceFilter, HeaderWriterFilter, CsrfFilter, LogoutFilter, UsernamePasswordAuthenticationFilter,
- RequestCacheAwareFilter, SecurityContextHolderAwareRequestFilter,
- AnonymousAuthenticationFilter, SessionManagementFilter, ExceptionTranslationFilter, FilterSecurityInterceptor ]
+ then: "FilterChains configured correctly"
+ def filterChains = filterChains()
+ filterChains.size() == 2
+ filterChains[0].requestMatcher.pattern == '/resources/**'
+ filterChains[0].filters.empty
+ filterChains[1].requestMatcher instanceof AnyRequestMatcher
+ filterChains[1].filters.collect { it.class.name.contains('$') ? it.class.superclass : it.class } ==
+ [WebAsyncManagerIntegrationFilter, SecurityContextPersistenceFilter, HeaderWriterFilter, CsrfFilter, LogoutFilter, UsernamePasswordAuthenticationFilter,
+ RequestCacheAwareFilter, SecurityContextHolderAwareRequestFilter,
+ AnonymousAuthenticationFilter, SessionManagementFilter, ExceptionTranslationFilter, FilterSecurityInterceptor ]
- and: "UsernamePasswordAuthentictionFilter is configured correctly"
- UsernamePasswordAuthenticationFilter authFilter = findFilter(UsernamePasswordAuthenticationFilter,1)
- authFilter.usernameParameter == "username"
- authFilter.passwordParameter == "password"
- authFilter.failureHandler.defaultFailureUrl == "/login?error"
- authFilter.successHandler.defaultTargetUrl == "/"
- authFilter.requiresAuthentication(new MockHttpServletRequest(servletPath : "/login", method: "POST"), new MockHttpServletResponse())
- !authFilter.requiresAuthentication(new MockHttpServletRequest(servletPath : "/login", method: "GET"), new MockHttpServletResponse())
+ and: "UsernamePasswordAuthentictionFilter is configured correctly"
+ UsernamePasswordAuthenticationFilter authFilter = findFilter(UsernamePasswordAuthenticationFilter,1)
+ authFilter.usernameParameter == "username"
+ authFilter.passwordParameter == "password"
+ authFilter.failureHandler.defaultFailureUrl == "/login?error"
+ authFilter.successHandler.defaultTargetUrl == "/"
+ authFilter.requiresAuthentication(new MockHttpServletRequest(servletPath : "/login", method: "POST"), new MockHttpServletResponse())
+ !authFilter.requiresAuthentication(new MockHttpServletRequest(servletPath : "/login", method: "GET"), new MockHttpServletResponse())
- and: "SessionFixationProtectionStrategy is configured correctly"
- SessionFixationProtectionStrategy sessionStrategy = ReflectionTestUtils.getField(authFilter,"sessionStrategy").delegateStrategies.find { SessionFixationProtectionStrategy }
- sessionStrategy.migrateSessionAttributes
+ and: "SessionFixationProtectionStrategy is configured correctly"
+ SessionFixationProtectionStrategy sessionStrategy = ReflectionTestUtils.getField(authFilter,"sessionStrategy").delegateStrategies.find { SessionFixationProtectionStrategy }
+ sessionStrategy.migrateSessionAttributes
- and: "Exception handling is configured correctly"
- AuthenticationEntryPoint authEntryPoint = filterChains[1].filters.find { it instanceof ExceptionTranslationFilter}.authenticationEntryPoint
- MockHttpServletResponse response = new MockHttpServletResponse()
- authEntryPoint.commence(new MockHttpServletRequest(servletPath: "/private/"), response, new BadCredentialsException(""))
- response.redirectedUrl == "http://localhost/login"
- }
+ and: "Exception handling is configured correctly"
+ AuthenticationEntryPoint authEntryPoint = filterChains[1].filters.find { it instanceof ExceptionTranslationFilter}.authenticationEntryPoint
+ MockHttpServletResponse response = new MockHttpServletResponse()
+ authEntryPoint.commence(new MockHttpServletRequest(servletPath: "/private/"), response, new BadCredentialsException(""))
+ response.redirectedUrl == "http://localhost/login"
+ }
- @EnableWebSecurity
- static class FormLoginConfig extends BaseWebConfig {
- @Override
- public void configure(WebSecurity web) throws Exception {
- web
- .ignoring()
- .antMatchers("/resources/**");
- }
+ @EnableWebSecurity
+ static class FormLoginConfig extends BaseWebConfig {
+ @Override
+ public void configure(WebSecurity web) throws Exception {
+ web
+ .ignoring()
+ .antMatchers("/resources/**");
+ }
- @Override
- protected void configure(HttpSecurity http) {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .formLogin()
- .loginPage("/login")
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .formLogin()
+ .loginPage("/login")
+ }
+ }
- def "FormLogin.permitAll()"() {
- when: "load formLogin() with permitAll"
- context = new AnnotationConfigApplicationContext(FormLoginConfigPermitAll)
- FilterChainProxy filterChain = context.getBean(FilterChainProxy)
- MockHttpServletResponse response = new MockHttpServletResponse()
- request = new MockHttpServletRequest(servletPath : servletPath, requestURI: servletPath, queryString: query, method: method)
- setupCsrf()
+ def "FormLogin.permitAll()"() {
+ when: "load formLogin() with permitAll"
+ context = new AnnotationConfigApplicationContext(FormLoginConfigPermitAll)
+ FilterChainProxy filterChain = context.getBean(FilterChainProxy)
+ MockHttpServletResponse response = new MockHttpServletResponse()
+ request = new MockHttpServletRequest(servletPath : servletPath, requestURI: servletPath, queryString: query, method: method)
+ setupCsrf()
- then: "the formLogin URLs are granted access"
- filterChain.doFilter(request, response, new MockFilterChain())
- response.redirectedUrl == redirectUrl
+ then: "the formLogin URLs are granted access"
+ filterChain.doFilter(request, response, new MockFilterChain())
+ response.redirectedUrl == redirectUrl
- where:
- servletPath | method | query | redirectUrl
- "/login" | "GET" | null | null
- "/login" | "POST" | null | "/login?error"
- "/login" | "GET" | "error" | null
- }
+ where:
+ servletPath | method | query | redirectUrl
+ "/login" | "GET" | null | null
+ "/login" | "POST" | null | "/login?error"
+ "/login" | "GET" | "error" | null
+ }
- @EnableWebSecurity
- static class FormLoginConfigPermitAll extends BaseWebConfig {
+ @EnableWebSecurity
+ static class FormLoginConfigPermitAll extends BaseWebConfig {
- @Override
- protected void configure(HttpSecurity http) {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .formLogin()
- .permitAll()
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .formLogin()
+ .permitAll()
+ }
+ }
- @Unroll
- def "FormLogin loginConventions changes defaults"() {
- when: "load formLogin() with permitAll"
- loadConfig(FormLoginDefaultsConfig)
- MockHttpServletResponse response = new MockHttpServletResponse()
- request = new MockHttpServletRequest(servletPath : servletPath, requestURI: servletPath, queryString: query, method: method)
- setupCsrf()
+ @Unroll
+ def "FormLogin loginConventions changes defaults"() {
+ when: "load formLogin() with permitAll"
+ loadConfig(FormLoginDefaultsConfig)
+ MockHttpServletResponse response = new MockHttpServletResponse()
+ request = new MockHttpServletRequest(servletPath : servletPath, requestURI: servletPath, queryString: query, method: method)
+ setupCsrf()
- then: "the other default login/logout URLs are updated and granted access"
- springSecurityFilterChain.doFilter(request, response, new MockFilterChain())
- response.redirectedUrl == redirectUrl
+ then: "the other default login/logout URLs are updated and granted access"
+ springSecurityFilterChain.doFilter(request, response, new MockFilterChain())
+ response.redirectedUrl == redirectUrl
- where:
- servletPath | method | query | redirectUrl
- "/authenticate" | "GET" | null | null
- "/authenticate" | "POST" | null | "/authenticate?error"
- "/authenticate" | "GET" | "error" | null
- "/logout" | "POST" | null | "/authenticate?logout"
- "/authenticate" | "GET" | "logout"| null
- }
+ where:
+ servletPath | method | query | redirectUrl
+ "/authenticate" | "GET" | null | null
+ "/authenticate" | "POST" | null | "/authenticate?error"
+ "/authenticate" | "GET" | "error" | null
+ "/logout" | "POST" | null | "/authenticate?logout"
+ "/authenticate" | "GET" | "logout"| null
+ }
- @EnableWebSecurity
- static class FormLoginDefaultsConfig extends BaseWebConfig {
+ @EnableWebSecurity
+ static class FormLoginDefaultsConfig extends BaseWebConfig {
- @Override
- protected void configure(HttpSecurity http) {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .formLogin()
- .loginPage("/authenticate")
- .permitAll()
- .and()
- .logout()
- .permitAll()
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .formLogin()
+ .loginPage("/authenticate")
+ .permitAll()
+ .and()
+ .logout()
+ .permitAll()
+ }
+ }
- def "FormLogin loginProcessingUrl"() {
- setup:
- loadConfig(FormLoginLoginProcessingUrlConfig)
- request.servletPath = "/loginCheck"
- request.method = "POST"
- request.parameters.username = ["user"] as String[]
- request.parameters.password = ["password"] as String[]
- when:
- springSecurityFilterChain.doFilter(request, response, new MockFilterChain())
- then:
- response.redirectedUrl == "/"
- }
+ def "FormLogin loginProcessingUrl"() {
+ setup:
+ loadConfig(FormLoginLoginProcessingUrlConfig)
+ request.servletPath = "/loginCheck"
+ request.method = "POST"
+ request.parameters.username = ["user"] as String[]
+ request.parameters.password = ["password"] as String[]
+ when:
+ springSecurityFilterChain.doFilter(request, response, new MockFilterChain())
+ then:
+ response.redirectedUrl == "/"
+ }
- @EnableWebSecurity
- static class FormLoginLoginProcessingUrlConfig extends BaseWebConfig {
+ @EnableWebSecurity
+ static class FormLoginLoginProcessingUrlConfig extends BaseWebConfig {
- @Override
- protected void configure(HttpSecurity http) {
- http
- .authorizeRequests()
- .anyRequest().authenticated()
- .and()
- .formLogin()
- .loginProcessingUrl("/loginCheck")
- .loginPage("/login")
- //.failureUrl("/loginFailure")
- .defaultSuccessUrl("/", true)
- .passwordParameter("password")
- .usernameParameter("username")
- .permitAll()
- .and()
- .logout()
- .logoutSuccessUrl("/login")
- .logoutUrl("/logout")
- .deleteCookies("JSESSIONID")
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .authorizeRequests()
+ .anyRequest().authenticated()
+ .and()
+ .formLogin()
+ .loginProcessingUrl("/loginCheck")
+ .loginPage("/login")
+ //.failureUrl("/loginFailure")
+ .defaultSuccessUrl("/", true)
+ .passwordParameter("password")
+ .usernameParameter("username")
+ .permitAll()
+ .and()
+ .logout()
+ .logoutSuccessUrl("/login")
+ .logoutUrl("/logout")
+ .deleteCookies("JSESSIONID")
+ }
+ }
- def "FormLogin uses PortMapper"() {
- when: "load formLogin() with permitAll"
- FormLoginUsesPortMapperConfig.PORT_MAPPER = Mock(PortMapper)
- loadConfig(FormLoginUsesPortMapperConfig)
- then: "the formLogin URLs are granted access"
- findFilter(ExceptionTranslationFilter).authenticationEntryPoint.portMapper == FormLoginUsesPortMapperConfig.PORT_MAPPER
- }
+ def "FormLogin uses PortMapper"() {
+ when: "load formLogin() with permitAll"
+ FormLoginUsesPortMapperConfig.PORT_MAPPER = Mock(PortMapper)
+ loadConfig(FormLoginUsesPortMapperConfig)
+ then: "the formLogin URLs are granted access"
+ findFilter(ExceptionTranslationFilter).authenticationEntryPoint.portMapper == FormLoginUsesPortMapperConfig.PORT_MAPPER
+ }
- @EnableWebSecurity
- static class FormLoginUsesPortMapperConfig extends BaseWebConfig {
- static PortMapper PORT_MAPPER
+ @EnableWebSecurity
+ static class FormLoginUsesPortMapperConfig extends BaseWebConfig {
+ static PortMapper PORT_MAPPER
- @Override
- protected void configure(HttpSecurity http) {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .formLogin()
- .permitAll()
- .and()
- .portMapper()
- .portMapper(PORT_MAPPER)
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .formLogin()
+ .permitAll()
+ .and()
+ .portMapper()
+ .portMapper(PORT_MAPPER)
+ }
+ }
- def "FormLogin permitAll ignores failureUrl when failureHandler set"() {
- setup:
- PermitAllIgnoresFailureHandlerConfig.FAILURE_HANDLER = Mock(AuthenticationFailureHandler)
- loadConfig(PermitAllIgnoresFailureHandlerConfig)
- FilterChainProxy springSecurityFilterChain = context.getBean(FilterChainProxy)
- when: "access default failureUrl and configured explicit FailureHandler"
- MockHttpServletRequest request = new MockHttpServletRequest(servletPath:"/login",requestURI:"/login",queryString:"error",method:"GET")
- MockHttpServletResponse response = new MockHttpServletResponse()
- springSecurityFilterChain.doFilter(request,response,new MockFilterChain())
- then: "access is not granted to the failure handler (sent to login page)"
- response.status == 302
- }
+ def "FormLogin permitAll ignores failureUrl when failureHandler set"() {
+ setup:
+ PermitAllIgnoresFailureHandlerConfig.FAILURE_HANDLER = Mock(AuthenticationFailureHandler)
+ loadConfig(PermitAllIgnoresFailureHandlerConfig)
+ FilterChainProxy springSecurityFilterChain = context.getBean(FilterChainProxy)
+ when: "access default failureUrl and configured explicit FailureHandler"
+ MockHttpServletRequest request = new MockHttpServletRequest(servletPath:"/login",requestURI:"/login",queryString:"error",method:"GET")
+ MockHttpServletResponse response = new MockHttpServletResponse()
+ springSecurityFilterChain.doFilter(request,response,new MockFilterChain())
+ then: "access is not granted to the failure handler (sent to login page)"
+ response.status == 302
+ }
- @EnableWebSecurity
- static class PermitAllIgnoresFailureHandlerConfig extends BaseWebConfig {
- static AuthenticationFailureHandler FAILURE_HANDLER
+ @EnableWebSecurity
+ static class PermitAllIgnoresFailureHandlerConfig extends BaseWebConfig {
+ static AuthenticationFailureHandler FAILURE_HANDLER
- @Override
- protected void configure(HttpSecurity http) {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .formLogin()
- .failureHandler(FAILURE_HANDLER)
- .permitAll()
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .formLogin()
+ .failureHandler(FAILURE_HANDLER)
+ .permitAll()
+ }
+ }
- def "duplicate formLogin does not override"() {
- setup:
- DuplicateInvocationsDoesNotOverrideConfig.FAILURE_HANDLER = Mock(AuthenticationFailureHandler)
- when:
- loadConfig(DuplicateInvocationsDoesNotOverrideConfig)
- then:
- findFilter(UsernamePasswordAuthenticationFilter).usernameParameter == "custom-username"
- }
+ def "duplicate formLogin does not override"() {
+ setup:
+ DuplicateInvocationsDoesNotOverrideConfig.FAILURE_HANDLER = Mock(AuthenticationFailureHandler)
+ when:
+ loadConfig(DuplicateInvocationsDoesNotOverrideConfig)
+ then:
+ findFilter(UsernamePasswordAuthenticationFilter).usernameParameter == "custom-username"
+ }
- @EnableWebSecurity
- static class DuplicateInvocationsDoesNotOverrideConfig extends BaseWebConfig {
- static AuthenticationFailureHandler FAILURE_HANDLER
+ @EnableWebSecurity
+ static class DuplicateInvocationsDoesNotOverrideConfig extends BaseWebConfig {
+ static AuthenticationFailureHandler FAILURE_HANDLER
- @Override
- protected void configure(HttpSecurity http) {
- http
- .formLogin()
- .usernameParameter("custom-username")
- .and()
- .formLogin()
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .formLogin()
+ .usernameParameter("custom-username")
+ .and()
+ .formLogin()
+ }
+ }
- def "formLogin ObjectPostProcessor"() {
- setup: "initialize the AUTH_FILTER as a mock"
- AnyObjectPostProcessor opp = Mock()
- HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
- when:
- http
- .exceptionHandling()
- .and()
- .formLogin()
- .and()
- .build()
+ def "formLogin ObjectPostProcessor"() {
+ setup: "initialize the AUTH_FILTER as a mock"
+ AnyObjectPostProcessor opp = Mock()
+ HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
+ when:
+ http
+ .exceptionHandling()
+ .and()
+ .formLogin()
+ .and()
+ .build()
- then: "UsernamePasswordAuthenticationFilter is registered with ObjectPostProcessor"
- 1 * opp.postProcess(_ as UsernamePasswordAuthenticationFilter) >> {UsernamePasswordAuthenticationFilter o -> o}
- and: "LoginUrlAuthenticationEntryPoint is registered with ObjectPostProcessor"
- 1 * opp.postProcess(_ as LoginUrlAuthenticationEntryPoint) >> {LoginUrlAuthenticationEntryPoint o -> o}
- and: "ExceptionTranslationFilter is registered with ObjectPostProcessor"
- 1 * opp.postProcess(_ as ExceptionTranslationFilter) >> {ExceptionTranslationFilter o -> o}
- }
+ then: "UsernamePasswordAuthenticationFilter is registered with ObjectPostProcessor"
+ 1 * opp.postProcess(_ as UsernamePasswordAuthenticationFilter) >> {UsernamePasswordAuthenticationFilter o -> o}
+ and: "LoginUrlAuthenticationEntryPoint is registered with ObjectPostProcessor"
+ 1 * opp.postProcess(_ as LoginUrlAuthenticationEntryPoint) >> {LoginUrlAuthenticationEntryPoint o -> o}
+ and: "ExceptionTranslationFilter is registered with ObjectPostProcessor"
+ 1 * opp.postProcess(_ as ExceptionTranslationFilter) >> {ExceptionTranslationFilter o -> o}
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/HeadersConfigurerTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/HeadersConfigurerTests.groovy
index b0d2eba9a1..cb68d99baf 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/HeadersConfigurerTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/HeadersConfigurerTests.groovy
@@ -39,163 +39,163 @@ import spock.lang.Unroll;
*/
class HeadersConfigurerTests extends BaseSpringSpec {
- def "headers"() {
- setup:
- loadConfig(HeadersConfig)
- request.secure = true
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- responseHeaders == ['X-Content-Type-Options':'nosniff',
- 'X-Frame-Options':'DENY',
- 'Strict-Transport-Security': 'max-age=31536000 ; includeSubDomains',
- 'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
- 'Expires' : '0',
- 'Pragma':'no-cache',
- 'X-XSS-Protection' : '1; mode=block']
- }
+ def "headers"() {
+ setup:
+ loadConfig(HeadersConfig)
+ request.secure = true
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ responseHeaders == ['X-Content-Type-Options':'nosniff',
+ 'X-Frame-Options':'DENY',
+ 'Strict-Transport-Security': 'max-age=31536000 ; includeSubDomains',
+ 'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
+ 'Expires' : '0',
+ 'Pragma':'no-cache',
+ 'X-XSS-Protection' : '1; mode=block']
+ }
- @EnableWebSecurity
- static class HeadersConfig extends WebSecurityConfigurerAdapter {
+ @EnableWebSecurity
+ static class HeadersConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.headers()
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http.headers()
+ }
+ }
- def "headers.contentType"() {
- setup:
- loadConfig(ContentTypeOptionsConfig)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- responseHeaders == ['X-Content-Type-Options':'nosniff']
- }
+ def "headers.contentType"() {
+ setup:
+ loadConfig(ContentTypeOptionsConfig)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ responseHeaders == ['X-Content-Type-Options':'nosniff']
+ }
- @EnableWebSecurity
- static class ContentTypeOptionsConfig extends WebSecurityConfigurerAdapter {
+ @EnableWebSecurity
+ static class ContentTypeOptionsConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .headers()
- .defaultsDisabled()
- .contentTypeOptions()
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .headers()
+ .defaultsDisabled()
+ .contentTypeOptions()
+ }
+ }
- def "headers.frameOptions"() {
- setup:
- loadConfig(FrameOptionsConfig)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- responseHeaders == ['X-Frame-Options':'DENY']
- }
+ def "headers.frameOptions"() {
+ setup:
+ loadConfig(FrameOptionsConfig)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ responseHeaders == ['X-Frame-Options':'DENY']
+ }
- @EnableWebSecurity
- static class FrameOptionsConfig extends WebSecurityConfigurerAdapter {
+ @EnableWebSecurity
+ static class FrameOptionsConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .headers()
- .defaultsDisabled()
- .frameOptions()
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .headers()
+ .defaultsDisabled()
+ .frameOptions()
+ }
+ }
- def "headers.hsts"() {
- setup:
- loadConfig(HstsConfig)
- request.secure = true
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- responseHeaders == ['Strict-Transport-Security': 'max-age=31536000 ; includeSubDomains']
- }
+ def "headers.hsts"() {
+ setup:
+ loadConfig(HstsConfig)
+ request.secure = true
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ responseHeaders == ['Strict-Transport-Security': 'max-age=31536000 ; includeSubDomains']
+ }
- @EnableWebSecurity
- static class HstsConfig extends WebSecurityConfigurerAdapter {
+ @EnableWebSecurity
+ static class HstsConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .headers()
- .defaultsDisabled()
- .httpStrictTransportSecurity()
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .headers()
+ .defaultsDisabled()
+ .httpStrictTransportSecurity()
+ }
+ }
- def "headers.cacheControl"() {
- setup:
- loadConfig(CacheControlConfig)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- responseHeaders == ['Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
- 'Expires' : '0',
- 'Pragma':'no-cache']
- }
+ def "headers.cacheControl"() {
+ setup:
+ loadConfig(CacheControlConfig)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ responseHeaders == ['Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
+ 'Expires' : '0',
+ 'Pragma':'no-cache']
+ }
- @EnableWebSecurity
- static class CacheControlConfig extends WebSecurityConfigurerAdapter {
+ @EnableWebSecurity
+ static class CacheControlConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .headers()
- .defaultsDisabled()
- .cacheControl()
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .headers()
+ .defaultsDisabled()
+ .cacheControl()
+ }
+ }
- def "headers.xssProtection"() {
- setup:
- loadConfig(XssProtectionConfig)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- responseHeaders == ['X-XSS-Protection' : '1; mode=block']
- }
+ def "headers.xssProtection"() {
+ setup:
+ loadConfig(XssProtectionConfig)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ responseHeaders == ['X-XSS-Protection' : '1; mode=block']
+ }
- @EnableWebSecurity
- static class XssProtectionConfig extends WebSecurityConfigurerAdapter {
+ @EnableWebSecurity
+ static class XssProtectionConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .headers()
- .defaultsDisabled()
- .xssProtection()
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .headers()
+ .defaultsDisabled()
+ .xssProtection()
+ }
+ }
- def "headers custom x-frame-options"() {
- setup:
- loadConfig(HeadersCustomSameOriginConfig)
- request.secure = true
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- responseHeaders == ['X-Content-Type-Options':'nosniff',
- 'X-Frame-Options':'SAMEORIGIN',
- 'Strict-Transport-Security': 'max-age=31536000 ; includeSubDomains',
- 'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
- 'Expires' : '0',
- 'Pragma':'no-cache',
- 'X-XSS-Protection' : '1; mode=block']
- }
+ def "headers custom x-frame-options"() {
+ setup:
+ loadConfig(HeadersCustomSameOriginConfig)
+ request.secure = true
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ responseHeaders == ['X-Content-Type-Options':'nosniff',
+ 'X-Frame-Options':'SAMEORIGIN',
+ 'Strict-Transport-Security': 'max-age=31536000 ; includeSubDomains',
+ 'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
+ 'Expires' : '0',
+ 'Pragma':'no-cache',
+ 'X-XSS-Protection' : '1; mode=block']
+ }
- @EnableWebSecurity
- static class HeadersCustomSameOriginConfig extends WebSecurityConfigurerAdapter {
+ @EnableWebSecurity
+ static class HeadersCustomSameOriginConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .headers()
- .frameOptions().sameOrigin()
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .headers()
+ .frameOptions().sameOrigin()
+ }
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/HttpBasicConfigurerTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/HttpBasicConfigurerTests.groovy
index 07ec2195fb..77b1b7a26d 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/HttpBasicConfigurerTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/HttpBasicConfigurerTests.groovy
@@ -33,101 +33,101 @@ import org.springframework.security.web.authentication.www.BasicAuthenticationFi
*/
class HttpBasicConfigurerTests extends BaseSpringSpec {
- def "httBasic ObjectPostProcessor"() {
- setup:
- AnyObjectPostProcessor opp = Mock()
- HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
- when:
- http
- .httpBasic()
- .and()
- .build()
+ def "httBasic ObjectPostProcessor"() {
+ setup:
+ AnyObjectPostProcessor opp = Mock()
+ HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
+ when:
+ http
+ .httpBasic()
+ .and()
+ .build()
- then: "ExceptionTranslationFilter is registered with LifecycleManager"
- 1 * opp.postProcess(_ as BasicAuthenticationFilter) >> {BasicAuthenticationFilter o -> o}
- }
+ then: "ExceptionTranslationFilter is registered with LifecycleManager"
+ 1 * opp.postProcess(_ as BasicAuthenticationFilter) >> {BasicAuthenticationFilter o -> o}
+ }
- def "SEC-2198: http.httpBasic() defaults AuthenticationEntryPoint"() {
- setup:
- loadConfig(DefaultsEntryPointConfig)
- when:
- springSecurityFilterChain.doFilter(request, response, chain)
- then:
- response.status == 401
- response.getHeader("WWW-Authenticate") == 'Basic realm="Realm"'
- }
+ def "SEC-2198: http.httpBasic() defaults AuthenticationEntryPoint"() {
+ setup:
+ loadConfig(DefaultsEntryPointConfig)
+ when:
+ springSecurityFilterChain.doFilter(request, response, chain)
+ then:
+ response.status == 401
+ response.getHeader("WWW-Authenticate") == 'Basic realm="Realm"'
+ }
- @EnableWebSecurity
- static class DefaultsEntryPointConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .anyRequest().authenticated()
- .and()
- .httpBasic()
- }
+ @EnableWebSecurity
+ static class DefaultsEntryPointConfig extends WebSecurityConfigurerAdapter {
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .authorizeRequests()
+ .anyRequest().authenticated()
+ .and()
+ .httpBasic()
+ }
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth
- .inMemoryAuthentication()
- }
- }
+ @Override
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth
+ .inMemoryAuthentication()
+ }
+ }
- def "http.httpBasic().authenticationEntryPoint used for AuthenticationEntryPoint"() {
- setup:
- CustomAuthenticationEntryPointConfig.ENTRY_POINT = Mock(AuthenticationEntryPoint)
- when:
- loadConfig(CustomAuthenticationEntryPointConfig)
- then:
- findFilter(ExceptionTranslationFilter).authenticationEntryPoint == CustomAuthenticationEntryPointConfig.ENTRY_POINT
- }
+ def "http.httpBasic().authenticationEntryPoint used for AuthenticationEntryPoint"() {
+ setup:
+ CustomAuthenticationEntryPointConfig.ENTRY_POINT = Mock(AuthenticationEntryPoint)
+ when:
+ loadConfig(CustomAuthenticationEntryPointConfig)
+ then:
+ findFilter(ExceptionTranslationFilter).authenticationEntryPoint == CustomAuthenticationEntryPointConfig.ENTRY_POINT
+ }
- @EnableWebSecurity
- static class CustomAuthenticationEntryPointConfig extends WebSecurityConfigurerAdapter {
- static AuthenticationEntryPoint ENTRY_POINT
+ @EnableWebSecurity
+ static class CustomAuthenticationEntryPointConfig extends WebSecurityConfigurerAdapter {
+ static AuthenticationEntryPoint ENTRY_POINT
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .httpBasic()
- .authenticationEntryPoint(ENTRY_POINT)
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .httpBasic()
+ .authenticationEntryPoint(ENTRY_POINT)
+ }
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth
- .inMemoryAuthentication()
- }
- }
+ @Override
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth
+ .inMemoryAuthentication()
+ }
+ }
- def "duplicate httpBasic invocations does not override"() {
- setup:
- DuplicateDoesNotOverrideConfig.ENTRY_POINT = Mock(AuthenticationEntryPoint)
- when:
- loadConfig(DuplicateDoesNotOverrideConfig)
- then:
- findFilter(ExceptionTranslationFilter).authenticationEntryPoint == DuplicateDoesNotOverrideConfig.ENTRY_POINT
- }
+ def "duplicate httpBasic invocations does not override"() {
+ setup:
+ DuplicateDoesNotOverrideConfig.ENTRY_POINT = Mock(AuthenticationEntryPoint)
+ when:
+ loadConfig(DuplicateDoesNotOverrideConfig)
+ then:
+ findFilter(ExceptionTranslationFilter).authenticationEntryPoint == DuplicateDoesNotOverrideConfig.ENTRY_POINT
+ }
- @EnableWebSecurity
- static class DuplicateDoesNotOverrideConfig extends WebSecurityConfigurerAdapter {
- static AuthenticationEntryPoint ENTRY_POINT
+ @EnableWebSecurity
+ static class DuplicateDoesNotOverrideConfig extends WebSecurityConfigurerAdapter {
+ static AuthenticationEntryPoint ENTRY_POINT
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .httpBasic()
- .authenticationEntryPoint(ENTRY_POINT)
- .and()
- .httpBasic()
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .httpBasic()
+ .authenticationEntryPoint(ENTRY_POINT)
+ .and()
+ .httpBasic()
+ }
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth
- .inMemoryAuthentication()
- }
- }
+ @Override
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth
+ .inMemoryAuthentication()
+ }
+ }
}
\ No newline at end of file
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/JeeConfigurerTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/JeeConfigurerTests.groovy
index 1a5607f321..10f1a1445e 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/JeeConfigurerTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/JeeConfigurerTests.groovy
@@ -31,38 +31,38 @@ import org.springframework.security.web.authentication.preauth.j2ee.J2eePreAuthe
*/
class JeeConfigurerTests extends BaseSpringSpec {
- def "jee ObjectPostProcessor"() {
- setup:
- AnyObjectPostProcessor opp = Mock()
- HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
- when:
- http
- .jee()
- .and()
- .build()
+ def "jee ObjectPostProcessor"() {
+ setup:
+ AnyObjectPostProcessor opp = Mock()
+ HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
+ when:
+ http
+ .jee()
+ .and()
+ .build()
- then: "J2eePreAuthenticatedProcessingFilter is registered with LifecycleManager"
- 1 * opp.postProcess(_ as J2eePreAuthenticatedProcessingFilter) >> {J2eePreAuthenticatedProcessingFilter o -> o}
- and: "J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource is registered with LifecycleManager"
- 1 * opp.postProcess(_ as J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource) >> {J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource o -> o}
- }
+ then: "J2eePreAuthenticatedProcessingFilter is registered with LifecycleManager"
+ 1 * opp.postProcess(_ as J2eePreAuthenticatedProcessingFilter) >> {J2eePreAuthenticatedProcessingFilter o -> o}
+ and: "J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource is registered with LifecycleManager"
+ 1 * opp.postProcess(_ as J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource) >> {J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource o -> o}
+ }
- def "invoke jee twice does not override"() {
- when:
- loadConfig(InvokeTwiceDoesNotOverride)
- then:
- findFilter(J2eePreAuthenticatedProcessingFilter).authenticationDetailsSource.j2eeMappableRoles == ["ROLE_USER"] as Set
- }
+ def "invoke jee twice does not override"() {
+ when:
+ loadConfig(InvokeTwiceDoesNotOverride)
+ then:
+ findFilter(J2eePreAuthenticatedProcessingFilter).authenticationDetailsSource.j2eeMappableRoles == ["ROLE_USER"] as Set
+ }
- @EnableWebSecurity
- static class InvokeTwiceDoesNotOverride extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .jee()
- .mappableRoles("USER")
- .and()
- .jee()
- }
- }
+ @EnableWebSecurity
+ static class InvokeTwiceDoesNotOverride extends WebSecurityConfigurerAdapter {
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .jee()
+ .mappableRoles("USER")
+ .and()
+ .jee()
+ }
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/LogoutConfigurerTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/LogoutConfigurerTests.groovy
index df42a092b7..3ed19f5f24 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/LogoutConfigurerTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/LogoutConfigurerTests.groovy
@@ -30,85 +30,85 @@ import org.springframework.security.web.authentication.logout.LogoutFilter
*/
class LogoutConfigurerTests extends BaseSpringSpec {
- def "logout ObjectPostProcessor"() {
- setup:
- AnyObjectPostProcessor opp = Mock()
- HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
- when:
- http
- .logout()
- .and()
- .build()
+ def "logout ObjectPostProcessor"() {
+ setup:
+ AnyObjectPostProcessor opp = Mock()
+ HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
+ when:
+ http
+ .logout()
+ .and()
+ .build()
- then: "LogoutFilter is registered with LifecycleManager"
- 1 * opp.postProcess(_ as LogoutFilter) >> {LogoutFilter o -> o}
- }
+ then: "LogoutFilter is registered with LifecycleManager"
+ 1 * opp.postProcess(_ as LogoutFilter) >> {LogoutFilter o -> o}
+ }
- def "invoke logout twice does not override"() {
- when:
- loadConfig(InvokeTwiceDoesNotOverride)
- request.method = "POST"
- request.servletPath = "/custom/logout"
- findFilter(LogoutFilter).doFilter(request,response,chain)
- then:
- response.redirectedUrl == "/login?logout"
- }
+ def "invoke logout twice does not override"() {
+ when:
+ loadConfig(InvokeTwiceDoesNotOverride)
+ request.method = "POST"
+ request.servletPath = "/custom/logout"
+ findFilter(LogoutFilter).doFilter(request,response,chain)
+ then:
+ response.redirectedUrl == "/login?logout"
+ }
- @EnableWebSecurity
- static class InvokeTwiceDoesNotOverride extends WebSecurityConfigurerAdapter {
+ @EnableWebSecurity
+ static class InvokeTwiceDoesNotOverride extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .logout()
- .logoutUrl("/custom/logout")
- .and()
- .logout()
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .logout()
+ .logoutUrl("/custom/logout")
+ .and()
+ .logout()
+ }
+ }
- def "SEC-2311: Logout allows other methods if CSRF is disabled"() {
- when:
- loadConfig(CsrfDisabledConfig)
- request.method = "GET"
- request.servletPath = "/logout"
- findFilter(LogoutFilter).doFilter(request,response,chain)
- then:
- response.redirectedUrl == "/login?logout"
- }
+ def "SEC-2311: Logout allows other methods if CSRF is disabled"() {
+ when:
+ loadConfig(CsrfDisabledConfig)
+ request.method = "GET"
+ request.servletPath = "/logout"
+ findFilter(LogoutFilter).doFilter(request,response,chain)
+ then:
+ response.redirectedUrl == "/login?logout"
+ }
- @EnableWebSecurity
- static class CsrfDisabledConfig extends WebSecurityConfigurerAdapter {
+ @EnableWebSecurity
+ static class CsrfDisabledConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .csrf().disable()
- .logout()
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .csrf().disable()
+ .logout()
+ }
+ }
- def "SEC-2311: Logout allows other methods if CSRF is disabled with custom logout URL"() {
- when:
- loadConfig(CsrfDisabledCustomLogoutUrlConfig)
- request.method = "GET"
- request.servletPath = "/custom/logout"
- findFilter(LogoutFilter).doFilter(request,response,chain)
- then:
- response.redirectedUrl == "/login?logout"
- }
+ def "SEC-2311: Logout allows other methods if CSRF is disabled with custom logout URL"() {
+ when:
+ loadConfig(CsrfDisabledCustomLogoutUrlConfig)
+ request.method = "GET"
+ request.servletPath = "/custom/logout"
+ findFilter(LogoutFilter).doFilter(request,response,chain)
+ then:
+ response.redirectedUrl == "/login?logout"
+ }
- @EnableWebSecurity
- static class CsrfDisabledCustomLogoutUrlConfig extends WebSecurityConfigurerAdapter {
+ @EnableWebSecurity
+ static class CsrfDisabledCustomLogoutUrlConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .logout()
- .logoutUrl("/custom/logout")
- .and()
- .csrf().disable()
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .logout()
+ .logoutUrl("/custom/logout")
+ .and()
+ .csrf().disable()
+ }
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceDebugTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceDebugTests.groovy
index 4ad66b0d20..ac91a0f09b 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceDebugTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceDebugTests.groovy
@@ -64,14 +64,14 @@ import spock.lang.Ignore;
*
*/
public class NamespaceDebugTests extends BaseSpringSpec {
- def "debug=true"() {
- when: "Load configuraiton with debug enabled"
- loadConfig(DebugWebSecurity)
- then: "The DebugFilter is present"
- context.getBean("springSecurityFilterChain").class == DebugFilter
- }
+ def "debug=true"() {
+ when: "Load configuraiton with debug enabled"
+ loadConfig(DebugWebSecurity)
+ then: "The DebugFilter is present"
+ context.getBean("springSecurityFilterChain").class == DebugFilter
+ }
- @EnableWebSecurity(debug=true)
- static class DebugWebSecurity extends WebSecurityConfigurerAdapter {
- }
+ @EnableWebSecurity(debug=true)
+ static class DebugWebSecurity extends WebSecurityConfigurerAdapter {
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpAccessDeniedHandlerTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpAccessDeniedHandlerTests.groovy
index 2e48003260..8bfbbd4dea 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpAccessDeniedHandlerTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpAccessDeniedHandlerTests.groovy
@@ -37,44 +37,44 @@ import org.springframework.security.web.access.ExceptionTranslationFilter;
*
*/
public class NamespaceHttpAccessDeniedHandlerTests extends BaseSpringSpec {
- def "http/access-denied-handler@error-page"() {
- when:
- loadConfig(AccessDeniedPageConfig)
- then:
- findFilter(ExceptionTranslationFilter).accessDeniedHandler.errorPage == "/AccessDeniedPageConfig"
- }
+ def "http/access-denied-handler@error-page"() {
+ when:
+ loadConfig(AccessDeniedPageConfig)
+ then:
+ findFilter(ExceptionTranslationFilter).accessDeniedHandler.errorPage == "/AccessDeniedPageConfig"
+ }
- @Configuration
- static class AccessDeniedPageConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) {
- http.
- exceptionHandling()
- .accessDeniedPage("/AccessDeniedPageConfig")
- }
- }
+ @Configuration
+ static class AccessDeniedPageConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) {
+ http.
+ exceptionHandling()
+ .accessDeniedPage("/AccessDeniedPageConfig")
+ }
+ }
- def "http/access-denied-handler@ref"() {
- when:
- loadConfig(AccessDeniedHandlerRefConfig)
- then:
- findFilter(ExceptionTranslationFilter).accessDeniedHandler.class == AccessDeniedHandlerRefConfig.CustomAccessDeniedHandler
- }
+ def "http/access-denied-handler@ref"() {
+ when:
+ loadConfig(AccessDeniedHandlerRefConfig)
+ then:
+ findFilter(ExceptionTranslationFilter).accessDeniedHandler.class == AccessDeniedHandlerRefConfig.CustomAccessDeniedHandler
+ }
- @Configuration
- static class AccessDeniedHandlerRefConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) {
- CustomAccessDeniedHandler accessDeniedHandler = new CustomAccessDeniedHandler()
- http.
- exceptionHandling()
- .accessDeniedHandler(accessDeniedHandler)
- }
+ @Configuration
+ static class AccessDeniedHandlerRefConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) {
+ CustomAccessDeniedHandler accessDeniedHandler = new CustomAccessDeniedHandler()
+ http.
+ exceptionHandling()
+ .accessDeniedHandler(accessDeniedHandler)
+ }
- static class CustomAccessDeniedHandler implements AccessDeniedHandler {
- public void handle(HttpServletRequest request,
- HttpServletResponse response,
- AccessDeniedException accessDeniedException)
- throws IOException, ServletException {
- }
- }
- }
+ static class CustomAccessDeniedHandler implements AccessDeniedHandler {
+ public void handle(HttpServletRequest request,
+ HttpServletResponse response,
+ AccessDeniedException accessDeniedException)
+ throws IOException, ServletException {
+ }
+ }
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpAnonymousTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpAnonymousTests.groovy
index 2f2983aa2b..4724169945 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpAnonymousTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpAnonymousTests.groovy
@@ -32,98 +32,98 @@ import org.springframework.security.web.authentication.AnonymousAuthenticationFi
*
*/
public class NamespaceHttpAnonymousTests extends BaseSpringSpec {
- def "http/anonymous@enabled = true (default)"() {
- when:
- loadConfig(AnonymousConfig)
- then:
- def filter = findFilter(AnonymousAuthenticationFilter)
- filter != null
- def authManager = findFilter(FilterSecurityInterceptor).authenticationManager
- authManager.authenticate(new AnonymousAuthenticationToken(filter.key, filter.principal, filter.authorities)).authenticated
- }
+ def "http/anonymous@enabled = true (default)"() {
+ when:
+ loadConfig(AnonymousConfig)
+ then:
+ def filter = findFilter(AnonymousAuthenticationFilter)
+ filter != null
+ def authManager = findFilter(FilterSecurityInterceptor).authenticationManager
+ authManager.authenticate(new AnonymousAuthenticationToken(filter.key, filter.principal, filter.authorities)).authenticated
+ }
- @Configuration
- static class AnonymousConfig extends BaseWebConfig {
- @Override
- protected void configure(HttpSecurity http) {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER");
- }
- }
+ @Configuration
+ static class AnonymousConfig extends BaseWebConfig {
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER");
+ }
+ }
- def "http/anonymous@enabled = false"() {
- when:
- loadConfig(AnonymousDisabledConfig)
- then:
- findFilter(AnonymousAuthenticationFilter) == null
- }
+ def "http/anonymous@enabled = false"() {
+ when:
+ loadConfig(AnonymousDisabledConfig)
+ then:
+ findFilter(AnonymousAuthenticationFilter) == null
+ }
- @Configuration
- static class AnonymousDisabledConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) {
- http.anonymous().disable()
- }
- }
+ @Configuration
+ static class AnonymousDisabledConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) {
+ http.anonymous().disable()
+ }
+ }
- def "http/anonymous@granted-authority"() {
- when:
- loadConfig(AnonymousGrantedAuthorityConfig)
- then:
- findFilter(AnonymousAuthenticationFilter).authorities == AuthorityUtils.createAuthorityList("ROLE_ANON")
- }
+ def "http/anonymous@granted-authority"() {
+ when:
+ loadConfig(AnonymousGrantedAuthorityConfig)
+ then:
+ findFilter(AnonymousAuthenticationFilter).authorities == AuthorityUtils.createAuthorityList("ROLE_ANON")
+ }
- @Configuration
- static class AnonymousGrantedAuthorityConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) {
- http
- .anonymous()
- .authorities("ROLE_ANON")
- }
- }
+ @Configuration
+ static class AnonymousGrantedAuthorityConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) {
+ http
+ .anonymous()
+ .authorities("ROLE_ANON")
+ }
+ }
- def "http/anonymous@key"() {
- when:
- loadConfig(AnonymousKeyConfig)
- then:
- def filter = findFilter(AnonymousAuthenticationFilter)
- filter != null
- filter.key == "AnonymousKeyConfig"
- def authManager = findFilter(FilterSecurityInterceptor).authenticationManager
- authManager.authenticate(new AnonymousAuthenticationToken(filter.key, filter.principal, filter.authorities)).authenticated
- }
+ def "http/anonymous@key"() {
+ when:
+ loadConfig(AnonymousKeyConfig)
+ then:
+ def filter = findFilter(AnonymousAuthenticationFilter)
+ filter != null
+ filter.key == "AnonymousKeyConfig"
+ def authManager = findFilter(FilterSecurityInterceptor).authenticationManager
+ authManager.authenticate(new AnonymousAuthenticationToken(filter.key, filter.principal, filter.authorities)).authenticated
+ }
- @Configuration
- static class AnonymousKeyConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .anonymous().key("AnonymousKeyConfig")
- }
- }
+ @Configuration
+ static class AnonymousKeyConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .anonymous().key("AnonymousKeyConfig")
+ }
+ }
- def "http/anonymous@username"() {
- when:
- loadConfig(AnonymousUsernameConfig)
- then:
- def filter = findFilter(AnonymousAuthenticationFilter)
- filter != null
- filter.principal == "AnonymousUsernameConfig"
- def authManager = findFilter(FilterSecurityInterceptor).authenticationManager
- authManager.authenticate(new AnonymousAuthenticationToken(filter.key, filter.principal, filter.authorities)).principal == "AnonymousUsernameConfig"
- }
+ def "http/anonymous@username"() {
+ when:
+ loadConfig(AnonymousUsernameConfig)
+ then:
+ def filter = findFilter(AnonymousAuthenticationFilter)
+ filter != null
+ filter.principal == "AnonymousUsernameConfig"
+ def authManager = findFilter(FilterSecurityInterceptor).authenticationManager
+ authManager.authenticate(new AnonymousAuthenticationToken(filter.key, filter.principal, filter.authorities)).principal == "AnonymousUsernameConfig"
+ }
- @Configuration
- static class AnonymousUsernameConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .anonymous().principal("AnonymousUsernameConfig")
- }
- }
+ @Configuration
+ static class AnonymousUsernameConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .anonymous().principal("AnonymousUsernameConfig")
+ }
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpBasicTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpBasicTests.groovy
index 70786188f6..c10ce19665 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpBasicTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpBasicTests.groovy
@@ -40,117 +40,117 @@ import org.springframework.security.web.authentication.www.BasicAuthenticationFi
*/
public class NamespaceHttpBasicTests extends BaseSpringSpec {
- def "http/http-basic"() {
- setup:
- loadConfig(HttpBasicConfig)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_UNAUTHORIZED
- when: "fail to log in"
- super.setup()
- basicLogin("user","invalid")
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "unauthorized"
- response.status == HttpServletResponse.SC_UNAUTHORIZED
- response.getHeader("WWW-Authenticate") == 'Basic realm="Realm"'
- when: "login success"
- super.setup()
- basicLogin()
- then: "sent to default succes page"
- !response.committed
- }
+ def "http/http-basic"() {
+ setup:
+ loadConfig(HttpBasicConfig)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_UNAUTHORIZED
+ when: "fail to log in"
+ super.setup()
+ basicLogin("user","invalid")
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "unauthorized"
+ response.status == HttpServletResponse.SC_UNAUTHORIZED
+ response.getHeader("WWW-Authenticate") == 'Basic realm="Realm"'
+ when: "login success"
+ super.setup()
+ basicLogin()
+ then: "sent to default succes page"
+ !response.committed
+ }
- @Configuration
- static class HttpBasicConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .httpBasic();
- }
- }
+ @Configuration
+ static class HttpBasicConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .httpBasic();
+ }
+ }
- def "http@realm"() {
- setup:
- loadConfig(CustomHttpBasicConfig)
- when:
- basicLogin("user","invalid")
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "unauthorized"
- response.status == HttpServletResponse.SC_UNAUTHORIZED
- response.getHeader("WWW-Authenticate") == 'Basic realm="Custom Realm"'
- }
+ def "http@realm"() {
+ setup:
+ loadConfig(CustomHttpBasicConfig)
+ when:
+ basicLogin("user","invalid")
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "unauthorized"
+ response.status == HttpServletResponse.SC_UNAUTHORIZED
+ response.getHeader("WWW-Authenticate") == 'Basic realm="Custom Realm"'
+ }
- @Configuration
- static class CustomHttpBasicConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .httpBasic().realmName("Custom Realm");
- }
- }
+ @Configuration
+ static class CustomHttpBasicConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .httpBasic().realmName("Custom Realm");
+ }
+ }
- def "http-basic@authentication-details-source-ref"() {
- when:
- loadConfig(AuthenticationDetailsSourceHttpBasicConfig)
- then:
- findFilter(BasicAuthenticationFilter).authenticationDetailsSource.class == CustomAuthenticationDetailsSource
- }
+ def "http-basic@authentication-details-source-ref"() {
+ when:
+ loadConfig(AuthenticationDetailsSourceHttpBasicConfig)
+ then:
+ findFilter(BasicAuthenticationFilter).authenticationDetailsSource.class == CustomAuthenticationDetailsSource
+ }
- @Configuration
- static class AuthenticationDetailsSourceHttpBasicConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) {
- http
- .httpBasic()
- .authenticationDetailsSource(new CustomAuthenticationDetailsSource())
- }
- }
+ @Configuration
+ static class AuthenticationDetailsSourceHttpBasicConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) {
+ http
+ .httpBasic()
+ .authenticationDetailsSource(new CustomAuthenticationDetailsSource())
+ }
+ }
- static class CustomAuthenticationDetailsSource extends WebAuthenticationDetailsSource {}
+ static class CustomAuthenticationDetailsSource extends WebAuthenticationDetailsSource {}
- def "http-basic@entry-point-ref"() {
- setup:
- loadConfig(EntryPointRefHttpBasicConfig)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_INTERNAL_SERVER_ERROR
- when: "fail to log in"
- super.setup()
- basicLogin("user","invalid")
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "custom"
- response.status == HttpServletResponse.SC_INTERNAL_SERVER_ERROR
- when: "login success"
- super.setup()
- basicLogin()
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "sent to default succes page"
- !response.committed
- }
+ def "http-basic@entry-point-ref"() {
+ setup:
+ loadConfig(EntryPointRefHttpBasicConfig)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_INTERNAL_SERVER_ERROR
+ when: "fail to log in"
+ super.setup()
+ basicLogin("user","invalid")
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "custom"
+ response.status == HttpServletResponse.SC_INTERNAL_SERVER_ERROR
+ when: "login success"
+ super.setup()
+ basicLogin()
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "sent to default succes page"
+ !response.committed
+ }
- @Configuration
- static class EntryPointRefHttpBasicConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .httpBasic()
- .authenticationEntryPoint(new AuthenticationEntryPoint() {
- public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) {
- response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
- }
- })
- }
- }
+ @Configuration
+ static class EntryPointRefHttpBasicConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .httpBasic()
+ .authenticationEntryPoint(new AuthenticationEntryPoint() {
+ public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) {
+ response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
+ }
+ })
+ }
+ }
- def basicLogin(String username="user",String password="password") {
- def credentials = username + ":" + password
- request.addHeader("Authorization", "Basic " + credentials.bytes.encodeBase64())
- }
+ def basicLogin(String username="user",String password="password") {
+ def credentials = username + ":" + password
+ request.addHeader("Authorization", "Basic " + credentials.bytes.encodeBase64())
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpCustomFilterTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpCustomFilterTests.groovy
index 8b5c12dafe..bebf5b0ba5 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpCustomFilterTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpCustomFilterTests.groovy
@@ -65,105 +65,105 @@ import spock.lang.Ignore;
*
*/
public class NamespaceHttpCustomFilterTests extends BaseSpringSpec {
- def "http/custom-filter@before"() {
- when:
- loadConfig(CustomFilterBeforeConfig)
- then:
- filterChain().filters[0].class == CustomFilter
- }
+ def "http/custom-filter@before"() {
+ when:
+ loadConfig(CustomFilterBeforeConfig)
+ then:
+ filterChain().filters[0].class == CustomFilter
+ }
- @Configuration
- static class CustomFilterBeforeConfig extends BaseWebConfig {
- CustomFilterBeforeConfig() {
- // do not add the default filters to make testing easier
- super(true)
- }
+ @Configuration
+ static class CustomFilterBeforeConfig extends BaseWebConfig {
+ CustomFilterBeforeConfig() {
+ // do not add the default filters to make testing easier
+ super(true)
+ }
- protected void configure(HttpSecurity http) {
- http
- .addFilterBefore(new CustomFilter(), UsernamePasswordAuthenticationFilter.class)
- .formLogin()
- }
- }
+ protected void configure(HttpSecurity http) {
+ http
+ .addFilterBefore(new CustomFilter(), UsernamePasswordAuthenticationFilter.class)
+ .formLogin()
+ }
+ }
- def "http/custom-filter@after"() {
- when:
- loadConfig(CustomFilterAfterConfig)
- then:
- filterChain().filters[1].class == CustomFilter
- }
+ def "http/custom-filter@after"() {
+ when:
+ loadConfig(CustomFilterAfterConfig)
+ then:
+ filterChain().filters[1].class == CustomFilter
+ }
- @Configuration
- static class CustomFilterAfterConfig extends BaseWebConfig {
- CustomFilterAfterConfig() {
- // do not add the default filters to make testing easier
- super(true)
- }
+ @Configuration
+ static class CustomFilterAfterConfig extends BaseWebConfig {
+ CustomFilterAfterConfig() {
+ // do not add the default filters to make testing easier
+ super(true)
+ }
- protected void configure(HttpSecurity http) {
- http
- .addFilterAfter(new CustomFilter(), UsernamePasswordAuthenticationFilter.class)
- .formLogin()
- }
- }
+ protected void configure(HttpSecurity http) {
+ http
+ .addFilterAfter(new CustomFilter(), UsernamePasswordAuthenticationFilter.class)
+ .formLogin()
+ }
+ }
- def "http/custom-filter@position"() {
- when:
- loadConfig(CustomFilterPositionConfig)
- then:
- filterChain().filters.collect { it.class } == [CustomFilter]
- }
+ def "http/custom-filter@position"() {
+ when:
+ loadConfig(CustomFilterPositionConfig)
+ then:
+ filterChain().filters.collect { it.class } == [CustomFilter]
+ }
- @Configuration
- static class CustomFilterPositionConfig extends BaseWebConfig {
- CustomFilterPositionConfig() {
- // do not add the default filters to make testing easier
- super(true)
- }
+ @Configuration
+ static class CustomFilterPositionConfig extends BaseWebConfig {
+ CustomFilterPositionConfig() {
+ // do not add the default filters to make testing easier
+ super(true)
+ }
- protected void configure(HttpSecurity http) {
- http
- // this works so long as the CustomFilter extends one of the standard filters
- // if not, use addFilterBefore or addFilterAfter
- .addFilter(new CustomFilter())
- }
+ protected void configure(HttpSecurity http) {
+ http
+ // this works so long as the CustomFilter extends one of the standard filters
+ // if not, use addFilterBefore or addFilterAfter
+ .addFilter(new CustomFilter())
+ }
- }
+ }
- def "http/custom-filter no AuthenticationManager in HttpSecurity"() {
- when:
- loadConfig(NoAuthenticationManagerInHtppConfigurationConfig)
- then:
- filterChain().filters[0].class == CustomFilter
- }
+ def "http/custom-filter no AuthenticationManager in HttpSecurity"() {
+ when:
+ loadConfig(NoAuthenticationManagerInHtppConfigurationConfig)
+ then:
+ filterChain().filters[0].class == CustomFilter
+ }
- @EnableWebSecurity
- static class NoAuthenticationManagerInHtppConfigurationConfig extends WebSecurityConfigurerAdapter {
- NoAuthenticationManagerInHtppConfigurationConfig() {
- super(true)
- }
+ @EnableWebSecurity
+ static class NoAuthenticationManagerInHtppConfigurationConfig extends WebSecurityConfigurerAdapter {
+ NoAuthenticationManagerInHtppConfigurationConfig() {
+ super(true)
+ }
- protected AuthenticationManager authenticationManager()
- throws Exception {
- return new CustomAuthenticationManager();
- }
+ protected AuthenticationManager authenticationManager()
+ throws Exception {
+ return new CustomAuthenticationManager();
+ }
- @Override
- protected void configure(HttpSecurity http) {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .addFilterBefore(new CustomFilter(), UsernamePasswordAuthenticationFilter.class)
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .addFilterBefore(new CustomFilter(), UsernamePasswordAuthenticationFilter.class)
+ }
+ }
- static class CustomFilter extends UsernamePasswordAuthenticationFilter {}
+ static class CustomFilter extends UsernamePasswordAuthenticationFilter {}
- static class CustomAuthenticationManager implements AuthenticationManager {
- public Authentication authenticate(Authentication authentication)
- throws AuthenticationException {
- return null;
- }
- }
+ static class CustomAuthenticationManager implements AuthenticationManager {
+ public Authentication authenticate(Authentication authentication)
+ throws AuthenticationException {
+ return null;
+ }
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpExpressionHandlerTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpExpressionHandlerTests.groovy
index b59784daf1..ac9984315f 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpExpressionHandlerTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpExpressionHandlerTests.groovy
@@ -30,27 +30,27 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe
*
*/
public class NamespaceHttpExpressionHandlerTests extends BaseSpringSpec {
- def "http/expression-handler@ref"() {
- when:
- def parser = new SpelExpressionParser()
- ExpressionHandlerConfig.EXPRESSION_HANDLER = Mock(SecurityExpressionHandler.class)
- ExpressionHandlerConfig.EXPRESSION_HANDLER.getExpressionParser() >> parser
- loadConfig(ExpressionHandlerConfig)
- then:
- noExceptionThrown()
- }
+ def "http/expression-handler@ref"() {
+ when:
+ def parser = new SpelExpressionParser()
+ ExpressionHandlerConfig.EXPRESSION_HANDLER = Mock(SecurityExpressionHandler.class)
+ ExpressionHandlerConfig.EXPRESSION_HANDLER.getExpressionParser() >> parser
+ loadConfig(ExpressionHandlerConfig)
+ then:
+ noExceptionThrown()
+ }
- @EnableWebSecurity
- static class ExpressionHandlerConfig extends BaseWebConfig {
- static EXPRESSION_HANDLER;
+ @EnableWebSecurity
+ static class ExpressionHandlerConfig extends BaseWebConfig {
+ static EXPRESSION_HANDLER;
- protected void configure(HttpSecurity http) {
- http
- .authorizeRequests()
- .expressionHandler(EXPRESSION_HANDLER)
- .antMatchers("/users**","/sessions/**").hasRole("ADMIN")
- .antMatchers("/signup").permitAll()
- .anyRequest().hasRole("USER")
- }
- }
+ protected void configure(HttpSecurity http) {
+ http
+ .authorizeRequests()
+ .expressionHandler(EXPRESSION_HANDLER)
+ .antMatchers("/users**","/sessions/**").hasRole("ADMIN")
+ .antMatchers("/signup").permitAll()
+ .anyRequest().hasRole("USER")
+ }
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpFirewallTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpFirewallTests.groovy
index 9d41c3efb6..253e0de96e 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpFirewallTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpFirewallTests.groovy
@@ -38,73 +38,73 @@ import org.springframework.security.web.firewall.RequestRejectedException
*
*/
public class NamespaceHttpFirewallTests extends BaseSpringSpec {
- FilterChainProxy springSecurityFilterChain
- MockHttpServletRequest request
- MockHttpServletResponse response
- MockFilterChain chain
+ FilterChainProxy springSecurityFilterChain
+ MockHttpServletRequest request
+ MockHttpServletResponse response
+ MockFilterChain chain
- def setup() {
- request = new MockHttpServletRequest()
- response = new MockHttpServletResponse()
- chain = new MockFilterChain()
- }
+ def setup() {
+ request = new MockHttpServletRequest()
+ response = new MockHttpServletResponse()
+ chain = new MockFilterChain()
+ }
- def "http-firewall"() {
- setup:
- loadConfig(HttpFirewallConfig)
- springSecurityFilterChain = context.getBean(FilterChainProxy)
- request.setPathInfo("/public/../private/")
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "the default firewall is used"
- thrown(RequestRejectedException)
- }
+ def "http-firewall"() {
+ setup:
+ loadConfig(HttpFirewallConfig)
+ springSecurityFilterChain = context.getBean(FilterChainProxy)
+ request.setPathInfo("/public/../private/")
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "the default firewall is used"
+ thrown(RequestRejectedException)
+ }
- @Configuration
- static class HttpFirewallConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) {
- }
- }
+ @Configuration
+ static class HttpFirewallConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) {
+ }
+ }
- def "http-firewall@ref"() {
- setup:
- loadConfig(CustomHttpFirewallConfig)
- springSecurityFilterChain = context.getBean(FilterChainProxy)
- request.setParameter("deny", "true")
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "the custom firewall is used"
- thrown(RequestRejectedException)
- }
+ def "http-firewall@ref"() {
+ setup:
+ loadConfig(CustomHttpFirewallConfig)
+ springSecurityFilterChain = context.getBean(FilterChainProxy)
+ request.setParameter("deny", "true")
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "the custom firewall is used"
+ thrown(RequestRejectedException)
+ }
- @Configuration
- static class CustomHttpFirewallConfig extends BaseWebConfig {
- @Override
- protected void configure(HttpSecurity http) { }
+ @Configuration
+ static class CustomHttpFirewallConfig extends BaseWebConfig {
+ @Override
+ protected void configure(HttpSecurity http) { }
- @Override
- public void configure(WebSecurity builder) throws Exception {
- builder
- .httpFirewall(new CustomHttpFirewall())
- }
- }
+ @Override
+ public void configure(WebSecurity builder) throws Exception {
+ builder
+ .httpFirewall(new CustomHttpFirewall())
+ }
+ }
- static class CustomHttpFirewall extends DefaultHttpFirewall {
+ static class CustomHttpFirewall extends DefaultHttpFirewall {
- @Override
- public FirewalledRequest getFirewalledRequest(HttpServletRequest request)
- throws RequestRejectedException {
- if(request.getParameter("deny")) {
- throw new RequestRejectedException("custom rejection")
- }
- return super.getFirewalledRequest(request)
- }
+ @Override
+ public FirewalledRequest getFirewalledRequest(HttpServletRequest request)
+ throws RequestRejectedException {
+ if(request.getParameter("deny")) {
+ throw new RequestRejectedException("custom rejection")
+ }
+ return super.getFirewalledRequest(request)
+ }
- @Override
- public HttpServletResponse getFirewalledResponse(
- HttpServletResponse response) {
- return super.getFirewalledRequest(response)
- }
+ @Override
+ public HttpServletResponse getFirewalledResponse(
+ HttpServletResponse response) {
+ return super.getFirewalledRequest(response)
+ }
- }
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpFormLoginTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpFormLoginTests.groovy
index 0ed79e111a..8b4fa6b645 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpFormLoginTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpFormLoginTests.groovy
@@ -38,133 +38,133 @@ import org.springframework.security.web.authentication.WebAuthenticationDetailsS
*
*/
public class NamespaceHttpFormLoginTests extends BaseSpringSpec {
- FilterChainProxy springSecurityFilterChain
+ FilterChainProxy springSecurityFilterChain
- def "http/form-login"() {
- setup:
- loadConfig(FormLoginConfig)
- springSecurityFilterChain = context.getBean(FilterChainProxy)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.getRedirectedUrl() == "http://localhost/login"
- when: "fail to log in"
- super.setup()
- request.servletPath = "/login"
- request.method = "POST"
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "sent to login error page"
- response.getRedirectedUrl() == "/login?error"
- when: "login success"
- super.setup()
- request.servletPath = "/login"
- request.method = "POST"
- request.parameters.username = ["user"] as String[]
- request.parameters.password = ["password"] as String[]
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "sent to default succes page"
- response.getRedirectedUrl() == "/"
- }
+ def "http/form-login"() {
+ setup:
+ loadConfig(FormLoginConfig)
+ springSecurityFilterChain = context.getBean(FilterChainProxy)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.getRedirectedUrl() == "http://localhost/login"
+ when: "fail to log in"
+ super.setup()
+ request.servletPath = "/login"
+ request.method = "POST"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "sent to login error page"
+ response.getRedirectedUrl() == "/login?error"
+ when: "login success"
+ super.setup()
+ request.servletPath = "/login"
+ request.method = "POST"
+ request.parameters.username = ["user"] as String[]
+ request.parameters.password = ["password"] as String[]
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "sent to default succes page"
+ response.getRedirectedUrl() == "/"
+ }
- @Configuration
- static class FormLoginConfig extends BaseWebConfig {
+ @Configuration
+ static class FormLoginConfig extends BaseWebConfig {
- @Override
- public void configure(WebSecurity web) throws Exception {
- web
- .ignoring()
- .antMatchers("/resources/**");
- }
+ @Override
+ public void configure(WebSecurity web) throws Exception {
+ web
+ .ignoring()
+ .antMatchers("/resources/**");
+ }
- @Override
- protected void configure(HttpSecurity http) {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .formLogin()
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .formLogin()
+ }
+ }
- def "http/form-login custom"() {
- setup:
- loadConfig(FormLoginCustomConfig)
- springSecurityFilterChain = context.getBean(FilterChainProxy)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.getRedirectedUrl() == "http://localhost/authentication/login"
- when: "fail to log in"
- super.setup()
- request.servletPath = "/authentication/login/process"
- request.method = "POST"
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "sent to login error page"
- response.getRedirectedUrl() == "/authentication/login?failed"
- when: "login success"
- super.setup()
- request.servletPath = "/authentication/login/process"
- request.method = "POST"
- request.parameters.username = ["user"] as String[]
- request.parameters.password = ["password"] as String[]
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "sent to default succes page"
- response.getRedirectedUrl() == "/default"
- }
+ def "http/form-login custom"() {
+ setup:
+ loadConfig(FormLoginCustomConfig)
+ springSecurityFilterChain = context.getBean(FilterChainProxy)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.getRedirectedUrl() == "http://localhost/authentication/login"
+ when: "fail to log in"
+ super.setup()
+ request.servletPath = "/authentication/login/process"
+ request.method = "POST"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "sent to login error page"
+ response.getRedirectedUrl() == "/authentication/login?failed"
+ when: "login success"
+ super.setup()
+ request.servletPath = "/authentication/login/process"
+ request.method = "POST"
+ request.parameters.username = ["user"] as String[]
+ request.parameters.password = ["password"] as String[]
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "sent to default succes page"
+ response.getRedirectedUrl() == "/default"
+ }
- @Configuration
- static class FormLoginCustomConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) throws Exception {
- boolean alwaysUseDefaultSuccess = true;
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .formLogin()
- .usernameParameter("username") // form-login@username-parameter
- .passwordParameter("password") // form-login@password-parameter
- .loginPage("/authentication/login") // form-login@login-page
- .failureUrl("/authentication/login?failed") // form-login@authentication-failure-url
- .loginProcessingUrl("/authentication/login/process") // form-login@login-processing-url
- .defaultSuccessUrl("/default", alwaysUseDefaultSuccess) // form-login@default-target-url / form-login@always-use-default-target
- }
- }
+ @Configuration
+ static class FormLoginCustomConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) throws Exception {
+ boolean alwaysUseDefaultSuccess = true;
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .formLogin()
+ .usernameParameter("username") // form-login@username-parameter
+ .passwordParameter("password") // form-login@password-parameter
+ .loginPage("/authentication/login") // form-login@login-page
+ .failureUrl("/authentication/login?failed") // form-login@authentication-failure-url
+ .loginProcessingUrl("/authentication/login/process") // form-login@login-processing-url
+ .defaultSuccessUrl("/default", alwaysUseDefaultSuccess) // form-login@default-target-url / form-login@always-use-default-target
+ }
+ }
- def "http/form-login custom refs"() {
- when:
- loadConfig(FormLoginCustomRefsConfig)
- springSecurityFilterChain = context.getBean(FilterChainProxy)
- then: "CustomWebAuthenticationDetailsSource is used"
- findFilter(UsernamePasswordAuthenticationFilter).authenticationDetailsSource.class == CustomWebAuthenticationDetailsSource
- when: "fail to log in"
- request.servletPath = "/login"
- request.method = "POST"
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "sent to login error page"
- response.getRedirectedUrl() == "/custom/failure"
- when: "login success"
- super.setup()
- request.servletPath = "/login"
- request.method = "POST"
- request.parameters.username = ["user"] as String[]
- request.parameters.password = ["password"] as String[]
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "sent to default succes page"
- response.getRedirectedUrl() == "/custom/targetUrl"
- }
+ def "http/form-login custom refs"() {
+ when:
+ loadConfig(FormLoginCustomRefsConfig)
+ springSecurityFilterChain = context.getBean(FilterChainProxy)
+ then: "CustomWebAuthenticationDetailsSource is used"
+ findFilter(UsernamePasswordAuthenticationFilter).authenticationDetailsSource.class == CustomWebAuthenticationDetailsSource
+ when: "fail to log in"
+ request.servletPath = "/login"
+ request.method = "POST"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "sent to login error page"
+ response.getRedirectedUrl() == "/custom/failure"
+ when: "login success"
+ super.setup()
+ request.servletPath = "/login"
+ request.method = "POST"
+ request.parameters.username = ["user"] as String[]
+ request.parameters.password = ["password"] as String[]
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "sent to default succes page"
+ response.getRedirectedUrl() == "/custom/targetUrl"
+ }
- @Configuration
- static class FormLoginCustomRefsConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .formLogin()
- .loginPage("/login")
- .failureHandler(new SimpleUrlAuthenticationFailureHandler("/custom/failure")) // form-login@authentication-failure-handler-ref
- .successHandler(new SavedRequestAwareAuthenticationSuccessHandler( defaultTargetUrl : "/custom/targetUrl" )) // form-login@authentication-success-handler-ref
- .authenticationDetailsSource(new CustomWebAuthenticationDetailsSource()) // form-login@authentication-details-source-ref
- .and();
- }
- }
+ @Configuration
+ static class FormLoginCustomRefsConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .formLogin()
+ .loginPage("/login")
+ .failureHandler(new SimpleUrlAuthenticationFailureHandler("/custom/failure")) // form-login@authentication-failure-handler-ref
+ .successHandler(new SavedRequestAwareAuthenticationSuccessHandler( defaultTargetUrl : "/custom/targetUrl" )) // form-login@authentication-success-handler-ref
+ .authenticationDetailsSource(new CustomWebAuthenticationDetailsSource()) // form-login@authentication-details-source-ref
+ .and();
+ }
+ }
- static class CustomWebAuthenticationDetailsSource extends WebAuthenticationDetailsSource {}
+ static class CustomWebAuthenticationDetailsSource extends WebAuthenticationDetailsSource {}
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpHeadersTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpHeadersTests.groovy
index fad855cb7a..31e016f795 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpHeadersTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpHeadersTests.groovy
@@ -38,230 +38,230 @@ import org.springframework.security.web.util.matcher.RequestMatcher;
*/
public class NamespaceHttpHeadersTests extends BaseSpringSpec {
- def "http/headers"() {
- setup:
- loadConfig(HeadersDefaultConfig)
- request.secure = true
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- responseHeaders == ['X-Content-Type-Options':'nosniff',
- 'X-Frame-Options':'DENY',
- 'Strict-Transport-Security': 'max-age=31536000 ; includeSubDomains',
- 'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
- 'Pragma':'no-cache',
- 'Expires' : '0',
- 'X-XSS-Protection' : '1; mode=block']
- }
+ def "http/headers"() {
+ setup:
+ loadConfig(HeadersDefaultConfig)
+ request.secure = true
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ responseHeaders == ['X-Content-Type-Options':'nosniff',
+ 'X-Frame-Options':'DENY',
+ 'Strict-Transport-Security': 'max-age=31536000 ; includeSubDomains',
+ 'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
+ 'Pragma':'no-cache',
+ 'Expires' : '0',
+ 'X-XSS-Protection' : '1; mode=block']
+ }
- @Configuration
- static class HeadersDefaultConfig extends BaseWebConfig {
- @Override
- protected void configure(HttpSecurity http) {
- http
- .headers()
- }
- }
+ @Configuration
+ static class HeadersDefaultConfig extends BaseWebConfig {
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .headers()
+ }
+ }
- def "http/headers/cache-control"() {
- setup:
- loadConfig(HeadersCacheControlConfig)
- request.secure = true
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- responseHeaders == ['Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
- 'Expires' : '0',
- 'Pragma':'no-cache']
- }
+ def "http/headers/cache-control"() {
+ setup:
+ loadConfig(HeadersCacheControlConfig)
+ request.secure = true
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ responseHeaders == ['Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
+ 'Expires' : '0',
+ 'Pragma':'no-cache']
+ }
- @Configuration
- static class HeadersCacheControlConfig extends BaseWebConfig {
- @Override
- protected void configure(HttpSecurity http) {
- http
- .headers()
- .defaultsDisabled()
- .cacheControl()
- }
- }
+ @Configuration
+ static class HeadersCacheControlConfig extends BaseWebConfig {
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .headers()
+ .defaultsDisabled()
+ .cacheControl()
+ }
+ }
- def "http/headers/hsts"() {
- setup:
- loadConfig(HstsConfig)
- request.secure = true
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- responseHeaders == ['Strict-Transport-Security': 'max-age=31536000 ; includeSubDomains']
- }
+ def "http/headers/hsts"() {
+ setup:
+ loadConfig(HstsConfig)
+ request.secure = true
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ responseHeaders == ['Strict-Transport-Security': 'max-age=31536000 ; includeSubDomains']
+ }
- @Configuration
- static class HstsConfig extends BaseWebConfig {
- @Override
- protected void configure(HttpSecurity http) {
- http
- .headers()
- .defaultsDisabled()
- .httpStrictTransportSecurity()
- }
- }
+ @Configuration
+ static class HstsConfig extends BaseWebConfig {
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .headers()
+ .defaultsDisabled()
+ .httpStrictTransportSecurity()
+ }
+ }
- def "http/headers/hsts custom"() {
- setup:
- loadConfig(HstsCustomConfig)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- responseHeaders == ['Strict-Transport-Security': 'max-age=15768000']
- }
+ def "http/headers/hsts custom"() {
+ setup:
+ loadConfig(HstsCustomConfig)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ responseHeaders == ['Strict-Transport-Security': 'max-age=15768000']
+ }
- @Configuration
- static class HstsCustomConfig extends BaseWebConfig {
- @Override
- protected void configure(HttpSecurity http) {
- http
- .headers()
- // hsts@request-matcher-ref, hsts@max-age-seconds, hsts@include-subdomains
- .defaultsDisabled()
- .httpStrictTransportSecurity()
- .requestMatcher(AnyRequestMatcher.INSTANCE)
- .maxAgeInSeconds(15768000)
- .includeSubDomains(false)
- }
- }
+ @Configuration
+ static class HstsCustomConfig extends BaseWebConfig {
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .headers()
+ // hsts@request-matcher-ref, hsts@max-age-seconds, hsts@include-subdomains
+ .defaultsDisabled()
+ .httpStrictTransportSecurity()
+ .requestMatcher(AnyRequestMatcher.INSTANCE)
+ .maxAgeInSeconds(15768000)
+ .includeSubDomains(false)
+ }
+ }
- def "http/headers/frame-options@policy=SAMEORIGIN"() {
- setup:
- loadConfig(FrameOptionsSameOriginConfig)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- responseHeaders == ['X-Frame-Options': 'SAMEORIGIN']
- }
+ def "http/headers/frame-options@policy=SAMEORIGIN"() {
+ setup:
+ loadConfig(FrameOptionsSameOriginConfig)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ responseHeaders == ['X-Frame-Options': 'SAMEORIGIN']
+ }
- @Configuration
- static class FrameOptionsSameOriginConfig extends BaseWebConfig {
- @Override
- protected void configure(HttpSecurity http) {
- http
- .headers()
- // frame-options@policy=SAMEORIGIN
- .defaultsDisabled()
- .frameOptions()
- .sameOrigin()
- }
- }
+ @Configuration
+ static class FrameOptionsSameOriginConfig extends BaseWebConfig {
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .headers()
+ // frame-options@policy=SAMEORIGIN
+ .defaultsDisabled()
+ .frameOptions()
+ .sameOrigin()
+ }
+ }
- // frame-options@strategy, frame-options@value, frame-options@parameter are not provided instead use frame-options@ref
+ // frame-options@strategy, frame-options@value, frame-options@parameter are not provided instead use frame-options@ref
- def "http/headers/frame-options"() {
- setup:
- loadConfig(FrameOptionsAllowFromConfig)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- responseHeaders == ['X-Frame-Options': 'ALLOW-FROM https://example.com']
- }
+ def "http/headers/frame-options"() {
+ setup:
+ loadConfig(FrameOptionsAllowFromConfig)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ responseHeaders == ['X-Frame-Options': 'ALLOW-FROM https://example.com']
+ }
- @Configuration
- static class FrameOptionsAllowFromConfig extends BaseWebConfig {
- @Override
- protected void configure(HttpSecurity http) {
- http
- .headers()
- // frame-options@ref
- .defaultsDisabled()
- .addHeaderWriter(new XFrameOptionsHeaderWriter(new StaticAllowFromStrategy(new URI("https://example.com"))))
- }
- }
+ @Configuration
+ static class FrameOptionsAllowFromConfig extends BaseWebConfig {
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .headers()
+ // frame-options@ref
+ .defaultsDisabled()
+ .addHeaderWriter(new XFrameOptionsHeaderWriter(new StaticAllowFromStrategy(new URI("https://example.com"))))
+ }
+ }
- def "http/headers/xss-protection"() {
- setup:
- loadConfig(XssProtectionConfig)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- responseHeaders == ['X-XSS-Protection': '1; mode=block']
- }
+ def "http/headers/xss-protection"() {
+ setup:
+ loadConfig(XssProtectionConfig)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ responseHeaders == ['X-XSS-Protection': '1; mode=block']
+ }
- @Configuration
- static class XssProtectionConfig extends BaseWebConfig {
- @Override
- protected void configure(HttpSecurity http) {
- http
- .headers()
- // xss-protection
- .defaultsDisabled()
- .xssProtection()
- }
- }
+ @Configuration
+ static class XssProtectionConfig extends BaseWebConfig {
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .headers()
+ // xss-protection
+ .defaultsDisabled()
+ .xssProtection()
+ }
+ }
- def "http/headers/xss-protection custom"() {
- setup:
- loadConfig(XssProtectionCustomConfig)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- responseHeaders == ['X-XSS-Protection': '1']
- }
+ def "http/headers/xss-protection custom"() {
+ setup:
+ loadConfig(XssProtectionCustomConfig)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ responseHeaders == ['X-XSS-Protection': '1']
+ }
- @Configuration
- static class XssProtectionCustomConfig extends BaseWebConfig {
- @Override
- protected void configure(HttpSecurity http) {
- http
- .headers()
- // xss-protection@enabled and xss-protection@block
- .defaultsDisabled()
- .xssProtection()
- .xssProtectionEnabled(true)
- .block(false)
- }
- }
+ @Configuration
+ static class XssProtectionCustomConfig extends BaseWebConfig {
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .headers()
+ // xss-protection@enabled and xss-protection@block
+ .defaultsDisabled()
+ .xssProtection()
+ .xssProtectionEnabled(true)
+ .block(false)
+ }
+ }
- def "http/headers/content-type-options"() {
- setup:
- loadConfig(ContentTypeOptionsConfig)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- responseHeaders == ['X-Content-Type-Options': 'nosniff']
- }
+ def "http/headers/content-type-options"() {
+ setup:
+ loadConfig(ContentTypeOptionsConfig)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ responseHeaders == ['X-Content-Type-Options': 'nosniff']
+ }
- @Configuration
- static class ContentTypeOptionsConfig extends BaseWebConfig {
- @Override
- protected void configure(HttpSecurity http) {
- http
- .headers()
- // content-type-options
- .defaultsDisabled()
- .contentTypeOptions()
- }
- }
+ @Configuration
+ static class ContentTypeOptionsConfig extends BaseWebConfig {
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .headers()
+ // content-type-options
+ .defaultsDisabled()
+ .contentTypeOptions()
+ }
+ }
- // header@name / header@value are not provided instead use header@ref
+ // header@name / header@value are not provided instead use header@ref
- def "http/headers/header@ref"() {
- setup:
- loadConfig(HeaderRefConfig)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- responseHeaders == ['customHeaderName': 'customHeaderValue']
- }
+ def "http/headers/header@ref"() {
+ setup:
+ loadConfig(HeaderRefConfig)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ responseHeaders == ['customHeaderName': 'customHeaderValue']
+ }
- @Configuration
- static class HeaderRefConfig extends BaseWebConfig {
- @Override
- protected void configure(HttpSecurity http) {
- http
- .headers()
- .defaultsDisabled()
- .addHeaderWriter(new StaticHeadersWriter("customHeaderName", "customHeaderValue"))
- }
- }
+ @Configuration
+ static class HeaderRefConfig extends BaseWebConfig {
+ @Override
+ protected void configure(HttpSecurity http) {
+ http
+ .headers()
+ .defaultsDisabled()
+ .addHeaderWriter(new StaticHeadersWriter("customHeaderName", "customHeaderValue"))
+ }
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpInterceptUrlTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpInterceptUrlTests.groovy
index 53361f6789..eee8b02292 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpInterceptUrlTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpInterceptUrlTests.groovy
@@ -42,128 +42,128 @@ import org.springframework.security.web.context.HttpSessionSecurityContextReposi
*/
public class NamespaceHttpInterceptUrlTests extends BaseSpringSpec {
- def "http/intercept-url denied when not logged in"() {
- setup:
- loadConfig(HttpInterceptUrlConfig)
- request.servletPath == "/users"
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_FORBIDDEN
- }
+ def "http/intercept-url denied when not logged in"() {
+ setup:
+ loadConfig(HttpInterceptUrlConfig)
+ request.servletPath == "/users"
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_FORBIDDEN
+ }
- def "http/intercept-url denied when logged in"() {
- setup:
- loadConfig(HttpInterceptUrlConfig)
- login()
- request.setServletPath("/users")
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_FORBIDDEN
- }
+ def "http/intercept-url denied when logged in"() {
+ setup:
+ loadConfig(HttpInterceptUrlConfig)
+ login()
+ request.setServletPath("/users")
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_FORBIDDEN
+ }
- def "http/intercept-url allowed when logged in"() {
- setup:
- loadConfig(HttpInterceptUrlConfig)
- login("admin","ROLE_ADMIN")
- request.setServletPath("/users")
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_OK
- !response.isCommitted()
- }
+ def "http/intercept-url allowed when logged in"() {
+ setup:
+ loadConfig(HttpInterceptUrlConfig)
+ login("admin","ROLE_ADMIN")
+ request.setServletPath("/users")
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_OK
+ !response.isCommitted()
+ }
- def "http/intercept-url@method=POST"() {
- setup:
- loadConfig(HttpInterceptUrlConfig)
- when:
- login()
- request.setServletPath("/admin/post")
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_OK
- !response.isCommitted()
- when:
- super.setup()
- login()
- request.setServletPath("/admin/post")
- request.setMethod("POST")
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_FORBIDDEN
- when:
- super.setup()
- login("admin","ROLE_ADMIN")
- request.setServletPath("/admin/post")
- request.setMethod("POST")
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_OK
- !response.committed
- }
+ def "http/intercept-url@method=POST"() {
+ setup:
+ loadConfig(HttpInterceptUrlConfig)
+ when:
+ login()
+ request.setServletPath("/admin/post")
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_OK
+ !response.isCommitted()
+ when:
+ super.setup()
+ login()
+ request.setServletPath("/admin/post")
+ request.setMethod("POST")
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_FORBIDDEN
+ when:
+ super.setup()
+ login("admin","ROLE_ADMIN")
+ request.setServletPath("/admin/post")
+ request.setMethod("POST")
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_OK
+ !response.committed
+ }
- def "http/intercept-url@requires-channel"() {
- setup:
- loadConfig(HttpInterceptUrlConfig)
- when:
- request.setServletPath("/login")
- request.setRequestURI("/login")
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.redirectedUrl == "https://localhost/login"
- when:
- super.setup()
- request.setServletPath("/secured/a")
- request.setRequestURI("/secured/a")
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.redirectedUrl == "https://localhost/secured/a"
- when:
- super.setup()
- request.setSecure(true)
- request.setScheme("https")
- request.setServletPath("/user")
- request.setRequestURI("/user")
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.redirectedUrl == "http://localhost/user"
- }
+ def "http/intercept-url@requires-channel"() {
+ setup:
+ loadConfig(HttpInterceptUrlConfig)
+ when:
+ request.setServletPath("/login")
+ request.setRequestURI("/login")
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.redirectedUrl == "https://localhost/login"
+ when:
+ super.setup()
+ request.setServletPath("/secured/a")
+ request.setRequestURI("/secured/a")
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.redirectedUrl == "https://localhost/secured/a"
+ when:
+ super.setup()
+ request.setSecure(true)
+ request.setScheme("https")
+ request.setServletPath("/user")
+ request.setRequestURI("/user")
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.redirectedUrl == "http://localhost/user"
+ }
- @EnableWebSecurity
- static class HttpInterceptUrlConfig extends WebSecurityConfigurerAdapter {
+ @EnableWebSecurity
+ static class HttpInterceptUrlConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- // the line below is similar to intercept-url@pattern:
- //
- //
- .antMatchers("/users**","/sessions/**").hasRole("ADMIN")
- // the line below is similar to intercept-url@method:
- //
- //
- .antMatchers(HttpMethod.POST, "/admin/post","/admin/another-post/**").hasRole("ADMIN")
- .antMatchers("/signup").permitAll()
- .anyRequest().hasRole("USER")
- .and()
- .requiresChannel()
- // NOTE: channel security is configured separately of authorization (i.e. intercept-url@access
- // the line below is similar to intercept-url@requires-channel="https":
- //
- //
- .antMatchers("/login","/secured/**").requiresSecure()
- // the line below is similar to intercept-url@requires-channel="http":
- //
- .anyRequest().requiresInsecure()
- }
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth
- .inMemoryAuthentication()
- .withUser("user").password("password").roles("USER").and()
- .withUser("admin").password("password").roles("USER", "ADMIN")
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .authorizeRequests()
+ // the line below is similar to intercept-url@pattern:
+ //
+ //
+ .antMatchers("/users**","/sessions/**").hasRole("ADMIN")
+ // the line below is similar to intercept-url@method:
+ //
+ //
+ .antMatchers(HttpMethod.POST, "/admin/post","/admin/another-post/**").hasRole("ADMIN")
+ .antMatchers("/signup").permitAll()
+ .anyRequest().hasRole("USER")
+ .and()
+ .requiresChannel()
+ // NOTE: channel security is configured separately of authorization (i.e. intercept-url@access
+ // the line below is similar to intercept-url@requires-channel="https":
+ //
+ //
+ .antMatchers("/login","/secured/**").requiresSecure()
+ // the line below is similar to intercept-url@requires-channel="http":
+ //
+ .anyRequest().requiresInsecure()
+ }
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth
+ .inMemoryAuthentication()
+ .withUser("user").password("password").roles("USER").and()
+ .withUser("admin").password("password").roles("USER", "ADMIN")
+ }
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpJeeTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpJeeTests.groovy
index dd7072f807..2a8e5ef279 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpJeeTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpJeeTests.groovy
@@ -80,64 +80,64 @@ import org.springframework.test.util.ReflectionTestUtils;
*/
public class NamespaceHttpJeeTests extends BaseSpringSpec {
- def "http/jee@mappable-roles"() {
- when:
- loadConfig(JeeMappableRolesConfig)
- J2eePreAuthenticatedProcessingFilter filter = findFilter(J2eePreAuthenticatedProcessingFilter)
- AuthenticationManager authenticationManager = ReflectionTestUtils.getField(filter,"authenticationManager")
- then:
- authenticationManager
- filter.authenticationDetailsSource.class == J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource
- filter.authenticationDetailsSource.j2eeMappableRoles == ["ROLE_USER", "ROLE_ADMIN"] as Set
- authenticationManager.providers.find { it instanceof PreAuthenticatedAuthenticationProvider }.preAuthenticatedUserDetailsService.class == PreAuthenticatedGrantedAuthoritiesUserDetailsService
- }
+ def "http/jee@mappable-roles"() {
+ when:
+ loadConfig(JeeMappableRolesConfig)
+ J2eePreAuthenticatedProcessingFilter filter = findFilter(J2eePreAuthenticatedProcessingFilter)
+ AuthenticationManager authenticationManager = ReflectionTestUtils.getField(filter,"authenticationManager")
+ then:
+ authenticationManager
+ filter.authenticationDetailsSource.class == J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource
+ filter.authenticationDetailsSource.j2eeMappableRoles == ["ROLE_USER", "ROLE_ADMIN"] as Set
+ authenticationManager.providers.find { it instanceof PreAuthenticatedAuthenticationProvider }.preAuthenticatedUserDetailsService.class == PreAuthenticatedGrantedAuthoritiesUserDetailsService
+ }
- @EnableWebSecurity
- public static class JeeMappableRolesConfig extends WebSecurityConfigurerAdapter {
+ @EnableWebSecurity
+ public static class JeeMappableRolesConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .jee()
- .mappableRoles("USER","ADMIN");
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .jee()
+ .mappableRoles("USER","ADMIN");
+ }
+ }
- def "http/jee@user-service-ref"() {
- when:
- loadConfig(JeeUserServiceRefConfig)
- J2eePreAuthenticatedProcessingFilter filter = findFilter(J2eePreAuthenticatedProcessingFilter)
- AuthenticationManager authenticationManager = ReflectionTestUtils.getField(filter,"authenticationManager")
- then:
- authenticationManager
- filter.authenticationDetailsSource.class == J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource
- filter.authenticationDetailsSource.j2eeMappableRoles == ["ROLE_USER", "ROLE_ADMIN"] as Set
- authenticationManager.providers.find { it instanceof PreAuthenticatedAuthenticationProvider }.preAuthenticatedUserDetailsService.class == CustomUserService
- }
+ def "http/jee@user-service-ref"() {
+ when:
+ loadConfig(JeeUserServiceRefConfig)
+ J2eePreAuthenticatedProcessingFilter filter = findFilter(J2eePreAuthenticatedProcessingFilter)
+ AuthenticationManager authenticationManager = ReflectionTestUtils.getField(filter,"authenticationManager")
+ then:
+ authenticationManager
+ filter.authenticationDetailsSource.class == J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource
+ filter.authenticationDetailsSource.j2eeMappableRoles == ["ROLE_USER", "ROLE_ADMIN"] as Set
+ authenticationManager.providers.find { it instanceof PreAuthenticatedAuthenticationProvider }.preAuthenticatedUserDetailsService.class == CustomUserService
+ }
- @EnableWebSecurity
- public static class JeeUserServiceRefConfig extends WebSecurityConfigurerAdapter {
+ @EnableWebSecurity
+ public static class JeeUserServiceRefConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .jee()
- .mappableAuthorities("ROLE_USER","ROLE_ADMIN")
- .authenticatedUserDetailsService(new CustomUserService());
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .jee()
+ .mappableAuthorities("ROLE_USER","ROLE_ADMIN")
+ .authenticatedUserDetailsService(new CustomUserService());
+ }
+ }
- static class CustomUserService implements AuthenticationUserDetailsService {
- public UserDetails loadUserDetails(
- PreAuthenticatedAuthenticationToken token)
- throws UsernameNotFoundException {
- return null;
- }
- }
+ static class CustomUserService implements AuthenticationUserDetailsService {
+ public UserDetails loadUserDetails(
+ PreAuthenticatedAuthenticationToken token)
+ throws UsernameNotFoundException {
+ return null;
+ }
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpLogoutTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpLogoutTests.groovy
index 2fcdf94d1e..8e3edfb265 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpLogoutTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpLogoutTests.groovy
@@ -72,90 +72,90 @@ import org.springframework.security.web.util.matcher.RequestMatcher
*/
public class NamespaceHttpLogoutTests extends BaseSpringSpec {
- def "http/logout"() {
- setup:
- loadConfig(HttpLogoutConfig)
- login()
- request.servletPath = "/logout"
- request.method = "POST"
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- !authenticated()
- !request.getSession(false)
- response.redirectedUrl == "/login?logout"
- !response.getCookies()
- }
+ def "http/logout"() {
+ setup:
+ loadConfig(HttpLogoutConfig)
+ login()
+ request.servletPath = "/logout"
+ request.method = "POST"
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ !authenticated()
+ !request.getSession(false)
+ response.redirectedUrl == "/login?logout"
+ !response.getCookies()
+ }
- @Configuration
- static class HttpLogoutConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) throws Exception {
- }
- }
+ @Configuration
+ static class HttpLogoutConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) throws Exception {
+ }
+ }
- def "http/logout custom"() {
- setup:
- loadConfig(CustomHttpLogoutConfig)
- login()
- request.servletPath = "/custom-logout"
- request.method = "POST"
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- !authenticated()
- request.getSession(false)
- response.redirectedUrl == "/logout-success"
- response.getCookies().length == 1
- response.getCookies()[0].name == "remove"
- response.getCookies()[0].maxAge == 0
- }
+ def "http/logout custom"() {
+ setup:
+ loadConfig(CustomHttpLogoutConfig)
+ login()
+ request.servletPath = "/custom-logout"
+ request.method = "POST"
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ !authenticated()
+ request.getSession(false)
+ response.redirectedUrl == "/logout-success"
+ response.getCookies().length == 1
+ response.getCookies()[0].name == "remove"
+ response.getCookies()[0].maxAge == 0
+ }
- @Configuration
- static class CustomHttpLogoutConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .logout()
- .deleteCookies("remove") // logout@delete-cookies
- .invalidateHttpSession(false) // logout@invalidate-session=false (default is true)
- .logoutUrl("/custom-logout") // logout@logout-url (default is /logout)
- .logoutSuccessUrl("/logout-success") // logout@success-url (default is /login?logout)
- }
- }
+ @Configuration
+ static class CustomHttpLogoutConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .logout()
+ .deleteCookies("remove") // logout@delete-cookies
+ .invalidateHttpSession(false) // logout@invalidate-session=false (default is true)
+ .logoutUrl("/custom-logout") // logout@logout-url (default is /logout)
+ .logoutSuccessUrl("/logout-success") // logout@success-url (default is /login?logout)
+ }
+ }
- def "http/logout@success-handler-ref"() {
- setup:
- loadConfig(SuccessHandlerRefHttpLogoutConfig)
- login()
- request.servletPath = "/logout"
- request.method = "POST"
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- !authenticated()
- !request.getSession(false)
- response.redirectedUrl == "/SuccessHandlerRefHttpLogoutConfig"
- !response.getCookies()
- }
+ def "http/logout@success-handler-ref"() {
+ setup:
+ loadConfig(SuccessHandlerRefHttpLogoutConfig)
+ login()
+ request.servletPath = "/logout"
+ request.method = "POST"
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ !authenticated()
+ !request.getSession(false)
+ response.redirectedUrl == "/SuccessHandlerRefHttpLogoutConfig"
+ !response.getCookies()
+ }
- @Configuration
- static class SuccessHandlerRefHttpLogoutConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) throws Exception {
- SimpleUrlLogoutSuccessHandler logoutSuccessHandler = new SimpleUrlLogoutSuccessHandler(defaultTargetUrl:"/SuccessHandlerRefHttpLogoutConfig")
- http
- .logout()
- .logoutSuccessHandler(logoutSuccessHandler)
- }
- }
+ @Configuration
+ static class SuccessHandlerRefHttpLogoutConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) throws Exception {
+ SimpleUrlLogoutSuccessHandler logoutSuccessHandler = new SimpleUrlLogoutSuccessHandler(defaultTargetUrl:"/SuccessHandlerRefHttpLogoutConfig")
+ http
+ .logout()
+ .logoutSuccessHandler(logoutSuccessHandler)
+ }
+ }
- def login(String username="user", String role="ROLE_USER") {
- HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository()
- HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response)
- repo.loadContext(requestResponseHolder)
- repo.saveContext(new SecurityContextImpl(authentication: new UsernamePasswordAuthenticationToken(username, null, AuthorityUtils.createAuthorityList(role))), requestResponseHolder.request, requestResponseHolder.response)
- }
+ def login(String username="user", String role="ROLE_USER") {
+ HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository()
+ HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response)
+ repo.loadContext(requestResponseHolder)
+ repo.saveContext(new SecurityContextImpl(authentication: new UsernamePasswordAuthenticationToken(username, null, AuthorityUtils.createAuthorityList(role))), requestResponseHolder.request, requestResponseHolder.response)
+ }
- def authenticated() {
- HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response)
- new HttpSessionSecurityContextRepository().loadContext(requestResponseHolder)?.authentication?.authenticated
- }
+ def authenticated() {
+ HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response)
+ new HttpSessionSecurityContextRepository().loadContext(requestResponseHolder)?.authentication?.authenticated
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpOpenIDLoginTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpOpenIDLoginTests.groovy
index 86e22b0bf6..d3e96abd8a 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpOpenIDLoginTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpOpenIDLoginTests.groovy
@@ -44,185 +44,185 @@ import org.springframework.security.web.authentication.WebAuthenticationDetailsS
*
*/
public class NamespaceHttpOpenIDLoginTests extends BaseSpringSpec {
- def "http/openid-login"() {
- when:
- loadConfig(OpenIDLoginConfig)
- then:
- findFilter(OpenIDAuthenticationFilter).consumer.class == OpenID4JavaConsumer
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.getRedirectedUrl() == "http://localhost/login"
- when: "fail to log in"
- super.setup()
- request.servletPath = "/login/openid"
- request.method = "POST"
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "sent to login error page"
- response.getRedirectedUrl() == "/login?error"
- }
+ def "http/openid-login"() {
+ when:
+ loadConfig(OpenIDLoginConfig)
+ then:
+ findFilter(OpenIDAuthenticationFilter).consumer.class == OpenID4JavaConsumer
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.getRedirectedUrl() == "http://localhost/login"
+ when: "fail to log in"
+ super.setup()
+ request.servletPath = "/login/openid"
+ request.method = "POST"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "sent to login error page"
+ response.getRedirectedUrl() == "/login?error"
+ }
- @Configuration
- static class OpenIDLoginConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .openidLogin()
- .permitAll();
- }
- }
+ @Configuration
+ static class OpenIDLoginConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .openidLogin()
+ .permitAll();
+ }
+ }
- def "http/openid-login/attribute-exchange"() {
- when:
- loadConfig(OpenIDLoginAttributeExchangeConfig)
- OpenID4JavaConsumer consumer = findFilter(OpenIDAuthenticationFilter).consumer
- then:
- consumer.class == OpenID4JavaConsumer
+ def "http/openid-login/attribute-exchange"() {
+ when:
+ loadConfig(OpenIDLoginAttributeExchangeConfig)
+ OpenID4JavaConsumer consumer = findFilter(OpenIDAuthenticationFilter).consumer
+ then:
+ consumer.class == OpenID4JavaConsumer
- def googleAttrs = consumer.attributesToFetchFactory.createAttributeList("https://www.google.com/1")
- googleAttrs[0].name == "email"
- googleAttrs[0].type == "http://axschema.org/contact/email"
- googleAttrs[0].required
- googleAttrs[1].name == "firstname"
- googleAttrs[1].type == "http://axschema.org/namePerson/first"
- googleAttrs[1].required
- googleAttrs[2].name == "lastname"
- googleAttrs[2].type == "http://axschema.org/namePerson/last"
- googleAttrs[2].required
+ def googleAttrs = consumer.attributesToFetchFactory.createAttributeList("https://www.google.com/1")
+ googleAttrs[0].name == "email"
+ googleAttrs[0].type == "http://axschema.org/contact/email"
+ googleAttrs[0].required
+ googleAttrs[1].name == "firstname"
+ googleAttrs[1].type == "http://axschema.org/namePerson/first"
+ googleAttrs[1].required
+ googleAttrs[2].name == "lastname"
+ googleAttrs[2].type == "http://axschema.org/namePerson/last"
+ googleAttrs[2].required
- def yahooAttrs = consumer.attributesToFetchFactory.createAttributeList("https://rwinch.yahoo.com/rwinch/id")
- yahooAttrs[0].name == "email"
- yahooAttrs[0].type == "http://schema.openid.net/contact/email"
- yahooAttrs[0].required
- yahooAttrs[1].name == "fullname"
- yahooAttrs[1].type == "http://axschema.org/namePerson"
- yahooAttrs[1].required
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.getRedirectedUrl() == "http://localhost/login"
- when: "fail to log in"
- super.setup()
- request.servletPath = "/login/openid"
- request.method = "POST"
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "sent to login error page"
- response.getRedirectedUrl() == "/login?error"
- }
+ def yahooAttrs = consumer.attributesToFetchFactory.createAttributeList("https://rwinch.yahoo.com/rwinch/id")
+ yahooAttrs[0].name == "email"
+ yahooAttrs[0].type == "http://schema.openid.net/contact/email"
+ yahooAttrs[0].required
+ yahooAttrs[1].name == "fullname"
+ yahooAttrs[1].type == "http://axschema.org/namePerson"
+ yahooAttrs[1].required
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.getRedirectedUrl() == "http://localhost/login"
+ when: "fail to log in"
+ super.setup()
+ request.servletPath = "/login/openid"
+ request.method = "POST"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "sent to login error page"
+ response.getRedirectedUrl() == "/login?error"
+ }
- @Configuration
- static class OpenIDLoginAttributeExchangeConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .openidLogin()
- .attributeExchange("https://www.google.com/.*") // attribute-exchange@identifier-match
- .attribute("email") // openid-attribute@name
- .type("http://axschema.org/contact/email") // openid-attribute@type
- .required(true) // openid-attribute@required
- .count(1) // openid-attribute@count
- .and()
- .attribute("firstname")
- .type("http://axschema.org/namePerson/first")
- .required(true)
- .and()
- .attribute("lastname")
- .type("http://axschema.org/namePerson/last")
- .required(true)
- .and()
- .and()
- .attributeExchange(".*yahoo.com.*")
- .attribute("email")
- .type("http://schema.openid.net/contact/email")
- .required(true)
- .and()
- .attribute("fullname")
- .type("http://axschema.org/namePerson")
- .required(true)
- .and()
- .and()
- .permitAll();
- }
- }
+ @Configuration
+ static class OpenIDLoginAttributeExchangeConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .openidLogin()
+ .attributeExchange("https://www.google.com/.*") // attribute-exchange@identifier-match
+ .attribute("email") // openid-attribute@name
+ .type("http://axschema.org/contact/email") // openid-attribute@type
+ .required(true) // openid-attribute@required
+ .count(1) // openid-attribute@count
+ .and()
+ .attribute("firstname")
+ .type("http://axschema.org/namePerson/first")
+ .required(true)
+ .and()
+ .attribute("lastname")
+ .type("http://axschema.org/namePerson/last")
+ .required(true)
+ .and()
+ .and()
+ .attributeExchange(".*yahoo.com.*")
+ .attribute("email")
+ .type("http://schema.openid.net/contact/email")
+ .required(true)
+ .and()
+ .attribute("fullname")
+ .type("http://axschema.org/namePerson")
+ .required(true)
+ .and()
+ .and()
+ .permitAll();
+ }
+ }
- def "http/openid-login custom"() {
- setup:
- loadConfig(OpenIDLoginCustomConfig)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.getRedirectedUrl() == "http://localhost/authentication/login"
- when: "fail to log in"
- super.setup()
- request.servletPath = "/authentication/login/process"
- request.method = "POST"
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "sent to login error page"
- response.getRedirectedUrl() == "/authentication/login?failed"
- }
+ def "http/openid-login custom"() {
+ setup:
+ loadConfig(OpenIDLoginCustomConfig)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.getRedirectedUrl() == "http://localhost/authentication/login"
+ when: "fail to log in"
+ super.setup()
+ request.servletPath = "/authentication/login/process"
+ request.method = "POST"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "sent to login error page"
+ response.getRedirectedUrl() == "/authentication/login?failed"
+ }
- @Configuration
- static class OpenIDLoginCustomConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) throws Exception {
- boolean alwaysUseDefaultSuccess = true;
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .openidLogin()
- .permitAll()
- .loginPage("/authentication/login") // openid-login@login-page
- .failureUrl("/authentication/login?failed") // openid-login@authentication-failure-url
- .loginProcessingUrl("/authentication/login/process") // openid-login@login-processing-url
- .defaultSuccessUrl("/default", alwaysUseDefaultSuccess) // openid-login@default-target-url / openid-login@always-use-default-target
- }
- }
+ @Configuration
+ static class OpenIDLoginCustomConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) throws Exception {
+ boolean alwaysUseDefaultSuccess = true;
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .openidLogin()
+ .permitAll()
+ .loginPage("/authentication/login") // openid-login@login-page
+ .failureUrl("/authentication/login?failed") // openid-login@authentication-failure-url
+ .loginProcessingUrl("/authentication/login/process") // openid-login@login-processing-url
+ .defaultSuccessUrl("/default", alwaysUseDefaultSuccess) // openid-login@default-target-url / openid-login@always-use-default-target
+ }
+ }
- def "http/openid-login custom refs"() {
- when:
- OpenIDLoginCustomRefsConfig.AUDS = Mock(AuthenticationUserDetailsService)
- loadConfig(OpenIDLoginCustomRefsConfig)
- then: "CustomWebAuthenticationDetailsSource is used"
- findFilter(OpenIDAuthenticationFilter).authenticationDetailsSource.class == CustomWebAuthenticationDetailsSource
- findAuthenticationProvider(OpenIDAuthenticationProvider).userDetailsService == OpenIDLoginCustomRefsConfig.AUDS
- when: "fail to log in"
- request.servletPath = "/login/openid"
- request.method = "POST"
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "sent to login error page"
- response.getRedirectedUrl() == "/custom/failure"
- }
+ def "http/openid-login custom refs"() {
+ when:
+ OpenIDLoginCustomRefsConfig.AUDS = Mock(AuthenticationUserDetailsService)
+ loadConfig(OpenIDLoginCustomRefsConfig)
+ then: "CustomWebAuthenticationDetailsSource is used"
+ findFilter(OpenIDAuthenticationFilter).authenticationDetailsSource.class == CustomWebAuthenticationDetailsSource
+ findAuthenticationProvider(OpenIDAuthenticationProvider).userDetailsService == OpenIDLoginCustomRefsConfig.AUDS
+ when: "fail to log in"
+ request.servletPath = "/login/openid"
+ request.method = "POST"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "sent to login error page"
+ response.getRedirectedUrl() == "/custom/failure"
+ }
- @Configuration
- static class OpenIDLoginCustomRefsConfig extends BaseWebConfig {
- static AuthenticationUserDetailsService AUDS
+ @Configuration
+ static class OpenIDLoginCustomRefsConfig extends BaseWebConfig {
+ static AuthenticationUserDetailsService AUDS
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .openidLogin()
- // if using UserDetailsService wrap with new UserDetailsByNameServiceWrapper()
- .authenticationUserDetailsService(AUDS) // openid-login@user-service-ref
- .failureHandler(new SimpleUrlAuthenticationFailureHandler("/custom/failure")) // openid-login@authentication-failure-handler-ref
- .successHandler(new SavedRequestAwareAuthenticationSuccessHandler( defaultTargetUrl : "/custom/targetUrl" )) // openid-login@authentication-success-handler-ref
- .authenticationDetailsSource(new CustomWebAuthenticationDetailsSource()); // openid-login@authentication-details-source-ref
- }
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .openidLogin()
+ // if using UserDetailsService wrap with new UserDetailsByNameServiceWrapper()
+ .authenticationUserDetailsService(AUDS) // openid-login@user-service-ref
+ .failureHandler(new SimpleUrlAuthenticationFailureHandler("/custom/failure")) // openid-login@authentication-failure-handler-ref
+ .successHandler(new SavedRequestAwareAuthenticationSuccessHandler( defaultTargetUrl : "/custom/targetUrl" )) // openid-login@authentication-success-handler-ref
+ .authenticationDetailsSource(new CustomWebAuthenticationDetailsSource()); // openid-login@authentication-details-source-ref
+ }
- // only necessary to have easy access to the AuthenticationManager for testing/verification
- @Bean
- @Override
- public AuthenticationManager authenticationManagerBean()
- throws Exception {
- return super.authenticationManagerBean();
- }
+ // only necessary to have easy access to the AuthenticationManager for testing/verification
+ @Bean
+ @Override
+ public AuthenticationManager authenticationManagerBean()
+ throws Exception {
+ return super.authenticationManagerBean();
+ }
- }
+ }
- static class CustomWebAuthenticationDetailsSource extends WebAuthenticationDetailsSource {}
+ static class CustomWebAuthenticationDetailsSource extends WebAuthenticationDetailsSource {}
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpPortMappingsTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpPortMappingsTests.groovy
index 7505617499..b36c150117 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpPortMappingsTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpPortMappingsTests.groovy
@@ -38,78 +38,78 @@ import org.springframework.security.web.context.HttpSessionSecurityContextReposi
*
*/
public class NamespaceHttpPortMappingsTests extends BaseSpringSpec {
- FilterChainProxy springSecurityFilterChain
- MockHttpServletRequest request
- MockHttpServletResponse response
- MockFilterChain chain
+ FilterChainProxy springSecurityFilterChain
+ MockHttpServletRequest request
+ MockHttpServletResponse response
+ MockFilterChain chain
- def setup() {
- request = new MockHttpServletRequest()
- request.setMethod("GET")
- response = new MockHttpServletResponse()
- chain = new MockFilterChain()
- }
+ def setup() {
+ request = new MockHttpServletRequest()
+ request.setMethod("GET")
+ response = new MockHttpServletResponse()
+ chain = new MockFilterChain()
+ }
- def "http/port-mapper works with http/intercept-url@requires-channel"() {
- setup:
- loadConfig(HttpInterceptUrlWithPortMapperConfig)
- springSecurityFilterChain = context.getBean(FilterChainProxy)
- when:
- request.setServletPath("/login")
- request.setRequestURI("/login")
- request.setServerPort(9080);
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.redirectedUrl == "https://localhost:9443/login"
- when:
- setup()
- request.setServletPath("/secured/a")
- request.setRequestURI("/secured/a")
- request.setServerPort(9080);
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.redirectedUrl == "https://localhost:9443/secured/a"
- when:
- setup()
- request.setSecure(true)
- request.setScheme("https")
- request.setServerPort(9443);
- request.setServletPath("/user")
- request.setRequestURI("/user")
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.redirectedUrl == "http://localhost:9080/user"
- }
+ def "http/port-mapper works with http/intercept-url@requires-channel"() {
+ setup:
+ loadConfig(HttpInterceptUrlWithPortMapperConfig)
+ springSecurityFilterChain = context.getBean(FilterChainProxy)
+ when:
+ request.setServletPath("/login")
+ request.setRequestURI("/login")
+ request.setServerPort(9080);
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.redirectedUrl == "https://localhost:9443/login"
+ when:
+ setup()
+ request.setServletPath("/secured/a")
+ request.setRequestURI("/secured/a")
+ request.setServerPort(9080);
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.redirectedUrl == "https://localhost:9443/secured/a"
+ when:
+ setup()
+ request.setSecure(true)
+ request.setScheme("https")
+ request.setServerPort(9443);
+ request.setServletPath("/user")
+ request.setRequestURI("/user")
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.redirectedUrl == "http://localhost:9080/user"
+ }
- @EnableWebSecurity
- static class HttpInterceptUrlWithPortMapperConfig extends WebSecurityConfigurerAdapter {
+ @EnableWebSecurity
+ static class HttpInterceptUrlWithPortMapperConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .portMapper()
- .http(9080).mapsTo(9443)
- .and()
- .requiresChannel()
- .antMatchers("/login","/secured/**").requiresSecure()
- .anyRequest().requiresInsecure()
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .portMapper()
+ .http(9080).mapsTo(9443)
+ .and()
+ .requiresChannel()
+ .antMatchers("/login","/secured/**").requiresSecure()
+ .anyRequest().requiresInsecure()
+ }
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth
- .inMemoryAuthentication()
- .withUser("user").password("password").roles("USER").and()
- .withUser("admin").password("password").roles("USER", "ADMIN")
- }
- }
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth
+ .inMemoryAuthentication()
+ .withUser("user").password("password").roles("USER").and()
+ .withUser("admin").password("password").roles("USER", "ADMIN")
+ }
+ }
- def login(String username="user", String role="ROLE_USER") {
- HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository()
- HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response)
- repo.loadContext(requestResponseHolder)
- repo.saveContext(new SecurityContextImpl(authentication: new UsernamePasswordAuthenticationToken(username, null, AuthorityUtils.createAuthorityList(role))), requestResponseHolder.request, requestResponseHolder.response)
- }
+ def login(String username="user", String role="ROLE_USER") {
+ HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository()
+ HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response)
+ repo.loadContext(requestResponseHolder)
+ repo.saveContext(new SecurityContextImpl(authentication: new UsernamePasswordAuthenticationToken(username, null, AuthorityUtils.createAuthorityList(role))), requestResponseHolder.request, requestResponseHolder.response)
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpRequestCacheTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpRequestCacheTests.groovy
index a71a61f081..5427d93b87 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpRequestCacheTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpRequestCacheTests.groovy
@@ -39,35 +39,35 @@ import org.springframework.security.web.savedrequest.RequestCache;
*
*/
public class NamespaceHttpRequestCacheTests extends BaseSpringSpec {
- def "http/request-cache@ref"() {
- setup:
- RequestCacheRefConfig.REQUEST_CACHE = Mock(RequestCache)
- when:
- loadConfig(RequestCacheRefConfig)
- then:
- findFilter(ExceptionTranslationFilter).requestCache == RequestCacheRefConfig.REQUEST_CACHE
- }
+ def "http/request-cache@ref"() {
+ setup:
+ RequestCacheRefConfig.REQUEST_CACHE = Mock(RequestCache)
+ when:
+ loadConfig(RequestCacheRefConfig)
+ then:
+ findFilter(ExceptionTranslationFilter).requestCache == RequestCacheRefConfig.REQUEST_CACHE
+ }
- @Configuration
- static class RequestCacheRefConfig extends BaseWebConfig {
- static RequestCache REQUEST_CACHE
- protected void configure(HttpSecurity http) {
- http.
- requestCache()
- .requestCache(REQUEST_CACHE)
- }
- }
+ @Configuration
+ static class RequestCacheRefConfig extends BaseWebConfig {
+ static RequestCache REQUEST_CACHE
+ protected void configure(HttpSecurity http) {
+ http.
+ requestCache()
+ .requestCache(REQUEST_CACHE)
+ }
+ }
- def "http/request-cache@ref defaults to HttpSessionRequestCache"() {
- when:
- loadConfig(DefaultRequestCacheRefConfig)
- then:
- findFilter(ExceptionTranslationFilter).requestCache.class == HttpSessionRequestCache
- }
+ def "http/request-cache@ref defaults to HttpSessionRequestCache"() {
+ when:
+ loadConfig(DefaultRequestCacheRefConfig)
+ then:
+ findFilter(ExceptionTranslationFilter).requestCache.class == HttpSessionRequestCache
+ }
- @Configuration
- static class DefaultRequestCacheRefConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) {
- }
- }
+ @Configuration
+ static class DefaultRequestCacheRefConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) {
+ }
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpX509Tests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpX509Tests.groovy
index 9bd071e087..6deb100139 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpX509Tests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpX509Tests.groovy
@@ -55,201 +55,201 @@ import org.springframework.test.util.ReflectionTestUtils
*
*/
public class NamespaceHttpX509Tests extends BaseSpringSpec {
- def "http/x509 can authenticate"() {
- setup:
- X509Certificate certificate = loadCert("rod.cer")
- loadConfig(X509Config)
- when:
- request.setAttribute("javax.servlet.request.X509Certificate", [certificate] as X509Certificate[] )
- springSecurityFilterChain.doFilter(request, response, chain);
- then:
- response.status == 200
- authentication().name == 'rod'
- }
+ def "http/x509 can authenticate"() {
+ setup:
+ X509Certificate certificate = loadCert("rod.cer")
+ loadConfig(X509Config)
+ when:
+ request.setAttribute("javax.servlet.request.X509Certificate", [certificate] as X509Certificate[] )
+ springSecurityFilterChain.doFilter(request, response, chain);
+ then:
+ response.status == 200
+ authentication().name == 'rod'
+ }
- def "http/x509"() {
- when:
- loadConfig(X509Config)
- X509AuthenticationFilter filter = findFilter(X509AuthenticationFilter)
- AuthenticationManager authenticationManager = ReflectionTestUtils.getField(filter,"authenticationManager")
- then:
- authenticationManager
- filter.authenticationDetailsSource.class == WebAuthenticationDetailsSource
- authenticationManager.providers.find { it instanceof PreAuthenticatedAuthenticationProvider }.preAuthenticatedUserDetailsService.class == UserDetailsByNameServiceWrapper
- }
+ def "http/x509"() {
+ when:
+ loadConfig(X509Config)
+ X509AuthenticationFilter filter = findFilter(X509AuthenticationFilter)
+ AuthenticationManager authenticationManager = ReflectionTestUtils.getField(filter,"authenticationManager")
+ then:
+ authenticationManager
+ filter.authenticationDetailsSource.class == WebAuthenticationDetailsSource
+ authenticationManager.providers.find { it instanceof PreAuthenticatedAuthenticationProvider }.preAuthenticatedUserDetailsService.class == UserDetailsByNameServiceWrapper
+ }
- @EnableWebSecurity
- public static class X509Config extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth.
- inMemoryAuthentication()
- .withUser("rod").password("password").roles("USER","ADMIN");
- }
+ @EnableWebSecurity
+ public static class X509Config extends WebSecurityConfigurerAdapter {
+ @Override
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth.
+ inMemoryAuthentication()
+ .withUser("rod").password("password").roles("USER","ADMIN");
+ }
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .x509();
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .x509();
+ }
+ }
- def "http/x509@authentication-details-source-ref"() {
- setup:
- AuthenticationDetailsSourceRefConfig.AUTHENTICATION_DETAILS_SOURCE = Mock(AuthenticationDetailsSource)
- when:
- loadConfig(AuthenticationDetailsSourceRefConfig)
- X509AuthenticationFilter filter = findFilter(X509AuthenticationFilter)
- AuthenticationManager authenticationManager = ReflectionTestUtils.getField(filter,"authenticationManager")
- then:
- authenticationManager
- filter.authenticationDetailsSource == AuthenticationDetailsSourceRefConfig.AUTHENTICATION_DETAILS_SOURCE
- authenticationManager.providers.find { it instanceof PreAuthenticatedAuthenticationProvider }.preAuthenticatedUserDetailsService.class == UserDetailsByNameServiceWrapper
- }
+ def "http/x509@authentication-details-source-ref"() {
+ setup:
+ AuthenticationDetailsSourceRefConfig.AUTHENTICATION_DETAILS_SOURCE = Mock(AuthenticationDetailsSource)
+ when:
+ loadConfig(AuthenticationDetailsSourceRefConfig)
+ X509AuthenticationFilter filter = findFilter(X509AuthenticationFilter)
+ AuthenticationManager authenticationManager = ReflectionTestUtils.getField(filter,"authenticationManager")
+ then:
+ authenticationManager
+ filter.authenticationDetailsSource == AuthenticationDetailsSourceRefConfig.AUTHENTICATION_DETAILS_SOURCE
+ authenticationManager.providers.find { it instanceof PreAuthenticatedAuthenticationProvider }.preAuthenticatedUserDetailsService.class == UserDetailsByNameServiceWrapper
+ }
- @EnableWebSecurity
- public static class AuthenticationDetailsSourceRefConfig extends WebSecurityConfigurerAdapter {
- static AuthenticationDetailsSource AUTHENTICATION_DETAILS_SOURCE
+ @EnableWebSecurity
+ public static class AuthenticationDetailsSourceRefConfig extends WebSecurityConfigurerAdapter {
+ static AuthenticationDetailsSource AUTHENTICATION_DETAILS_SOURCE
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth.
- inMemoryAuthentication()
- .withUser("rod").password("password").roles("USER","ADMIN");
- }
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth.
+ inMemoryAuthentication()
+ .withUser("rod").password("password").roles("USER","ADMIN");
+ }
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .x509()
- .authenticationDetailsSource(AUTHENTICATION_DETAILS_SOURCE);
- }
- }
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .x509()
+ .authenticationDetailsSource(AUTHENTICATION_DETAILS_SOURCE);
+ }
+ }
- def "http/x509@subject-principal-regex"() {
- setup:
- X509Certificate certificate = loadCert("rodatexampledotcom.cer")
- loadConfig(SubjectPrincipalRegexConfig)
- when:
- request.setAttribute("javax.servlet.request.X509Certificate", [certificate] as X509Certificate[] )
- springSecurityFilterChain.doFilter(request, response, chain);
- then:
- response.status == 200
- authentication().name == 'rod'
- }
+ def "http/x509@subject-principal-regex"() {
+ setup:
+ X509Certificate certificate = loadCert("rodatexampledotcom.cer")
+ loadConfig(SubjectPrincipalRegexConfig)
+ when:
+ request.setAttribute("javax.servlet.request.X509Certificate", [certificate] as X509Certificate[] )
+ springSecurityFilterChain.doFilter(request, response, chain);
+ then:
+ response.status == 200
+ authentication().name == 'rod'
+ }
- @EnableWebSecurity
- public static class SubjectPrincipalRegexConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth.
- inMemoryAuthentication()
- .withUser("rod").password("password").roles("USER","ADMIN");
- }
+ @EnableWebSecurity
+ public static class SubjectPrincipalRegexConfig extends WebSecurityConfigurerAdapter {
+ @Override
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth.
+ inMemoryAuthentication()
+ .withUser("rod").password("password").roles("USER","ADMIN");
+ }
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .x509()
- .subjectPrincipalRegex('CN=(.*?)@example.com(?:,|$)');
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .x509()
+ .subjectPrincipalRegex('CN=(.*?)@example.com(?:,|$)');
+ }
+ }
- def "http/x509@user-service-ref"() {
- setup:
- X509Certificate certificate = loadCert("rodatexampledotcom.cer")
- loadConfig(UserDetailsServiceRefConfig)
- when:
- request.setAttribute("javax.servlet.request.X509Certificate", [certificate] as X509Certificate[] )
- springSecurityFilterChain.doFilter(request, response, chain);
- then:
- response.status == 200
- authentication().name == 'customuser'
- }
+ def "http/x509@user-service-ref"() {
+ setup:
+ X509Certificate certificate = loadCert("rodatexampledotcom.cer")
+ loadConfig(UserDetailsServiceRefConfig)
+ when:
+ request.setAttribute("javax.servlet.request.X509Certificate", [certificate] as X509Certificate[] )
+ springSecurityFilterChain.doFilter(request, response, chain);
+ then:
+ response.status == 200
+ authentication().name == 'customuser'
+ }
- @EnableWebSecurity
- public static class UserDetailsServiceRefConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth.
- inMemoryAuthentication()
- .withUser("rod").password("password").roles("USER","ADMIN");
- }
+ @EnableWebSecurity
+ public static class UserDetailsServiceRefConfig extends WebSecurityConfigurerAdapter {
+ @Override
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth.
+ inMemoryAuthentication()
+ .withUser("rod").password("password").roles("USER","ADMIN");
+ }
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .x509()
- .userDetailsService(new CustomUserDetailsService());
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .x509()
+ .userDetailsService(new CustomUserDetailsService());
+ }
+ }
- def "http/x509 custom AuthenticationUserDetailsService"() {
- setup:
- X509Certificate certificate = loadCert("rodatexampledotcom.cer")
- loadConfig(AuthenticationUserDetailsServiceConfig)
- when:
- request.setAttribute("javax.servlet.request.X509Certificate", [certificate] as X509Certificate[] )
- springSecurityFilterChain.doFilter(request, response, chain);
- then:
- response.status == 200
- authentication().name == 'customuser'
- }
+ def "http/x509 custom AuthenticationUserDetailsService"() {
+ setup:
+ X509Certificate certificate = loadCert("rodatexampledotcom.cer")
+ loadConfig(AuthenticationUserDetailsServiceConfig)
+ when:
+ request.setAttribute("javax.servlet.request.X509Certificate", [certificate] as X509Certificate[] )
+ springSecurityFilterChain.doFilter(request, response, chain);
+ then:
+ response.status == 200
+ authentication().name == 'customuser'
+ }
- @EnableWebSecurity
- public static class AuthenticationUserDetailsServiceConfig extends WebSecurityConfigurerAdapter {
- static AuthenticationDetailsSource AUTHENTICATION_DETAILS_SOURCE
+ @EnableWebSecurity
+ public static class AuthenticationUserDetailsServiceConfig extends WebSecurityConfigurerAdapter {
+ static AuthenticationDetailsSource AUTHENTICATION_DETAILS_SOURCE
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth.
- inMemoryAuthentication()
- .withUser("rod").password("password").roles("USER","ADMIN");
- }
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth.
+ inMemoryAuthentication()
+ .withUser("rod").password("password").roles("USER","ADMIN");
+ }
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .x509()
- .userDetailsService(new CustomUserDetailsService());
- }
- }
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .x509()
+ .userDetailsService(new CustomUserDetailsService());
+ }
+ }
- def loadCert(String location) {
- CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
- certFactory.generateCertificate(Thread.currentThread().contextClassLoader.getResourceAsStream(location))
- }
+ def loadCert(String location) {
+ CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
+ certFactory.generateCertificate(Thread.currentThread().contextClassLoader.getResourceAsStream(location))
+ }
- static class CustomUserDetailsService implements UserDetailsService {
+ static class CustomUserDetailsService implements UserDetailsService {
- public UserDetails loadUserByUsername(String username)
- throws UsernameNotFoundException {
- return new User("customuser", "password", AuthorityUtils.createAuthorityList("ROLE_USER"));
- }
+ public UserDetails loadUserByUsername(String username)
+ throws UsernameNotFoundException {
+ return new User("customuser", "password", AuthorityUtils.createAuthorityList("ROLE_USER"));
+ }
- }
+ }
- static class CustomAuthenticationUserDetailsService implements AuthenticationUserDetailsService {
- public UserDetails loadUserDetails(
- PreAuthenticatedAuthenticationToken token)
- throws UsernameNotFoundException {
- return new User("customuser", "password", AuthorityUtils.createAuthorityList("ROLE_USER"));
- }
- }
+ static class CustomAuthenticationUserDetailsService implements AuthenticationUserDetailsService {
+ public UserDetails loadUserDetails(
+ PreAuthenticatedAuthenticationToken token)
+ throws UsernameNotFoundException {
+ return new User("customuser", "password", AuthorityUtils.createAuthorityList("ROLE_USER"));
+ }
+ }
- def authentication() {
- HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response)
- new HttpSessionSecurityContextRepository().loadContext(requestResponseHolder)?.authentication
- }
+ def authentication() {
+ HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response)
+ new HttpSessionSecurityContextRepository().loadContext(requestResponseHolder)?.authentication
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceRememberMeTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceRememberMeTests.groovy
index 73844980f9..ec21d29d8c 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceRememberMeTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceRememberMeTests.groovy
@@ -55,333 +55,333 @@ import org.springframework.test.util.ReflectionTestUtils;
*/
public class NamespaceRememberMeTests extends BaseSpringSpec {
- def "http/remember-me"() {
- setup:
- loadConfig(RememberMeConfig)
- when: "login with remember me"
- super.setup()
- request.servletPath = "/login"
- request.method = "POST"
- request.parameters.username = ["user"] as String[]
- request.parameters.password = ["password"] as String[]
- request.parameters.'remember-me' = ["true"] as String[]
- springSecurityFilterChain.doFilter(request,response,chain)
- Cookie rememberMeCookie = getRememberMeCookie()
- then: "response contains remember me cookie"
- rememberMeCookie != null
- when: "session expires"
- super.setup()
- request.setCookies(rememberMeCookie)
- request.requestURI = "/abc"
- springSecurityFilterChain.doFilter(request,response,chain)
- MockHttpSession session = request.getSession()
- then: "initialized to RememberMeAuthenticationToken"
- SecurityContext context = new HttpSessionSecurityContextRepository().loadContext(new HttpRequestResponseHolder(request, response))
- context.getAuthentication() instanceof RememberMeAuthenticationToken
- when: "logout"
- super.setup()
- request.setSession(session)
- super.setupCsrf()
- request.setCookies(rememberMeCookie)
- request.servletPath = "/logout"
- request.method = "POST"
- springSecurityFilterChain.doFilter(request,response,chain)
- rememberMeCookie = getRememberMeCookie()
- then: "logout cookie expired"
- response.getRedirectedUrl() == "/login?logout"
- rememberMeCookie.maxAge == 0
- when: "use remember me after logout"
- super.setup()
- request.setCookies(rememberMeCookie)
- request.requestURI = "/abc"
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "sent to default login page"
- response.getRedirectedUrl() == "http://localhost/login"
- }
+ def "http/remember-me"() {
+ setup:
+ loadConfig(RememberMeConfig)
+ when: "login with remember me"
+ super.setup()
+ request.servletPath = "/login"
+ request.method = "POST"
+ request.parameters.username = ["user"] as String[]
+ request.parameters.password = ["password"] as String[]
+ request.parameters.'remember-me' = ["true"] as String[]
+ springSecurityFilterChain.doFilter(request,response,chain)
+ Cookie rememberMeCookie = getRememberMeCookie()
+ then: "response contains remember me cookie"
+ rememberMeCookie != null
+ when: "session expires"
+ super.setup()
+ request.setCookies(rememberMeCookie)
+ request.requestURI = "/abc"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ MockHttpSession session = request.getSession()
+ then: "initialized to RememberMeAuthenticationToken"
+ SecurityContext context = new HttpSessionSecurityContextRepository().loadContext(new HttpRequestResponseHolder(request, response))
+ context.getAuthentication() instanceof RememberMeAuthenticationToken
+ when: "logout"
+ super.setup()
+ request.setSession(session)
+ super.setupCsrf()
+ request.setCookies(rememberMeCookie)
+ request.servletPath = "/logout"
+ request.method = "POST"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ rememberMeCookie = getRememberMeCookie()
+ then: "logout cookie expired"
+ response.getRedirectedUrl() == "/login?logout"
+ rememberMeCookie.maxAge == 0
+ when: "use remember me after logout"
+ super.setup()
+ request.setCookies(rememberMeCookie)
+ request.requestURI = "/abc"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "sent to default login page"
+ response.getRedirectedUrl() == "http://localhost/login"
+ }
- @Configuration
- static class RememberMeConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .formLogin()
- .and()
- .rememberMe()
- }
- }
+ @Configuration
+ static class RememberMeConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .formLogin()
+ .and()
+ .rememberMe()
+ }
+ }
- def "http/remember-me@services-ref"() {
- setup:
- RememberMeServicesRefConfig.REMEMBER_ME_SERVICES = Mock(RememberMeServices)
- when: "use custom remember-me services"
- loadConfig(RememberMeServicesRefConfig)
- then: "custom remember-me services used"
- findFilter(RememberMeAuthenticationFilter).rememberMeServices == RememberMeServicesRefConfig.REMEMBER_ME_SERVICES
- findFilter(UsernamePasswordAuthenticationFilter).rememberMeServices == RememberMeServicesRefConfig.REMEMBER_ME_SERVICES
- }
+ def "http/remember-me@services-ref"() {
+ setup:
+ RememberMeServicesRefConfig.REMEMBER_ME_SERVICES = Mock(RememberMeServices)
+ when: "use custom remember-me services"
+ loadConfig(RememberMeServicesRefConfig)
+ then: "custom remember-me services used"
+ findFilter(RememberMeAuthenticationFilter).rememberMeServices == RememberMeServicesRefConfig.REMEMBER_ME_SERVICES
+ findFilter(UsernamePasswordAuthenticationFilter).rememberMeServices == RememberMeServicesRefConfig.REMEMBER_ME_SERVICES
+ }
- @Configuration
- static class RememberMeServicesRefConfig extends BaseWebConfig {
- static RememberMeServices REMEMBER_ME_SERVICES
- protected void configure(HttpSecurity http) throws Exception {
- http
- .formLogin()
- .and()
- .rememberMe()
- .rememberMeServices(REMEMBER_ME_SERVICES)
- }
- }
+ @Configuration
+ static class RememberMeServicesRefConfig extends BaseWebConfig {
+ static RememberMeServices REMEMBER_ME_SERVICES
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .formLogin()
+ .and()
+ .rememberMe()
+ .rememberMeServices(REMEMBER_ME_SERVICES)
+ }
+ }
- def "http/remember-me@authentication-success-handler-ref"() {
- setup:
- AuthSuccessConfig.SUCCESS_HANDLER = Mock(AuthenticationSuccessHandler)
- when: "use custom success handler"
- loadConfig(AuthSuccessConfig)
- then: "custom remember-me success handler is used"
- findFilter(RememberMeAuthenticationFilter).successHandler == AuthSuccessConfig.SUCCESS_HANDLER
- }
+ def "http/remember-me@authentication-success-handler-ref"() {
+ setup:
+ AuthSuccessConfig.SUCCESS_HANDLER = Mock(AuthenticationSuccessHandler)
+ when: "use custom success handler"
+ loadConfig(AuthSuccessConfig)
+ then: "custom remember-me success handler is used"
+ findFilter(RememberMeAuthenticationFilter).successHandler == AuthSuccessConfig.SUCCESS_HANDLER
+ }
- @Configuration
- static class AuthSuccessConfig extends BaseWebConfig {
- static AuthenticationSuccessHandler SUCCESS_HANDLER
- protected void configure(HttpSecurity http) throws Exception {
- http
- .formLogin()
- .and()
- .rememberMe()
- .authenticationSuccessHandler(SUCCESS_HANDLER)
- }
- }
+ @Configuration
+ static class AuthSuccessConfig extends BaseWebConfig {
+ static AuthenticationSuccessHandler SUCCESS_HANDLER
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .formLogin()
+ .and()
+ .rememberMe()
+ .authenticationSuccessHandler(SUCCESS_HANDLER)
+ }
+ }
- // http/remember-me@data-source-ref is not supported directly. Instead use http/remember-me@token-repository-ref example
+ // http/remember-me@data-source-ref is not supported directly. Instead use http/remember-me@token-repository-ref example
- def "http/remember-me@key"() {
- when: "use custom key"
- loadConfig(KeyConfig)
- AuthenticationManager authManager = context.getBean(AuthenticationManager)
- then: "custom key services used"
- findFilter(RememberMeAuthenticationFilter).rememberMeServices.key == "KeyConfig"
- authManager.authenticate(new RememberMeAuthenticationToken("KeyConfig", "user", AuthorityUtils.createAuthorityList("ROLE_USER")))
- }
+ def "http/remember-me@key"() {
+ when: "use custom key"
+ loadConfig(KeyConfig)
+ AuthenticationManager authManager = context.getBean(AuthenticationManager)
+ then: "custom key services used"
+ findFilter(RememberMeAuthenticationFilter).rememberMeServices.key == "KeyConfig"
+ authManager.authenticate(new RememberMeAuthenticationToken("KeyConfig", "user", AuthorityUtils.createAuthorityList("ROLE_USER")))
+ }
- @Configuration
- static class KeyConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .formLogin()
- .and()
- .rememberMe()
- .key("KeyConfig")
- }
+ @Configuration
+ static class KeyConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .formLogin()
+ .and()
+ .rememberMe()
+ .key("KeyConfig")
+ }
- @Bean
- @Override
- public AuthenticationManager authenticationManagerBean()
- throws Exception {
- return super.authenticationManagerBean();
- }
- }
+ @Bean
+ @Override
+ public AuthenticationManager authenticationManagerBean()
+ throws Exception {
+ return super.authenticationManagerBean();
+ }
+ }
- // http/remember-me@services-alias is not supported use standard aliasing instead (i.e. @Bean("alias"))
+ // http/remember-me@services-alias is not supported use standard aliasing instead (i.e. @Bean("alias"))
- def "http/remember-me@token-repository-ref"() {
- setup:
- TokenRepositoryRefConfig.TOKEN_REPOSITORY = Mock(PersistentTokenRepository)
- when: "use custom token services"
- loadConfig(TokenRepositoryRefConfig)
- then: "custom token services used with PersistentTokenBasedRememberMeServices"
- PersistentTokenBasedRememberMeServices rememberMeServices = findFilter(RememberMeAuthenticationFilter).rememberMeServices
- findFilter(RememberMeAuthenticationFilter).rememberMeServices.tokenRepository == TokenRepositoryRefConfig.TOKEN_REPOSITORY
- }
+ def "http/remember-me@token-repository-ref"() {
+ setup:
+ TokenRepositoryRefConfig.TOKEN_REPOSITORY = Mock(PersistentTokenRepository)
+ when: "use custom token services"
+ loadConfig(TokenRepositoryRefConfig)
+ then: "custom token services used with PersistentTokenBasedRememberMeServices"
+ PersistentTokenBasedRememberMeServices rememberMeServices = findFilter(RememberMeAuthenticationFilter).rememberMeServices
+ findFilter(RememberMeAuthenticationFilter).rememberMeServices.tokenRepository == TokenRepositoryRefConfig.TOKEN_REPOSITORY
+ }
- @Configuration
- static class TokenRepositoryRefConfig extends BaseWebConfig {
- static PersistentTokenRepository TOKEN_REPOSITORY
- protected void configure(HttpSecurity http) throws Exception {
- // JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl()
- // tokenRepository.setDataSource(dataSource);
- http
- .formLogin()
- .and()
- .rememberMe()
- .tokenRepository(TOKEN_REPOSITORY)
- }
- }
+ @Configuration
+ static class TokenRepositoryRefConfig extends BaseWebConfig {
+ static PersistentTokenRepository TOKEN_REPOSITORY
+ protected void configure(HttpSecurity http) throws Exception {
+ // JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl()
+ // tokenRepository.setDataSource(dataSource);
+ http
+ .formLogin()
+ .and()
+ .rememberMe()
+ .tokenRepository(TOKEN_REPOSITORY)
+ }
+ }
- def "http/remember-me@token-validity-seconds"() {
- when: "use token validity"
- loadConfig(TokenValiditySecondsConfig)
- then: "custom token validity used"
- findFilter(RememberMeAuthenticationFilter).rememberMeServices.tokenValiditySeconds == 1
- }
+ def "http/remember-me@token-validity-seconds"() {
+ when: "use token validity"
+ loadConfig(TokenValiditySecondsConfig)
+ then: "custom token validity used"
+ findFilter(RememberMeAuthenticationFilter).rememberMeServices.tokenValiditySeconds == 1
+ }
- @Configuration
- static class TokenValiditySecondsConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .formLogin()
- .and()
- .rememberMe()
- .tokenValiditySeconds(1)
- }
- }
+ @Configuration
+ static class TokenValiditySecondsConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .formLogin()
+ .and()
+ .rememberMe()
+ .tokenValiditySeconds(1)
+ }
+ }
- def "http/remember-me@token-validity-seconds default"() {
- when: "use token validity"
- loadConfig(DefaultTokenValiditySecondsConfig)
- then: "custom token validity used"
- findFilter(RememberMeAuthenticationFilter).rememberMeServices.tokenValiditySeconds == AbstractRememberMeServices.TWO_WEEKS_S
- }
+ def "http/remember-me@token-validity-seconds default"() {
+ when: "use token validity"
+ loadConfig(DefaultTokenValiditySecondsConfig)
+ then: "custom token validity used"
+ findFilter(RememberMeAuthenticationFilter).rememberMeServices.tokenValiditySeconds == AbstractRememberMeServices.TWO_WEEKS_S
+ }
- @Configuration
- static class DefaultTokenValiditySecondsConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .formLogin()
- .and()
- .rememberMe()
- }
- }
+ @Configuration
+ static class DefaultTokenValiditySecondsConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .formLogin()
+ .and()
+ .rememberMe()
+ }
+ }
- def "http/remember-me@use-secure-cookie"() {
- when: "use secure cookies = true"
- loadConfig(UseSecureCookieConfig)
- then: "secure cookies will be used"
- ReflectionTestUtils.getField(findFilter(RememberMeAuthenticationFilter).rememberMeServices, "useSecureCookie") == true
- }
+ def "http/remember-me@use-secure-cookie"() {
+ when: "use secure cookies = true"
+ loadConfig(UseSecureCookieConfig)
+ then: "secure cookies will be used"
+ ReflectionTestUtils.getField(findFilter(RememberMeAuthenticationFilter).rememberMeServices, "useSecureCookie") == true
+ }
- @Configuration
- static class UseSecureCookieConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .formLogin()
- .and()
- .rememberMe()
- .useSecureCookie(true)
- }
- }
+ @Configuration
+ static class UseSecureCookieConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .formLogin()
+ .and()
+ .rememberMe()
+ .useSecureCookie(true)
+ }
+ }
- def "http/remember-me@remember-me-parameter"() {
- when: "use custom rememberMeParameter"
- loadConfig(RememberMeParameterConfig)
- then: "custom rememberMeParameter will be used"
- findFilter(RememberMeAuthenticationFilter).rememberMeServices.parameter == "rememberMe"
- }
+ def "http/remember-me@remember-me-parameter"() {
+ when: "use custom rememberMeParameter"
+ loadConfig(RememberMeParameterConfig)
+ then: "custom rememberMeParameter will be used"
+ findFilter(RememberMeAuthenticationFilter).rememberMeServices.parameter == "rememberMe"
+ }
- @Configuration
- static class RememberMeParameterConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .formLogin()
- .and()
- .rememberMe()
- .rememberMeParameter("rememberMe")
- }
- }
+ @Configuration
+ static class RememberMeParameterConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .formLogin()
+ .and()
+ .rememberMe()
+ .rememberMeParameter("rememberMe")
+ }
+ }
- // SEC-2880
- def "http/remember-me@remember-me-cookie"() {
- when: "use custom rememberMeCookieName"
- loadConfig(RememberMeCookieNameConfig)
- then: "custom rememberMeCookieName will be used"
- findFilter(RememberMeAuthenticationFilter).rememberMeServices.cookieName == "rememberMe"
- }
+ // SEC-2880
+ def "http/remember-me@remember-me-cookie"() {
+ when: "use custom rememberMeCookieName"
+ loadConfig(RememberMeCookieNameConfig)
+ then: "custom rememberMeCookieName will be used"
+ findFilter(RememberMeAuthenticationFilter).rememberMeServices.cookieName == "rememberMe"
+ }
- @Configuration
- static class RememberMeCookieNameConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .formLogin()
- .and()
- .rememberMe()
- .rememberMeCookieName("rememberMe")
- }
- }
+ @Configuration
+ static class RememberMeCookieNameConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .formLogin()
+ .and()
+ .rememberMe()
+ .rememberMeCookieName("rememberMe")
+ }
+ }
- def "http/remember-me@use-secure-cookie defaults"() {
- when: "use secure cookies not specified"
- loadConfig(DefaultUseSecureCookieConfig)
- then: "secure cookies will be null (use secure if the request is secure)"
- ReflectionTestUtils.getField(findFilter(RememberMeAuthenticationFilter).rememberMeServices, "useSecureCookie") == null
- }
+ def "http/remember-me@use-secure-cookie defaults"() {
+ when: "use secure cookies not specified"
+ loadConfig(DefaultUseSecureCookieConfig)
+ then: "secure cookies will be null (use secure if the request is secure)"
+ ReflectionTestUtils.getField(findFilter(RememberMeAuthenticationFilter).rememberMeServices, "useSecureCookie") == null
+ }
- @Configuration
- static class DefaultUseSecureCookieConfig extends BaseWebConfig {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .formLogin()
- .and()
- .rememberMe()
- }
- }
+ @Configuration
+ static class DefaultUseSecureCookieConfig extends BaseWebConfig {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .formLogin()
+ .and()
+ .rememberMe()
+ }
+ }
- def "http/remember-me defaults UserDetailsService with custom UserDetailsService"() {
- setup:
- DefaultsUserDetailsServiceWithDaoConfig.USERDETAILS_SERVICE = Mock(UserDetailsService)
- loadConfig(DefaultsUserDetailsServiceWithDaoConfig)
- when:
- request.setCookies(createRememberMeCookie())
- springSecurityFilterChain.doFilter(request, response, chain)
- then: "RememberMeServices defaults to the custom UserDetailsService"
- 1 * DefaultsUserDetailsServiceWithDaoConfig.USERDETAILS_SERVICE.loadUserByUsername("user")
- }
+ def "http/remember-me defaults UserDetailsService with custom UserDetailsService"() {
+ setup:
+ DefaultsUserDetailsServiceWithDaoConfig.USERDETAILS_SERVICE = Mock(UserDetailsService)
+ loadConfig(DefaultsUserDetailsServiceWithDaoConfig)
+ when:
+ request.setCookies(createRememberMeCookie())
+ springSecurityFilterChain.doFilter(request, response, chain)
+ then: "RememberMeServices defaults to the custom UserDetailsService"
+ 1 * DefaultsUserDetailsServiceWithDaoConfig.USERDETAILS_SERVICE.loadUserByUsername("user")
+ }
- @EnableWebSecurity
- static class DefaultsUserDetailsServiceWithDaoConfig extends WebSecurityConfigurerAdapter {
- static UserDetailsService USERDETAILS_SERVICE
+ @EnableWebSecurity
+ static class DefaultsUserDetailsServiceWithDaoConfig extends WebSecurityConfigurerAdapter {
+ static UserDetailsService USERDETAILS_SERVICE
- protected void configure(HttpSecurity http) throws Exception {
- http
- .formLogin()
- .and()
- .rememberMe()
- }
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .formLogin()
+ .and()
+ .rememberMe()
+ }
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth
- .userDetailsService(USERDETAILS_SERVICE);
- }
- }
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth
+ .userDetailsService(USERDETAILS_SERVICE);
+ }
+ }
- def "http/remember-me@user-service-ref"() {
- setup:
- UserServiceRefConfig.USERDETAILS_SERVICE = Mock(UserDetailsService)
- when: "use custom UserDetailsService"
- loadConfig(UserServiceRefConfig)
- then: "custom UserDetailsService is used"
- ReflectionTestUtils.getField(findFilter(RememberMeAuthenticationFilter).rememberMeServices, "userDetailsService") == UserServiceRefConfig.USERDETAILS_SERVICE
- }
+ def "http/remember-me@user-service-ref"() {
+ setup:
+ UserServiceRefConfig.USERDETAILS_SERVICE = Mock(UserDetailsService)
+ when: "use custom UserDetailsService"
+ loadConfig(UserServiceRefConfig)
+ then: "custom UserDetailsService is used"
+ ReflectionTestUtils.getField(findFilter(RememberMeAuthenticationFilter).rememberMeServices, "userDetailsService") == UserServiceRefConfig.USERDETAILS_SERVICE
+ }
- @Configuration
- static class UserServiceRefConfig extends BaseWebConfig {
- static UserDetailsService USERDETAILS_SERVICE
- protected void configure(HttpSecurity http) throws Exception {
- http
- .formLogin()
- .and()
- .rememberMe()
- .userDetailsService(USERDETAILS_SERVICE)
- }
- }
+ @Configuration
+ static class UserServiceRefConfig extends BaseWebConfig {
+ static UserDetailsService USERDETAILS_SERVICE
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .formLogin()
+ .and()
+ .rememberMe()
+ .userDetailsService(USERDETAILS_SERVICE)
+ }
+ }
- Cookie createRememberMeCookie() {
- MockHttpServletRequest request = new MockHttpServletRequest()
- MockHttpServletResponse response = new MockHttpServletResponse()
- super.setupCsrf("CSRF_TOKEN", request, response)
+ Cookie createRememberMeCookie() {
+ MockHttpServletRequest request = new MockHttpServletRequest()
+ MockHttpServletResponse response = new MockHttpServletResponse()
+ super.setupCsrf("CSRF_TOKEN", request, response)
- MockFilterChain chain = new MockFilterChain()
- request.servletPath = "/login"
- request.method = "POST"
- request.parameters.username = ["user"] as String[]
- request.parameters.password = ["password"] as String[]
- request.parameters.'remember-me' = ["true"] as String[]
- springSecurityFilterChain.doFilter(request, response, chain)
- response.getCookie("remember-me")
- }
+ MockFilterChain chain = new MockFilterChain()
+ request.servletPath = "/login"
+ request.method = "POST"
+ request.parameters.username = ["user"] as String[]
+ request.parameters.password = ["password"] as String[]
+ request.parameters.'remember-me' = ["true"] as String[]
+ springSecurityFilterChain.doFilter(request, response, chain)
+ response.getCookie("remember-me")
+ }
- Cookie getRememberMeCookie(String cookieName="remember-me") {
- response.getCookie(cookieName)
- }
+ Cookie getRememberMeCookie(String cookieName="remember-me") {
+ response.getCookie(cookieName)
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/PermitAllSupportTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/PermitAllSupportTests.groovy
index cdaa088c73..10e6bb3fcd 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/PermitAllSupportTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/PermitAllSupportTests.groovy
@@ -30,40 +30,40 @@ import org.springframework.security.web.util.matcher.RequestMatcher
*
*/
class PermitAllSupportTests extends BaseSpringSpec {
- def "PermitAllSupport.ExactUrlRequestMatcher"() {
- expect:
- RequestMatcher matcher = new PermitAllSupport.ExactUrlRequestMatcher(processUrl)
- matcher.matches(new MockHttpServletRequest(requestURI:requestURI,contextPath:contextPath,queryString: query)) == matches
- where:
- processUrl | requestURI | contextPath | query | matches
- "/login" | "/sample/login" | "/sample" | null | true
- "/login" | "/sample/login" | "/sample" | "error" | false
- "/login?error" | "/sample/login" | "/sample" | "error" | true
- }
+ def "PermitAllSupport.ExactUrlRequestMatcher"() {
+ expect:
+ RequestMatcher matcher = new PermitAllSupport.ExactUrlRequestMatcher(processUrl)
+ matcher.matches(new MockHttpServletRequest(requestURI:requestURI,contextPath:contextPath,queryString: query)) == matches
+ where:
+ processUrl | requestURI | contextPath | query | matches
+ "/login" | "/sample/login" | "/sample" | null | true
+ "/login" | "/sample/login" | "/sample" | "error" | false
+ "/login?error" | "/sample/login" | "/sample" | "error" | true
+ }
- def "PermitAllSupport throws Exception when authorizedUrls() not invoked"() {
- when:
- loadConfig(NoAuthorizedUrlsConfig)
- then:
- BeanCreationException e = thrown()
- e.message.contains "permitAll only works with HttpSecurity.authorizeRequests"
+ def "PermitAllSupport throws Exception when authorizedUrls() not invoked"() {
+ when:
+ loadConfig(NoAuthorizedUrlsConfig)
+ then:
+ BeanCreationException e = thrown()
+ e.message.contains "permitAll only works with HttpSecurity.authorizeRequests"
- }
+ }
- @EnableWebSecurity
- static class NoAuthorizedUrlsConfig extends WebSecurityConfigurerAdapter {
+ @EnableWebSecurity
+ static class NoAuthorizedUrlsConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth
- .inMemoryAuthentication()
- }
+ @Override
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth
+ .inMemoryAuthentication()
+ }
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .formLogin()
- .permitAll()
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .formLogin()
+ .permitAll()
+ }
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/PortMapperConfigurerTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/PortMapperConfigurerTests.groovy
index 4428f91bd0..aff2afd2ec 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/PortMapperConfigurerTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/PortMapperConfigurerTests.groovy
@@ -36,28 +36,28 @@ import org.springframework.security.web.session.SessionManagementFilter
*/
class PortMapperConfigurerTests extends BaseSpringSpec {
- def "invoke portMapper twice does not override"() {
- setup:
- loadConfig(InvokeTwiceDoesNotOverride)
- request.setServerPort(543)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.redirectedUrl == "https://localhost:123"
- }
+ def "invoke portMapper twice does not override"() {
+ setup:
+ loadConfig(InvokeTwiceDoesNotOverride)
+ request.setServerPort(543)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.redirectedUrl == "https://localhost:123"
+ }
- @EnableWebSecurity
- static class InvokeTwiceDoesNotOverride extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .requiresChannel()
- .anyRequest().requiresSecure()
- .and()
- .portMapper()
- .http(543).mapsTo(123)
- .and()
- .portMapper()
- }
- }
+ @EnableWebSecurity
+ static class InvokeTwiceDoesNotOverride extends WebSecurityConfigurerAdapter {
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .requiresChannel()
+ .anyRequest().requiresSecure()
+ .and()
+ .portMapper()
+ .http(543).mapsTo(123)
+ .and()
+ .portMapper()
+ }
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/RememberMeConfigurerTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/RememberMeConfigurerTests.groovy
index e86f7856ef..3a00787b1d 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/RememberMeConfigurerTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/RememberMeConfigurerTests.groovy
@@ -48,151 +48,151 @@ import org.springframework.security.web.context.HttpSessionSecurityContextReposi
*/
public class RememberMeConfigurerTests extends BaseSpringSpec {
- def "rememberMe() null UserDetailsService provides meaningful error"() {
- setup: "Load Config without UserDetailsService specified"
- loadConfig(NullUserDetailsConfig)
- when:
- request.setCookies(createRememberMeCookie())
- springSecurityFilterChain.doFilter(request, response, chain)
- then: "A good error message is provided"
- Exception success = thrown()
- success.message.contains "UserDetailsService is required"
- }
+ def "rememberMe() null UserDetailsService provides meaningful error"() {
+ setup: "Load Config without UserDetailsService specified"
+ loadConfig(NullUserDetailsConfig)
+ when:
+ request.setCookies(createRememberMeCookie())
+ springSecurityFilterChain.doFilter(request, response, chain)
+ then: "A good error message is provided"
+ Exception success = thrown()
+ success.message.contains "UserDetailsService is required"
+ }
- @EnableWebSecurity
- static class NullUserDetailsConfig extends WebSecurityConfigurerAdapter {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .formLogin()
- .and()
- .rememberMe()
- }
+ @EnableWebSecurity
+ static class NullUserDetailsConfig extends WebSecurityConfigurerAdapter {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .formLogin()
+ .and()
+ .rememberMe()
+ }
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- User user = new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER"))
- DaoAuthenticationProvider provider = new DaoAuthenticationProvider()
- provider.userDetailsService = new InMemoryUserDetailsManager([user])
- auth
- .authenticationProvider(provider)
- }
- }
+ @Override
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ User user = new User("user", "password", AuthorityUtils.createAuthorityList("ROLE_USER"))
+ DaoAuthenticationProvider provider = new DaoAuthenticationProvider()
+ provider.userDetailsService = new InMemoryUserDetailsManager([user])
+ auth
+ .authenticationProvider(provider)
+ }
+ }
- def "rememberMe ObjectPostProcessor"() {
- setup:
- AnyObjectPostProcessor opp = Mock()
- HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
- UserDetailsService uds = authenticationBldr.getDefaultUserDetailsService()
- when:
- http
- .rememberMe()
- .userDetailsService(authenticationBldr.getDefaultUserDetailsService())
- .and()
- .build()
+ def "rememberMe ObjectPostProcessor"() {
+ setup:
+ AnyObjectPostProcessor opp = Mock()
+ HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
+ UserDetailsService uds = authenticationBldr.getDefaultUserDetailsService()
+ when:
+ http
+ .rememberMe()
+ .userDetailsService(authenticationBldr.getDefaultUserDetailsService())
+ .and()
+ .build()
- then: "RememberMeAuthenticationFilter is registered with LifecycleManager"
- 1 * opp.postProcess(_ as RememberMeAuthenticationFilter) >> {RememberMeAuthenticationFilter o -> o}
- }
+ then: "RememberMeAuthenticationFilter is registered with LifecycleManager"
+ 1 * opp.postProcess(_ as RememberMeAuthenticationFilter) >> {RememberMeAuthenticationFilter o -> o}
+ }
- def "invoke rememberMe twice does not reset"() {
- setup:
- AnyObjectPostProcessor opp = Mock()
- HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
- UserDetailsService uds = authenticationBldr.getDefaultUserDetailsService()
- when:
- http
- .rememberMe()
- .userDetailsService(authenticationBldr.getDefaultUserDetailsService())
- .and()
- .rememberMe()
- then: "RememberMeAuthenticationFilter is registered with LifecycleManager"
- http.getConfigurer(RememberMeConfigurer).userDetailsService != null
- }
+ def "invoke rememberMe twice does not reset"() {
+ setup:
+ AnyObjectPostProcessor opp = Mock()
+ HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
+ UserDetailsService uds = authenticationBldr.getDefaultUserDetailsService()
+ when:
+ http
+ .rememberMe()
+ .userDetailsService(authenticationBldr.getDefaultUserDetailsService())
+ .and()
+ .rememberMe()
+ then: "RememberMeAuthenticationFilter is registered with LifecycleManager"
+ http.getConfigurer(RememberMeConfigurer).userDetailsService != null
+ }
- def "http/remember-me with Global AuthenticationManagerBuilder"() {
- setup:
- loadConfig(RememberMeConfig)
- when: "login with remember me"
- super.setup()
- request.servletPath = "/login"
- request.method = "POST"
- request.parameters.username = ["user"] as String[]
- request.parameters.password = ["password"] as String[]
- request.parameters.'remember-me' = ["true"] as String[]
- springSecurityFilterChain.doFilter(request,response,chain)
- Cookie rememberMeCookie = getRememberMeCookie()
- then: "response contains remember me cookie"
- rememberMeCookie != null
- when: "session expires"
- super.setup()
- request.setCookies(rememberMeCookie)
- request.requestURI = "/abc"
- springSecurityFilterChain.doFilter(request,response,chain)
- MockHttpSession session = request.getSession()
- then: "initialized to RememberMeAuthenticationToken"
- SecurityContext context = new HttpSessionSecurityContextRepository().loadContext(new HttpRequestResponseHolder(request, response))
- context.getAuthentication() instanceof RememberMeAuthenticationToken
- when: "logout"
- super.setup()
- request.setSession(session)
- super.setupCsrf()
- request.setCookies(rememberMeCookie)
- request.servletPath = "/logout"
- request.method = "POST"
- springSecurityFilterChain.doFilter(request,response,chain)
- rememberMeCookie = getRememberMeCookie()
- then: "logout cookie expired"
- response.getRedirectedUrl() == "/login?logout"
- rememberMeCookie.maxAge == 0
- when: "use remember me after logout"
- super.setup()
- request.setCookies(rememberMeCookie)
- request.requestURI = "/abc"
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "sent to default login page"
- response.getRedirectedUrl() == "http://localhost/login"
- }
+ def "http/remember-me with Global AuthenticationManagerBuilder"() {
+ setup:
+ loadConfig(RememberMeConfig)
+ when: "login with remember me"
+ super.setup()
+ request.servletPath = "/login"
+ request.method = "POST"
+ request.parameters.username = ["user"] as String[]
+ request.parameters.password = ["password"] as String[]
+ request.parameters.'remember-me' = ["true"] as String[]
+ springSecurityFilterChain.doFilter(request,response,chain)
+ Cookie rememberMeCookie = getRememberMeCookie()
+ then: "response contains remember me cookie"
+ rememberMeCookie != null
+ when: "session expires"
+ super.setup()
+ request.setCookies(rememberMeCookie)
+ request.requestURI = "/abc"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ MockHttpSession session = request.getSession()
+ then: "initialized to RememberMeAuthenticationToken"
+ SecurityContext context = new HttpSessionSecurityContextRepository().loadContext(new HttpRequestResponseHolder(request, response))
+ context.getAuthentication() instanceof RememberMeAuthenticationToken
+ when: "logout"
+ super.setup()
+ request.setSession(session)
+ super.setupCsrf()
+ request.setCookies(rememberMeCookie)
+ request.servletPath = "/logout"
+ request.method = "POST"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ rememberMeCookie = getRememberMeCookie()
+ then: "logout cookie expired"
+ response.getRedirectedUrl() == "/login?logout"
+ rememberMeCookie.maxAge == 0
+ when: "use remember me after logout"
+ super.setup()
+ request.setCookies(rememberMeCookie)
+ request.requestURI = "/abc"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "sent to default login page"
+ response.getRedirectedUrl() == "http://localhost/login"
+ }
- @EnableWebSecurity
- static class RememberMeConfig extends WebSecurityConfigurerAdapter {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .anyRequest().hasRole("USER")
- .and()
- .formLogin()
- .and()
- .rememberMe()
- }
+ @EnableWebSecurity
+ static class RememberMeConfig extends WebSecurityConfigurerAdapter {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .authorizeRequests()
+ .anyRequest().hasRole("USER")
+ .and()
+ .formLogin()
+ .and()
+ .rememberMe()
+ }
- @Autowired
- public void configureGlobal(AuthenticationManagerBuilder auth) {
- auth
- .inMemoryAuthentication()
- .withUser("user").password("password").roles("USER");
- }
- }
+ @Autowired
+ public void configureGlobal(AuthenticationManagerBuilder auth) {
+ auth
+ .inMemoryAuthentication()
+ .withUser("user").password("password").roles("USER");
+ }
+ }
- Cookie createRememberMeCookie() {
- MockHttpServletRequest request = new MockHttpServletRequest()
- MockHttpServletResponse response = new MockHttpServletResponse()
- super.setupCsrf("CSRF_TOKEN", request, response)
+ Cookie createRememberMeCookie() {
+ MockHttpServletRequest request = new MockHttpServletRequest()
+ MockHttpServletResponse response = new MockHttpServletResponse()
+ super.setupCsrf("CSRF_TOKEN", request, response)
- MockFilterChain chain = new MockFilterChain()
- request.servletPath = "/login"
- request.method = "POST"
- request.parameters.username = ["user"] as String[]
- request.parameters.password = ["password"] as String[]
- request.parameters.'remember-me' = ["true"] as String[]
- springSecurityFilterChain.doFilter(request, response, chain)
- response.getCookie("remember-me")
- }
+ MockFilterChain chain = new MockFilterChain()
+ request.servletPath = "/login"
+ request.method = "POST"
+ request.parameters.username = ["user"] as String[]
+ request.parameters.password = ["password"] as String[]
+ request.parameters.'remember-me' = ["true"] as String[]
+ springSecurityFilterChain.doFilter(request, response, chain)
+ response.getCookie("remember-me")
+ }
- Cookie getRememberMeCookie(String cookieName="remember-me") {
- response.getCookie(cookieName)
- }
+ Cookie getRememberMeCookie(String cookieName="remember-me") {
+ response.getCookie(cookieName)
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/RequestCacheConfigurerTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/RequestCacheConfigurerTests.groovy
index 1d139dee0f..aafa851c6a 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/RequestCacheConfigurerTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/RequestCacheConfigurerTests.groovy
@@ -36,149 +36,149 @@ import spock.lang.Unroll;
*/
class RequestCacheConfigurerTests extends BaseSpringSpec {
- def "requestCache ObjectPostProcessor"() {
- setup:
- AnyObjectPostProcessor opp = Mock()
- HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
- when:
- http
- .requestCache()
- .and()
- .build()
+ def "requestCache ObjectPostProcessor"() {
+ setup:
+ AnyObjectPostProcessor opp = Mock()
+ HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
+ when:
+ http
+ .requestCache()
+ .and()
+ .build()
- then: "RequestCacheAwareFilter is registered with LifecycleManager"
- 1 * opp.postProcess(_ as RequestCacheAwareFilter) >> {RequestCacheAwareFilter o -> o}
- }
+ then: "RequestCacheAwareFilter is registered with LifecycleManager"
+ 1 * opp.postProcess(_ as RequestCacheAwareFilter) >> {RequestCacheAwareFilter o -> o}
+ }
- def "invoke requestCache twice does not reset"() {
- setup:
- RequestCache RC = Mock()
- AnyObjectPostProcessor opp = Mock()
- HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
- when:
- http
- .requestCache()
- .requestCache(RC)
- .and()
- .requestCache()
+ def "invoke requestCache twice does not reset"() {
+ setup:
+ RequestCache RC = Mock()
+ AnyObjectPostProcessor opp = Mock()
+ HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
+ when:
+ http
+ .requestCache()
+ .requestCache(RC)
+ .and()
+ .requestCache()
- then:
- http.getSharedObject(RequestCache) == RC
- }
+ then:
+ http.getSharedObject(RequestCache) == RC
+ }
- def "RequestCache disables faviocon.ico"() {
- setup:
- loadConfig(RequestCacheDefautlsConfig)
- request.servletPath = "/favicon.ico"
- request.requestURI = "/favicon.ico"
- request.method = "GET"
- when: "request favicon.ico"
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "sent to the login page"
- response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
- response.redirectedUrl == "http://localhost/login"
- when: "authenticate successfully"
- super.setupWeb(request.session)
- request.servletPath = "/login"
- request.setParameter("username","user")
- request.setParameter("password","password")
- request.method = "POST"
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "sent to default URL since it was favicon.ico"
- response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
- response.redirectedUrl == "/"
- }
+ def "RequestCache disables faviocon.ico"() {
+ setup:
+ loadConfig(RequestCacheDefautlsConfig)
+ request.servletPath = "/favicon.ico"
+ request.requestURI = "/favicon.ico"
+ request.method = "GET"
+ when: "request favicon.ico"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "sent to the login page"
+ response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
+ response.redirectedUrl == "http://localhost/login"
+ when: "authenticate successfully"
+ super.setupWeb(request.session)
+ request.servletPath = "/login"
+ request.setParameter("username","user")
+ request.setParameter("password","password")
+ request.method = "POST"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "sent to default URL since it was favicon.ico"
+ response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
+ response.redirectedUrl == "/"
+ }
- def "SEC-2321: RequestCache disables application/json"() {
- setup:
- loadConfig(RequestCacheDefautlsConfig)
- request.addHeader("Accept", MediaType.APPLICATION_JSON_VALUE)
- request.method = "GET"
- request.servletPath = "/messages"
- request.requestURI = "/messages"
- when: "request application/json"
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "sent to the login page"
- response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
- response.redirectedUrl == "http://localhost/login"
- when: "authenticate successfully"
- super.setupWeb(request.session)
- request.servletPath = "/login"
- request.setParameter("username","user")
- request.setParameter("password","password")
- request.method = "POST"
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "sent to default URL since it was 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"
- response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
- response.redirectedUrl == "/"
- }
+ def "SEC-2321: RequestCache disables application/json"() {
+ setup:
+ loadConfig(RequestCacheDefautlsConfig)
+ request.addHeader("Accept", MediaType.APPLICATION_JSON_VALUE)
+ request.method = "GET"
+ request.servletPath = "/messages"
+ request.requestURI = "/messages"
+ when: "request application/json"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "sent to the login page"
+ response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
+ response.redirectedUrl == "http://localhost/login"
+ when: "authenticate successfully"
+ super.setupWeb(request.session)
+ request.servletPath = "/login"
+ request.setParameter("username","user")
+ request.setParameter("password","password")
+ request.method = "POST"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "sent to default URL since it was 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"
+ response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
+ response.redirectedUrl == "/"
+ }
- def "SEC-2321: RequestCache disables X-Requested-With"() {
- setup:
- loadConfig(RequestCacheDefautlsConfig)
- request.addHeader("X-Requested-With", "XMLHttpRequest")
- request.method = "GET"
- request.servletPath = "/messages"
- request.requestURI = "/messages"
- when: "request X-Requested-With"
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "sent to the login page"
- response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
- response.redirectedUrl == "http://localhost/login"
- when: "authenticate successfully"
- super.setupWeb(request.session)
- request.servletPath = "/login"
- request.setParameter("username","user")
- request.setParameter("password","password")
- request.method = "POST"
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "sent to default URL since it was X-Requested-With"
- response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
- response.redirectedUrl == "/"
- }
+ def "SEC-2321: RequestCache disables X-Requested-With"() {
+ setup:
+ loadConfig(RequestCacheDefautlsConfig)
+ request.addHeader("X-Requested-With", "XMLHttpRequest")
+ request.method = "GET"
+ request.servletPath = "/messages"
+ request.requestURI = "/messages"
+ when: "request X-Requested-With"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "sent to the login page"
+ response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
+ response.redirectedUrl == "http://localhost/login"
+ when: "authenticate successfully"
+ super.setupWeb(request.session)
+ request.servletPath = "/login"
+ request.setParameter("username","user")
+ request.setParameter("password","password")
+ request.method = "POST"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "sent to default URL since it was X-Requested-With"
+ response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
+ response.redirectedUrl == "/"
+ }
- @Unroll
- def "RequestCache saves #headerName: #headerValue"() {
- setup:
- loadConfig(RequestCacheDefautlsConfig)
- request.addHeader(headerName, headerValue)
- request.method = "GET"
- request.servletPath = "/messages"
- request.requestURI = "/messages"
- when: "request content type"
- springSecurityFilterChain.doFilter(request,response,chain)
- super.setupWeb(request.session)
- request.servletPath = "/login"
- request.setParameter("username","user")
- request.setParameter("password","password")
- request.method = "POST"
- springSecurityFilterChain.doFilter(request,response,chain)
- then: "sent to saved URL"
- response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
- response.redirectedUrl == "http://localhost/messages"
- where:
- headerName << ["Accept", "Accept", "Accept", "X-Requested-With"]
- headerValue << [MediaType.ALL_VALUE, MediaType.TEXT_HTML, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8","com.android"]
+ @Unroll
+ def "RequestCache saves #headerName: #headerValue"() {
+ setup:
+ loadConfig(RequestCacheDefautlsConfig)
+ request.addHeader(headerName, headerValue)
+ request.method = "GET"
+ request.servletPath = "/messages"
+ request.requestURI = "/messages"
+ when: "request content type"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ super.setupWeb(request.session)
+ request.servletPath = "/login"
+ request.setParameter("username","user")
+ request.setParameter("password","password")
+ request.method = "POST"
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then: "sent to saved URL"
+ response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
+ response.redirectedUrl == "http://localhost/messages"
+ where:
+ headerName << ["Accept", "Accept", "Accept", "X-Requested-With"]
+ headerValue << [MediaType.ALL_VALUE, MediaType.TEXT_HTML, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8","com.android"]
- }
+ }
- @EnableWebSecurity
- static class RequestCacheDefautlsConfig extends WebSecurityConfigurerAdapter {
+ @EnableWebSecurity
+ static class RequestCacheDefautlsConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .anyRequest().authenticated()
- .and()
- .formLogin()
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .authorizeRequests()
+ .anyRequest().authenticated()
+ .and()
+ .formLogin()
+ }
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth
- .inMemoryAuthentication()
- .withUser("user").password("password").roles("USER")
- }
- }
+ @Override
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth
+ .inMemoryAuthentication()
+ .withUser("user").password("password").roles("USER")
+ }
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/RequestMatcherConfigurerTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/RequestMatcherConfigurerTests.groovy
index 4df6a7e097..a233eeaa78 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/RequestMatcherConfigurerTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/RequestMatcherConfigurerTests.groovy
@@ -51,34 +51,34 @@ import spock.lang.Unroll;
class RequestMatcherConfigurerTests extends BaseSpringSpec {
- @Unroll
- def "SEC-2908 - multiple invocations of authorizeRequests() chains #path"(def path) {
- setup:
- loadConfig(Sec2908Config)
- request.servletPath = path
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.status == HttpServletResponse.SC_FORBIDDEN
- where:
- path << ['/oauth/abc','/api/abc']
- }
+ @Unroll
+ def "SEC-2908 - multiple invocations of authorizeRequests() chains #path"(def path) {
+ setup:
+ loadConfig(Sec2908Config)
+ request.servletPath = path
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.status == HttpServletResponse.SC_FORBIDDEN
+ where:
+ path << ['/oauth/abc','/api/abc']
+ }
- @Configuration
- @EnableWebSecurity
- static class Sec2908Config extends WebSecurityConfigurerAdapter {
+ @Configuration
+ @EnableWebSecurity
+ static class Sec2908Config extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .requestMatchers()
- .antMatchers("/api/**")
- .and()
- .requestMatchers()
- .antMatchers("/oauth/**")
- .and()
- .authorizeRequests()
- .anyRequest().denyAll();
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .requestMatchers()
+ .antMatchers("/api/**")
+ .and()
+ .requestMatchers()
+ .antMatchers("/oauth/**")
+ .and()
+ .authorizeRequests()
+ .anyRequest().denyAll();
+ }
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/SecurityContextConfigurerTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/SecurityContextConfigurerTests.groovy
index 07f6e2e693..ac509e5235 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/SecurityContextConfigurerTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/SecurityContextConfigurerTests.groovy
@@ -31,40 +31,40 @@ import org.springframework.security.web.context.SecurityContextRepository
*/
class SecurityContextConfigurerTests extends BaseSpringSpec {
- def "securityContext ObjectPostProcessor"() {
- setup:
- AnyObjectPostProcessor opp = Mock()
- HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
- when:
- http
- .securityContext()
- .and()
- .build()
+ def "securityContext ObjectPostProcessor"() {
+ setup:
+ AnyObjectPostProcessor opp = Mock()
+ HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
+ when:
+ http
+ .securityContext()
+ .and()
+ .build()
- then: "SecurityContextPersistenceFilter is registered with LifecycleManager"
- 1 * opp.postProcess(_ as SecurityContextPersistenceFilter) >> {SecurityContextPersistenceFilter o -> o}
- }
+ then: "SecurityContextPersistenceFilter is registered with LifecycleManager"
+ 1 * opp.postProcess(_ as SecurityContextPersistenceFilter) >> {SecurityContextPersistenceFilter o -> o}
+ }
- def "invoke securityContext twice does not override"() {
- setup:
- InvokeTwiceDoesNotOverrideConfig.SCR = Mock(SecurityContextRepository)
- when:
- loadConfig(InvokeTwiceDoesNotOverrideConfig)
- then:
- findFilter(SecurityContextPersistenceFilter).repo == InvokeTwiceDoesNotOverrideConfig.SCR
- }
+ def "invoke securityContext twice does not override"() {
+ setup:
+ InvokeTwiceDoesNotOverrideConfig.SCR = Mock(SecurityContextRepository)
+ when:
+ loadConfig(InvokeTwiceDoesNotOverrideConfig)
+ then:
+ findFilter(SecurityContextPersistenceFilter).repo == InvokeTwiceDoesNotOverrideConfig.SCR
+ }
- @EnableWebSecurity
- static class InvokeTwiceDoesNotOverrideConfig extends WebSecurityConfigurerAdapter {
- static SecurityContextRepository SCR
+ @EnableWebSecurity
+ static class InvokeTwiceDoesNotOverrideConfig extends WebSecurityConfigurerAdapter {
+ static SecurityContextRepository SCR
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .securityContext()
- .securityContextRepository(SCR)
- .and()
- .securityContext()
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .securityContext()
+ .securityContextRepository(SCR)
+ .and()
+ .securityContext()
+ }
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/ServletApiConfigurerTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/ServletApiConfigurerTests.groovy
index a87b7d40e7..414bdaac73 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/ServletApiConfigurerTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/ServletApiConfigurerTests.groovy
@@ -36,116 +36,116 @@ import org.springframework.security.web.servletapi.SecurityContextHolderAwareReq
*/
class ServletApiConfigurerTests extends BaseSpringSpec {
- def "servletApi ObjectPostProcessor"() {
- setup:
- AnyObjectPostProcessor opp = Mock()
- HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
- when:
- http
- .servletApi()
- .and()
- .build()
+ def "servletApi ObjectPostProcessor"() {
+ setup:
+ AnyObjectPostProcessor opp = Mock()
+ HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
+ when:
+ http
+ .servletApi()
+ .and()
+ .build()
- then: "SecurityContextHolderAwareRequestFilter is registered with LifecycleManager"
- 1 * opp.postProcess(_ as SecurityContextHolderAwareRequestFilter) >> {SecurityContextHolderAwareRequestFilter o -> o}
- }
+ then: "SecurityContextHolderAwareRequestFilter is registered with LifecycleManager"
+ 1 * opp.postProcess(_ as SecurityContextHolderAwareRequestFilter) >> {SecurityContextHolderAwareRequestFilter o -> o}
+ }
- def "SecurityContextHolderAwareRequestFilter properties set"() {
- when:
- loadConfig(ServletApiConfig)
- SecurityContextHolderAwareRequestFilter filter = findFilter(SecurityContextHolderAwareRequestFilter)
- then: "SEC-2215: authenticationManager != null"
- filter.authenticationManager != null
- and: "authenticationEntryPoint != null"
- filter.authenticationEntryPoint != null
- and: "requestFactory != null"
- filter.requestFactory != null
- and: "logoutHandlers populated"
- filter.logoutHandlers.collect { it.class } == [CsrfLogoutHandler, SecurityContextLogoutHandler]
- }
+ def "SecurityContextHolderAwareRequestFilter properties set"() {
+ when:
+ loadConfig(ServletApiConfig)
+ SecurityContextHolderAwareRequestFilter filter = findFilter(SecurityContextHolderAwareRequestFilter)
+ then: "SEC-2215: authenticationManager != null"
+ filter.authenticationManager != null
+ and: "authenticationEntryPoint != null"
+ filter.authenticationEntryPoint != null
+ and: "requestFactory != null"
+ filter.requestFactory != null
+ and: "logoutHandlers populated"
+ filter.logoutHandlers.collect { it.class } == [CsrfLogoutHandler, SecurityContextLogoutHandler]
+ }
- @CompileStatic
- @EnableWebSecurity
- static class ServletApiConfig extends WebSecurityConfigurerAdapter {
+ @CompileStatic
+ @EnableWebSecurity
+ static class ServletApiConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth
- .inMemoryAuthentication()
- .withUser("user").password("password").roles("USER")
- }
- }
+ @Override
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth
+ .inMemoryAuthentication()
+ .withUser("user").password("password").roles("USER")
+ }
+ }
- def "SecurityContextHolderAwareRequestFilter.authenticationEntryPoint = customEntryPoint"() {
- setup:
- CustomEntryPointConfig.ENTRYPOINT = Mock(AuthenticationEntryPoint)
- when: "load config with customEntryPoint"
- loadConfig(CustomEntryPointConfig)
- then: "SecurityContextHolderAwareRequestFilter.authenticationEntryPoint == customEntryPoint"
- findFilter(SecurityContextHolderAwareRequestFilter).authenticationEntryPoint == CustomEntryPointConfig.ENTRYPOINT
- }
+ def "SecurityContextHolderAwareRequestFilter.authenticationEntryPoint = customEntryPoint"() {
+ setup:
+ CustomEntryPointConfig.ENTRYPOINT = Mock(AuthenticationEntryPoint)
+ when: "load config with customEntryPoint"
+ loadConfig(CustomEntryPointConfig)
+ then: "SecurityContextHolderAwareRequestFilter.authenticationEntryPoint == customEntryPoint"
+ findFilter(SecurityContextHolderAwareRequestFilter).authenticationEntryPoint == CustomEntryPointConfig.ENTRYPOINT
+ }
- @EnableWebSecurity
- static class CustomEntryPointConfig extends WebSecurityConfigurerAdapter {
- static AuthenticationEntryPoint ENTRYPOINT
+ @EnableWebSecurity
+ static class CustomEntryPointConfig extends WebSecurityConfigurerAdapter {
+ static AuthenticationEntryPoint ENTRYPOINT
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .exceptionHandling()
- .authenticationEntryPoint(ENTRYPOINT)
- .and()
- .formLogin()
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .exceptionHandling()
+ .authenticationEntryPoint(ENTRYPOINT)
+ .and()
+ .formLogin()
+ }
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth
- .inMemoryAuthentication()
- .withUser("user").password("password").roles("USER")
- }
- }
+ @Override
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth
+ .inMemoryAuthentication()
+ .withUser("user").password("password").roles("USER")
+ }
+ }
- def "invoke servletApi twice does not override"() {
- setup:
- InvokeTwiceDoesNotOverrideConfig.ENTRYPOINT = Mock(AuthenticationEntryPoint)
- when:
- loadConfig(InvokeTwiceDoesNotOverrideConfig)
- then:
- findFilter(SecurityContextHolderAwareRequestFilter).authenticationEntryPoint == InvokeTwiceDoesNotOverrideConfig.ENTRYPOINT
- }
+ def "invoke servletApi twice does not override"() {
+ setup:
+ InvokeTwiceDoesNotOverrideConfig.ENTRYPOINT = Mock(AuthenticationEntryPoint)
+ when:
+ loadConfig(InvokeTwiceDoesNotOverrideConfig)
+ then:
+ findFilter(SecurityContextHolderAwareRequestFilter).authenticationEntryPoint == InvokeTwiceDoesNotOverrideConfig.ENTRYPOINT
+ }
- @EnableWebSecurity
- static class InvokeTwiceDoesNotOverrideConfig extends WebSecurityConfigurerAdapter {
- static AuthenticationEntryPoint ENTRYPOINT
+ @EnableWebSecurity
+ static class InvokeTwiceDoesNotOverrideConfig extends WebSecurityConfigurerAdapter {
+ static AuthenticationEntryPoint ENTRYPOINT
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .exceptionHandling()
- .authenticationEntryPoint(ENTRYPOINT)
- .and()
- .exceptionHandling()
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .exceptionHandling()
+ .authenticationEntryPoint(ENTRYPOINT)
+ .and()
+ .exceptionHandling()
+ }
+ }
- def "use sharedObject trustResolver"() {
- setup:
- SharedTrustResolverConfig.TR = Mock(AuthenticationTrustResolver)
- when:
- loadConfig(SharedTrustResolverConfig)
- then:
- findFilter(SecurityContextHolderAwareRequestFilter).trustResolver == SharedTrustResolverConfig.TR
- }
+ def "use sharedObject trustResolver"() {
+ setup:
+ SharedTrustResolverConfig.TR = Mock(AuthenticationTrustResolver)
+ when:
+ loadConfig(SharedTrustResolverConfig)
+ then:
+ findFilter(SecurityContextHolderAwareRequestFilter).trustResolver == SharedTrustResolverConfig.TR
+ }
- @EnableWebSecurity
- static class SharedTrustResolverConfig extends WebSecurityConfigurerAdapter {
- static AuthenticationTrustResolver TR
+ @EnableWebSecurity
+ static class SharedTrustResolverConfig extends WebSecurityConfigurerAdapter {
+ static AuthenticationTrustResolver TR
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .setSharedObject(AuthenticationTrustResolver, TR)
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .setSharedObject(AuthenticationTrustResolver, TR)
+ }
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/UrlAuthorizationsTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/UrlAuthorizationsTests.groovy
index c9da5a5c49..e42590bb85 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/UrlAuthorizationsTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/UrlAuthorizationsTests.groovy
@@ -32,48 +32,48 @@ import org.springframework.security.web.access.intercept.FilterSecurityIntercept
*/
public class UrlAuthorizationsTests extends BaseSpringSpec {
- def "hasAnyAuthority('ROLE_USER')"() {
- when:
- def expression = UrlAuthorizationConfigurer.hasAnyAuthority("ROLE_USER")
- then:
- expression == ["ROLE_USER"]
- }
+ def "hasAnyAuthority('ROLE_USER')"() {
+ when:
+ def expression = UrlAuthorizationConfigurer.hasAnyAuthority("ROLE_USER")
+ then:
+ expression == ["ROLE_USER"]
+ }
- def "hasAnyAuthority('ROLE_USER','ROLE_ADMIN')"() {
- when:
- def expression = UrlAuthorizationConfigurer.hasAnyAuthority("ROLE_USER","ROLE_ADMIN")
- then:
- expression == ["ROLE_USER","ROLE_ADMIN"]
- }
+ def "hasAnyAuthority('ROLE_USER','ROLE_ADMIN')"() {
+ when:
+ def expression = UrlAuthorizationConfigurer.hasAnyAuthority("ROLE_USER","ROLE_ADMIN")
+ then:
+ expression == ["ROLE_USER","ROLE_ADMIN"]
+ }
- def "hasAnyRole('USER')"() {
- when:
- def expression = UrlAuthorizationConfigurer.hasAnyRole("USER")
- then:
- expression == ["ROLE_USER"]
- }
+ def "hasAnyRole('USER')"() {
+ when:
+ def expression = UrlAuthorizationConfigurer.hasAnyRole("USER")
+ then:
+ expression == ["ROLE_USER"]
+ }
- def "hasAnyRole('ROLE_USER','ROLE_ADMIN')"() {
- when:
- def expression = UrlAuthorizationConfigurer.hasAnyRole("USER","ADMIN")
- then:
- expression == ["ROLE_USER","ROLE_ADMIN"]
- }
+ def "hasAnyRole('ROLE_USER','ROLE_ADMIN')"() {
+ when:
+ def expression = UrlAuthorizationConfigurer.hasAnyRole("USER","ADMIN")
+ then:
+ expression == ["ROLE_USER","ROLE_ADMIN"]
+ }
- def "uses AffirmativeBased AccessDecisionManager"() {
- when: "Load Config with no specific AccessDecisionManager"
- loadConfig(NoSpecificAccessDecessionManagerConfig)
- then: "AccessDecessionManager matches the HttpSecurityBuilder's default"
- findFilter(FilterSecurityInterceptor).accessDecisionManager.class == AffirmativeBased
- }
+ def "uses AffirmativeBased AccessDecisionManager"() {
+ when: "Load Config with no specific AccessDecisionManager"
+ loadConfig(NoSpecificAccessDecessionManagerConfig)
+ then: "AccessDecessionManager matches the HttpSecurityBuilder's default"
+ findFilter(FilterSecurityInterceptor).accessDecisionManager.class == AffirmativeBased
+ }
- @EnableWebSecurity
- static class NoSpecificAccessDecessionManagerConfig extends WebSecurityConfigurerAdapter {
- protected void configure(HttpSecurity http) throws Exception {
- http
- .apply(new UrlAuthorizationConfigurer()).getRegistry()
- .antMatchers("/a").hasRole("ADMIN")
- .anyRequest().hasRole("USER")
- }
- }
+ @EnableWebSecurity
+ static class NoSpecificAccessDecessionManagerConfig extends WebSecurityConfigurerAdapter {
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .apply(new UrlAuthorizationConfigurer()).getRegistry()
+ .antMatchers("/a").hasRole("ADMIN")
+ .anyRequest().hasRole("USER")
+ }
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/X509ConfigurerTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/X509ConfigurerTests.groovy
index f536a3f334..a76e8dd72c 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/X509ConfigurerTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/X509ConfigurerTests.groovy
@@ -30,31 +30,31 @@ import org.springframework.security.web.authentication.preauth.x509.X509Authenti
*/
class X509ConfigurerTests extends BaseSpringSpec {
- def "x509 ObjectPostProcessor"() {
- setup:
- AnyObjectPostProcessor opp = Mock()
- HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
- when:
- http
- .x509()
- .and()
- .build()
+ def "x509 ObjectPostProcessor"() {
+ setup:
+ AnyObjectPostProcessor opp = Mock()
+ HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
+ when:
+ http
+ .x509()
+ .and()
+ .build()
- then: "X509AuthenticationFilter is registered with LifecycleManager"
- 1 * opp.postProcess(_ as X509AuthenticationFilter) >> {X509AuthenticationFilter o -> o}
- }
+ then: "X509AuthenticationFilter is registered with LifecycleManager"
+ 1 * opp.postProcess(_ as X509AuthenticationFilter) >> {X509AuthenticationFilter o -> o}
+ }
- def "invoke x509 twice does not override"() {
- setup:
- AnyObjectPostProcessor opp = Mock()
- HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
- when:
- http
- .x509()
- .subjectPrincipalRegex(".*")
- .and()
- .x509()
- then:
- http.getConfigurer(X509Configurer).subjectPrincipalRegex == ".*"
- }
+ def "invoke x509 twice does not override"() {
+ setup:
+ AnyObjectPostProcessor opp = Mock()
+ HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
+ when:
+ http
+ .x509()
+ .subjectPrincipalRegex(".*")
+ .and()
+ .x509()
+ then:
+ http.getConfigurer(X509Configurer).subjectPrincipalRegex == ".*"
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/openid/OpenIDLoginConfigurerTests.groovy b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/openid/OpenIDLoginConfigurerTests.groovy
index 6e5986e877..6eba5bd854 100644
--- a/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/openid/OpenIDLoginConfigurerTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/openid/OpenIDLoginConfigurerTests.groovy
@@ -34,53 +34,53 @@ import org.springframework.security.openid.OpenIDAuthenticationToken
*/
class OpenIDLoginConfigurerTests extends BaseSpringSpec {
- def "openidLogin ObjectPostProcessor"() {
- setup:
- AnyObjectPostProcessor opp = Mock()
- HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
- UserDetailsService uds = authenticationBldr.getDefaultUserDetailsService()
- when:
- http
- .openidLogin()
- .authenticationUserDetailsService(new UserDetailsByNameServiceWrapper(uds))
- .and()
- .build()
+ def "openidLogin ObjectPostProcessor"() {
+ setup:
+ AnyObjectPostProcessor opp = Mock()
+ HttpSecurity http = new HttpSecurity(opp, authenticationBldr, [:])
+ UserDetailsService uds = authenticationBldr.getDefaultUserDetailsService()
+ when:
+ http
+ .openidLogin()
+ .authenticationUserDetailsService(new UserDetailsByNameServiceWrapper(uds))
+ .and()
+ .build()
- then: "OpenIDAuthenticationFilter is registered with LifecycleManager"
- 1 * opp.postProcess(_ as OpenIDAuthenticationFilter) >> {OpenIDAuthenticationFilter o -> o}
- and: "OpenIDAuthenticationProvider is registered with LifecycleManager"
- 1 * opp.postProcess(_ as OpenIDAuthenticationProvider) >> {OpenIDAuthenticationProvider o -> o}
- }
+ then: "OpenIDAuthenticationFilter is registered with LifecycleManager"
+ 1 * opp.postProcess(_ as OpenIDAuthenticationFilter) >> {OpenIDAuthenticationFilter o -> o}
+ and: "OpenIDAuthenticationProvider is registered with LifecycleManager"
+ 1 * opp.postProcess(_ as OpenIDAuthenticationProvider) >> {OpenIDAuthenticationProvider o -> o}
+ }
- def "invoke openidLogin twice does not override"() {
- setup:
- loadConfig(InvokeTwiceDoesNotOverrideConfig)
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.redirectedUrl.endsWith("/login/custom")
+ def "invoke openidLogin twice does not override"() {
+ setup:
+ loadConfig(InvokeTwiceDoesNotOverrideConfig)
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.redirectedUrl.endsWith("/login/custom")
- }
+ }
- @EnableWebSecurity
- static class InvokeTwiceDoesNotOverrideConfig extends WebSecurityConfigurerAdapter {
+ @EnableWebSecurity
+ static class InvokeTwiceDoesNotOverrideConfig extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth
- .inMemoryAuthentication()
- }
+ @Override
+ protected void configure(AuthenticationManagerBuilder auth) throws Exception {
+ auth
+ .inMemoryAuthentication()
+ }
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .authorizeRequests()
- .anyRequest().authenticated()
- .and()
- .openidLogin()
- .loginPage("/login/custom")
- .and()
- .openidLogin()
- }
- }
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .authorizeRequests()
+ .anyRequest().authenticated()
+ .and()
+ .openidLogin()
+ .loginPage("/login/custom")
+ .and()
+ .openidLogin()
+ }
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/debug/SecurityDebugBeanFactoryPostProcessorTest.groovy b/config/src/test/groovy/org/springframework/security/config/debug/SecurityDebugBeanFactoryPostProcessorTest.groovy
index 43eb213f58..60c7779b86 100644
--- a/config/src/test/groovy/org/springframework/security/config/debug/SecurityDebugBeanFactoryPostProcessorTest.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/debug/SecurityDebugBeanFactoryPostProcessorTest.groovy
@@ -22,18 +22,18 @@ import org.springframework.security.web.debug.DebugFilter;
class SecurityDebugBeanFactoryPostProcessorTest extends AbstractHttpConfigTests {
- // SEC-1885
- def 'SEC-1885 - SecurityDebugBeanFactoryPostProcessor works when dependencies have Autowired constructor'() {
- when: 'debug used and FilterChainProxy has dependency with @Autowired constructor'
- xml.debug()
- httpAutoConfig {}
- xml.'authentication-manager'() {
- 'authentication-provider'('ref': 'authProvider')
- }
- xml.'context:component-scan'('base-package':'org.springframework.security.config.debug')
- createAppContext('')
- then: 'TestAuthenticationProvider.() is not thrown'
- appContext.getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN) instanceof DebugFilter
- appContext.getBean(BeanIds.FILTER_CHAIN_PROXY) instanceof FilterChainProxy
- }
+ // SEC-1885
+ def 'SEC-1885 - SecurityDebugBeanFactoryPostProcessor works when dependencies have Autowired constructor'() {
+ when: 'debug used and FilterChainProxy has dependency with @Autowired constructor'
+ xml.debug()
+ httpAutoConfig {}
+ xml.'authentication-manager'() {
+ 'authentication-provider'('ref': 'authProvider')
+ }
+ xml.'context:component-scan'('base-package':'org.springframework.security.config.debug')
+ createAppContext('')
+ then: 'TestAuthenticationProvider.() is not thrown'
+ appContext.getBean(BeanIds.SPRING_SECURITY_FILTER_CHAIN) instanceof DebugFilter
+ appContext.getBean(BeanIds.FILTER_CHAIN_PROXY) instanceof FilterChainProxy
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/http/FormLoginBeanDefinitionParserTests.groovy b/config/src/test/groovy/org/springframework/security/config/http/FormLoginBeanDefinitionParserTests.groovy
index d8def9663a..42c8d9b49a 100644
--- a/config/src/test/groovy/org/springframework/security/config/http/FormLoginBeanDefinitionParserTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/http/FormLoginBeanDefinitionParserTests.groovy
@@ -10,104 +10,104 @@ import org.springframework.mock.web.MockHttpServletResponse
*/
class FormLoginBeanDefinitionParserTests extends AbstractHttpConfigTests {
- def 'form-login default login page'() {
- setup:
- MockHttpServletRequest request = new MockHttpServletRequest(method:'GET',requestURI:'/login')
- MockHttpServletResponse response = new MockHttpServletResponse()
- MockFilterChain chain = new MockFilterChain()
- httpAutoConfig {
- csrf(disabled:true)
- }
- createAppContext()
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.getContentAsString() == """Login Page
+ def 'form-login default login page'() {
+ setup:
+ MockHttpServletRequest request = new MockHttpServletRequest(method:'GET',requestURI:'/login')
+ MockHttpServletResponse response = new MockHttpServletResponse()
+ MockFilterChain chain = new MockFilterChain()
+ httpAutoConfig {
+ csrf(disabled:true)
+ }
+ createAppContext()
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.getContentAsString() == """Login Page
Login with Username and Password
"""
- }
+ }
- def 'form-login default login page custom attributes'() {
- setup:
- MockHttpServletRequest request = new MockHttpServletRequest(method:'GET',requestURI:'/login')
- MockHttpServletResponse response = new MockHttpServletResponse()
- MockFilterChain chain = new MockFilterChain()
- httpAutoConfig {
- 'form-login'('login-processing-url':'/login_custom','username-parameter':'custom_user','password-parameter':'custom_password')
- csrf(disabled:true)
- }
- createAppContext()
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.getContentAsString() == """Login Page
+ def 'form-login default login page custom attributes'() {
+ setup:
+ MockHttpServletRequest request = new MockHttpServletRequest(method:'GET',requestURI:'/login')
+ MockHttpServletResponse response = new MockHttpServletResponse()
+ MockFilterChain chain = new MockFilterChain()
+ httpAutoConfig {
+ 'form-login'('login-processing-url':'/login_custom','username-parameter':'custom_user','password-parameter':'custom_password')
+ csrf(disabled:true)
+ }
+ createAppContext()
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.getContentAsString() == """Login Page
Login with Username and Password
"""
- }
+ }
- def 'openid-login default login page'() {
- setup:
- MockHttpServletRequest request = new MockHttpServletRequest(method:'GET',requestURI:'/login')
- MockHttpServletResponse response = new MockHttpServletResponse()
- MockFilterChain chain = new MockFilterChain()
- httpAutoConfig {
- 'openid-login'()
- csrf(disabled:true)
- }
- createAppContext()
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.getContentAsString() == """Login Page
+ def 'openid-login default login page'() {
+ setup:
+ MockHttpServletRequest request = new MockHttpServletRequest(method:'GET',requestURI:'/login')
+ MockHttpServletResponse response = new MockHttpServletResponse()
+ MockFilterChain chain = new MockFilterChain()
+ httpAutoConfig {
+ 'openid-login'()
+ csrf(disabled:true)
+ }
+ createAppContext()
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.getContentAsString() == """Login Page
Login with Username and Password
Login with OpenID Identity
"""
- }
+ }
- def 'openid-login default login page custom attributes'() {
- setup:
- MockHttpServletRequest request = new MockHttpServletRequest(method:'GET',requestURI:'/login')
- MockHttpServletResponse response = new MockHttpServletResponse()
- MockFilterChain chain = new MockFilterChain()
- httpAutoConfig {
- 'openid-login'('login-processing-url':'/login_custom')
- csrf(disabled:true)
- }
- createAppContext()
- when:
- springSecurityFilterChain.doFilter(request,response,chain)
- then:
- response.getContentAsString() == """Login Page
+ def 'openid-login default login page custom attributes'() {
+ setup:
+ MockHttpServletRequest request = new MockHttpServletRequest(method:'GET',requestURI:'/login')
+ MockHttpServletResponse response = new MockHttpServletResponse()
+ MockFilterChain chain = new MockFilterChain()
+ httpAutoConfig {
+ 'openid-login'('login-processing-url':'/login_custom')
+ csrf(disabled:true)
+ }
+ createAppContext()
+ when:
+ springSecurityFilterChain.doFilter(request,response,chain)
+ then:
+ response.getContentAsString() == """Login Page
Login with Username and Password
Login with OpenID Identity
"""
- }
+ }
}
diff --git a/config/src/test/groovy/org/springframework/security/config/http/SecurityContextHolderAwareRequestConfigTests.groovy b/config/src/test/groovy/org/springframework/security/config/http/SecurityContextHolderAwareRequestConfigTests.groovy
index b9aa986262..003ce4ab3a 100644
--- a/config/src/test/groovy/org/springframework/security/config/http/SecurityContextHolderAwareRequestConfigTests.groovy
+++ b/config/src/test/groovy/org/springframework/security/config/http/SecurityContextHolderAwareRequestConfigTests.groovy
@@ -45,101 +45,101 @@ import org.springframework.security.web.servletapi.SecurityContextHolderAwareReq
*/
class SecurityContextHolderAwareRequestConfigTests extends AbstractHttpConfigTests {
- def withAutoConfig() {
- httpAutoConfig () {
- csrf(disabled:true)
- }
- createAppContext(AUTH_PROVIDER_XML)
+ def withAutoConfig() {
+ httpAutoConfig () {
+ csrf(disabled:true)
+ }
+ createAppContext(AUTH_PROVIDER_XML)
- def securityContextAwareFilter = getFilter(SecurityContextHolderAwareRequestFilter)
+ def securityContextAwareFilter = getFilter(SecurityContextHolderAwareRequestFilter)
- expect:
- securityContextAwareFilter.authenticationEntryPoint.loginFormUrl == getFilter(ExceptionTranslationFilter).authenticationEntryPoint.loginFormUrl
- securityContextAwareFilter.authenticationManager == getFilter(UsernamePasswordAuthenticationFilter).authenticationManager
- securityContextAwareFilter.logoutHandlers.size() == 1
- securityContextAwareFilter.logoutHandlers[0].class == SecurityContextLogoutHandler
- }
+ expect:
+ securityContextAwareFilter.authenticationEntryPoint.loginFormUrl == getFilter(ExceptionTranslationFilter).authenticationEntryPoint.loginFormUrl
+ securityContextAwareFilter.authenticationManager == getFilter(UsernamePasswordAuthenticationFilter).authenticationManager
+ securityContextAwareFilter.logoutHandlers.size() == 1
+ securityContextAwareFilter.logoutHandlers[0].class == SecurityContextLogoutHandler
+ }
- def explicitEntryPoint() {
- xml.http() {
- 'http-basic'('entry-point-ref': 'ep')
- }
- bean('ep', BasicAuthenticationEntryPoint.class.name, ['realmName':'whocares'],[:])
- createAppContext(AUTH_PROVIDER_XML)
+ def explicitEntryPoint() {
+ xml.http() {
+ 'http-basic'('entry-point-ref': 'ep')
+ }
+ bean('ep', BasicAuthenticationEntryPoint.class.name, ['realmName':'whocares'],[:])
+ createAppContext(AUTH_PROVIDER_XML)
- def securityContextAwareFilter = getFilter(SecurityContextHolderAwareRequestFilter)
+ def securityContextAwareFilter = getFilter(SecurityContextHolderAwareRequestFilter)
- expect:
- securityContextAwareFilter.authenticationEntryPoint == getFilter(ExceptionTranslationFilter).authenticationEntryPoint
- securityContextAwareFilter.authenticationManager == getFilter(BasicAuthenticationFilter).authenticationManager
- securityContextAwareFilter.logoutHandlers == null
- }
+ expect:
+ securityContextAwareFilter.authenticationEntryPoint == getFilter(ExceptionTranslationFilter).authenticationEntryPoint
+ securityContextAwareFilter.authenticationManager == getFilter(BasicAuthenticationFilter).authenticationManager
+ securityContextAwareFilter.logoutHandlers == null
+ }
- def formLogin() {
- xml.http() {
- 'form-login'()
- }
- createAppContext(AUTH_PROVIDER_XML)
+ def formLogin() {
+ xml.http() {
+ 'form-login'()
+ }
+ createAppContext(AUTH_PROVIDER_XML)
- def securityContextAwareFilter = getFilter(SecurityContextHolderAwareRequestFilter)
+ def securityContextAwareFilter = getFilter(SecurityContextHolderAwareRequestFilter)
- expect:
- securityContextAwareFilter.authenticationEntryPoint.loginFormUrl == getFilter(ExceptionTranslationFilter).authenticationEntryPoint.loginFormUrl
- securityContextAwareFilter.authenticationManager == getFilter(UsernamePasswordAuthenticationFilter).authenticationManager
- securityContextAwareFilter.logoutHandlers == null
- }
+ expect:
+ securityContextAwareFilter.authenticationEntryPoint.loginFormUrl == getFilter(ExceptionTranslationFilter).authenticationEntryPoint.loginFormUrl
+ securityContextAwareFilter.authenticationManager == getFilter(UsernamePasswordAuthenticationFilter).authenticationManager
+ securityContextAwareFilter.logoutHandlers == null
+ }
- def multiHttp() {
- xml.http('authentication-manager-ref' : 'authManager', 'pattern' : '/first/**') {
- 'form-login'('login-page' : '/login')
- 'logout'('invalidate-session' : 'true')
- csrf(disabled:true)
- }
- xml.http('authentication-manager-ref' : 'authManager2') {
- 'form-login'('login-page' : '/login2')
- 'logout'('invalidate-session' : 'false')
- csrf(disabled:true)
- }
+ def multiHttp() {
+ xml.http('authentication-manager-ref' : 'authManager', 'pattern' : '/first/**') {
+ 'form-login'('login-page' : '/login')
+ 'logout'('invalidate-session' : 'true')
+ csrf(disabled:true)
+ }
+ xml.http('authentication-manager-ref' : 'authManager2') {
+ 'form-login'('login-page' : '/login2')
+ 'logout'('invalidate-session' : 'false')
+ csrf(disabled:true)
+ }
- String secondAuthManager = AUTH_PROVIDER_XML.replace("alias='authManager'", "id='authManager2'")
- createAppContext(AUTH_PROVIDER_XML + secondAuthManager)
+ String secondAuthManager = AUTH_PROVIDER_XML.replace("alias='authManager'", "id='authManager2'")
+ createAppContext(AUTH_PROVIDER_XML + secondAuthManager)
- def securityContextAwareFilter = getFilters('/first/filters').find { it instanceof SecurityContextHolderAwareRequestFilter }
- def secondSecurityContextAwareFilter = getFilter(SecurityContextHolderAwareRequestFilter)
+ def securityContextAwareFilter = getFilters('/first/filters').find { it instanceof SecurityContextHolderAwareRequestFilter }
+ def secondSecurityContextAwareFilter = getFilter(SecurityContextHolderAwareRequestFilter)
- expect:
- securityContextAwareFilter.authenticationEntryPoint.loginFormUrl == '/login'
- securityContextAwareFilter.authenticationManager == getFilters('/first/filters').find { it instanceof UsernamePasswordAuthenticationFilter}.authenticationManager
- securityContextAwareFilter.authenticationManager.parent == appContext.getBean('authManager')
- securityContextAwareFilter.logoutHandlers.size() == 1
- securityContextAwareFilter.logoutHandlers[0].class == SecurityContextLogoutHandler
- securityContextAwareFilter.logoutHandlers[0].invalidateHttpSession == true
+ expect:
+ securityContextAwareFilter.authenticationEntryPoint.loginFormUrl == '/login'
+ securityContextAwareFilter.authenticationManager == getFilters('/first/filters').find { it instanceof UsernamePasswordAuthenticationFilter}.authenticationManager
+ securityContextAwareFilter.authenticationManager.parent == appContext.getBean('authManager')
+ securityContextAwareFilter.logoutHandlers.size() == 1
+ securityContextAwareFilter.logoutHandlers[0].class == SecurityContextLogoutHandler
+ securityContextAwareFilter.logoutHandlers[0].invalidateHttpSession == true
- secondSecurityContextAwareFilter.authenticationEntryPoint.loginFormUrl == '/login2'
- secondSecurityContextAwareFilter.authenticationManager == getFilter(UsernamePasswordAuthenticationFilter).authenticationManager
- secondSecurityContextAwareFilter.authenticationManager.parent == appContext.getBean('authManager2')
- securityContextAwareFilter.logoutHandlers.size() == 1
- secondSecurityContextAwareFilter.logoutHandlers[0].class == SecurityContextLogoutHandler
- secondSecurityContextAwareFilter.logoutHandlers[0].invalidateHttpSession == false
- }
+ secondSecurityContextAwareFilter.authenticationEntryPoint.loginFormUrl == '/login2'
+ secondSecurityContextAwareFilter.authenticationManager == getFilter(UsernamePasswordAuthenticationFilter).authenticationManager
+ secondSecurityContextAwareFilter.authenticationManager.parent == appContext.getBean('authManager2')
+ securityContextAwareFilter.logoutHandlers.size() == 1
+ secondSecurityContextAwareFilter.logoutHandlers[0].class == SecurityContextLogoutHandler
+ secondSecurityContextAwareFilter.logoutHandlers[0].invalidateHttpSession == false
+ }
- def logoutCustom() {
- xml.http() {
- 'form-login'('login-page' : '/login')
- 'logout'('invalidate-session' : 'false', 'logout-success-url' : '/login?logout', 'delete-cookies' : 'JSESSIONID')
- csrf(disabled:true)
- }
- createAppContext(AUTH_PROVIDER_XML)
+ def logoutCustom() {
+ xml.http() {
+ 'form-login'('login-page' : '/login')
+ 'logout'('invalidate-session' : 'false', 'logout-success-url' : '/login?logout', 'delete-cookies' : 'JSESSIONID')
+ csrf(disabled:true)
+ }
+ createAppContext(AUTH_PROVIDER_XML)
- def securityContextAwareFilter = getFilter(SecurityContextHolderAwareRequestFilter)
+ def securityContextAwareFilter = getFilter(SecurityContextHolderAwareRequestFilter)
- expect:
- securityContextAwareFilter.authenticationEntryPoint.loginFormUrl == getFilter(ExceptionTranslationFilter).authenticationEntryPoint.loginFormUrl
- securityContextAwareFilter.authenticationManager == getFilter(UsernamePasswordAuthenticationFilter).authenticationManager
- securityContextAwareFilter.logoutHandlers.size() == 2
- securityContextAwareFilter.logoutHandlers[0].class == SecurityContextLogoutHandler
- securityContextAwareFilter.logoutHandlers[0].invalidateHttpSession == false
- securityContextAwareFilter.logoutHandlers[1].class == CookieClearingLogoutHandler
- securityContextAwareFilter.logoutHandlers[1].cookiesToClear == ['JSESSIONID']
- }
+ expect:
+ securityContextAwareFilter.authenticationEntryPoint.loginFormUrl == getFilter(ExceptionTranslationFilter).authenticationEntryPoint.loginFormUrl
+ securityContextAwareFilter.authenticationManager == getFilter(UsernamePasswordAuthenticationFilter).authenticationManager
+ securityContextAwareFilter.logoutHandlers.size() == 2
+ securityContextAwareFilter.logoutHandlers[0].class == SecurityContextLogoutHandler
+ securityContextAwareFilter.logoutHandlers[0].invalidateHttpSession == false
+ securityContextAwareFilter.logoutHandlers[1].class == CookieClearingLogoutHandler
+ securityContextAwareFilter.logoutHandlers[1].cookiesToClear == ['JSESSIONID']
+ }
}
diff --git a/config/src/test/resources/org/springframework/security/config/annotation/configuration/AutowireBeanFactoryObjectPostProcessorTests-aopconfig.xml b/config/src/test/resources/org/springframework/security/config/annotation/configuration/AutowireBeanFactoryObjectPostProcessorTests-aopconfig.xml
index d8f52e8d6c..a36e2f41d3 100644
--- a/config/src/test/resources/org/springframework/security/config/annotation/configuration/AutowireBeanFactoryObjectPostProcessorTests-aopconfig.xml
+++ b/config/src/test/resources/org/springframework/security/config/annotation/configuration/AutowireBeanFactoryObjectPostProcessorTests-aopconfig.xml
@@ -1,23 +1,23 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:aop="http://www.springframework.org/schema/aop"
+ xmlns:p="http://www.springframework.org/schema/p"
+ xmlns:context="http://www.springframework.org/schema/context"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
+ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
+ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
-
+
-
+
-
-
-
-
+
+
+
+
diff --git a/core/src/test/resources/org/springframework/security/authentication/jaas/DefaultJaasAuthenticationProviderTests.xml b/core/src/test/resources/org/springframework/security/authentication/jaas/DefaultJaasAuthenticationProviderTests.xml
index c1303be7fb..2fa38a2189 100644
--- a/core/src/test/resources/org/springframework/security/authentication/jaas/DefaultJaasAuthenticationProviderTests.xml
+++ b/core/src/test/resources/org/springframework/security/authentication/jaas/DefaultJaasAuthenticationProviderTests.xml
@@ -1,41 +1,41 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/itest/context/src/integration-test/resources/logback-test.xml b/itest/context/src/integration-test/resources/logback-test.xml
index 9c25571377..8d5df5d3e2 100644
--- a/itest/context/src/integration-test/resources/logback-test.xml
+++ b/itest/context/src/integration-test/resources/logback-test.xml
@@ -1,15 +1,15 @@
-
- %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
-
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
-
+
diff --git a/itest/context/src/integration-test/resources/sec-933-app-context.xml b/itest/context/src/integration-test/resources/sec-933-app-context.xml
index da52fd9558..ee5b77ca1c 100755
--- a/itest/context/src/integration-test/resources/sec-933-app-context.xml
+++ b/itest/context/src/integration-test/resources/sec-933-app-context.xml
@@ -1,32 +1,32 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:aop="http://www.springframework.org/schema/aop"
+ xmlns:tx="http://www.springframework.org/schema/tx"
+ xmlns:security="http://www.springframework.org/schema/security"
+ xsi:schemaLocation="
+ http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
+ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
+ http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
-
+
-
-
-
+
+
+
-
-
-
+
+
+
-
-
-
+
+
+
-
+
diff --git a/itest/context/src/integration-test/resources/sec-936-app-context.xml b/itest/context/src/integration-test/resources/sec-936-app-context.xml
index dc3a11f9dd..3a2dc0c29a 100755
--- a/itest/context/src/integration-test/resources/sec-936-app-context.xml
+++ b/itest/context/src/integration-test/resources/sec-936-app-context.xml
@@ -1,54 +1,54 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:util="http://www.springframework.org/schema/util"
+ xmlns:security="http://www.springframework.org/schema/security"
+ xsi:schemaLocation="
+ http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
+ http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
-
-
-
-
-
-
-
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
- securityInterceptor
- httpInvokerClientInterceptor
-
-
-
+
+
+
+
+ securityInterceptor
+ httpInvokerClientInterceptor
+
+
+
-
-
-
+
+
+
diff --git a/itest/misc/src/integration-test/java/org/springframework/security/concurrent/SessionRegistryImplMTTests.java b/itest/misc/src/integration-test/java/org/springframework/security/concurrent/SessionRegistryImplMTTests.java
index 178eec9a3d..b2d2eb37c1 100644
--- a/itest/misc/src/integration-test/java/org/springframework/security/concurrent/SessionRegistryImplMTTests.java
+++ b/itest/misc/src/integration-test/java/org/springframework/security/concurrent/SessionRegistryImplMTTests.java
@@ -28,185 +28,185 @@ import java.util.Random;
* @author Luke Taylor
*/
public class SessionRegistryImplMTTests extends TestCase {
- private static final Random rnd = new Random();
- private static boolean errorOccurred;
+ private static final Random rnd = new Random();
+ private static boolean errorOccurred;
- protected void setUp() throws Exception {
- errorOccurred = false;
- }
+ protected void setUp() throws Exception {
+ errorOccurred = false;
+ }
- /**
- * Reproduces the NPE mentioned in SEC-484 where a sessionId is removed from
- * the set of sessions before it is removed from the list of sessions for a principal.
- * getAllSessions(principal, false) then finds the sessionId in the principal's session list
- * but reads null for the SessionInformation with the same Id.
- * Note that this is not guaranteed to produce the error but is a good testing point. Increasing the number
- * of sessions makes a failure more likely, but slows the test considerably.
- * Inserting temporary sleep statements in SessionRegistryClassImpl will also help.
- */
- public void testConcurrencyOfReadAndRemoveIsSafe() {
- Object principal = "Joe Principal";
- SessionRegistryImpl sessionregistry = new SessionRegistryImpl();
- Set sessions = Collections.synchronizedSet(new HashSet());
- // Register some sessions
- for (int i = 0; i < 50; i++) {
- String sessionId = Integer.toString(i);
- sessions.add(sessionId);
- sessionregistry.registerNewSession(sessionId, principal);
- }
+ /**
+ * Reproduces the NPE mentioned in SEC-484 where a sessionId is removed from
+ * the set of sessions before it is removed from the list of sessions for a principal.
+ * getAllSessions(principal, false) then finds the sessionId in the principal's session list
+ * but reads null for the SessionInformation with the same Id.
+ * Note that this is not guaranteed to produce the error but is a good testing point. Increasing the number
+ * of sessions makes a failure more likely, but slows the test considerably.
+ * Inserting temporary sleep statements in SessionRegistryClassImpl will also help.
+ */
+ public void testConcurrencyOfReadAndRemoveIsSafe() {
+ Object principal = "Joe Principal";
+ SessionRegistryImpl sessionregistry = new SessionRegistryImpl();
+ Set sessions = Collections.synchronizedSet(new HashSet());
+ // Register some sessions
+ for (int i = 0; i < 50; i++) {
+ String sessionId = Integer.toString(i);
+ sessions.add(sessionId);
+ sessionregistry.registerNewSession(sessionId, principal);
+ }
- // Pile of readers to hammer the getAllSessions method.
- for (int i=0; i < 10; i++) {
- Thread reader = new Thread(new SessionRegistryReader(principal, sessionregistry));
- reader.start();
- }
+ // Pile of readers to hammer the getAllSessions method.
+ for (int i=0; i < 10; i++) {
+ Thread reader = new Thread(new SessionRegistryReader(principal, sessionregistry));
+ reader.start();
+ }
- Thread remover = new Thread(new SessionRemover("remover", sessionregistry, sessions));
+ Thread remover = new Thread(new SessionRemover("remover", sessionregistry, sessions));
- remover.start();
+ remover.start();
- while(remover.isAlive()) {
- pause(250);
- }
+ while(remover.isAlive()) {
+ pause(250);
+ }
- assertFalse("Thread errors detected; review log output for details", errorOccurred);
- }
+ assertFalse("Thread errors detected; review log output for details", errorOccurred);
+ }
- public void testConcurrentRemovalIsSafe() {
- Object principal = "Some principal object";
- SessionRegistryImpl sessionregistry = new SessionRegistryImpl();
- // The session list (effectivelly the containers sessions).
- Set sessions = Collections.synchronizedSet(new HashSet());
- Thread registerer = new Thread(new SessionRegisterer(principal, sessionregistry, 100, sessions));
+ public void testConcurrentRemovalIsSafe() {
+ Object principal = "Some principal object";
+ SessionRegistryImpl sessionregistry = new SessionRegistryImpl();
+ // The session list (effectivelly the containers sessions).
+ Set sessions = Collections.synchronizedSet(new HashSet());
+ Thread registerer = new Thread(new SessionRegisterer(principal, sessionregistry, 100, sessions));
- registerer.start();
+ registerer.start();
- int nRemovers = 4;
+ int nRemovers = 4;
- SessionRemover[] removers = new SessionRemover[nRemovers];
- Thread[] removerThreads = new Thread[nRemovers];
+ SessionRemover[] removers = new SessionRemover[nRemovers];
+ Thread[] removerThreads = new Thread[nRemovers];
- for (int i = 0; i < removers.length; i++) {
- removers[i] = new SessionRemover("remover" + i, sessionregistry, sessions);
- removerThreads[i] = new Thread(removers[i], "remover" + i);
- removerThreads[i].start();
- }
+ for (int i = 0; i < removers.length; i++) {
+ removers[i] = new SessionRemover("remover" + i, sessionregistry, sessions);
+ removerThreads[i] = new Thread(removers[i], "remover" + i);
+ removerThreads[i].start();
+ }
- while (stillRunning(removerThreads)) {
- pause(500);
- }
- }
+ while (stillRunning(removerThreads)) {
+ pause(500);
+ }
+ }
- private boolean stillRunning(Thread[] threads) {
- for (int i = 0; i < threads.length; i++) {
- if (threads[i].isAlive()) {
- return true;
- }
- }
+ private boolean stillRunning(Thread[] threads) {
+ for (int i = 0; i < threads.length; i++) {
+ if (threads[i].isAlive()) {
+ return true;
+ }
+ }
- return false;
- }
+ return false;
+ }
- private static class SessionRegisterer implements Runnable {
- private SessionRegistry sessionregistry;
- private int nIterations;
- private Set sessionList;
- private Object principal;
+ private static class SessionRegisterer implements Runnable {
+ private SessionRegistry sessionregistry;
+ private int nIterations;
+ private Set sessionList;
+ private Object principal;
- public SessionRegisterer(Object principal, SessionRegistry sessionregistry, int nIterations, Set sessionList) {
- this.sessionregistry = sessionregistry;
- this.nIterations = nIterations;
- this.sessionList = sessionList;
- this.principal = principal;
- }
+ public SessionRegisterer(Object principal, SessionRegistry sessionregistry, int nIterations, Set sessionList) {
+ this.sessionregistry = sessionregistry;
+ this.nIterations = nIterations;
+ this.sessionList = sessionList;
+ this.principal = principal;
+ }
- public void run() {
- for (int i=0; i < nIterations && !errorOccurred; i++) {
- String sessionId = Integer.toString(i);
- sessionList.add(sessionId);
- try {
- sessionregistry.registerNewSession(sessionId,principal);
- pause(20);
- Thread.yield();
- } catch(Exception e) {
- e.printStackTrace();
- errorOccurred = true;
- }
- }
- }
- }
+ public void run() {
+ for (int i=0; i < nIterations && !errorOccurred; i++) {
+ String sessionId = Integer.toString(i);
+ sessionList.add(sessionId);
+ try {
+ sessionregistry.registerNewSession(sessionId,principal);
+ pause(20);
+ Thread.yield();
+ } catch(Exception e) {
+ e.printStackTrace();
+ errorOccurred = true;
+ }
+ }
+ }
+ }
- private static class SessionRegistryReader implements Runnable {
- private SessionRegistry sessionRegistry;
- private Object principal;
+ private static class SessionRegistryReader implements Runnable {
+ private SessionRegistry sessionRegistry;
+ private Object principal;
- public SessionRegistryReader(Object principal, SessionRegistry sessionregistry) {
- this.sessionRegistry = sessionregistry;
- this.principal = principal;
- }
+ public SessionRegistryReader(Object principal, SessionRegistry sessionregistry) {
+ this.sessionRegistry = sessionregistry;
+ this.principal = principal;
+ }
- public void run() {
- while (!errorOccurred) {
- try {
- sessionRegistry.getAllSessions(principal, false);
- sessionRegistry.getAllPrincipals();
- sessionRegistry.getAllSessions(principal, true);
- Thread.yield();
- } catch (Exception e) {
- e.printStackTrace();
- errorOccurred = true;
- }
- }
- }
- }
+ public void run() {
+ while (!errorOccurred) {
+ try {
+ sessionRegistry.getAllSessions(principal, false);
+ sessionRegistry.getAllPrincipals();
+ sessionRegistry.getAllSessions(principal, true);
+ Thread.yield();
+ } catch (Exception e) {
+ e.printStackTrace();
+ errorOccurred = true;
+ }
+ }
+ }
+ }
- private static class SessionRemover implements Runnable {
- private SessionRegistry sessionregistry;
- private Set sessionList;
- private String name;
+ private static class SessionRemover implements Runnable {
+ private SessionRegistry sessionregistry;
+ private Set sessionList;
+ private String name;
- public SessionRemover(String name, SessionRegistry sessionregistry, Set sessionList) {
- this.name = name;
- this.sessionregistry = sessionregistry;
- this.sessionList = sessionList;
- }
+ public SessionRemover(String name, SessionRegistry sessionregistry, Set sessionList) {
+ this.name = name;
+ this.sessionregistry = sessionregistry;
+ this.sessionList = sessionList;
+ }
- public void run() {
- boolean finished = false;
+ public void run() {
+ boolean finished = false;
- while (!finished && !errorOccurred) {
- if (sessionList.isEmpty()) {
- finished = true;
- // List of sessions appears to be empty but give it a chance to fill up again
- System.out.println(name + ": Session list empty. Waiting.");
- pause(500);
- }
+ while (!finished && !errorOccurred) {
+ if (sessionList.isEmpty()) {
+ finished = true;
+ // List of sessions appears to be empty but give it a chance to fill up again
+ System.out.println(name + ": Session list empty. Waiting.");
+ pause(500);
+ }
- Object[] sessions = sessionList.toArray();
+ Object[] sessions = sessionList.toArray();
- if (sessions.length > 0) {
- finished = false;
- String sessionId = (String) sessions[0];
+ if (sessions.length > 0) {
+ finished = false;
+ String sessionId = (String) sessions[0];
// System.out.println(name + ": removing " + sessionId);
- try {
- sessionregistry.removeSessionInformation(sessionId);
+ try {
+ sessionregistry.removeSessionInformation(sessionId);
- pause(rnd.nextInt(100));
+ pause(rnd.nextInt(100));
- sessionList.remove(sessionId);
- Thread.yield();
- } catch (Exception e) {
- e.printStackTrace();
- errorOccurred = true;
- }
- }
- }
- }
- }
+ sessionList.remove(sessionId);
+ Thread.yield();
+ } catch (Exception e) {
+ e.printStackTrace();
+ errorOccurred = true;
+ }
+ }
+ }
+ }
+ }
- private static void pause(int length) {
- try {
- Thread.sleep(length);
- } catch (InterruptedException ignore) {}
- }
+ private static void pause(int length) {
+ try {
+ Thread.sleep(length);
+ } catch (InterruptedException ignore) {}
+ }
}
diff --git a/itest/misc/src/integration-test/java/org/springframework/security/context/SecurityContextHolderMTTests.java b/itest/misc/src/integration-test/java/org/springframework/security/context/SecurityContextHolderMTTests.java
index 143b151779..cb1cc0e911 100644
--- a/itest/misc/src/integration-test/java/org/springframework/security/context/SecurityContextHolderMTTests.java
+++ b/itest/misc/src/integration-test/java/org/springframework/security/context/SecurityContextHolderMTTests.java
@@ -16,201 +16,201 @@ import org.springframework.security.providers.UsernamePasswordAuthenticationToke
* @Author Luke Taylor
*/
public class SecurityContextHolderMTTests extends TestCase{
- private int errors = 0;
+ private int errors = 0;
- private static final int NUM_OPS = 25;
- private static final int NUM_THREADS = 25;
+ private static final int NUM_OPS = 25;
+ private static final int NUM_THREADS = 25;
- public final void setUp() throws Exception {
- SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
- }
+ public final void setUp() throws Exception {
+ SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
+ }
- public void testSynchronizationCustomStrategyLoading() {
- SecurityContextHolder.setStrategyName(InheritableThreadLocalSecurityContextHolderStrategy.class.getName());
- assertTrue(new SecurityContextHolder().toString()
- .lastIndexOf("SecurityContextHolder[strategy='org.springframework.security.context.InheritableThreadLocalSecurityContextHolderStrategy'") != -1);
- loadStartAndWaitForThreads(true, "Main_", NUM_THREADS, false, true);
- assertEquals("Thread errors detected; review log output for details", 0, errors);
- }
+ public void testSynchronizationCustomStrategyLoading() {
+ SecurityContextHolder.setStrategyName(InheritableThreadLocalSecurityContextHolderStrategy.class.getName());
+ assertTrue(new SecurityContextHolder().toString()
+ .lastIndexOf("SecurityContextHolder[strategy='org.springframework.security.context.InheritableThreadLocalSecurityContextHolderStrategy'") != -1);
+ loadStartAndWaitForThreads(true, "Main_", NUM_THREADS, false, true);
+ assertEquals("Thread errors detected; review log output for details", 0, errors);
+ }
- public void testSynchronizationGlobal() throws Exception {
- SecurityContextHolder.clearContext();
- SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);
- loadStartAndWaitForThreads(true, "Main_", NUM_THREADS, true, false);
- assertEquals("Thread errors detected; review log output for details", 0, errors);
- }
+ public void testSynchronizationGlobal() throws Exception {
+ SecurityContextHolder.clearContext();
+ SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);
+ loadStartAndWaitForThreads(true, "Main_", NUM_THREADS, true, false);
+ assertEquals("Thread errors detected; review log output for details", 0, errors);
+ }
- public void testSynchronizationInheritableThreadLocal()
- throws Exception {
- SecurityContextHolder.clearContext();
- SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
- loadStartAndWaitForThreads(true, "Main_", NUM_THREADS, false, true);
- assertEquals("Thread errors detected; review log output for details", 0, errors);
- }
+ public void testSynchronizationInheritableThreadLocal()
+ throws Exception {
+ SecurityContextHolder.clearContext();
+ SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
+ loadStartAndWaitForThreads(true, "Main_", NUM_THREADS, false, true);
+ assertEquals("Thread errors detected; review log output for details", 0, errors);
+ }
- public void testSynchronizationThreadLocal() throws Exception {
- SecurityContextHolder.clearContext();
- SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_THREADLOCAL);
- loadStartAndWaitForThreads(true, "Main_", NUM_THREADS, false, false);
- assertEquals("Thread errors detected; review log output for details", 0, errors);
- }
+ public void testSynchronizationThreadLocal() throws Exception {
+ SecurityContextHolder.clearContext();
+ SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_THREADLOCAL);
+ loadStartAndWaitForThreads(true, "Main_", NUM_THREADS, false, false);
+ assertEquals("Thread errors detected; review log output for details", 0, errors);
+ }
- private void startAndRun(Thread[] threads) {
- // Start them up
- for (int i = 0; i < threads.length; i++) {
- threads[i].start();
- }
+ private void startAndRun(Thread[] threads) {
+ // Start them up
+ for (int i = 0; i < threads.length; i++) {
+ threads[i].start();
+ }
- // Wait for them to finish
- while (stillRunning(threads)) {
- try {
- Thread.sleep(250);
- } catch (InterruptedException ignore) {}
- }
- }
+ // Wait for them to finish
+ while (stillRunning(threads)) {
+ try {
+ Thread.sleep(250);
+ } catch (InterruptedException ignore) {}
+ }
+ }
- private boolean stillRunning(Thread[] threads) {
- for (int i = 0; i < threads.length; i++) {
- if (threads[i].isAlive()) {
- return true;
- }
- }
+ private boolean stillRunning(Thread[] threads) {
+ for (int i = 0; i < threads.length; i++) {
+ if (threads[i].isAlive()) {
+ return true;
+ }
+ }
- return false;
- }
+ return false;
+ }
- private void loadStartAndWaitForThreads(boolean topLevelThread, String prefix, int createThreads,
- boolean expectAllThreadsToUseIdenticalAuthentication, boolean expectChildrenToShareAuthenticationWithParent) {
- Thread[] threads = new Thread[createThreads];
- errors = 0;
+ private void loadStartAndWaitForThreads(boolean topLevelThread, String prefix, int createThreads,
+ boolean expectAllThreadsToUseIdenticalAuthentication, boolean expectChildrenToShareAuthenticationWithParent) {
+ Thread[] threads = new Thread[createThreads];
+ errors = 0;
- if (topLevelThread) {
- // PARENT (TOP-LEVEL) THREAD CREATION
- if (expectChildrenToShareAuthenticationWithParent) {
- // An InheritableThreadLocal
- for (int i = 0; i < threads.length; i++) {
- if ((i % 2) == 0) {
- // Don't inject auth into current thread; neither current thread or child will have authentication
- threads[i] = makeThread(prefix + "Unauth_Parent_" + i, true, false, false, true, null);
- } else {
- // Inject auth into current thread, but not child; current thread will have auth, child will also have auth
- threads[i] = makeThread(prefix + "Auth_Parent_" + i, true, true, false, true,
- prefix + "Auth_Parent_" + i);
- }
- }
- } else if (expectAllThreadsToUseIdenticalAuthentication) {
- // A global
- SecurityContextHolder.getContext()
- .setAuthentication(new UsernamePasswordAuthenticationToken("GLOBAL_USERNAME",
- "pass"));
+ if (topLevelThread) {
+ // PARENT (TOP-LEVEL) THREAD CREATION
+ if (expectChildrenToShareAuthenticationWithParent) {
+ // An InheritableThreadLocal
+ for (int i = 0; i < threads.length; i++) {
+ if ((i % 2) == 0) {
+ // Don't inject auth into current thread; neither current thread or child will have authentication
+ threads[i] = makeThread(prefix + "Unauth_Parent_" + i, true, false, false, true, null);
+ } else {
+ // Inject auth into current thread, but not child; current thread will have auth, child will also have auth
+ threads[i] = makeThread(prefix + "Auth_Parent_" + i, true, true, false, true,
+ prefix + "Auth_Parent_" + i);
+ }
+ }
+ } else if (expectAllThreadsToUseIdenticalAuthentication) {
+ // A global
+ SecurityContextHolder.getContext()
+ .setAuthentication(new UsernamePasswordAuthenticationToken("GLOBAL_USERNAME",
+ "pass"));
- for (int i = 0; i < threads.length; i++) {
- if ((i % 2) == 0) {
- // Don't inject auth into current thread;both current thread and child will have same authentication
- threads[i] = makeThread(prefix + "Unauth_Parent_" + i, true, false, true, true,
- "GLOBAL_USERNAME");
- } else {
- // Inject auth into current thread; current thread will have auth, child will also have auth
- threads[i] = makeThread(prefix + "Auth_Parent_" + i, true, true, true, true, "GLOBAL_USERNAME");
- }
- }
- } else {
- // A standard ThreadLocal
- for (int i = 0; i < threads.length; i++) {
- if ((i % 2) == 0) {
- // Don't inject auth into current thread; neither current thread or child will have authentication
- threads[i] = makeThread(prefix + "Unauth_Parent_" + i, true, false, false, false, null);
- } else {
- // Inject auth into current thread, but not child; current thread will have auth, child will not have auth
- threads[i] = makeThread(prefix + "Auth_Parent_" + i, true, true, false, false,
- prefix + "Auth_Parent_" + i);
- }
- }
- }
- } else {
- // CHILD THREAD CREATION
- if (expectChildrenToShareAuthenticationWithParent || expectAllThreadsToUseIdenticalAuthentication) {
- // The children being created are all expected to have security (ie an InheritableThreadLocal/global AND auth was injected into parent)
- for (int i = 0; i < threads.length; i++) {
- String expectedUsername = prefix;
+ for (int i = 0; i < threads.length; i++) {
+ if ((i % 2) == 0) {
+ // Don't inject auth into current thread;both current thread and child will have same authentication
+ threads[i] = makeThread(prefix + "Unauth_Parent_" + i, true, false, true, true,
+ "GLOBAL_USERNAME");
+ } else {
+ // Inject auth into current thread; current thread will have auth, child will also have auth
+ threads[i] = makeThread(prefix + "Auth_Parent_" + i, true, true, true, true, "GLOBAL_USERNAME");
+ }
+ }
+ } else {
+ // A standard ThreadLocal
+ for (int i = 0; i < threads.length; i++) {
+ if ((i % 2) == 0) {
+ // Don't inject auth into current thread; neither current thread or child will have authentication
+ threads[i] = makeThread(prefix + "Unauth_Parent_" + i, true, false, false, false, null);
+ } else {
+ // Inject auth into current thread, but not child; current thread will have auth, child will not have auth
+ threads[i] = makeThread(prefix + "Auth_Parent_" + i, true, true, false, false,
+ prefix + "Auth_Parent_" + i);
+ }
+ }
+ }
+ } else {
+ // CHILD THREAD CREATION
+ if (expectChildrenToShareAuthenticationWithParent || expectAllThreadsToUseIdenticalAuthentication) {
+ // The children being created are all expected to have security (ie an InheritableThreadLocal/global AND auth was injected into parent)
+ for (int i = 0; i < threads.length; i++) {
+ String expectedUsername = prefix;
- if (expectAllThreadsToUseIdenticalAuthentication) {
- expectedUsername = "GLOBAL_USERNAME";
- }
+ if (expectAllThreadsToUseIdenticalAuthentication) {
+ expectedUsername = "GLOBAL_USERNAME";
+ }
- // Don't inject auth into current thread; the current thread will obtain auth from its parent
- // NB: As topLevelThread = true, no further child threads will be created
- threads[i] = makeThread(prefix + "->child->Inherited_Auth_Child_" + i, false, false,
- expectAllThreadsToUseIdenticalAuthentication, false, expectedUsername);
- }
- } else {
- // The children being created are NOT expected to have security (ie not an InheritableThreadLocal OR auth was not injected into parent)
- for (int i = 0; i < threads.length; i++) {
- // Don't inject auth into current thread; neither current thread or child will have authentication
- // NB: As topLevelThread = true, no further child threads will be created
- threads[i] = makeThread(prefix + "->child->Unauth_Child_" + i, false, false, false, false, null);
- }
- }
- }
+ // Don't inject auth into current thread; the current thread will obtain auth from its parent
+ // NB: As topLevelThread = true, no further child threads will be created
+ threads[i] = makeThread(prefix + "->child->Inherited_Auth_Child_" + i, false, false,
+ expectAllThreadsToUseIdenticalAuthentication, false, expectedUsername);
+ }
+ } else {
+ // The children being created are NOT expected to have security (ie not an InheritableThreadLocal OR auth was not injected into parent)
+ for (int i = 0; i < threads.length; i++) {
+ // Don't inject auth into current thread; neither current thread or child will have authentication
+ // NB: As topLevelThread = true, no further child threads will be created
+ threads[i] = makeThread(prefix + "->child->Unauth_Child_" + i, false, false, false, false, null);
+ }
+ }
+ }
- // Start and execute the threads
- startAndRun(threads);
- }
+ // Start and execute the threads
+ startAndRun(threads);
+ }
- private Thread makeThread(final String threadIdentifier, final boolean topLevelThread,
- final boolean injectAuthIntoCurrentThread, final boolean expectAllThreadsToUseIdenticalAuthentication,
- final boolean expectChildrenToShareAuthenticationWithParent, final String expectedUsername) {
- final Random rnd = new Random();
+ private Thread makeThread(final String threadIdentifier, final boolean topLevelThread,
+ final boolean injectAuthIntoCurrentThread, final boolean expectAllThreadsToUseIdenticalAuthentication,
+ final boolean expectChildrenToShareAuthenticationWithParent, final String expectedUsername) {
+ final Random rnd = new Random();
- Thread t = new Thread(new Runnable() {
- public void run() {
- if (injectAuthIntoCurrentThread) {
- // Set authentication in this thread
- SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
- expectedUsername, "pass"));
+ Thread t = new Thread(new Runnable() {
+ public void run() {
+ if (injectAuthIntoCurrentThread) {
+ // Set authentication in this thread
+ SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
+ expectedUsername, "pass"));
- //System.out.println(threadIdentifier + " - set to " + SecurityContextHolder.getContext().getAuthentication());
- } else {
- //System.out.println(threadIdentifier + " - not set (currently " + SecurityContextHolder.getContext().getAuthentication() + ")");
- }
+ //System.out.println(threadIdentifier + " - set to " + SecurityContextHolder.getContext().getAuthentication());
+ } else {
+ //System.out.println(threadIdentifier + " - not set (currently " + SecurityContextHolder.getContext().getAuthentication() + ")");
+ }
- // Do some operations in current thread, checking authentication is as expected in the current thread (ie another thread doesn't change it)
- for (int i = 0; i < NUM_OPS; i++) {
- String currentUsername = (SecurityContextHolder.getContext().getAuthentication() == null)
- ? null : SecurityContextHolder.getContext().getAuthentication().getName();
+ // Do some operations in current thread, checking authentication is as expected in the current thread (ie another thread doesn't change it)
+ for (int i = 0; i < NUM_OPS; i++) {
+ String currentUsername = (SecurityContextHolder.getContext().getAuthentication() == null)
+ ? null : SecurityContextHolder.getContext().getAuthentication().getName();
- if ((i % 7) == 0) {
- System.out.println(threadIdentifier + " at " + i + " username " + currentUsername);
- }
+ if ((i % 7) == 0) {
+ System.out.println(threadIdentifier + " at " + i + " username " + currentUsername);
+ }
- try {
- assertEquals("Failed on iteration " + i + "; Authentication was '"
- + currentUsername + "' but principal was expected to contain username '"
- + expectedUsername + "'", expectedUsername, currentUsername);
- } catch (ComparisonFailure err) {
- errors++;
- throw err;
- }
+ try {
+ assertEquals("Failed on iteration " + i + "; Authentication was '"
+ + currentUsername + "' but principal was expected to contain username '"
+ + expectedUsername + "'", expectedUsername, currentUsername);
+ } catch (ComparisonFailure err) {
+ errors++;
+ throw err;
+ }
- try {
- Thread.sleep(rnd.nextInt(250));
- } catch (InterruptedException ignore) {}
- }
+ try {
+ Thread.sleep(rnd.nextInt(250));
+ } catch (InterruptedException ignore) {}
+ }
- // Load some children threads, checking the authentication is as expected in the children (ie another thread doesn't change it)
- if (topLevelThread) {
- // Make four children, but we don't want the children to have any more children (so anti-nature, huh?)
- if (injectAuthIntoCurrentThread && expectChildrenToShareAuthenticationWithParent) {
- loadStartAndWaitForThreads(false, threadIdentifier, 4,
- expectAllThreadsToUseIdenticalAuthentication, true);
- } else {
- loadStartAndWaitForThreads(false, threadIdentifier, 4,
- expectAllThreadsToUseIdenticalAuthentication, false);
- }
- }
- }
- }, threadIdentifier);
+ // Load some children threads, checking the authentication is as expected in the children (ie another thread doesn't change it)
+ if (topLevelThread) {
+ // Make four children, but we don't want the children to have any more children (so anti-nature, huh?)
+ if (injectAuthIntoCurrentThread && expectChildrenToShareAuthenticationWithParent) {
+ loadStartAndWaitForThreads(false, threadIdentifier, 4,
+ expectAllThreadsToUseIdenticalAuthentication, true);
+ } else {
+ loadStartAndWaitForThreads(false, threadIdentifier, 4,
+ expectAllThreadsToUseIdenticalAuthentication, false);
+ }
+ }
+ }
+ }, threadIdentifier);
- return t;
- }
+ return t;
+ }
}
diff --git a/itest/web/src/integration-test/resources/logback-test.xml b/itest/web/src/integration-test/resources/logback-test.xml
index 9c25571377..8d5df5d3e2 100644
--- a/itest/web/src/integration-test/resources/logback-test.xml
+++ b/itest/web/src/integration-test/resources/logback-test.xml
@@ -1,15 +1,15 @@
-
- %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
-
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
-
+
diff --git a/itest/web/src/main/webapp/WEB-INF/http-security-basic.xml b/itest/web/src/main/webapp/WEB-INF/http-security-basic.xml
index 341225f6f7..3656a25bbb 100644
--- a/itest/web/src/main/webapp/WEB-INF/http-security-basic.xml
+++ b/itest/web/src/main/webapp/WEB-INF/http-security-basic.xml
@@ -1,14 +1,14 @@
+ xmlns:beans="http://www.springframework.org/schema/beans"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
-
-
-
-
+
+
+
+
diff --git a/itest/web/src/main/webapp/WEB-INF/http-security-concurrency.xml b/itest/web/src/main/webapp/WEB-INF/http-security-concurrency.xml
index db67eac821..48181b2f46 100644
--- a/itest/web/src/main/webapp/WEB-INF/http-security-concurrency.xml
+++ b/itest/web/src/main/webapp/WEB-INF/http-security-concurrency.xml
@@ -1,34 +1,34 @@
+ xmlns:beans="http://www.springframework.org/schema/beans"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
-
+
-
-
+
+
-
-
-
+
+
+
-
-
+
+
-
-
+
+
-
-
-
+
+
+
-
-
+
+
diff --git a/itest/web/src/main/webapp/WEB-INF/http-security-custom-concurrency.xml b/itest/web/src/main/webapp/WEB-INF/http-security-custom-concurrency.xml
index 7a37bdda59..caf9f7b5d5 100644
--- a/itest/web/src/main/webapp/WEB-INF/http-security-custom-concurrency.xml
+++ b/itest/web/src/main/webapp/WEB-INF/http-security-custom-concurrency.xml
@@ -1,56 +1,56 @@
+ xmlns:beans="http://www.springframework.org/schema/beans"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
-
+
-
-
+
+
-
-
+
+
-
-
+
+
-
-
+
+
-
-
-
+
+
+
-
-
-
-
+
+
+
+
-
-
-
-
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
diff --git a/itest/web/src/main/webapp/WEB-INF/in-memory-provider.xml b/itest/web/src/main/webapp/WEB-INF/in-memory-provider.xml
index b4b513fa25..b3dcd648a5 100644
--- a/itest/web/src/main/webapp/WEB-INF/in-memory-provider.xml
+++ b/itest/web/src/main/webapp/WEB-INF/in-memory-provider.xml
@@ -1,21 +1,21 @@
+ xmlns:beans="http://www.springframework.org/schema/beans"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/aspectj-xml/src/main/resources/aspectj-context.xml b/samples/aspectj-xml/src/main/resources/aspectj-context.xml
index 6aa5a29db9..8cbe51c357 100644
--- a/samples/aspectj-xml/src/main/resources/aspectj-context.xml
+++ b/samples/aspectj-xml/src/main/resources/aspectj-context.xml
@@ -1,48 +1,48 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:sec="http://www.springframework.org/schema/security"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
-
+
-
+
-
+
diff --git a/samples/aspectj-xml/src/test/resources/logback-test.xml b/samples/aspectj-xml/src/test/resources/logback-test.xml
index f293b342dc..ddf04b2972 100644
--- a/samples/aspectj-xml/src/test/resources/logback-test.xml
+++ b/samples/aspectj-xml/src/test/resources/logback-test.xml
@@ -1,14 +1,14 @@
-
- %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
-
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
-
+
diff --git a/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/CasSampleProxyTests.groovy b/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/CasSampleProxyTests.groovy
index 059e0f16e7..5fd34836fd 100644
--- a/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/CasSampleProxyTests.groovy
+++ b/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/CasSampleProxyTests.groovy
@@ -33,90 +33,90 @@ import spock.lang.*
*/
@Stepwise
class CasSampleProxyTests extends AbstractCasTests {
- HttpClient client = new HttpClient()
- @Shared String casServerUrl = LoginPage.url.replaceFirst('/login','')
- @Shared JettyCasService service = new JettyCasService().init(casServerUrl)
- @Shared Cas20ProxyRetriever retriever = new Cas20ProxyRetriever(casServerUrl,'UTF-8')
- @Shared String pt
+ HttpClient client = new HttpClient()
+ @Shared String casServerUrl = LoginPage.url.replaceFirst('/login','')
+ @Shared JettyCasService service = new JettyCasService().init(casServerUrl)
+ @Shared Cas20ProxyRetriever retriever = new Cas20ProxyRetriever(casServerUrl,'UTF-8')
+ @Shared String pt
- def cleanupSpec() {
- service.stop()
- }
+ def cleanupSpec() {
+ service.stop()
+ }
- def 'access secure page succeeds with ROLE_USER'() {
- setup: 'Obtain a pgt for a user with ROLE_USER'
- driver.get LoginPage.url+"?service="+service.serviceUrl()
- at LoginPage
- login 'scott'
- when: 'User with ROLE_USER accesses the secure page'
- def content = getSecured(getBaseUrl()+SecurePage.url).responseBodyAsString
- then: 'The secure page is returned'
- content.contains('Secure Page
')
- }
+ def 'access secure page succeeds with ROLE_USER'() {
+ setup: 'Obtain a pgt for a user with ROLE_USER'
+ driver.get LoginPage.url+"?service="+service.serviceUrl()
+ at LoginPage
+ login 'scott'
+ when: 'User with ROLE_USER accesses the secure page'
+ def content = getSecured(getBaseUrl()+SecurePage.url).responseBodyAsString
+ then: 'The secure page is returned'
+ content.contains('Secure Page
')
+ }
- def 'access proxy ticket sample succeeds with ROLE_USER'() {
- when: 'a proxy ticket is used to create another proxy ticket'
- def content = getSecured(getBaseUrl()+ProxyTicketSamplePage.url).responseBodyAsString
- then: 'The proxy ticket sample page is returned'
- content.contains('Secure Page using a Proxy Ticket
')
- }
+ def 'access proxy ticket sample succeeds with ROLE_USER'() {
+ when: 'a proxy ticket is used to create another proxy ticket'
+ def content = getSecured(getBaseUrl()+ProxyTicketSamplePage.url).responseBodyAsString
+ then: 'The proxy ticket sample page is returned'
+ content.contains('Secure Page using a Proxy Ticket
')
+ }
- def 'access extremely secure page with ROLE_USER is denied'() {
- when: 'User with ROLE_USER accesses the extremely secure page'
- GetMethod method = getSecured(getBaseUrl()+ExtremelySecurePage.url)
- then: 'access is denied'
- assert method.responseBodyAsString =~ /(?i)403.*?Denied/
- assert 403 == method.statusCode
- }
+ def 'access extremely secure page with ROLE_USER is denied'() {
+ when: 'User with ROLE_USER accesses the extremely secure page'
+ GetMethod method = getSecured(getBaseUrl()+ExtremelySecurePage.url)
+ then: 'access is denied'
+ assert method.responseBodyAsString =~ /(?i)403.*?Denied/
+ assert 403 == method.statusCode
+ }
- def 'access secure page with ROLE_SUPERVISOR succeeds'() {
- setup: 'Obtain pgt for user with ROLE_SUPERVISOR'
- to LocalLogoutPage
- casServerLogout.click()
- driver.get(LoginPage.url+"?service="+service.serviceUrl())
- at LoginPage
- login 'rod'
- when: 'User with ROLE_SUPERVISOR accesses the secure page'
- def content = getSecured(getBaseUrl()+ExtremelySecurePage.url).responseBodyAsString
- then: 'The secure page is returned'
- content.contains('VERY Secure Page
')
- }
+ def 'access secure page with ROLE_SUPERVISOR succeeds'() {
+ setup: 'Obtain pgt for user with ROLE_SUPERVISOR'
+ to LocalLogoutPage
+ casServerLogout.click()
+ driver.get(LoginPage.url+"?service="+service.serviceUrl())
+ at LoginPage
+ login 'rod'
+ when: 'User with ROLE_SUPERVISOR accesses the secure page'
+ def content = getSecured(getBaseUrl()+ExtremelySecurePage.url).responseBodyAsString
+ then: 'The secure page is returned'
+ content.contains('VERY Secure Page
')
+ }
- def 'access extremely secure page with ROLE_SUPERVISOR reusing pt succeeds (stateless mode works)'() {
- when: 'User with ROLE_SUPERVISOR accesses extremely secure page with used pt'
- def content = getSecured(getBaseUrl()+ExtremelySecurePage.url,pt).responseBodyAsString
- then: 'The extremely secure page is returned'
- content.contains('VERY Secure Page
')
- }
+ def 'access extremely secure page with ROLE_SUPERVISOR reusing pt succeeds (stateless mode works)'() {
+ when: 'User with ROLE_SUPERVISOR accesses extremely secure page with used pt'
+ def content = getSecured(getBaseUrl()+ExtremelySecurePage.url,pt).responseBodyAsString
+ then: 'The extremely secure page is returned'
+ content.contains('VERY Secure Page
')
+ }
- def 'access secure page with invalid proxy ticket fails'() {
- when: 'Invalid ticket is used to access secure page'
- GetMethod method = getSecured(getBaseUrl()+SecurePage.url,'invalidticket')
- then: 'Authentication fails'
- method.statusCode == 401
- }
+ def 'access secure page with invalid proxy ticket fails'() {
+ when: 'Invalid ticket is used to access secure page'
+ GetMethod method = getSecured(getBaseUrl()+SecurePage.url,'invalidticket')
+ then: 'Authentication fails'
+ method.statusCode == 401
+ }
- /**
- * Gets the result of calling a url with a proxy ticket
- * @param targetUrl the absolute url to attempt to access
- * @param pt the proxy ticket to use. Defaults to {@link #getPt(String)} with targetUrl specified for the targetUrl.
- * @return the GetMethod after calling a url with a specified proxy ticket
- */
- GetMethod getSecured(String targetUrl,String pt=getPt(targetUrl)) {
- assert pt != null
- GetMethod method = new GetMethod(targetUrl+"?ticket="+pt)
- int status = client.executeMethod(method)
- method
- }
+ /**
+ * Gets the result of calling a url with a proxy ticket
+ * @param targetUrl the absolute url to attempt to access
+ * @param pt the proxy ticket to use. Defaults to {@link #getPt(String)} with targetUrl specified for the targetUrl.
+ * @return the GetMethod after calling a url with a specified proxy ticket
+ */
+ GetMethod getSecured(String targetUrl,String pt=getPt(targetUrl)) {
+ assert pt != null
+ GetMethod method = new GetMethod(targetUrl+"?ticket="+pt)
+ int status = client.executeMethod(method)
+ method
+ }
- /**
- * Obtains a proxy ticket using the pgt from the {@link #service}.
- * @param targetService the targetService that the proxy ticket will be valid for
- * @return a proxy ticket for targetService
- */
- String getPt(String targetService) {
- assert service.pgt != null
- pt = retriever.getProxyTicketIdFor(service.pgt, targetService)
- pt
- }
+ /**
+ * Obtains a proxy ticket using the pgt from the {@link #service}.
+ * @param targetService the targetService that the proxy ticket will be valid for
+ * @return a proxy ticket for targetService
+ */
+ String getPt(String targetService) {
+ assert service.pgt != null
+ pt = retriever.getProxyTicketIdFor(service.pgt, targetService)
+ pt
+ }
}
\ No newline at end of file
diff --git a/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/CasSampleTests.groovy b/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/CasSampleTests.groovy
index 4730e392db..088ee27490 100644
--- a/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/CasSampleTests.groovy
+++ b/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/CasSampleTests.groovy
@@ -34,102 +34,102 @@ import spock.lang.Stepwise;
*/
@Stepwise
class CasSampleTests extends AbstractCasTests {
- @Shared String casServerLogoutUrl = LoginPage.url.replaceFirst('/login','/logout')
+ @Shared String casServerLogoutUrl = LoginPage.url.replaceFirst('/login','/logout')
- def 'access home page with unauthenticated user succeeds'() {
- when: 'Unauthenticated user accesses the Home Page'
- to HomePage
- then: 'The home page succeeds'
- at HomePage
- }
+ def 'access home page with unauthenticated user succeeds'() {
+ when: 'Unauthenticated user accesses the Home Page'
+ to HomePage
+ then: 'The home page succeeds'
+ at HomePage
+ }
- def 'access extremely secure page with unauthenitcated user requires login'() {
- when: 'Unauthenticated user accesses the extremely secure page'
- via ExtremelySecurePage
- then: 'The login page is displayed'
- at LoginPage
- }
+ def 'access extremely secure page with unauthenitcated user requires login'() {
+ when: 'Unauthenticated user accesses the extremely secure page'
+ via ExtremelySecurePage
+ then: 'The login page is displayed'
+ at LoginPage
+ }
- def 'authenticate attempt with invaid ticket fails'() {
- when: 'present invalid ticket'
- go "login/cas?ticket=invalid"
- then: 'the login failed page is displayed'
- $("h2").text() == 'Login to CAS failed!'
- }
+ def 'authenticate attempt with invaid ticket fails'() {
+ when: 'present invalid ticket'
+ go "login/cas?ticket=invalid"
+ then: 'the login failed page is displayed'
+ $("h2").text() == 'Login to CAS failed!'
+ }
- def 'access secure page with unauthenticated user requires login'() {
- when: 'Unauthenticated user accesses the secure page'
- via SecurePage
- then: 'The login page is displayed'
- at LoginPage
- }
+ def 'access secure page with unauthenticated user requires login'() {
+ when: 'Unauthenticated user accesses the secure page'
+ via SecurePage
+ then: 'The login page is displayed'
+ at LoginPage
+ }
- def 'saved request is used for secure page'() {
- when: 'login with ROLE_USER after requesting the secure page'
- login 'scott'
- then: 'the secure page is displayed'
- at SecurePage
- }
+ def 'saved request is used for secure page'() {
+ when: 'login with ROLE_USER after requesting the secure page'
+ login 'scott'
+ then: 'the secure page is displayed'
+ at SecurePage
+ }
- def 'access proxy ticket sample with ROLE_USER is allowed'() {
- when: 'user with ROLE_USER requests the proxy ticket sample page'
- to ProxyTicketSamplePage
- then: 'the proxy ticket sample page is displayed'
- at ProxyTicketSamplePage
- }
+ def 'access proxy ticket sample with ROLE_USER is allowed'() {
+ when: 'user with ROLE_USER requests the proxy ticket sample page'
+ to ProxyTicketSamplePage
+ then: 'the proxy ticket sample page is displayed'
+ at ProxyTicketSamplePage
+ }
- def 'access extremely secure page with ROLE_USER is denied'() {
- when: 'User with ROLE_USER accesses extremely secure page'
- via ExtremelySecurePage
- then: 'the access denied page is displayed'
- at AccessDeniedPage
- }
+ def 'access extremely secure page with ROLE_USER is denied'() {
+ when: 'User with ROLE_USER accesses extremely secure page'
+ via ExtremelySecurePage
+ then: 'the access denied page is displayed'
+ at AccessDeniedPage
+ }
- def 'clicking local logout link displays local logout page'() {
- setup: 'Navigate to page with logout link'
- to SecurePage
- when: 'Local logout link is clicked'
- navModule.logout.click()
- then: 'the local logout page is displayed'
- at LocalLogoutPage
- }
+ def 'clicking local logout link displays local logout page'() {
+ setup: 'Navigate to page with logout link'
+ to SecurePage
+ when: 'Local logout link is clicked'
+ navModule.logout.click()
+ then: 'the local logout page is displayed'
+ at LocalLogoutPage
+ }
- def 'clicking cas server logout link successfully performs logout'() {
- when: 'the cas server logout link is clicked and the secure page is requested'
- casServerLogout.click()
- via SecurePage
- then: 'the login page is displayed'
- at LoginPage
- }
+ def 'clicking cas server logout link successfully performs logout'() {
+ when: 'the cas server logout link is clicked and the secure page is requested'
+ casServerLogout.click()
+ via SecurePage
+ then: 'the login page is displayed'
+ at LoginPage
+ }
- def 'access extremely secure page with ROLE_SUPERVISOR succeeds'() {
- setup: 'login with ROLE_SUPERVISOR'
- login 'rod'
- when: 'access extremely secure page'
- to ExtremelySecurePage
- then: 'extremely secure page is displayed'
- at ExtremelySecurePage
- }
+ def 'access extremely secure page with ROLE_SUPERVISOR succeeds'() {
+ setup: 'login with ROLE_SUPERVISOR'
+ login 'rod'
+ when: 'access extremely secure page'
+ to ExtremelySecurePage
+ then: 'extremely secure page is displayed'
+ at ExtremelySecurePage
+ }
- def 'after logout extremely secure page requires login'() {
- when: 'logout and request extremely secure page'
- navModule.logout.click()
- casServerLogout.click()
- via ExtremelySecurePage
- then: 'login page is displayed'
- at LoginPage
- }
+ def 'after logout extremely secure page requires login'() {
+ when: 'logout and request extremely secure page'
+ navModule.logout.click()
+ casServerLogout.click()
+ via ExtremelySecurePage
+ then: 'login page is displayed'
+ at LoginPage
+ }
- def 'logging out of the cas server successfully logs out of the cas sample application'() {
- setup: 'login with ROLE_USER'
- via SecurePage
- at LoginPage
- login 'rod'
- at SecurePage
- when: 'logout of the CAS Server'
- go casServerLogoutUrl
- via SecurePage
- then: 'user is logged out of the CAS Service'
- at LoginPage
- }
+ def 'logging out of the cas server successfully logs out of the cas sample application'() {
+ setup: 'login with ROLE_USER'
+ via SecurePage
+ at LoginPage
+ login 'rod'
+ at SecurePage
+ when: 'logout of the CAS Server'
+ go casServerLogoutUrl
+ via SecurePage
+ then: 'user is logged out of the CAS Service'
+ at LoginPage
+ }
}
\ No newline at end of file
diff --git a/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/JettyCasService.groovy b/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/JettyCasService.groovy
index 5660a27d66..6ba5c63fa1 100644
--- a/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/JettyCasService.groovy
+++ b/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/JettyCasService.groovy
@@ -38,87 +38,87 @@ import org.jasig.cas.client.validation.Cas20ProxyTicketValidator;
* @author Rob Winch
*/
class JettyCasService extends Server {
- private Cas20ProxyTicketValidator validator
- private int port = availablePort()
+ private Cas20ProxyTicketValidator validator
+ private int port = availablePort()
- /**
- * The Proxy Granting Ticket. To initialize pgt, authenticate to the CAS Server with the service parameter
- * equal to {@link #serviceUrl()}.
- */
- String pgt
+ /**
+ * The Proxy Granting Ticket. To initialize pgt, authenticate to the CAS Server with the service parameter
+ * equal to {@link #serviceUrl()}.
+ */
+ String pgt
- /**
- * Start the CAS Service which will be available at {@link #serviceUrl()}.
- *
- * @param casServerUrl
- * @return
- */
- def init(String casServerUrl) {
- ProxyGrantingTicketStorage storage = new ProxyGrantingTicketStorageImpl()
- validator = new Cas20ProxyTicketValidator(casServerUrl)
- validator.setAcceptAnyProxy(true)
- validator.setProxyGrantingTicketStorage(storage)
- validator.setProxyCallbackUrl(absoluteUrl('callback'))
+ /**
+ * Start the CAS Service which will be available at {@link #serviceUrl()}.
+ *
+ * @param casServerUrl
+ * @return
+ */
+ def init(String casServerUrl) {
+ ProxyGrantingTicketStorage storage = new ProxyGrantingTicketStorageImpl()
+ validator = new Cas20ProxyTicketValidator(casServerUrl)
+ validator.setAcceptAnyProxy(true)
+ validator.setProxyGrantingTicketStorage(storage)
+ validator.setProxyCallbackUrl(absoluteUrl('callback'))
- String password = System.getProperty('javax.net.ssl.trustStorePassword','password')
- SslSelectChannelConnector ssl_connector = new SslSelectChannelConnector()
- ssl_connector.setPort(port)
- ssl_connector.setKeystore(getTrustStore())
- ssl_connector.setPassword(password)
- ssl_connector.setKeyPassword(password)
- addConnector(ssl_connector)
- setHandler(new AbstractHandler() {
- public void handle(String target, Request baseRequest,
- HttpServletRequest request, HttpServletResponse response)
- throws IOException, ServletException {
- def st = request.getParameter('ticket')
- if(st) {
- JettyCasService.this.validator.validate(st, JettyCasService.this.serviceUrl())
- }
- def pgt = request.getParameter('pgtId')
- if(pgt) {
- JettyCasService.this.pgt = pgt
- }
- response.setStatus(HttpServletResponse.SC_OK);
- baseRequest.setHandled(true);
- }
- })
- start()
- this
- }
+ String password = System.getProperty('javax.net.ssl.trustStorePassword','password')
+ SslSelectChannelConnector ssl_connector = new SslSelectChannelConnector()
+ ssl_connector.setPort(port)
+ ssl_connector.setKeystore(getTrustStore())
+ ssl_connector.setPassword(password)
+ ssl_connector.setKeyPassword(password)
+ addConnector(ssl_connector)
+ setHandler(new AbstractHandler() {
+ public void handle(String target, Request baseRequest,
+ HttpServletRequest request, HttpServletResponse response)
+ throws IOException, ServletException {
+ def st = request.getParameter('ticket')
+ if(st) {
+ JettyCasService.this.validator.validate(st, JettyCasService.this.serviceUrl())
+ }
+ def pgt = request.getParameter('pgtId')
+ if(pgt) {
+ JettyCasService.this.pgt = pgt
+ }
+ response.setStatus(HttpServletResponse.SC_OK);
+ baseRequest.setHandled(true);
+ }
+ })
+ start()
+ this
+ }
- /**
- * Returns the absolute URL that this CAS service is available at.
- * @return
- */
- String serviceUrl() {
- absoluteUrl('service')
- }
+ /**
+ * Returns the absolute URL that this CAS service is available at.
+ * @return
+ */
+ String serviceUrl() {
+ absoluteUrl('service')
+ }
- /**
- * Given a relative url, will provide an absolute url for this CAS Service.
- * @param relativeUrl the relative url (i.e. service, callback, etc)
- * @return
- */
- private String absoluteUrl(String relativeUrl) {
- "https://localhost:${port}/${relativeUrl}"
- }
+ /**
+ * Given a relative url, will provide an absolute url for this CAS Service.
+ * @param relativeUrl the relative url (i.e. service, callback, etc)
+ * @return
+ */
+ private String absoluteUrl(String relativeUrl) {
+ "https://localhost:${port}/${relativeUrl}"
+ }
- private static String getTrustStore() {
- String trustStoreLocation = System.getProperty('javax.net.ssl.trustStore')
- if(trustStoreLocation == null || !new File(trustStoreLocation).isFile()) {
- throw new IllegalStateException('Could not find the trust store at path "'+trustStoreLocation+'". Specify the location using the javax.net.ssl.trustStore system property.')
- }
- trustStoreLocation
- }
- /**
- * Obtains a random available port (i.e. one that is not in use)
- * @return
- */
- private static int availablePort() {
- ServerSocket server = new ServerSocket(0)
- int port = server.localPort
- server.close()
- port
- }
+ private static String getTrustStore() {
+ String trustStoreLocation = System.getProperty('javax.net.ssl.trustStore')
+ if(trustStoreLocation == null || !new File(trustStoreLocation).isFile()) {
+ throw new IllegalStateException('Could not find the trust store at path "'+trustStoreLocation+'". Specify the location using the javax.net.ssl.trustStore system property.')
+ }
+ trustStoreLocation
+ }
+ /**
+ * Obtains a random available port (i.e. one that is not in use)
+ * @return
+ */
+ private static int availablePort() {
+ ServerSocket server = new ServerSocket(0)
+ int port = server.localPort
+ server.close()
+ port
+ }
}
\ No newline at end of file
diff --git a/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/modules/NavModule.groovy b/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/modules/NavModule.groovy
index 5269610e56..064763feb4 100644
--- a/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/modules/NavModule.groovy
+++ b/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/modules/NavModule.groovy
@@ -24,8 +24,8 @@ import org.springframework.security.samples.cas.pages.*
* @author Rob Winch
*/
class NavModule extends Module {
- static content = {
- home(to: HomePage) { $("a", text: "Home") }
- logout(to: LocalLogoutPage) { $("a", text: "Logout") }
- }
+ static content = {
+ home(to: HomePage) { $("a", text: "Home") }
+ logout(to: LocalLogoutPage) { $("a", text: "Logout") }
+ }
}
\ No newline at end of file
diff --git a/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/AccessDeniedPage.groovy b/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/AccessDeniedPage.groovy
index bad135669f..9207893c55 100644
--- a/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/AccessDeniedPage.groovy
+++ b/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/AccessDeniedPage.groovy
@@ -23,5 +23,5 @@ import geb.*
* @author Rob Winch
*/
class AccessDeniedPage extends Page {
- static at = { $("*",text: iContains(~/.*?403.*/)) }
+ static at = { $("*",text: iContains(~/.*?403.*/)) }
}
\ No newline at end of file
diff --git a/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/ExtremelySecurePage.groovy b/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/ExtremelySecurePage.groovy
index 6ba879f965..e3d7ffd5aa 100644
--- a/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/ExtremelySecurePage.groovy
+++ b/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/ExtremelySecurePage.groovy
@@ -24,9 +24,9 @@ import org.springframework.security.samples.cas.modules.*
* @author Rob Winch
*/
class ExtremelySecurePage extends Page {
- static url = "secure/extreme/"
- static at = { assert $('h1').text() == 'VERY Secure Page'; true; }
- static content = {
- navModule { module NavModule }
- }
+ static url = "secure/extreme/"
+ static at = { assert $('h1').text() == 'VERY Secure Page'; true; }
+ static content = {
+ navModule { module NavModule }
+ }
}
\ No newline at end of file
diff --git a/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/HomePage.groovy b/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/HomePage.groovy
index 9305a04b42..c80ffad74a 100644
--- a/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/HomePage.groovy
+++ b/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/HomePage.groovy
@@ -23,10 +23,10 @@ import geb.*
* @author Rob Winch
*/
class HomePage extends Page {
- static at = { assert $('h1').text() == 'Home Page'; true}
- static url = ''
- static content = {
- securePage { $('a',text: 'Secure page') }
- extremelySecurePage { $('a',text: 'Extremely secure page') }
- }
+ static at = { assert $('h1').text() == 'Home Page'; true}
+ static url = ''
+ static content = {
+ securePage { $('a',text: 'Secure page') }
+ extremelySecurePage { $('a',text: 'Extremely secure page') }
+ }
}
\ No newline at end of file
diff --git a/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/LocalLogoutPage.groovy b/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/LocalLogoutPage.groovy
index 7a91fd9748..be9d321a56 100644
--- a/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/LocalLogoutPage.groovy
+++ b/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/LocalLogoutPage.groovy
@@ -27,9 +27,9 @@ import geb.*
* @author Rob Winch
*/
class LocalLogoutPage extends Page {
- static url = 'cas-logout.jsp'
- static at = { assert driver.currentUrl.endsWith(url); true }
- static content = {
- casServerLogout { $('a',text: 'Logout of CAS') }
- }
+ static url = 'cas-logout.jsp'
+ static at = { assert driver.currentUrl.endsWith(url); true }
+ static content = {
+ casServerLogout { $('a',text: 'Logout of CAS') }
+ }
}
diff --git a/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/LoginPage.groovy b/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/LoginPage.groovy
index 5f7793e84e..bd9c8ea16e 100644
--- a/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/LoginPage.groovy
+++ b/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/LoginPage.groovy
@@ -23,24 +23,24 @@ import geb.*
* @author Rob Winch
*/
class LoginPage extends Page {
- static url = loginUrl()
- static at = { assert driver.currentUrl.startsWith(loginUrl()); true}
- static content = {
- login(required:false) { user, password=user ->
- loginForm.username = user
- loginForm.password = password
- submit.click()
- }
- loginForm { $('#login') }
- submit { $('input', type: 'submit') }
- }
+ static url = loginUrl()
+ static at = { assert driver.currentUrl.startsWith(loginUrl()); true}
+ static content = {
+ login(required:false) { user, password=user ->
+ loginForm.username = user
+ loginForm.password = password
+ submit.click()
+ }
+ loginForm { $('#login') }
+ submit { $('input', type: 'submit') }
+ }
- /**
- * Gets the login page url which might change based upon the system properties. This is to support using a randomly available port for CI.
- * @return
- */
- private static String loginUrl() {
- def host = System.getProperty('cas.server.host', 'localhost:9443')
- "https://${host}/cas/login"
- }
+ /**
+ * Gets the login page url which might change based upon the system properties. This is to support using a randomly available port for CI.
+ * @return
+ */
+ private static String loginUrl() {
+ def host = System.getProperty('cas.server.host', 'localhost:9443')
+ "https://${host}/cas/login"
+ }
}
\ No newline at end of file
diff --git a/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/ProxyTicketSamplePage.groovy b/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/ProxyTicketSamplePage.groovy
index 6d9208e8ee..04357f47b7 100644
--- a/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/ProxyTicketSamplePage.groovy
+++ b/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/ProxyTicketSamplePage.groovy
@@ -25,9 +25,9 @@ import org.springframework.security.samples.cas.modules.*
* @author Rob Winch
*/
class ProxyTicketSamplePage extends Page {
- static url = "secure/ptSample"
- static at = { assert $('h1').text() == 'Secure Page using a Proxy Ticket'; true}
- static content = {
- navModule { module NavModule }
- }
+ static url = "secure/ptSample"
+ static at = { assert $('h1').text() == 'Secure Page using a Proxy Ticket'; true}
+ static content = {
+ navModule { module NavModule }
+ }
}
\ No newline at end of file
diff --git a/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/SecurePage.groovy b/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/SecurePage.groovy
index ce860c460b..9ca5322d9e 100644
--- a/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/SecurePage.groovy
+++ b/samples/cas/sample-xml/src/integration-test/groovy/org/springframework/security/samples/cas/pages/SecurePage.groovy
@@ -25,9 +25,9 @@ import org.springframework.security.samples.cas.modules.*
* @author Rob Winch
*/
class SecurePage extends Page {
- static url = "secure/"
- static at = { assert $('h1').text() == 'Secure Page'; true}
- static content = {
- navModule { module NavModule }
- }
+ static url = "secure/"
+ static at = { assert $('h1').text() == 'Secure Page'; true}
+ static content = {
+ navModule { module NavModule }
+ }
}
\ No newline at end of file
diff --git a/samples/cas/sample-xml/src/integration-test/resources/logback-test.xml b/samples/cas/sample-xml/src/integration-test/resources/logback-test.xml
index ffe3e134e3..480bcda899 100644
--- a/samples/cas/sample-xml/src/integration-test/resources/logback-test.xml
+++ b/samples/cas/sample-xml/src/integration-test/resources/logback-test.xml
@@ -1,11 +1,11 @@
-
- %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
-
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
-
+
\ No newline at end of file
diff --git a/samples/cas/server/src/main/webapp/WEB-INF/classes/log4j.xml b/samples/cas/server/src/main/webapp/WEB-INF/classes/log4j.xml
index c1ce7fa6fd..bb38a82ef0 100644
--- a/samples/cas/server/src/main/webapp/WEB-INF/classes/log4j.xml
+++ b/samples/cas/server/src/main/webapp/WEB-INF/classes/log4j.xml
@@ -2,16 +2,16 @@
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/cas/server/src/main/webapp/WEB-INF/deployerConfigContext.xml b/samples/cas/server/src/main/webapp/WEB-INF/deployerConfigContext.xml
index 2279123657..b3409d5a66 100644
--- a/samples/cas/server/src/main/webapp/WEB-INF/deployerConfigContext.xml
+++ b/samples/cas/server/src/main/webapp/WEB-INF/deployerConfigContext.xml
@@ -1,22 +1,22 @@
+ xmlns:b="http://www.springframework.org/schema/beans"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
-
-
-
+
+
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
-
+
-
-
-
-
-
-
+
+
+
+
+
+
-
-
+
+
-
-
-
-
-
+
+
+
+
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
-
-
-
+
+
+
diff --git a/samples/contacts-xml/src/main/webapp/WEB-INF/classes/logback.xml b/samples/contacts-xml/src/main/webapp/WEB-INF/classes/logback.xml
index aa5aa97993..a4392fd3e2 100644
--- a/samples/contacts-xml/src/main/webapp/WEB-INF/classes/logback.xml
+++ b/samples/contacts-xml/src/main/webapp/WEB-INF/classes/logback.xml
@@ -1,14 +1,14 @@
-
- %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
-
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
-
+
diff --git a/samples/contacts-xml/src/main/webapp/WEB-INF/contacts-servlet.xml b/samples/contacts-xml/src/main/webapp/WEB-INF/contacts-servlet.xml
index ab318cc88f..9c3e171c6a 100644
--- a/samples/contacts-xml/src/main/webapp/WEB-INF/contacts-servlet.xml
+++ b/samples/contacts-xml/src/main/webapp/WEB-INF/contacts-servlet.xml
@@ -1,27 +1,27 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:p="http://www.springframework.org/schema/p"
+ xmlns:context="http://www.springframework.org/schema/context"
+ xmlns:mvc="http://www.springframework.org/schema/mvc"
+ xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
+ http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
-
+
-
-
+
+
-
-
+
+
-
-
-
+
+
+
-
-
-
-
+
+
+
+
diff --git a/samples/contacts-xml/src/main/webapp/WEB-INF/remoting-servlet.xml b/samples/contacts-xml/src/main/webapp/WEB-INF/remoting-servlet.xml
index 0044b601e6..994c28a647 100644
--- a/samples/contacts-xml/src/main/webapp/WEB-INF/remoting-servlet.xml
+++ b/samples/contacts-xml/src/main/webapp/WEB-INF/remoting-servlet.xml
@@ -6,44 +6,44 @@
-->
-
-
-
+
+
+
-
-
-
-
-
-
+
+
+
+
+
+
-
-
+
+
-
-
+
+
diff --git a/samples/contacts-xml/src/test/resources/logback-test.xml b/samples/contacts-xml/src/test/resources/logback-test.xml
index f293b342dc..ddf04b2972 100644
--- a/samples/contacts-xml/src/test/resources/logback-test.xml
+++ b/samples/contacts-xml/src/test/resources/logback-test.xml
@@ -1,14 +1,14 @@
-
- %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
-
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
-
+
diff --git a/samples/dms-xml/src/main/resources/applicationContext-dms-insecure.xml b/samples/dms-xml/src/main/resources/applicationContext-dms-insecure.xml
index fdda3cc9c3..24acf276ae 100755
--- a/samples/dms-xml/src/main/resources/applicationContext-dms-insecure.xml
+++ b/samples/dms-xml/src/main/resources/applicationContext-dms-insecure.xml
@@ -5,36 +5,36 @@
-->
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
-
-
-
+
+
+
-
-
-
-
-
-
+
+
+
+
+
+
-
-
-
- sample.dms.DocumentDao.*=PROPAGATION_REQUIRED
-
-
-
-
+
+
+
+ sample.dms.DocumentDao.*=PROPAGATION_REQUIRED
+
+
+
+
-
-
-
+
+
+
-
-
-
-
+
+
+
+
diff --git a/samples/dms-xml/src/main/resources/applicationContext-dms-secure.xml b/samples/dms-xml/src/main/resources/applicationContext-dms-secure.xml
index 59853dbcc8..02b8ec5270 100755
--- a/samples/dms-xml/src/main/resources/applicationContext-dms-secure.xml
+++ b/samples/dms-xml/src/main/resources/applicationContext-dms-secure.xml
@@ -6,77 +6,77 @@
-->
+ xmlns:s="http://www.springframework.org/schema/security"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
-
-
-
+
+
+
-
-
-
-
-
-
+
+
+
+
+
+
-
-
-
- sample.dms.secured.SecureDocumentDao.*=PROPAGATION_REQUIRED
- sample.dms.DocumentDao.*=PROPAGATION_REQUIRED
- org.springframework.security.acls.model.AclService.*=PROPAGATION_REQUIRED
- org.springframework.security.acls.model.MutableAclService.*=PROPAGATION_REQUIRED
- org.springframework.security.acls.jdbc.JdbcMutableAclService.*=PROPAGATION_REQUIRED
- org.springframework.security.acls.jdbc.JdbcAclService.*=PROPAGATION_REQUIRED
-
-
-
-
+
+
+
+ sample.dms.secured.SecureDocumentDao.*=PROPAGATION_REQUIRED
+ sample.dms.DocumentDao.*=PROPAGATION_REQUIRED
+ org.springframework.security.acls.model.AclService.*=PROPAGATION_REQUIRED
+ org.springframework.security.acls.model.MutableAclService.*=PROPAGATION_REQUIRED
+ org.springframework.security.acls.jdbc.JdbcMutableAclService.*=PROPAGATION_REQUIRED
+ org.springframework.security.acls.jdbc.JdbcAclService.*=PROPAGATION_REQUIRED
+
+
+
+
-
-
-
-
+
+
+
+
-
-
-
-
-
+
+
+
+
+
-
+
-
-
-
+
+
+
-
+
-
-
-
-
-
+
+
+
+
+
-
-
+
+
-
+
@@ -86,13 +86,13 @@
-
+
-
+
-
+
@@ -101,145 +101,145 @@
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
+
+
+
+
+
-
-
-
-
-
+
+
+
+
+
-
-
-
-
-
-
-
+
+
+
+
+
+
+
-
-
-
+
+
+
-
-
-
-
+
+
+
+
-
-
-
-
-
+
+
+
+
+
diff --git a/samples/dms-xml/src/main/resources/applicationContext-dms-shared.xml b/samples/dms-xml/src/main/resources/applicationContext-dms-shared.xml
index de98911b05..cdd9167ed4 100755
--- a/samples/dms-xml/src/main/resources/applicationContext-dms-shared.xml
+++ b/samples/dms-xml/src/main/resources/applicationContext-dms-shared.xml
@@ -4,15 +4,15 @@
-
-->
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
-
-
-
+
+
+
-
+
-
+
diff --git a/samples/gae-xml/src/main/webapp/WEB-INF/appengine-web.xml b/samples/gae-xml/src/main/webapp/WEB-INF/appengine-web.xml
index 3a42c3f899..bdda5dfcc4 100644
--- a/samples/gae-xml/src/main/webapp/WEB-INF/appengine-web.xml
+++ b/samples/gae-xml/src/main/webapp/WEB-INF/appengine-web.xml
@@ -1,10 +1,10 @@
- gaespringsec
- 1
- true
+ gaespringsec
+ 1
+ true
-
-
-
+
+
+
diff --git a/samples/gae-xml/src/main/webapp/WEB-INF/applicationContext-security.xml b/samples/gae-xml/src/main/webapp/WEB-INF/applicationContext-security.xml
index cac56bce24..005b54b627 100644
--- a/samples/gae-xml/src/main/webapp/WEB-INF/applicationContext-security.xml
+++ b/samples/gae-xml/src/main/webapp/WEB-INF/applicationContext-security.xml
@@ -1,47 +1,47 @@
+ xmlns:b="http://www.springframework.org/schema/beans"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
-
-
-
-
+
+
+
+
-
-
-
-
-
-
-
+
+
+
+
+
+
+
-
+
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
+
+
+
-
-
-
+
+
+
-
+
diff --git a/samples/gae-xml/src/main/webapp/WEB-INF/gae-servlet.xml b/samples/gae-xml/src/main/webapp/WEB-INF/gae-servlet.xml
index 6835929075..34a38b2bcd 100644
--- a/samples/gae-xml/src/main/webapp/WEB-INF/gae-servlet.xml
+++ b/samples/gae-xml/src/main/webapp/WEB-INF/gae-servlet.xml
@@ -1,25 +1,25 @@
+ xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
+ xmlns:mvc="http://www.springframework.org/schema/mvc"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
+ http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
-
-
+
+
-
+
-
-
+
+
-
-
-
+
+
+
-
-
-
-
+
+
+
+
diff --git a/samples/helloworld-jc/src/integration-test/groovy/org/springframework/security/samples/HelloWorldJcTests.groovy b/samples/helloworld-jc/src/integration-test/groovy/org/springframework/security/samples/HelloWorldJcTests.groovy
index c21fa82aca..341679e4d0 100644
--- a/samples/helloworld-jc/src/integration-test/groovy/org/springframework/security/samples/HelloWorldJcTests.groovy
+++ b/samples/helloworld-jc/src/integration-test/groovy/org/springframework/security/samples/HelloWorldJcTests.groovy
@@ -27,30 +27,30 @@ import org.springframework.security.samples.pages.*
*/
@Stepwise
class HelloWorldJcTests extends GebReportingSpec {
- def 'access home page with unauthenticated user sends to login page'() {
- when: 'Unauthenticated user accesses the Home Page'
- via HomePage
- then: 'The login page is displayed'
- at LoginPage
- }
+ def 'access home page with unauthenticated user sends to login page'() {
+ when: 'Unauthenticated user accesses the Home Page'
+ via HomePage
+ then: 'The login page is displayed'
+ at LoginPage
+ }
- def 'authenticated user is sent to original page'() {
- when: 'user authenticates'
- login()
- then: 'The home page is displayed'
- at HomePage
- and: 'The username is displayed'
- message == 'Hello user'
- }
+ def 'authenticated user is sent to original page'() {
+ when: 'user authenticates'
+ login()
+ then: 'The home page is displayed'
+ at HomePage
+ and: 'The username is displayed'
+ message == 'Hello user'
+ }
- def 'authenticated user logs out'() {
- when: 'user logs out'
- logout()
- then: 'the login page is displayed'
- at LoginPage
- when: 'Unauthenticated user accesses the Home Page'
- via HomePage
- then: 'The login page is displayed'
- at LoginPage
- }
+ def 'authenticated user logs out'() {
+ when: 'user logs out'
+ logout()
+ then: 'the login page is displayed'
+ at LoginPage
+ when: 'Unauthenticated user accesses the Home Page'
+ via HomePage
+ then: 'The login page is displayed'
+ at LoginPage
+ }
}
\ No newline at end of file
diff --git a/samples/helloworld-jc/src/integration-test/groovy/org/springframework/security/samples/pages/LoginPage.groovy b/samples/helloworld-jc/src/integration-test/groovy/org/springframework/security/samples/pages/LoginPage.groovy
index b2a553064b..a227f98a05 100644
--- a/samples/helloworld-jc/src/integration-test/groovy/org/springframework/security/samples/pages/LoginPage.groovy
+++ b/samples/helloworld-jc/src/integration-test/groovy/org/springframework/security/samples/pages/LoginPage.groovy
@@ -23,15 +23,15 @@ import geb.*
* @author Rob Winch
*/
class LoginPage extends Page {
- static url = 'login'
- static at = { assert driver.title == 'Login Page'; true}
- static content = {
- login(required:false) { user='user', password='password' ->
- loginForm.username = user
- loginForm.password = password
- submit.click()
- }
- loginForm { $('form') }
- submit { $('input', type: 'submit') }
- }
+ static url = 'login'
+ static at = { assert driver.title == 'Login Page'; true}
+ static content = {
+ login(required:false) { user='user', password='password' ->
+ loginForm.username = user
+ loginForm.password = password
+ submit.click()
+ }
+ loginForm { $('form') }
+ submit { $('input', type: 'submit') }
+ }
}
\ No newline at end of file
diff --git a/samples/helloworld-xml/src/integration-test/groovy/org/springframework/security/samples/HelloWorldXmlTests.groovy b/samples/helloworld-xml/src/integration-test/groovy/org/springframework/security/samples/HelloWorldXmlTests.groovy
index bac45484be..5444063f26 100644
--- a/samples/helloworld-xml/src/integration-test/groovy/org/springframework/security/samples/HelloWorldXmlTests.groovy
+++ b/samples/helloworld-xml/src/integration-test/groovy/org/springframework/security/samples/HelloWorldXmlTests.groovy
@@ -28,30 +28,30 @@ import org.springframework.security.samples.pages.*
*/
@Stepwise
class HelloWorldXmlTests extends GebReportingSpec {
- def 'access home page with unauthenticated user sends to login page'() {
- when: 'Unauthenticated user accesses the Home Page'
- via HomePage
- then: 'The login page is displayed'
- at LoginPage
- }
+ def 'access home page with unauthenticated user sends to login page'() {
+ when: 'Unauthenticated user accesses the Home Page'
+ via HomePage
+ then: 'The login page is displayed'
+ at LoginPage
+ }
- def 'authenticated user is sent to original page'() {
- when: 'user authenticates'
- login()
- then: 'The home page is displayed'
- at HomePage
- and: 'The username is displayed'
- message == 'Hello user'
- }
+ def 'authenticated user is sent to original page'() {
+ when: 'user authenticates'
+ login()
+ then: 'The home page is displayed'
+ at HomePage
+ and: 'The username is displayed'
+ message == 'Hello user'
+ }
- def 'authenticated user logs out'() {
- when: 'user logs out'
- logout()
- then: 'the login page is displayed'
- at LoginPage
- when: 'Unauthenticated user accesses the Home Page'
- via HomePage
- then: 'The login page is displayed'
- at LoginPage
- }
+ def 'authenticated user logs out'() {
+ when: 'user logs out'
+ logout()
+ then: 'the login page is displayed'
+ at LoginPage
+ when: 'Unauthenticated user accesses the Home Page'
+ via HomePage
+ then: 'The login page is displayed'
+ at LoginPage
+ }
}
\ No newline at end of file
diff --git a/samples/helloworld-xml/src/integration-test/groovy/org/springframework/security/samples/pages/HomePage.groovy b/samples/helloworld-xml/src/integration-test/groovy/org/springframework/security/samples/pages/HomePage.groovy
index 83e1128cfd..beb1d580d1 100644
--- a/samples/helloworld-xml/src/integration-test/groovy/org/springframework/security/samples/pages/HomePage.groovy
+++ b/samples/helloworld-xml/src/integration-test/groovy/org/springframework/security/samples/pages/HomePage.groovy
@@ -23,10 +23,10 @@ import geb.*
* @author Rob Winch
*/
class HomePage extends Page {
- static url = ''
- static at = { assert driver.title == 'Hello Security'; true}
- static content = {
- message { $('p').text() }
- logout { $('input', type: 'submit').click() }
- }
+ static url = ''
+ static at = { assert driver.title == 'Hello Security'; true}
+ static content = {
+ message { $('p').text() }
+ logout { $('input', type: 'submit').click() }
+ }
}
\ No newline at end of file
diff --git a/samples/helloworld-xml/src/integration-test/groovy/org/springframework/security/samples/pages/LoginPage.groovy b/samples/helloworld-xml/src/integration-test/groovy/org/springframework/security/samples/pages/LoginPage.groovy
index b2a553064b..a227f98a05 100644
--- a/samples/helloworld-xml/src/integration-test/groovy/org/springframework/security/samples/pages/LoginPage.groovy
+++ b/samples/helloworld-xml/src/integration-test/groovy/org/springframework/security/samples/pages/LoginPage.groovy
@@ -23,15 +23,15 @@ import geb.*
* @author Rob Winch
*/
class LoginPage extends Page {
- static url = 'login'
- static at = { assert driver.title == 'Login Page'; true}
- static content = {
- login(required:false) { user='user', password='password' ->
- loginForm.username = user
- loginForm.password = password
- submit.click()
- }
- loginForm { $('form') }
- submit { $('input', type: 'submit') }
- }
+ static url = 'login'
+ static at = { assert driver.title == 'Login Page'; true}
+ static content = {
+ login(required:false) { user='user', password='password' ->
+ loginForm.username = user
+ loginForm.password = password
+ submit.click()
+ }
+ loginForm { $('form') }
+ submit { $('input', type: 'submit') }
+ }
}
\ No newline at end of file
diff --git a/samples/helloworld-xml/src/main/webapp/WEB-INF/spring/security.xml b/samples/helloworld-xml/src/main/webapp/WEB-INF/spring/security.xml
index 5f8031a5ac..d39e52a2f1 100644
--- a/samples/helloworld-xml/src/main/webapp/WEB-INF/spring/security.xml
+++ b/samples/helloworld-xml/src/main/webapp/WEB-INF/spring/security.xml
@@ -1,11 +1,11 @@
-
+ xmlns:b="http://www.springframework.org/schema/beans"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
+ http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
+
-
-
-
+
+
+
\ No newline at end of file
diff --git a/samples/jaas-xml/src/main/resources/applicationContext-security.xml b/samples/jaas-xml/src/main/resources/applicationContext-security.xml
index 267d75865a..42228d8414 100644
--- a/samples/jaas-xml/src/main/resources/applicationContext-security.xml
+++ b/samples/jaas-xml/src/main/resources/applicationContext-security.xml
@@ -1,52 +1,52 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:sec="http://www.springframework.org/schema/security"
+ xmlns:p="http://www.springframework.org/schema/p"
+ xmlns:util="http://www.springframework.org/schema/util"
+ xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
+ http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
-
-
-
+
+
+
-
-
-
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/ldap-xml/src/main/webapp/WEB-INF/applicationContext-security.xml b/samples/ldap-xml/src/main/webapp/WEB-INF/applicationContext-security.xml
index e585af29b7..16a8ead1a1 100644
--- a/samples/ldap-xml/src/main/webapp/WEB-INF/applicationContext-security.xml
+++ b/samples/ldap-xml/src/main/webapp/WEB-INF/applicationContext-security.xml
@@ -1,65 +1,65 @@
+ xmlns:s="http://www.springframework.org/schema/security"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
-
-
-
-
+
+
+
+
-
-
-
-
+
+
+
+
-
+
-
+
-
-
-
-
+
+
+
+
-
+
-
-
-
-
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/ldap-xml/src/main/webapp/WEB-INF/classes/logback.xml b/samples/ldap-xml/src/main/webapp/WEB-INF/classes/logback.xml
index 0bbb0e3369..1f4d925e4c 100644
--- a/samples/ldap-xml/src/main/webapp/WEB-INF/classes/logback.xml
+++ b/samples/ldap-xml/src/main/webapp/WEB-INF/classes/logback.xml
@@ -1,14 +1,14 @@
-
- %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
-
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
-
+
diff --git a/samples/messages-jc/src/main/resources/tiles/tiles-def.xml b/samples/messages-jc/src/main/resources/tiles/tiles-def.xml
index 944570744e..691e4c8858 100644
--- a/samples/messages-jc/src/main/resources/tiles/tiles-def.xml
+++ b/samples/messages-jc/src/main/resources/tiles/tiles-def.xml
@@ -1,57 +1,57 @@
+ "-//Apache Software Foundation//DTD Tiles Configuration 2.1//EN"
+ "http://tiles.apache.org/dtds/tiles-config_2_1.dtd">
-
-
-
+ template="layout">
+
+
+
+ template="messages/{1} :: content"/>
+ template="messages/{1} :: title"/>
+ template="messages/{1} :: /html/head/link"/>
-
-
-
+ template="layout">
+
+
+
+ template="user/{1} :: content"/>
+ template="user/{1} :: title"/>
+ template="user/{1} :: /html/head/link"/>
-
-
-
+ template="layout">
+
+
+
+ template="{1} :: content"/>
+ template="{1} :: title"/>
+ template="{1} :: /html/head/link"/>
\ No newline at end of file
diff --git a/samples/servletapi-xml/src/main/webapp/WEB-INF/spring-servlet.xml b/samples/servletapi-xml/src/main/webapp/WEB-INF/spring-servlet.xml
index 404f7b815c..b8b114d6f7 100644
--- a/samples/servletapi-xml/src/main/webapp/WEB-INF/spring-servlet.xml
+++ b/samples/servletapi-xml/src/main/webapp/WEB-INF/spring-servlet.xml
@@ -5,8 +5,8 @@
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
+ http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
+ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
@@ -18,7 +18,7 @@
+ p:prefix="/WEB-INF/views/"
+ p:suffix=".jsp" />
\ No newline at end of file
diff --git a/samples/tutorial-xml/src/main/resources/applicationContext-business.xml b/samples/tutorial-xml/src/main/resources/applicationContext-business.xml
index 3442315314..6745f83d34 100644
--- a/samples/tutorial-xml/src/main/resources/applicationContext-business.xml
+++ b/samples/tutorial-xml/src/main/resources/applicationContext-business.xml
@@ -1,24 +1,24 @@
-
+
-
-
-
+
+
+
-
-
-
-
+
+
+
+
diff --git a/samples/tutorial-xml/src/main/webapp/WEB-INF/bank-servlet.xml b/samples/tutorial-xml/src/main/webapp/WEB-INF/bank-servlet.xml
index b6e9e7075b..006c9b9c5d 100644
--- a/samples/tutorial-xml/src/main/webapp/WEB-INF/bank-servlet.xml
+++ b/samples/tutorial-xml/src/main/webapp/WEB-INF/bank-servlet.xml
@@ -1,20 +1,20 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
-
-
-
+
+
+
-
-
-
+
+
+
-
-
-
-
+
+
+
+
diff --git a/samples/tutorial-xml/src/main/webapp/WEB-INF/classes/logback.xml b/samples/tutorial-xml/src/main/webapp/WEB-INF/classes/logback.xml
index aa5aa97993..a4392fd3e2 100644
--- a/samples/tutorial-xml/src/main/webapp/WEB-INF/classes/logback.xml
+++ b/samples/tutorial-xml/src/main/webapp/WEB-INF/classes/logback.xml
@@ -1,14 +1,14 @@
-
- %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
-
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
-
+
diff --git a/sandbox/heavyduty/src/main/java/bigbank/Account.java b/sandbox/heavyduty/src/main/java/bigbank/Account.java
index 6b5b986980..695642304f 100755
--- a/sandbox/heavyduty/src/main/java/bigbank/Account.java
+++ b/sandbox/heavyduty/src/main/java/bigbank/Account.java
@@ -9,42 +9,42 @@ package bigbank;
* @author Ben Alex
*/
public class Account {
- private long id = -1;
- private String holder;
- private double balance;
+ private long id = -1;
+ private String holder;
+ private double balance;
- public Account(String holder) {
- super();
- this.holder = holder;
- }
+ public Account(String holder) {
+ super();
+ this.holder = holder;
+ }
- public long getId() {
- return id;
- }
+ public long getId() {
+ return id;
+ }
- public void setId(long id) {
- this.id = id;
- }
+ public void setId(long id) {
+ this.id = id;
+ }
- public String getHolder() {
- return holder;
- }
+ public String getHolder() {
+ return holder;
+ }
- public void setHolder(String holder) {
- this.holder = holder;
- }
+ public void setHolder(String holder) {
+ this.holder = holder;
+ }
- public double getBalance() {
- return balance;
- }
+ public double getBalance() {
+ return balance;
+ }
- public void setBalance(double balance) {
- this.balance = balance;
- }
+ public void setBalance(double balance) {
+ this.balance = balance;
+ }
- public String toString() {
- return "Account[id=" + id + ",balance=" + balance +",holder=" + holder + "]";
- }
+ public String toString() {
+ return "Account[id=" + id + ",balance=" + balance +",holder=" + holder + "]";
+ }
}
diff --git a/sandbox/heavyduty/src/main/java/bigbank/BankDao.java b/sandbox/heavyduty/src/main/java/bigbank/BankDao.java
index 6c22619305..67806a7e76 100755
--- a/sandbox/heavyduty/src/main/java/bigbank/BankDao.java
+++ b/sandbox/heavyduty/src/main/java/bigbank/BankDao.java
@@ -1,7 +1,7 @@
package bigbank;
public interface BankDao {
- public Account readAccount(Long id);
- public void createOrUpdateAccount(Account account);
- public Account[] findAccounts();
+ public Account readAccount(Long id);
+ public void createOrUpdateAccount(Account account);
+ public Account[] findAccounts();
}
diff --git a/sandbox/heavyduty/src/main/java/bigbank/BankDaoStub.java b/sandbox/heavyduty/src/main/java/bigbank/BankDaoStub.java
index 2bfbbeaa4b..0cb6018d84 100755
--- a/sandbox/heavyduty/src/main/java/bigbank/BankDaoStub.java
+++ b/sandbox/heavyduty/src/main/java/bigbank/BankDaoStub.java
@@ -4,29 +4,29 @@ import java.util.HashMap;
import java.util.Map;
public class BankDaoStub implements BankDao {
- private long id = 0;
- private Map accounts = new HashMap();
+ private long id = 0;
+ private Map accounts = new HashMap();
- public void createOrUpdateAccount(Account account) {
- if (account.getId() == -1) {
- id++;
- account.setId(id);
- }
- accounts.put(new Long(account.getId()), account);
- System.out.println("SAVE: " + account);
- }
+ public void createOrUpdateAccount(Account account) {
+ if (account.getId() == -1) {
+ id++;
+ account.setId(id);
+ }
+ accounts.put(new Long(account.getId()), account);
+ System.out.println("SAVE: " + account);
+ }
- public Account[] findAccounts() {
- Account[] a = (Account[]) accounts.values().toArray(new Account[] {});
- System.out.println("Returning " + a.length + " account(s):");
- for (int i = 0; i < a.length; i++) {
- System.out.println(" > " + a[i]);
- }
- return a;
- }
+ public Account[] findAccounts() {
+ Account[] a = (Account[]) accounts.values().toArray(new Account[] {});
+ System.out.println("Returning " + a.length + " account(s):");
+ for (int i = 0; i < a.length; i++) {
+ System.out.println(" > " + a[i]);
+ }
+ return a;
+ }
- public Account readAccount(Long id) {
- return (Account) accounts.get(id);
- }
+ public Account readAccount(Long id) {
+ return (Account) accounts.get(id);
+ }
}
diff --git a/sandbox/heavyduty/src/main/java/bigbank/BankService.java b/sandbox/heavyduty/src/main/java/bigbank/BankService.java
index 6f99db8546..75478d32d4 100755
--- a/sandbox/heavyduty/src/main/java/bigbank/BankService.java
+++ b/sandbox/heavyduty/src/main/java/bigbank/BankService.java
@@ -4,12 +4,12 @@ import org.springframework.security.access.annotation.Secured;
public interface BankService {
- @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
- public Account readAccount(Long id);
+ @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
+ public Account readAccount(Long id);
- @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
- public Account[] findAccounts();
+ @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
+ public Account[] findAccounts();
- @Secured("ROLE_TELLER")
- public Account post(Account account, double amount);
+ @Secured("ROLE_TELLER")
+ public Account post(Account account, double amount);
}
diff --git a/sandbox/heavyduty/src/main/java/bigbank/BankServiceImpl.java b/sandbox/heavyduty/src/main/java/bigbank/BankServiceImpl.java
index 31a384cafe..0dbdfd5a16 100755
--- a/sandbox/heavyduty/src/main/java/bigbank/BankServiceImpl.java
+++ b/sandbox/heavyduty/src/main/java/bigbank/BankServiceImpl.java
@@ -4,37 +4,37 @@ import org.aspectj.lang.annotation.Pointcut;
import org.springframework.util.Assert;
public class BankServiceImpl implements BankService {
- private BankDao bankDao;
+ private BankDao bankDao;
- // Not used unless you declare a
- @Pointcut("execution(* bigbank.BankServiceImpl.*(..))")
- public void myPointcut() {}
+ // Not used unless you declare a
+ @Pointcut("execution(* bigbank.BankServiceImpl.*(..))")
+ public void myPointcut() {}
- public BankServiceImpl(BankDao bankDao) {
- Assert.notNull(bankDao);
- this.bankDao = bankDao;
- }
+ public BankServiceImpl(BankDao bankDao) {
+ Assert.notNull(bankDao);
+ this.bankDao = bankDao;
+ }
- public Account[] findAccounts() {
- return this.bankDao.findAccounts();
- }
+ public Account[] findAccounts() {
+ return this.bankDao.findAccounts();
+ }
- public Account post(Account account, double amount) {
- Assert.notNull(account);
- Assert.notNull(account.getId());
+ public Account post(Account account, double amount) {
+ Assert.notNull(account);
+ Assert.notNull(account.getId());
- // We read account bank from DAO so it reflects the latest balance
- Account a = bankDao.readAccount(account.getId());
- if (account == null) {
- throw new IllegalArgumentException("Couldn't find requested account");
- }
+ // We read account bank from DAO so it reflects the latest balance
+ Account a = bankDao.readAccount(account.getId());
+ if (account == null) {
+ throw new IllegalArgumentException("Couldn't find requested account");
+ }
- a.setBalance(a.getBalance() + amount);
- bankDao.createOrUpdateAccount(a);
- return a;
- }
+ a.setBalance(a.getBalance() + amount);
+ bankDao.createOrUpdateAccount(a);
+ return a;
+ }
- public Account readAccount(Long id) {
- return bankDao.readAccount(id);
- }
+ public Account readAccount(Long id) {
+ return bankDao.readAccount(id);
+ }
}
diff --git a/sandbox/heavyduty/src/main/java/bigbank/SeedData.java b/sandbox/heavyduty/src/main/java/bigbank/SeedData.java
index 6eaf6ec16c..43fc536737 100755
--- a/sandbox/heavyduty/src/main/java/bigbank/SeedData.java
+++ b/sandbox/heavyduty/src/main/java/bigbank/SeedData.java
@@ -4,18 +4,18 @@ import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
public class SeedData implements InitializingBean{
- private BankDao bankDao;
+ private BankDao bankDao;
- public void afterPropertiesSet() throws Exception {
- Assert.notNull(bankDao);
- bankDao.createOrUpdateAccount(new Account("rod"));
- bankDao.createOrUpdateAccount(new Account("dianne"));
- bankDao.createOrUpdateAccount(new Account("scott"));
- bankDao.createOrUpdateAccount(new Account("peter"));
- }
+ public void afterPropertiesSet() throws Exception {
+ Assert.notNull(bankDao);
+ bankDao.createOrUpdateAccount(new Account("rod"));
+ bankDao.createOrUpdateAccount(new Account("dianne"));
+ bankDao.createOrUpdateAccount(new Account("scott"));
+ bankDao.createOrUpdateAccount(new Account("peter"));
+ }
- public void setBankDao(BankDao bankDao) {
- this.bankDao = bankDao;
- }
+ public void setBankDao(BankDao bankDao) {
+ this.bankDao = bankDao;
+ }
}
diff --git a/sandbox/heavyduty/src/main/java/bigbank/web/ListAccounts.java b/sandbox/heavyduty/src/main/java/bigbank/web/ListAccounts.java
index 50ffdcf18a..959a7500ac 100755
--- a/sandbox/heavyduty/src/main/java/bigbank/web/ListAccounts.java
+++ b/sandbox/heavyduty/src/main/java/bigbank/web/ListAccounts.java
@@ -11,18 +11,18 @@ import bigbank.BankService;
public class ListAccounts implements Controller {
- private BankService bankService;
+ private BankService bankService;
- public ListAccounts(BankService bankService) {
- Assert.notNull(bankService);
- this.bankService = bankService;
- }
+ public ListAccounts(BankService bankService) {
+ Assert.notNull(bankService);
+ this.bankService = bankService;
+ }
- public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
- // Actual business logic
- ModelAndView mav = new ModelAndView("listAccounts");
- mav.addObject("accounts", bankService.findAccounts());
- return mav;
- }
+ public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ // Actual business logic
+ ModelAndView mav = new ModelAndView("listAccounts");
+ mav.addObject("accounts", bankService.findAccounts());
+ return mav;
+ }
}
diff --git a/sandbox/heavyduty/src/main/java/bigbank/web/PostAccounts.java b/sandbox/heavyduty/src/main/java/bigbank/web/PostAccounts.java
index ae9d99bd81..52fd4fe934 100755
--- a/sandbox/heavyduty/src/main/java/bigbank/web/PostAccounts.java
+++ b/sandbox/heavyduty/src/main/java/bigbank/web/PostAccounts.java
@@ -13,26 +13,26 @@ import bigbank.BankService;
public class PostAccounts implements Controller {
- private BankService bankService;
+ private BankService bankService;
- public PostAccounts(BankService bankService) {
- Assert.notNull(bankService);
- this.bankService = bankService;
- }
+ public PostAccounts(BankService bankService) {
+ Assert.notNull(bankService);
+ this.bankService = bankService;
+ }
- public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
- // Security check (this is unnecessary if Spring Security is performing the authorization)
+ public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ // Security check (this is unnecessary if Spring Security is performing the authorization)
// if (!request.isUserInRole("ROLE_TELLER")) {
// throw new AccessDeniedException("You must be a teller to post transactions (Spring Security message)"); // only for Spring Security managed authentication
// }
- // Actual business logic
- Long id = ServletRequestUtils.getRequiredLongParameter(request, "id");
- Double amount = ServletRequestUtils.getRequiredDoubleParameter(request, "amount");
- Account a = bankService.readAccount(id);
- bankService.post(a, amount);
+ // Actual business logic
+ Long id = ServletRequestUtils.getRequiredLongParameter(request, "id");
+ Double amount = ServletRequestUtils.getRequiredDoubleParameter(request, "amount");
+ Account a = bankService.readAccount(id);
+ bankService.post(a, amount);
- return new ModelAndView("redirect:listAccounts.html");
- }
+ return new ModelAndView("redirect:listAccounts.html");
+ }
}
diff --git a/sandbox/heavyduty/src/main/java/heavyduty/web/TestMultiActionController.java b/sandbox/heavyduty/src/main/java/heavyduty/web/TestMultiActionController.java
index c5ec4e11d7..a9a0c8fbdf 100644
--- a/sandbox/heavyduty/src/main/java/heavyduty/web/TestMultiActionController.java
+++ b/sandbox/heavyduty/src/main/java/heavyduty/web/TestMultiActionController.java
@@ -17,34 +17,34 @@ import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
* Reproduces SEC-830.
*/
public class TestMultiActionController extends MultiActionController {
- public static final String VIEW_NAME = "multi-action-test";
+ public static final String VIEW_NAME = "multi-action-test";
- public String login(HttpServletRequest request, HttpServletResponse response) {
- return "login";
- }
+ public String login(HttpServletRequest request, HttpServletResponse response) {
+ return "login";
+ }
- public void step1(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- String[] x = request.getParameterValues("x");
- logger.info("x= " + (x == null ? "null" : Arrays.asList(x)));
- String[] y = request.getParameterValues("y");
- logger.info("y = " + (y == null ? "null" : Arrays.asList(y)));
- request.getRequestDispatcher("/testMulti.htm?action=step1xtra&x=5&x=5").forward(request, response);
- }
+ public void step1(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+ String[] x = request.getParameterValues("x");
+ logger.info("x= " + (x == null ? "null" : Arrays.asList(x)));
+ String[] y = request.getParameterValues("y");
+ logger.info("y = " + (y == null ? "null" : Arrays.asList(y)));
+ request.getRequestDispatcher("/testMulti.htm?action=step1xtra&x=5&x=5").forward(request, response);
+ }
- public ModelAndView step1xtra(HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException {
- logger.info("x = " + Arrays.asList(request.getParameterValues("x")));
- return createView("step2");
- }
+ public ModelAndView step1xtra(HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException {
+ logger.info("x = " + Arrays.asList(request.getParameterValues("x")));
+ return createView("step2");
+ }
- public ModelAndView step2(HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException {
- return createView("step1");
- }
+ public ModelAndView step2(HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException {
+ return createView("step1");
+ }
- private ModelAndView createView(String name) {
- Map model = new HashMap();
- model.put("nextAction", name);
- return new ModelAndView(VIEW_NAME, model);
- }
+ private ModelAndView createView(String name) {
+ Map model = new HashMap();
+ model.put("nextAction", name);
+ return new ModelAndView(VIEW_NAME, model);
+ }
}
diff --git a/sandbox/heavyduty/src/main/java/sample/TestVoter.java b/sandbox/heavyduty/src/main/java/sample/TestVoter.java
index 31d20c2330..27b31d1ac4 100644
--- a/sandbox/heavyduty/src/main/java/sample/TestVoter.java
+++ b/sandbox/heavyduty/src/main/java/sample/TestVoter.java
@@ -9,21 +9,21 @@ import org.springframework.security.core.Authentication;
public class TestVoter implements AccessDecisionVoter {
- public boolean supports(ConfigAttribute attribute) {
- return true;
- }
+ public boolean supports(ConfigAttribute attribute) {
+ return true;
+ }
- public boolean supports(Class> clazz) {
- return MethodInvocation.class.isAssignableFrom(clazz);
- }
+ public boolean supports(Class> clazz) {
+ return MethodInvocation.class.isAssignableFrom(clazz);
+ }
- public int vote(Authentication authentication, Object object, Collection config) {
- MethodInvocation mi = (MethodInvocation) object;
+ public int vote(Authentication authentication, Object object, Collection config) {
+ MethodInvocation mi = (MethodInvocation) object;
- mi.getMethod().getParameterAnnotations();
+ mi.getMethod().getParameterAnnotations();
- return ACCESS_GRANTED;
- }
+ return ACCESS_GRANTED;
+ }
}
diff --git a/sandbox/heavyduty/src/main/java/sample/dao/GenericDAO.java b/sandbox/heavyduty/src/main/java/sample/dao/GenericDAO.java
index 93f2483e89..ab00438321 100755
--- a/sandbox/heavyduty/src/main/java/sample/dao/GenericDAO.java
+++ b/sandbox/heavyduty/src/main/java/sample/dao/GenericDAO.java
@@ -8,39 +8,39 @@ import java.io.Serializable;
*/
public interface GenericDAO
{
- /**
- * persist
- * @param transientInstance objet to persist
- */
- void persist(T transientInstance);
+ /**
+ * persist
+ * @param transientInstance objet to persist
+ */
+ void persist(T transientInstance);
- /**
- * refresh
- * @param instance objet to refresh
- */
- void refresh(T instance);
+ /**
+ * refresh
+ * @param instance objet to refresh
+ */
+ void refresh(T instance);
- /**
- * delete
- * @param persistentInstance objet to delete
- */
- void delete(T persistentInstance);
+ /**
+ * delete
+ * @param persistentInstance objet to delete
+ */
+ void delete(T persistentInstance);
- /**
- * merge
- * @param detachedInstance objet to merge
- * @return merged object
- */
- T merge(T detachedInstance);
+ /**
+ * merge
+ * @param detachedInstance objet to merge
+ * @return merged object
+ */
+ T merge(T detachedInstance);
- /**
- * read
- * @param id of object to read
- * @return read object
- */
- T read(PK id);
+ /**
+ * read
+ * @param id of object to read
+ * @return read object
+ */
+ T read(PK id);
}
\ No newline at end of file
diff --git a/sandbox/heavyduty/src/main/java/sample/dao/UserDAO.java b/sandbox/heavyduty/src/main/java/sample/dao/UserDAO.java
index 51f3e54f15..b7f339b42e 100755
--- a/sandbox/heavyduty/src/main/java/sample/dao/UserDAO.java
+++ b/sandbox/heavyduty/src/main/java/sample/dao/UserDAO.java
@@ -9,5 +9,5 @@ import sample.domain.User;
*/
public interface UserDAO extends GenericDAO {
- public User findByUsername(String username);
+ public User findByUsername(String username);
}
diff --git a/sandbox/heavyduty/src/main/java/sample/dao/impl/GenericDAOImpl.java b/sandbox/heavyduty/src/main/java/sample/dao/impl/GenericDAOImpl.java
index 1288370250..e9dc82567d 100755
--- a/sandbox/heavyduty/src/main/java/sample/dao/impl/GenericDAOImpl.java
+++ b/sandbox/heavyduty/src/main/java/sample/dao/impl/GenericDAOImpl.java
@@ -12,113 +12,113 @@ import sample.dao.GenericDAO;
public class GenericDAOImpl
- implements GenericDAO {
- /** type */
- private Class type;
+ implements GenericDAO {
+ /** type */
+ private Class type;
- /** the logger */
- private static final Log LOG = LogFactory.getLog(GenericDAOImpl.class);
+ /** the logger */
+ private static final Log LOG = LogFactory.getLog(GenericDAOImpl.class);
- @PersistenceContext
- private EntityManager entityManager;
+ @PersistenceContext
+ private EntityManager entityManager;
- /**
- * Minimal constructor
- *
- * @param t
- * type POJO hibernate
- */
- public GenericDAOImpl(Class t) {
- this.type = t;
- }
+ /**
+ * Minimal constructor
+ *
+ * @param t
+ * type POJO hibernate
+ */
+ public GenericDAOImpl(Class t) {
+ this.type = t;
+ }
- /**
- * read data
- *
- * @param id
- * data id
- * @return data
- */
- public T read(PK id) {
- if (id == null) {
- throw new IllegalArgumentException("Id cannot be null or empty");
- }
+ /**
+ * read data
+ *
+ * @param id
+ * data id
+ * @return data
+ */
+ public T read(PK id) {
+ if (id == null) {
+ throw new IllegalArgumentException("Id cannot be null or empty");
+ }
- // find() au lieu de getReference() pour forcer l'initialisation de
- // l'objet, sinon on ne recupère
- // qu'un proxy non-initialisé !
- return entityManager.find(type, id);
+ // find() au lieu de getReference() pour forcer l'initialisation de
+ // l'objet, sinon on ne recupère
+ // qu'un proxy non-initialisé !
+ return entityManager.find(type, id);
- }
+ }
- /**
- * persist data
- *
- * @param transientInstance
- * data to persist
- * @see sido.common.dao.GenericDAO#persist(T)
- */
- public void persist(T transientInstance) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Persisting instance of "
- + transientInstance.getClass().getSimpleName());
- }
- entityManager.persist(transientInstance);
- }
+ /**
+ * persist data
+ *
+ * @param transientInstance
+ * data to persist
+ * @see sido.common.dao.GenericDAO#persist(T)
+ */
+ public void persist(T transientInstance) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Persisting instance of "
+ + transientInstance.getClass().getSimpleName());
+ }
+ entityManager.persist(transientInstance);
+ }
- /**
- *
- * attach clean
- *
- * @param instance
- * data to attach
- * @see sido.common.dao.GenericDAO#refresh(T)
- */
- public void refresh(T instance) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("refreshing instance of "
- + instance.getClass().getSimpleName());
- }
- entityManager.refresh(instance);
- }
+ /**
+ *
+ * attach clean
+ *
+ * @param instance
+ * data to attach
+ * @see sido.common.dao.GenericDAO#refresh(T)
+ */
+ public void refresh(T instance) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("refreshing instance of "
+ + instance.getClass().getSimpleName());
+ }
+ entityManager.refresh(instance);
+ }
- /**
- * delete
- *
- * @param persistentInstance
- * data to delete
- * @see sido.common.dao.GenericDAO#delete(T)
- */
- public void delete(T persistentInstance) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("deleting instance of "
- + persistentInstance.getClass().getSimpleName());
- }
- entityManager.remove(persistentInstance);
- }
+ /**
+ * delete
+ *
+ * @param persistentInstance
+ * data to delete
+ * @see sido.common.dao.GenericDAO#delete(T)
+ */
+ public void delete(T persistentInstance) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("deleting instance of "
+ + persistentInstance.getClass().getSimpleName());
+ }
+ entityManager.remove(persistentInstance);
+ }
- /**
- * merge
- *
- * @param detachedInstance
- * data to merge
- * @return the merged data
- * @see sido.common.dao.GenericDAO#merge(T)
- */
- public T merge(T detachedInstance) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("merging instance of "
- + detachedInstance.getClass().getSimpleName());
- }
- return entityManager.merge(detachedInstance);
- }
+ /**
+ * merge
+ *
+ * @param detachedInstance
+ * data to merge
+ * @return the merged data
+ * @see sido.common.dao.GenericDAO#merge(T)
+ */
+ public T merge(T detachedInstance) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("merging instance of "
+ + detachedInstance.getClass().getSimpleName());
+ }
+ return entityManager.merge(detachedInstance);
+ }
- /**
- * @return the entityManager
- */
- public EntityManager getEntityManager() {
- return entityManager;
- }
+ /**
+ * @return the entityManager
+ */
+ public EntityManager getEntityManager() {
+ return entityManager;
+ }
}
diff --git a/sandbox/heavyduty/src/main/java/sample/dao/impl/UserDAOImpl.java b/sandbox/heavyduty/src/main/java/sample/dao/impl/UserDAOImpl.java
index da29fa1b6e..d70d143fd3 100755
--- a/sandbox/heavyduty/src/main/java/sample/dao/impl/UserDAOImpl.java
+++ b/sandbox/heavyduty/src/main/java/sample/dao/impl/UserDAOImpl.java
@@ -9,19 +9,19 @@ import sample.domain.User;
*/
@Repository
public class UserDAOImpl extends GenericDAOImpl implements
- sample.dao.UserDAO {
+ sample.dao.UserDAO {
- /**
- * Required constructor
- */
- public UserDAOImpl() {
- super(User.class);
- }
+ /**
+ * Required constructor
+ */
+ public UserDAOImpl() {
+ super(User.class);
+ }
- public User findByUsername(String username) {
- return (User) getEntityManager().createNamedQuery("User.findByUsername")
- .setParameter("username", username).getSingleResult();
- }
+ public User findByUsername(String username) {
+ return (User) getEntityManager().createNamedQuery("User.findByUsername")
+ .setParameter("username", username).getSingleResult();
+ }
}
diff --git a/sandbox/heavyduty/src/main/java/sample/domain/User.java b/sandbox/heavyduty/src/main/java/sample/domain/User.java
index 31cdc1026e..c7e489d7c1 100755
--- a/sandbox/heavyduty/src/main/java/sample/domain/User.java
+++ b/sandbox/heavyduty/src/main/java/sample/domain/User.java
@@ -19,88 +19,88 @@ import javax.persistence.NamedQuery;
@NamedQuery(name = "User.findByUsername", query = "from User where username= :username")
public class User implements Serializable {
- /** serialVersionUID */
- private static final long serialVersionUID = 7073017148588882593L;
+ /** serialVersionUID */
+ private static final long serialVersionUID = 7073017148588882593L;
- /** The id. */
- @Id
- @GeneratedValue(strategy=GenerationType.IDENTITY)
- private Long id;
+ /** The id. */
+ @Id
+ @GeneratedValue(strategy=GenerationType.IDENTITY)
+ private Long id;
- /** The username. */
- @Basic(optional = false)
- private String username;
+ /** The username. */
+ @Basic(optional = false)
+ private String username;
- /** The username. */
- @Basic(optional = false)
- private String password;
+ /** The username. */
+ @Basic(optional = false)
+ private String password;
- /**
- * Default constructor
- */
- public User() {
- super();
- }
+ /**
+ * Default constructor
+ */
+ public User() {
+ super();
+ }
- /**
- * @param username
- * @param password
- */
- public User(String username, String password) {
- super();
- this.username = username;
- this.password = password;
- }
+ /**
+ * @param username
+ * @param password
+ */
+ public User(String username, String password) {
+ super();
+ this.username = username;
+ this.password = password;
+ }
- /**
- * @return the id
- */
- public Long getId() {
- return id;
- }
+ /**
+ * @return the id
+ */
+ public Long getId() {
+ return id;
+ }
- /**
- * @param id the id to set
- */
- public void setId(Long id) {
- this.id = id;
- }
+ /**
+ * @param id the id to set
+ */
+ public void setId(Long id) {
+ this.id = id;
+ }
- /**
- * @return the username
- */
- public String getUsername() {
- return username;
- }
+ /**
+ * @return the username
+ */
+ public String getUsername() {
+ return username;
+ }
- /**
- * @param username the username to set
- */
- public void setUsername(String username) {
- this.username = username;
- }
+ /**
+ * @param username the username to set
+ */
+ public void setUsername(String username) {
+ this.username = username;
+ }
- /**
- * Full constructor
- * @param username
- */
- public User(String username, String password, Date derniereConnexion,
- String key) {
- super();
- this.username = username;
- }
+ /**
+ * Full constructor
+ * @param username
+ */
+ public User(String username, String password, Date derniereConnexion,
+ String key) {
+ super();
+ this.username = username;
+ }
- /**
- * @return the password
- */
- public String getPassword() {
- return password;
- }
+ /**
+ * @return the password
+ */
+ public String getPassword() {
+ return password;
+ }
- /**
- * @param password the password to set
- */
- public void setPassword(String password) {
- this.password = password;
- }
+ /**
+ * @param password the password to set
+ */
+ public void setPassword(String password) {
+ this.password = password;
+ }
}
diff --git a/sandbox/heavyduty/src/main/java/sample/service/UserService.java b/sandbox/heavyduty/src/main/java/sample/service/UserService.java
index e520583d55..4a14cfc273 100755
--- a/sandbox/heavyduty/src/main/java/sample/service/UserService.java
+++ b/sandbox/heavyduty/src/main/java/sample/service/UserService.java
@@ -5,11 +5,11 @@ import org.springframework.security.core.userdetails.UserDetailsService;
public interface UserService extends UserDetailsService {
- /**
- * Register a new User in database
- * @param username
- */
- public UserDetails register(String username, String password);
+ /**
+ * Register a new User in database
+ * @param username
+ */
+ public UserDetails register(String username, String password);
diff --git a/sandbox/heavyduty/src/main/java/sample/service/impl/UserServiceImpl.java b/sandbox/heavyduty/src/main/java/sample/service/impl/UserServiceImpl.java
index 69be491dd3..cb45006232 100755
--- a/sandbox/heavyduty/src/main/java/sample/service/impl/UserServiceImpl.java
+++ b/sandbox/heavyduty/src/main/java/sample/service/impl/UserServiceImpl.java
@@ -25,42 +25,42 @@ import sample.service.UserService;
@Transactional
public class UserServiceImpl implements UserService {
- /** The logger */
- private static final Log LOG = LogFactory.getLog(UserServiceImpl.class);
+ /** The logger */
+ private static final Log LOG = LogFactory.getLog(UserServiceImpl.class);
- /** The User DAO */
- @Autowired
- private UserDAO userDAO = null;
+ /** The User DAO */
+ @Autowired
+ private UserDAO userDAO = null;
- public UserDetails loadUserByUsername(String username)
- throws AuthenticationException {
- try {
- User user = userDAO.findByUsername(username);
+ public UserDetails loadUserByUsername(String username)
+ throws AuthenticationException {
+ try {
+ User user = userDAO.findByUsername(username);
- return new org.springframework.security.core.userdetails.User(user
- .getUsername(), user.getPassword(), true, true, true, true,
- AuthorityUtils.createAuthorityList("ROLE_USER"));
- } catch (Exception e) {
- LOG.error(e.getMessage(), e);
- throw new UsernameNotFoundException("No matching account", e);
- }
- }
+ return new org.springframework.security.core.userdetails.User(user
+ .getUsername(), user.getPassword(), true, true, true, true,
+ AuthorityUtils.createAuthorityList("ROLE_USER"));
+ } catch (Exception e) {
+ LOG.error(e.getMessage(), e);
+ throw new UsernameNotFoundException("No matching account", e);
+ }
+ }
- public UserDetails register(String username, String password) {
- User user = new User(username, password);
- userDAO.persist(user);
- return new org.springframework.security.core.userdetails.User(user
- .getUsername(), user.getPassword(), true, true, true, true,
- AuthorityUtils.createAuthorityList("ROLE_USER"));
+ public UserDetails register(String username, String password) {
+ User user = new User(username, password);
+ userDAO.persist(user);
+ return new org.springframework.security.core.userdetails.User(user
+ .getUsername(), user.getPassword(), true, true, true, true,
+ AuthorityUtils.createAuthorityList("ROLE_USER"));
- }
+ }
- /**
- * @param userDAO
- * the userDAO to set
- */
- public void setUserDAO(UserDAO userDAO) {
- this.userDAO = userDAO;
- }
+ /**
+ * @param userDAO
+ * the userDAO to set
+ */
+ public void setUserDAO(UserDAO userDAO) {
+ this.userDAO = userDAO;
+ }
}
diff --git a/sandbox/heavyduty/src/main/resources/applicationContext-business.xml b/sandbox/heavyduty/src/main/resources/applicationContext-business.xml
index f8d5228937..65376beb8f 100755
--- a/sandbox/heavyduty/src/main/resources/applicationContext-business.xml
+++ b/sandbox/heavyduty/src/main/resources/applicationContext-business.xml
@@ -1,24 +1,24 @@
-
+
-
-
-
+
+
+
-
-
-
-
+
+
+
+
\ No newline at end of file
diff --git a/sandbox/heavyduty/src/main/webapp/WEB-INF/appContext-misc.xml b/sandbox/heavyduty/src/main/webapp/WEB-INF/appContext-misc.xml
index fe88354e47..506f314d55 100755
--- a/sandbox/heavyduty/src/main/webapp/WEB-INF/appContext-misc.xml
+++ b/sandbox/heavyduty/src/main/webapp/WEB-INF/appContext-misc.xml
@@ -7,58 +7,58 @@
-->
+ xmlns:sec="http://www.springframework.org/schema/security"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:util="http://www.springframework.org/schema/util"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.xsd
+ http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
+
+
+
+
+
+
+
-
-
-
-
+
+
+
+
-
- My Realm
-
+
+ My Realm
+
-
-
-
-
-
-
- bigbank.BankService.post*=ROLE_SUPERVISOR
- bigbank.BankService.find*=ROLE_SUPERVISOR
-
-
-
+
+
+
+
+
+
+ bigbank.BankService.post*=ROLE_SUPERVISOR
+ bigbank.BankService.find*=ROLE_SUPERVISOR
+
+
+
diff --git a/sandbox/heavyduty/src/main/webapp/WEB-INF/appContext-persistence.xml b/sandbox/heavyduty/src/main/webapp/WEB-INF/appContext-persistence.xml
index 84e67eb41d..8b82eb9c20 100755
--- a/sandbox/heavyduty/src/main/webapp/WEB-INF/appContext-persistence.xml
+++ b/sandbox/heavyduty/src/main/webapp/WEB-INF/appContext-persistence.xml
@@ -7,15 +7,15 @@
xmlns:context="http://www.springframework.org/schema/context"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
- http://www.springframework.org/schema/config http://www.springframework.org/schema/config/spring-config-2.5.xsd
- http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
+ http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
+ http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
+ http://www.springframework.org/schema/config http://www.springframework.org/schema/config/spring-config-2.5.xsd
+ http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.xsd
+ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
-
+
@@ -25,31 +25,31 @@
-
+
-
-
+
+
-
-
-
-
-
-
-
-
+ class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
+
+
+
+
+
+
+
+
-
-
-
-
+
+
+
+
\ No newline at end of file
diff --git a/sandbox/heavyduty/src/main/webapp/WEB-INF/appContext-security.xml b/sandbox/heavyduty/src/main/webapp/WEB-INF/appContext-security.xml
index 1e8be3e95b..e78dad3351 100755
--- a/sandbox/heavyduty/src/main/webapp/WEB-INF/appContext-security.xml
+++ b/sandbox/heavyduty/src/main/webapp/WEB-INF/appContext-security.xml
@@ -6,122 +6,122 @@
-->
+ xmlns:b="http://www.springframework.org/schema/beans"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:aop="http://www.springframework.org/schema/aop"
+ xmlns:context="http://www.springframework.org/schema/context"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
+ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
+ http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">
-
-
+
+
-
-
-
+
+
+
-
+
-
-
-
-
-
-
-
+
+
+
+
+
+
+
-
-
-
-
-
-
+
+
+
+
+
+
-
+
-
-
-
+
+
+
-
-
-
-
+
+
+
+
-
-
+
+
-
+
-
+
-
+
-
+
-
-
-
+
+
+
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
-
+
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/sandbox/heavyduty/src/main/webapp/WEB-INF/heavyduty-servlet.xml b/sandbox/heavyduty/src/main/webapp/WEB-INF/heavyduty-servlet.xml
index 4d46d8c5d7..2aaaa2aac2 100755
--- a/sandbox/heavyduty/src/main/webapp/WEB-INF/heavyduty-servlet.xml
+++ b/sandbox/heavyduty/src/main/webapp/WEB-INF/heavyduty-servlet.xml
@@ -1,34 +1,34 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
-
-
-
-
-
+
+
+
+
+
-
-
-
+
+
+
-
-
-
-
+
+
+
+
-
-
-
- **/testMulti.htm=testMultiController
-
-
-
+
+
+
+ **/testMulti.htm=testMultiController
+
+
+
\ No newline at end of file
diff --git a/sandbox/webflow/src/main/resources/applicationContext-business.xml b/sandbox/webflow/src/main/resources/applicationContext-business.xml
index f8d5228937..65376beb8f 100644
--- a/sandbox/webflow/src/main/resources/applicationContext-business.xml
+++ b/sandbox/webflow/src/main/resources/applicationContext-business.xml
@@ -1,24 +1,24 @@
-
+
-
-
-
+
+
+
-
-
-
-
+
+
+
+
\ No newline at end of file
diff --git a/sandbox/webflow/src/main/webapp/WEB-INF/security-config.xml b/sandbox/webflow/src/main/webapp/WEB-INF/security-config.xml
index e3e9a41433..297c358d35 100644
--- a/sandbox/webflow/src/main/webapp/WEB-INF/security-config.xml
+++ b/sandbox/webflow/src/main/webapp/WEB-INF/security-config.xml
@@ -1,36 +1,36 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:security="http://www.springframework.org/schema/security"
+ xsi:schemaLocation="
+ http://www.springframework.org/schema/beans
+ http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/security
+ http://www.springframework.org/schema/security/spring-security-2.0.2.xsd">
-
-
-
-
-
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
+ usernames/passwords are:
+ keith/melbourne
+ erwin/leuven
+ jeremy/atlanta
+ scott/rochester
+ -->
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/sandbox/webflow/src/main/webapp/WEB-INF/webflow-servlet.xml b/sandbox/webflow/src/main/webapp/WEB-INF/webflow-servlet.xml
index 96a3c91682..2205b387fd 100644
--- a/sandbox/webflow/src/main/webapp/WEB-INF/webflow-servlet.xml
+++ b/sandbox/webflow/src/main/webapp/WEB-INF/webflow-servlet.xml
@@ -1,59 +1,59 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:webflow="http://www.springframework.org/schema/webflow-config"
+ xsi:schemaLocation="
+ http://www.springframework.org/schema/beans
+ http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/webflow-config
+ http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.0.xsd">
-
-
-
- /secure=flowController
-
-
-
-
-
-
+
+
+
+ /secure=flowController
+
+
+
+
+
+
-
-
-
+
+
+
-
-
-
-
+
+
+
+
-
+
-
-
-
+
+
+
-
-
-
-
-
-
+
+
+
+
+
+
-
-
-
-
+
+
+
+
-
-
+
+
-
-
-
+
+
+
-
+
\ No newline at end of file
diff --git a/web/src/test/groovy/org/springframework/security/web/context/AbstractSecurityWebApplicationInitializerTests.groovy b/web/src/test/groovy/org/springframework/security/web/context/AbstractSecurityWebApplicationInitializerTests.groovy
index 928b51cf5d..1f7361fc51 100644
--- a/web/src/test/groovy/org/springframework/security/web/context/AbstractSecurityWebApplicationInitializerTests.groovy
+++ b/web/src/test/groovy/org/springframework/security/web/context/AbstractSecurityWebApplicationInitializerTests.groovy
@@ -33,276 +33,276 @@ import spock.lang.Specification
*
*/
class AbstractSecurityWebApplicationInitializerTests extends Specification {
- def DEFAULT_DISPATCH = EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.ASYNC)
+ def DEFAULT_DISPATCH = EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.ASYNC)
- def defaults() {
- setup:
- ServletContext context = Mock()
- FilterRegistration.Dynamic registration = Mock()
- when:
- new AbstractSecurityWebApplicationInitializer(){}.onStartup(context)
- then:
- 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> registration
- 1 * registration.addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
- 1 * registration.setAsyncSupported(true)
- 0 * context.addListener(_)
- }
+ def defaults() {
+ setup:
+ ServletContext context = Mock()
+ FilterRegistration.Dynamic registration = Mock()
+ when:
+ new AbstractSecurityWebApplicationInitializer(){}.onStartup(context)
+ then:
+ 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> registration
+ 1 * registration.addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
+ 1 * registration.setAsyncSupported(true)
+ 0 * context.addListener(_)
+ }
- def "defaults with ContextLoaderListener"() {
- setup:
- ServletContext context = Mock()
- FilterRegistration.Dynamic registration = Mock()
- when:
- new AbstractSecurityWebApplicationInitializer(MyRootConfiguration){}.onStartup(context)
- then:
- 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> registration
- 1 * registration.addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
- 1 * registration.setAsyncSupported(true)
- 1 * context.addListener(_ as ContextLoaderListener)
- }
+ def "defaults with ContextLoaderListener"() {
+ setup:
+ ServletContext context = Mock()
+ FilterRegistration.Dynamic registration = Mock()
+ when:
+ new AbstractSecurityWebApplicationInitializer(MyRootConfiguration){}.onStartup(context)
+ then:
+ 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> registration
+ 1 * registration.addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
+ 1 * registration.setAsyncSupported(true)
+ 1 * context.addListener(_ as ContextLoaderListener)
+ }
- @Configuration
- static class MyRootConfiguration {}
+ @Configuration
+ static class MyRootConfiguration {}
- def "enableHttpSessionEventPublisher() = true"() {
- setup:
- ServletContext context = Mock()
- FilterRegistration.Dynamic registration = Mock()
- when:
- new AbstractSecurityWebApplicationInitializer(){
- protected boolean enableHttpSessionEventPublisher() {
- return true;
- }
- }.onStartup(context)
- then:
- 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> registration
- 1 * registration.addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
- 1 * registration.setAsyncSupported(true)
- 1 * context.addListener(HttpSessionEventPublisher.class.name)
- }
+ def "enableHttpSessionEventPublisher() = true"() {
+ setup:
+ ServletContext context = Mock()
+ FilterRegistration.Dynamic registration = Mock()
+ when:
+ new AbstractSecurityWebApplicationInitializer(){
+ protected boolean enableHttpSessionEventPublisher() {
+ return true;
+ }
+ }.onStartup(context)
+ then:
+ 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> registration
+ 1 * registration.addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
+ 1 * registration.setAsyncSupported(true)
+ 1 * context.addListener(HttpSessionEventPublisher.class.name)
+ }
- def "custom getSecurityDispatcherTypes()"() {
- setup:
- ServletContext context = Mock()
- FilterRegistration.Dynamic registration = Mock()
- when:
- new AbstractSecurityWebApplicationInitializer(){
- protected EnumSet getSecurityDispatcherTypes() {
- return EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.FORWARD);
- }
- }.onStartup(context)
- then:
- 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> registration
- 1 * registration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.FORWARD), false, "/*");
- 1 * registration.setAsyncSupported(true)
- 0 * context.addListener(_)
- }
+ def "custom getSecurityDispatcherTypes()"() {
+ setup:
+ ServletContext context = Mock()
+ FilterRegistration.Dynamic registration = Mock()
+ when:
+ new AbstractSecurityWebApplicationInitializer(){
+ protected EnumSet getSecurityDispatcherTypes() {
+ return EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.FORWARD);
+ }
+ }.onStartup(context)
+ then:
+ 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> registration
+ 1 * registration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.FORWARD), false, "/*");
+ 1 * registration.setAsyncSupported(true)
+ 0 * context.addListener(_)
+ }
- def "custom getDispatcherWebApplicationContextSuffix"() {
- setup:
- ServletContext context = Mock()
- FilterRegistration.Dynamic registration = Mock()
- when:
- new AbstractSecurityWebApplicationInitializer(){
- protected String getDispatcherWebApplicationContextSuffix() {
- return "dispatcher"
- }
- }.onStartup(context)
- then:
- 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == "org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher"}) >> registration
- 1 * registration.addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
- 1 * registration.setAsyncSupported(true)
- 0 * context.addListener(_)
- }
+ def "custom getDispatcherWebApplicationContextSuffix"() {
+ setup:
+ ServletContext context = Mock()
+ FilterRegistration.Dynamic registration = Mock()
+ when:
+ new AbstractSecurityWebApplicationInitializer(){
+ protected String getDispatcherWebApplicationContextSuffix() {
+ return "dispatcher"
+ }
+ }.onStartup(context)
+ then:
+ 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == "org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher"}) >> registration
+ 1 * registration.addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
+ 1 * registration.setAsyncSupported(true)
+ 0 * context.addListener(_)
+ }
- def "springSecurityFilterChain already registered"() {
- setup:
- ServletContext context = Mock()
- FilterRegistration.Dynamic registration = Mock()
- when:
- new AbstractSecurityWebApplicationInitializer(){}.onStartup(context)
- then:
- 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> null
- IllegalStateException success = thrown()
- success.message == "Duplicate Filter registration for 'springSecurityFilterChain'. Check to ensure the Filter is only configured once."
- }
+ def "springSecurityFilterChain already registered"() {
+ setup:
+ ServletContext context = Mock()
+ FilterRegistration.Dynamic registration = Mock()
+ when:
+ new AbstractSecurityWebApplicationInitializer(){}.onStartup(context)
+ then:
+ 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> null
+ IllegalStateException success = thrown()
+ success.message == "Duplicate Filter registration for 'springSecurityFilterChain'. Check to ensure the Filter is only configured once."
+ }
- def "insertFilters"() {
- setup:
- Filter filter1 = Mock()
- Filter filter2 = Mock()
- ServletContext context = Mock()
- FilterRegistration.Dynamic registration = Mock()
- when:
- new AbstractSecurityWebApplicationInitializer(){
- protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
- insertFilters(context, filter1, filter2);
- }
- }.onStartup(context)
- then:
- 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> registration
- 3 * registration.addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
- 3 * registration.setAsyncSupported(true)
- 0 * context.addListener(_)
- 1 * context.addFilter(_, filter1) >> registration
- 1 * context.addFilter(_, filter2) >> registration
- }
+ def "insertFilters"() {
+ setup:
+ Filter filter1 = Mock()
+ Filter filter2 = Mock()
+ ServletContext context = Mock()
+ FilterRegistration.Dynamic registration = Mock()
+ when:
+ new AbstractSecurityWebApplicationInitializer(){
+ protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
+ insertFilters(context, filter1, filter2);
+ }
+ }.onStartup(context)
+ then:
+ 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> registration
+ 3 * registration.addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
+ 3 * registration.setAsyncSupported(true)
+ 0 * context.addListener(_)
+ 1 * context.addFilter(_, filter1) >> registration
+ 1 * context.addFilter(_, filter2) >> registration
+ }
- def "insertFilters already registered"() {
- setup:
- Filter filter1 = Mock()
- ServletContext context = Mock()
- FilterRegistration.Dynamic registration = Mock()
- when:
- new AbstractSecurityWebApplicationInitializer(){
- protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
- insertFilters(context, filter1);
- }
- }.onStartup(context)
- then:
- 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> registration
- 1 * registration.addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
- 1 * context.addFilter(_, filter1) >> null
- IllegalStateException success = thrown()
- success.message == "Duplicate Filter registration for 'filter'. Check to ensure the Filter is only configured once."
- }
+ def "insertFilters already registered"() {
+ setup:
+ Filter filter1 = Mock()
+ ServletContext context = Mock()
+ FilterRegistration.Dynamic registration = Mock()
+ when:
+ new AbstractSecurityWebApplicationInitializer(){
+ protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
+ insertFilters(context, filter1);
+ }
+ }.onStartup(context)
+ then:
+ 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> registration
+ 1 * registration.addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
+ 1 * context.addFilter(_, filter1) >> null
+ IllegalStateException success = thrown()
+ success.message == "Duplicate Filter registration for 'filter'. Check to ensure the Filter is only configured once."
+ }
- def "insertFilters no filters"() {
- setup:
- ServletContext context = Mock()
- FilterRegistration.Dynamic registration = Mock()
- when:
- new AbstractSecurityWebApplicationInitializer(){
- protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
- insertFilters(context);
- }
- }.onStartup(context)
- then:
- 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> registration
- IllegalArgumentException success = thrown()
- success.message == "filters cannot be null or empty"
- }
+ def "insertFilters no filters"() {
+ setup:
+ ServletContext context = Mock()
+ FilterRegistration.Dynamic registration = Mock()
+ when:
+ new AbstractSecurityWebApplicationInitializer(){
+ protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
+ insertFilters(context);
+ }
+ }.onStartup(context)
+ then:
+ 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> registration
+ IllegalArgumentException success = thrown()
+ success.message == "filters cannot be null or empty"
+ }
- def "insertFilters filters with null"() {
- setup:
- Filter filter1 = Mock()
- ServletContext context = Mock()
- FilterRegistration.Dynamic registration = Mock()
- when:
- new AbstractSecurityWebApplicationInitializer(){
- protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
- insertFilters(context, filter1, null);
- }
- }.onStartup(context)
- then:
- 2 * context.addFilter(_, _) >> registration
- IllegalArgumentException success = thrown()
- success.message == "filters cannot contain null values. Got [Mock for type 'Filter' named 'filter1', null]"
- }
+ def "insertFilters filters with null"() {
+ setup:
+ Filter filter1 = Mock()
+ ServletContext context = Mock()
+ FilterRegistration.Dynamic registration = Mock()
+ when:
+ new AbstractSecurityWebApplicationInitializer(){
+ protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
+ insertFilters(context, filter1, null);
+ }
+ }.onStartup(context)
+ then:
+ 2 * context.addFilter(_, _) >> registration
+ IllegalArgumentException success = thrown()
+ success.message == "filters cannot contain null values. Got [Mock for type 'Filter' named 'filter1', null]"
+ }
- def "appendFilters"() {
- setup:
- Filter filter1 = Mock()
- Filter filter2 = Mock()
- ServletContext context = Mock()
- FilterRegistration.Dynamic registration = Mock()
- when:
- new AbstractSecurityWebApplicationInitializer(){
- protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
- appendFilters(context,filter1, filter2);
- }
- }.onStartup(context)
- then:
- 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> registration
- 1 * registration.addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
- 2 * registration.addMappingForUrlPatterns(DEFAULT_DISPATCH, true, "/*");
- 3 * registration.setAsyncSupported(true)
- 0 * context.addListener(_)
- 1 * context.addFilter(_, filter1) >> registration
- 1 * context.addFilter(_, filter2) >> registration
- }
+ def "appendFilters"() {
+ setup:
+ Filter filter1 = Mock()
+ Filter filter2 = Mock()
+ ServletContext context = Mock()
+ FilterRegistration.Dynamic registration = Mock()
+ when:
+ new AbstractSecurityWebApplicationInitializer(){
+ protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
+ appendFilters(context,filter1, filter2);
+ }
+ }.onStartup(context)
+ then:
+ 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> registration
+ 1 * registration.addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
+ 2 * registration.addMappingForUrlPatterns(DEFAULT_DISPATCH, true, "/*");
+ 3 * registration.setAsyncSupported(true)
+ 0 * context.addListener(_)
+ 1 * context.addFilter(_, filter1) >> registration
+ 1 * context.addFilter(_, filter2) >> registration
+ }
- def "appendFilters already registered"() {
- setup:
- Filter filter1 = Mock()
- ServletContext context = Mock()
- FilterRegistration.Dynamic registration = Mock()
- when:
- new AbstractSecurityWebApplicationInitializer(){
- protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
- appendFilters(context, filter1);
- }
- }.onStartup(context)
- then:
- 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> registration
- 1 * registration.addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
- 1 * context.addFilter(_, filter1) >> null
- IllegalStateException success = thrown()
- success.message == "Duplicate Filter registration for 'filter'. Check to ensure the Filter is only configured once."
- }
+ def "appendFilters already registered"() {
+ setup:
+ Filter filter1 = Mock()
+ ServletContext context = Mock()
+ FilterRegistration.Dynamic registration = Mock()
+ when:
+ new AbstractSecurityWebApplicationInitializer(){
+ protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
+ appendFilters(context, filter1);
+ }
+ }.onStartup(context)
+ then:
+ 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> registration
+ 1 * registration.addMappingForUrlPatterns(DEFAULT_DISPATCH, false, "/*");
+ 1 * context.addFilter(_, filter1) >> null
+ IllegalStateException success = thrown()
+ success.message == "Duplicate Filter registration for 'filter'. Check to ensure the Filter is only configured once."
+ }
- def "appendFilters no filters"() {
- setup:
- ServletContext context = Mock()
- FilterRegistration.Dynamic registration = Mock()
- when:
- new AbstractSecurityWebApplicationInitializer(){
- protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
- appendFilters(context);
- }
- }.onStartup(context)
- then:
- 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> registration
- IllegalArgumentException success = thrown()
- success.message == "filters cannot be null or empty"
- }
+ def "appendFilters no filters"() {
+ setup:
+ ServletContext context = Mock()
+ FilterRegistration.Dynamic registration = Mock()
+ when:
+ new AbstractSecurityWebApplicationInitializer(){
+ protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
+ appendFilters(context);
+ }
+ }.onStartup(context)
+ then:
+ 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> registration
+ IllegalArgumentException success = thrown()
+ success.message == "filters cannot be null or empty"
+ }
- def "sessionTrackingModes defaults"() {
- setup:
- ServletContext context = Mock()
- FilterRegistration.Dynamic registration = Mock()
- when:
- new AbstractSecurityWebApplicationInitializer(){ }.onStartup(context)
- then:
- 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> registration
- 1 * context.setSessionTrackingModes({Set modes -> modes.size() == 1 && modes.containsAll([SessionTrackingMode.COOKIE]) })
- }
+ def "sessionTrackingModes defaults"() {
+ setup:
+ ServletContext context = Mock()
+ FilterRegistration.Dynamic registration = Mock()
+ when:
+ new AbstractSecurityWebApplicationInitializer(){ }.onStartup(context)
+ then:
+ 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> registration
+ 1 * context.setSessionTrackingModes({Set modes -> modes.size() == 1 && modes.containsAll([SessionTrackingMode.COOKIE]) })
+ }
- def "sessionTrackingModes override"() {
- setup:
- ServletContext context = Mock()
- FilterRegistration.Dynamic registration = Mock()
- when:
- new AbstractSecurityWebApplicationInitializer(){
- @Override
- public Set getSessionTrackingModes() {
- return [SessionTrackingMode.SSL]
- }
- }.onStartup(context)
- then:
- 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> registration
- 1 * context.setSessionTrackingModes({Set modes -> modes.size() == 1 && modes.containsAll([SessionTrackingMode.SSL]) })
- }
+ def "sessionTrackingModes override"() {
+ setup:
+ ServletContext context = Mock()
+ FilterRegistration.Dynamic registration = Mock()
+ when:
+ new AbstractSecurityWebApplicationInitializer(){
+ @Override
+ public Set getSessionTrackingModes() {
+ return [SessionTrackingMode.SSL]
+ }
+ }.onStartup(context)
+ then:
+ 1 * context.addFilter("springSecurityFilterChain", {DelegatingFilterProxy f -> f.targetBeanName == "springSecurityFilterChain" && f.contextAttribute == null}) >> registration
+ 1 * context.setSessionTrackingModes({Set modes -> modes.size() == 1 && modes.containsAll([SessionTrackingMode.SSL]) })
+ }
- def "appendFilters filters with null"() {
- setup:
- Filter filter1 = Mock()
- ServletContext context = Mock()
- FilterRegistration.Dynamic registration = Mock()
- when:
- new AbstractSecurityWebApplicationInitializer(){
- protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
- appendFilters(context, filter1, null);
- }
- }.onStartup(context)
- then:
- 2 * context.addFilter(_, _) >> registration
- IllegalArgumentException success = thrown()
- success.message == "filters cannot contain null values. Got [Mock for type 'Filter' named 'filter1', null]"
- }
+ def "appendFilters filters with null"() {
+ setup:
+ Filter filter1 = Mock()
+ ServletContext context = Mock()
+ FilterRegistration.Dynamic registration = Mock()
+ when:
+ new AbstractSecurityWebApplicationInitializer(){
+ protected void afterSpringSecurityFilterChain(ServletContext servletContext) {
+ appendFilters(context, filter1, null);
+ }
+ }.onStartup(context)
+ then:
+ 2 * context.addFilter(_, _) >> registration
+ IllegalArgumentException success = thrown()
+ success.message == "filters cannot contain null values. Got [Mock for type 'Filter' named 'filter1', null]"
+ }
- def "DEFAULT_FILTER_NAME == springSecurityFilterChain"() {
- expect:
- AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME == "springSecurityFilterChain"
- }
+ def "DEFAULT_FILTER_NAME == springSecurityFilterChain"() {
+ expect:
+ AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME == "springSecurityFilterChain"
+ }
}