SEC-1574: Add CSRF Support
This commit is contained in:
@@ -55,4 +55,5 @@ public abstract class Elements {
|
||||
public static final String DEBUG = "debug";
|
||||
public static final String HTTP_FIREWALL = "http-firewall";
|
||||
public static final String HEADERS = "headers";
|
||||
public static final String CSRF = "csrf";
|
||||
}
|
||||
|
||||
@@ -37,6 +37,7 @@ import org.springframework.security.web.authentication.www.BasicAuthenticationFi
|
||||
import org.springframework.security.web.authentication.www.DigestAuthenticationFilter;
|
||||
import org.springframework.security.web.context.SecurityContextPersistenceFilter;
|
||||
import org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter;
|
||||
import org.springframework.security.web.csrf.CsrfFilter;
|
||||
import org.springframework.security.web.header.HeaderWriterFilter;
|
||||
import org.springframework.security.web.jaasapi.JaasApiIntegrationFilter;
|
||||
import org.springframework.security.web.savedrequest.RequestCacheAwareFilter;
|
||||
@@ -69,6 +70,8 @@ final class FilterComparator implements Comparator<Filter>, Serializable {
|
||||
order += STEP;
|
||||
put(HeaderWriterFilter.class, order);
|
||||
order += STEP;
|
||||
put(CsrfFilter.class, order);
|
||||
order += STEP;
|
||||
put(LogoutFilter.class, order);
|
||||
order += STEP;
|
||||
put(X509AuthenticationFilter.class, order);
|
||||
|
||||
@@ -38,6 +38,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.config.annotation.web.configurers.AnonymousConfigurer;
|
||||
import org.springframework.security.config.annotation.web.configurers.ChannelSecurityConfigurer;
|
||||
import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer;
|
||||
import org.springframework.security.config.annotation.web.configurers.ExceptionHandlingConfigurer;
|
||||
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
|
||||
import org.springframework.security.config.annotation.web.configurers.FormLoginConfigurer;
|
||||
@@ -663,6 +664,17 @@ public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<Defaul
|
||||
return getOrApply(new ServletApiConfigurer<HttpSecurity>());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Adds CSRF support
|
||||
*
|
||||
* @return the {@link ServletApiConfigurer} for further customizations
|
||||
* @throws Exception
|
||||
*/
|
||||
public CsrfConfigurer<HttpSecurity> csrf() throws Exception {
|
||||
return getOrApply(new CsrfConfigurer<HttpSecurity>());
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides logout support. This is automatically applied when using
|
||||
* {@link WebSecurityConfigurerAdapter}. The default is that accessing
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.config.annotation.web.configuration;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.web.servlet.support.csrf.CsrfRequestDataValueProcessor;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.support.RequestDataValueProcessor;
|
||||
|
||||
/**
|
||||
* Used to add a {@link RequestDataValueProcessor} for Spring MVC and Spring
|
||||
* Security CSRF integration. This configuration is added whenever
|
||||
* {@link EnableWebMvc} is added by {@link SpringWebMvcImportSelector} and the
|
||||
* DispatcherServlet is present on the classpath.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*/
|
||||
@Configuration
|
||||
class CsrfWebMvcConfiguration {
|
||||
|
||||
@Bean
|
||||
public RequestDataValueProcessor requestDataValueProcessor() {
|
||||
return new CsrfRequestDataValueProcessor();
|
||||
}
|
||||
}
|
||||
@@ -77,7 +77,7 @@ import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
|
||||
@Retention(value=java.lang.annotation.RetentionPolicy.RUNTIME)
|
||||
@Target(value={java.lang.annotation.ElementType.TYPE})
|
||||
@Documented
|
||||
@Import({WebSecurityConfiguration.class,ObjectPostProcessorConfiguration.class,AuthenticationConfiguration.class})
|
||||
@Import({WebSecurityConfiguration.class,ObjectPostProcessorConfiguration.class,AuthenticationConfiguration.class, SpringWebMvcImportSelector.class})
|
||||
public @interface EnableWebSecurity {
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.config.annotation.web.configuration;
|
||||
|
||||
import org.springframework.context.annotation.ImportSelector;
|
||||
import org.springframework.core.type.AnnotationMetadata;
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
/**
|
||||
* Used by {@link EnableWebSecurity} to conditionaly import
|
||||
* {@link CsrfWebMvcConfiguration} when the DispatcherServlet is present on the
|
||||
* classpath.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*/
|
||||
class SpringWebMvcImportSelector implements ImportSelector {
|
||||
|
||||
/* (non-Javadoc)
|
||||
* @see org.springframework.context.annotation.ImportSelector#selectImports(org.springframework.core.type.AnnotationMetadata)
|
||||
*/
|
||||
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
|
||||
boolean webmvcPresent = ClassUtils.isPresent("org.springframework.web.servlet.DispatcherServlet", getClass().getClassLoader());
|
||||
return webmvcPresent ? new String[] {"org.springframework.security.config.annotation.web.configuration.CsrfWebMvcConfiguration"} : new String[] {};
|
||||
}
|
||||
}
|
||||
@@ -154,6 +154,7 @@ public abstract class WebSecurityConfigurerAdapter implements SecurityConfigurer
|
||||
http.setSharedObject(ContentNegotiationStrategy.class, contentNegotiationStrategy);
|
||||
if(!disableDefaults) {
|
||||
http
|
||||
.csrf().and()
|
||||
.addFilter(new WebAsyncManagerIntegrationFilter())
|
||||
.exceptionHandling().and()
|
||||
.headers().and()
|
||||
|
||||
@@ -30,4 +30,15 @@ import org.springframework.security.web.DefaultSecurityFilterChain;
|
||||
*/
|
||||
abstract class AbstractHttpConfigurer<B extends HttpSecurityBuilder<B>> extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, B> {
|
||||
|
||||
/**
|
||||
* Disables the {@link AbstractHttpConfigurer} by removing it. After doing
|
||||
* so a fresh version of the configuration can be applied.
|
||||
*
|
||||
* @return the {@link HttpSecurityBuilder} for additional customizations
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public B disable() {
|
||||
getBuilder().removeConfigurer(getClass());
|
||||
return getBuilder();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ import org.springframework.security.web.authentication.AnonymousAuthenticationFi
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*/
|
||||
public final class AnonymousConfigurer<H extends HttpSecurityBuilder<H>> extends SecurityConfigurerAdapter<DefaultSecurityFilterChain,H> {
|
||||
public final class AnonymousConfigurer<H extends HttpSecurityBuilder<H>> extends AbstractHttpConfigurer<H> {
|
||||
private String key;
|
||||
private AuthenticationProvider authenticationProvider;
|
||||
private AnonymousAuthenticationFilter authenticationFilter;
|
||||
@@ -53,18 +53,6 @@ public final class AnonymousConfigurer<H extends HttpSecurityBuilder<H>> extends
|
||||
public AnonymousConfigurer() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Disables anonymous authentication.
|
||||
*
|
||||
* @return the {@link HttpSecurity} since no further customization of anonymous authentication would be
|
||||
* meaningful.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public H disable() {
|
||||
getBuilder().removeConfigurer(getClass());
|
||||
return getBuilder();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the key to identify tokens created for anonymous authentication. Default is a secure randomly generated
|
||||
* key.
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.config.annotation.web.configurers;
|
||||
|
||||
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.web.access.AccessDeniedHandler;
|
||||
import org.springframework.security.web.csrf.CsrfAuthenticationStrategy;
|
||||
import org.springframework.security.web.csrf.CsrfFilter;
|
||||
import org.springframework.security.web.csrf.CsrfLogoutHandler;
|
||||
import org.springframework.security.web.csrf.CsrfTokenRepository;
|
||||
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
|
||||
import org.springframework.security.web.util.RequestMatcher;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Adds <a
|
||||
* href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)"
|
||||
* >CSRF</a> protection for the methods as specified by
|
||||
* {@link #requireCsrfProtectionMatcher(RequestMatcher)}.
|
||||
*
|
||||
* <h2>Security Filters</h2>
|
||||
*
|
||||
* The following Filters are populated
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@link CsrfFilter}</li>
|
||||
* </ul>
|
||||
*
|
||||
* <h2>Shared Objects Created</h2>
|
||||
*
|
||||
* No shared objects are created.
|
||||
*
|
||||
* <h2>Shared Objects Used</h2>
|
||||
*
|
||||
* <ul>
|
||||
* <li>
|
||||
* {@link ExceptionHandlingConfigurer#accessDeniedHandler(AccessDeniedHandler)}
|
||||
* is used to determine how to handle CSRF attempts</li>
|
||||
* </ul>
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*/
|
||||
public final class CsrfConfigurer<H extends HttpSecurityBuilder<H>> extends AbstractHttpConfigurer<H> {
|
||||
private CsrfTokenRepository csrfTokenRepository = new HttpSessionCsrfTokenRepository();
|
||||
private RequestMatcher requireCsrfProtectionMatcher;
|
||||
|
||||
/**
|
||||
* Creates a new instance
|
||||
* @see HttpSecurity#csrf()
|
||||
*/
|
||||
public CsrfConfigurer() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Specify the {@link CsrfTokenRepository} to use. The default is an {@link HttpSessionCsrfTokenRepository}.
|
||||
*
|
||||
* @param csrfTokenRepository the {@link CsrfTokenRepository} to use
|
||||
* @return the {@link CsrfConfigurer} for further customizations
|
||||
*/
|
||||
public CsrfConfigurer<H> csrfTokenRepository(CsrfTokenRepository csrfTokenRepository) {
|
||||
Assert.notNull(csrfTokenRepository, "csrfTokenRepository cannot be null");
|
||||
this.csrfTokenRepository = csrfTokenRepository;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Specify the {@link RequestMatcher} to use for determining when CSRF
|
||||
* should be applied. The default is to ignore GET, HEAD, TRACE, OPTIONS and
|
||||
* process all other requests.
|
||||
*
|
||||
* @param requireCsrfProtectionMatcher
|
||||
* the {@link RequestMatcher} to use
|
||||
* @return the {@link CsrfConfigurer} for further customizations
|
||||
*/
|
||||
public CsrfConfigurer<H> requireCsrfProtectionMatcher(RequestMatcher requireCsrfProtectionMatcher) {
|
||||
Assert.notNull(csrfTokenRepository, "requireCsrfProtectionMatcher cannot be null");
|
||||
this.requireCsrfProtectionMatcher = requireCsrfProtectionMatcher;
|
||||
return this;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public void configure(H http) throws Exception {
|
||||
CsrfFilter filter = new CsrfFilter(csrfTokenRepository);
|
||||
if(requireCsrfProtectionMatcher != null) {
|
||||
filter.setRequireCsrfProtectionMatcher(requireCsrfProtectionMatcher);
|
||||
}
|
||||
ExceptionHandlingConfigurer<H> exceptionConfig = http.getConfigurer(ExceptionHandlingConfigurer.class);
|
||||
if(exceptionConfig != null) {
|
||||
AccessDeniedHandler accessDeniedHandler = exceptionConfig.getAccessDeniedHandler();
|
||||
if(accessDeniedHandler != null) {
|
||||
filter.setAccessDeniedHandler(accessDeniedHandler);
|
||||
}
|
||||
}
|
||||
LogoutConfigurer<H> logoutConfigurer = http.getConfigurer(LogoutConfigurer.class);
|
||||
if(logoutConfigurer != null) {
|
||||
logoutConfigurer.addLogoutHandler(new CsrfLogoutHandler(csrfTokenRepository));
|
||||
}
|
||||
SessionManagementConfigurer<H> sessionConfigurer = http.getConfigurer(SessionManagementConfigurer.class);
|
||||
if(sessionConfigurer != null) {
|
||||
sessionConfigurer.addSessionAuthenticationStrategy(new CsrfAuthenticationStrategy(csrfTokenRepository));
|
||||
}
|
||||
filter = postProcess(filter);
|
||||
http.addFilter(filter);
|
||||
}
|
||||
}
|
||||
@@ -153,6 +153,15 @@ public final class ExceptionHandlingConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
return this.authenticationEntryPoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the {@link AccessDeniedHandler} that is configured.
|
||||
*
|
||||
* @return the {@link AccessDeniedHandler}
|
||||
*/
|
||||
AccessDeniedHandler getAccessDeniedHandler() {
|
||||
return this.accessDeniedHandler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(H http) throws Exception {
|
||||
AuthenticationEntryPoint entryPoint = getAuthenticationEntryPoint(http);
|
||||
|
||||
@@ -16,7 +16,6 @@
|
||||
package org.springframework.security.config.annotation.web.configurers;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import javax.servlet.http.HttpSession;
|
||||
@@ -31,6 +30,8 @@ import org.springframework.security.web.authentication.logout.LogoutSuccessHandl
|
||||
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
|
||||
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
|
||||
import org.springframework.security.web.authentication.ui.DefaultLoginPageViewFilter;
|
||||
import org.springframework.security.web.util.AntPathRequestMatcher;
|
||||
import org.springframework.security.web.util.RequestMatcher;
|
||||
|
||||
/**
|
||||
* Adds logout support. Other {@link SecurityConfigurer} instances may invoke
|
||||
@@ -63,7 +64,7 @@ public final class LogoutConfigurer<H extends HttpSecurityBuilder<H>> extends Ab
|
||||
private SecurityContextLogoutHandler contextLogoutHandler = new SecurityContextLogoutHandler();
|
||||
private String logoutSuccessUrl = "/login?logout";
|
||||
private LogoutSuccessHandler logoutSuccessHandler;
|
||||
private String logoutUrl = "/logout";
|
||||
private RequestMatcher logoutRequestMatcher = new AntPathRequestMatcher("/logout", "POST");
|
||||
private boolean permitAll;
|
||||
private boolean customLogoutSuccess;
|
||||
|
||||
@@ -97,12 +98,22 @@ public final class LogoutConfigurer<H extends HttpSecurityBuilder<H>> extends Ab
|
||||
}
|
||||
|
||||
/**
|
||||
* The URL that triggers logout to occur. The default is "/logout"
|
||||
* The URL that triggers logout to occur on HTTP POST. The default is "/logout"
|
||||
* @param logoutUrl the URL that will invoke logout.
|
||||
* @return the {@link LogoutConfigurer} for further customization
|
||||
*/
|
||||
public LogoutConfigurer<H> logoutUrl(String logoutUrl) {
|
||||
this.logoutUrl = logoutUrl;
|
||||
return logoutRequestMatcher(new AntPathRequestMatcher(logoutUrl, "POST"));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* The RequestMatcher that triggers logout to occur on HTTP POST. The default is "/logout"
|
||||
* @param logoutRequestMatcher the RequestMatcher used to determine if logout should occur.
|
||||
* @return the {@link LogoutConfigurer} for further customization
|
||||
*/
|
||||
public LogoutConfigurer<H> logoutRequestMatcher(RequestMatcher logoutRequestMatcher) {
|
||||
this.logoutRequestMatcher = logoutRequestMatcher;
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -189,7 +200,8 @@ public final class LogoutConfigurer<H extends HttpSecurityBuilder<H>> extends Ab
|
||||
@Override
|
||||
public void init(H http) throws Exception {
|
||||
if(permitAll) {
|
||||
PermitAllSupport.permitAll(http, this.logoutUrl, this.logoutSuccessUrl);
|
||||
PermitAllSupport.permitAll(http, this.logoutSuccessUrl);
|
||||
PermitAllSupport.permitAll(http, this.logoutRequestMatcher);
|
||||
}
|
||||
|
||||
DefaultLoginPageViewFilter loginPageGeneratingFilter = http.getSharedObject(DefaultLoginPageViewFilter.class);
|
||||
@@ -245,7 +257,7 @@ public final class LogoutConfigurer<H extends HttpSecurityBuilder<H>> extends Ab
|
||||
logoutHandlers.add(contextLogoutHandler);
|
||||
LogoutHandler[] handlers = logoutHandlers.toArray(new LogoutHandler[logoutHandlers.size()]);
|
||||
LogoutFilter result = new LogoutFilter(getLogoutSuccessHandler(), handlers);
|
||||
result.setFilterProcessesUrl(logoutUrl);
|
||||
result.setLogoutRequestMatcher(logoutRequestMatcher);
|
||||
result = postProcess(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -31,17 +31,25 @@ import org.springframework.security.web.util.RequestMatcher;
|
||||
*/
|
||||
final class PermitAllSupport {
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static void permitAll(HttpSecurityBuilder<? extends HttpSecurityBuilder<?>> http, String... urls) {
|
||||
for(String url : urls) {
|
||||
if(url != null) {
|
||||
permitAll(http, new ExactUrlRequestMatcher(url));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static void permitAll(HttpSecurityBuilder<? extends HttpSecurityBuilder<?>> http, RequestMatcher... requestMatchers) {
|
||||
ExpressionUrlAuthorizationConfigurer<?> configurer = http.getConfigurer(ExpressionUrlAuthorizationConfigurer.class);
|
||||
|
||||
if(configurer == null) {
|
||||
throw new IllegalStateException("permitAll only works with HttpSecurity.authorizeRequests()");
|
||||
}
|
||||
|
||||
for(String url : urls) {
|
||||
if(url != null) {
|
||||
configurer.addMapping(0, new UrlMapping(new ExactUrlRequestMatcher(url), SecurityConfig.createList(ExpressionUrlAuthorizationConfigurer.permitAll)));
|
||||
for(RequestMatcher matcher : requestMatchers) {
|
||||
if(matcher != null) {
|
||||
configurer.addMapping(0, new UrlMapping(matcher, SecurityConfig.createList(ExpressionUrlAuthorizationConfigurer.permitAll)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
|
||||
import org.springframework.security.web.savedrequest.RequestCache;
|
||||
import org.springframework.security.web.savedrequest.RequestCacheAwareFilter;
|
||||
import org.springframework.security.web.util.AntPathRequestMatcher;
|
||||
|
||||
/**
|
||||
* Adds request cache for Spring Security. Specifically this ensures that
|
||||
@@ -71,6 +72,11 @@ public final class RequestCacheConfigurer<H extends HttpSecurityBuilder<H>> exte
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(H http) throws Exception {
|
||||
http.setSharedObject(RequestCache.class, getRequestCache(http));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configure(H http) throws Exception {
|
||||
RequestCache requestCache = getRequestCache(http);
|
||||
@@ -93,6 +99,8 @@ public final class RequestCacheConfigurer<H extends HttpSecurityBuilder<H>> exte
|
||||
if(result != null) {
|
||||
return result;
|
||||
}
|
||||
return new HttpSessionRequestCache();
|
||||
HttpSessionRequestCache defaultCache = new HttpSessionRequestCache();
|
||||
defaultCache.setRequestMatcher(new AntPathRequestMatcher("/**", "GET"));
|
||||
return defaultCache;
|
||||
}
|
||||
}
|
||||
@@ -64,12 +64,6 @@ public final class ServletApiConfigurer<H extends HttpSecurityBuilder<H>> extend
|
||||
return this;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public H disable() {
|
||||
getBuilder().removeConfigurer(getClass());
|
||||
return getBuilder();
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public void configure(H http) throws Exception {
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
*/
|
||||
package org.springframework.security.config.annotation.web.configurers;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
@@ -80,6 +81,7 @@ import org.springframework.util.Assert;
|
||||
public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>> extends AbstractHttpConfigurer<H> {
|
||||
private SessionAuthenticationStrategy sessionFixationAuthenticationStrategy = createDefaultSessionFixationProtectionStrategy();
|
||||
private SessionAuthenticationStrategy sessionAuthenticationStrategy;
|
||||
private List<SessionAuthenticationStrategy> sessionAuthenticationStrategies = new ArrayList<SessionAuthenticationStrategy>();
|
||||
private SessionRegistry sessionRegistry = new SessionRegistryImpl();
|
||||
private Integer maximumSessions;
|
||||
private String expiredUrl;
|
||||
@@ -173,6 +175,18 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an additional {@link SessionAuthenticationStrategy} to be used within the {@link CompositeSessionAuthenticationStrategy}.
|
||||
*
|
||||
* @param sessionAuthenticationStrategy
|
||||
* @return the {@link SessionManagementConfigurer} for further
|
||||
* customizations
|
||||
*/
|
||||
SessionManagementConfigurer<H> addSessionAuthenticationStrategy(SessionAuthenticationStrategy sessionAuthenticationStrategy) {
|
||||
this.sessionAuthenticationStrategies.add(sessionAuthenticationStrategy);
|
||||
return this;
|
||||
}
|
||||
|
||||
public SessionFixationConfigurer sessionFixation() {
|
||||
return new SessionFixationConfigurer();
|
||||
}
|
||||
@@ -400,6 +414,7 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
if(sessionAuthenticationStrategy != null) {
|
||||
return sessionAuthenticationStrategy;
|
||||
}
|
||||
List<SessionAuthenticationStrategy> delegateStrategies = sessionAuthenticationStrategies;
|
||||
if(isConcurrentSessionControlEnabled()) {
|
||||
ConcurrentSessionControlAuthenticationStrategy concurrentSessionControlStrategy = new ConcurrentSessionControlAuthenticationStrategy(sessionRegistry);
|
||||
concurrentSessionControlStrategy.setMaximumSessions(maximumSessions);
|
||||
@@ -409,11 +424,11 @@ public final class SessionManagementConfigurer<H extends HttpSecurityBuilder<H>>
|
||||
RegisterSessionAuthenticationStrategy registerSessionStrategy = new RegisterSessionAuthenticationStrategy(sessionRegistry);
|
||||
registerSessionStrategy = postProcess(registerSessionStrategy);
|
||||
|
||||
List<SessionAuthenticationStrategy> delegateStrategies = Arrays.asList(concurrentSessionControlStrategy, sessionFixationAuthenticationStrategy, registerSessionStrategy);
|
||||
sessionAuthenticationStrategy = postProcess(new CompositeSessionAuthenticationStrategy(delegateStrategies));
|
||||
delegateStrategies.addAll(Arrays.asList(concurrentSessionControlStrategy, sessionFixationAuthenticationStrategy, registerSessionStrategy));
|
||||
} else {
|
||||
sessionAuthenticationStrategy = sessionFixationAuthenticationStrategy;
|
||||
delegateStrategies.add(sessionFixationAuthenticationStrategy);
|
||||
}
|
||||
sessionAuthenticationStrategy = postProcess(new CompositeSessionAuthenticationStrategy(delegateStrategies));
|
||||
return sessionAuthenticationStrategy;
|
||||
}
|
||||
|
||||
|
||||
@@ -116,6 +116,7 @@ final class AuthenticationConfigBuilder {
|
||||
private BeanReference jeeProviderRef;
|
||||
private RootBeanDefinition preAuthEntryPoint;
|
||||
private BeanMetadataElement mainEntryPoint;
|
||||
private BeanMetadataElement accessDeniedHandler;
|
||||
|
||||
private BeanDefinition logoutFilter;
|
||||
@SuppressWarnings("rawtypes")
|
||||
@@ -125,9 +126,10 @@ final class AuthenticationConfigBuilder {
|
||||
private final BeanReference requestCache;
|
||||
private final BeanReference portMapper;
|
||||
private final BeanReference portResolver;
|
||||
private final BeanMetadataElement csrfLogoutHandler;
|
||||
|
||||
public AuthenticationConfigBuilder(Element element, ParserContext pc, SessionCreationPolicy sessionPolicy,
|
||||
BeanReference requestCache, BeanReference authenticationManager, BeanReference sessionStrategy, BeanReference portMapper, BeanReference portResolver) {
|
||||
BeanReference requestCache, BeanReference authenticationManager, BeanReference sessionStrategy, BeanReference portMapper, BeanReference portResolver, BeanMetadataElement csrfLogoutHandler) {
|
||||
this.httpElt = element;
|
||||
this.pc = pc;
|
||||
this.requestCache = requestCache;
|
||||
@@ -136,6 +138,7 @@ final class AuthenticationConfigBuilder {
|
||||
&& sessionPolicy != SessionCreationPolicy.STATELESS;
|
||||
this.portMapper = portMapper;
|
||||
this.portResolver = portResolver;
|
||||
this.csrfLogoutHandler = csrfLogoutHandler;
|
||||
|
||||
createAnonymousFilter();
|
||||
createRememberMeFilter(authenticationManager);
|
||||
@@ -483,7 +486,7 @@ final class AuthenticationConfigBuilder {
|
||||
void createLogoutFilter() {
|
||||
Element logoutElt = DomUtils.getChildElementByTagName(httpElt, Elements.LOGOUT);
|
||||
if (logoutElt != null || autoConfig) {
|
||||
LogoutBeanDefinitionParser logoutParser = new LogoutBeanDefinitionParser(rememberMeServicesId);
|
||||
LogoutBeanDefinitionParser logoutParser = new LogoutBeanDefinitionParser(rememberMeServicesId, csrfLogoutHandler);
|
||||
logoutFilter = logoutParser.parse(logoutElt, pc);
|
||||
logoutHandlers = logoutParser.getLogoutHandlers();
|
||||
}
|
||||
@@ -493,6 +496,9 @@ final class AuthenticationConfigBuilder {
|
||||
ManagedList getLogoutHandlers() {
|
||||
if(logoutHandlers == null && rememberMeProviderRef != null) {
|
||||
logoutHandlers = new ManagedList();
|
||||
if(csrfLogoutHandler != null) {
|
||||
logoutHandlers.add(csrfLogoutHandler);
|
||||
}
|
||||
logoutHandlers.add(new RuntimeBeanReference(rememberMeServicesId));
|
||||
logoutHandlers.add(new RootBeanDefinition(SecurityContextLogoutHandler.class));
|
||||
}
|
||||
@@ -504,6 +510,10 @@ final class AuthenticationConfigBuilder {
|
||||
return mainEntryPoint;
|
||||
}
|
||||
|
||||
BeanMetadataElement getAccessDeniedHandlerBean() {
|
||||
return accessDeniedHandler;
|
||||
}
|
||||
|
||||
void createAnonymousFilter() {
|
||||
Element anonymousElt = DomUtils.getChildElementByTagName(httpElt, Elements.ANONYMOUS);
|
||||
|
||||
@@ -559,7 +569,8 @@ final class AuthenticationConfigBuilder {
|
||||
|
||||
void createExceptionTranslationFilter() {
|
||||
BeanDefinitionBuilder etfBuilder = BeanDefinitionBuilder.rootBeanDefinition(ExceptionTranslationFilter.class);
|
||||
etfBuilder.addPropertyValue("accessDeniedHandler", createAccessDeniedHandler(httpElt, pc));
|
||||
accessDeniedHandler = createAccessDeniedHandler(httpElt, pc);
|
||||
etfBuilder.addPropertyValue("accessDeniedHandler", accessDeniedHandler);
|
||||
assert requestCache != null;
|
||||
mainEntryPoint = selectEntryPoint();
|
||||
etfBuilder.addConstructorArgValue(mainEntryPoint);
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* Copyright 2002-2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.config.http;
|
||||
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.beans.factory.parsing.BeanComponentDefinition;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
|
||||
import org.springframework.beans.factory.support.RootBeanDefinition;
|
||||
import org.springframework.beans.factory.xml.BeanDefinitionParser;
|
||||
import org.springframework.beans.factory.xml.ParserContext;
|
||||
import org.springframework.security.web.csrf.CsrfAuthenticationStrategy;
|
||||
import org.springframework.security.web.csrf.CsrfFilter;
|
||||
import org.springframework.security.web.csrf.CsrfLogoutHandler;
|
||||
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
|
||||
import org.springframework.security.web.servlet.support.csrf.CsrfRequestDataValueProcessor;
|
||||
import org.springframework.util.ClassUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* Parser for the {@code CsrfFilter}.
|
||||
*
|
||||
* @author Rob Winch
|
||||
* @since 3.2
|
||||
*/
|
||||
public class CsrfBeanDefinitionParser implements BeanDefinitionParser {
|
||||
|
||||
private static final String REQUEST_DATA_VALUE_PROCESSOR = "requestDataValueProcessor";
|
||||
private static final String DISPATCHER_SERVLET_CLASS_NAME = "org.springframework.web.servlet.DispatcherServlet";
|
||||
private static final String ATT_MATCHER = "request-matcher-ref";
|
||||
private static final String ATT_REPOSITORY = "token-repository-ref";
|
||||
|
||||
private String csrfRepositoryRef;
|
||||
|
||||
public BeanDefinition parse(Element element, ParserContext pc) {
|
||||
boolean webmvcPresent = ClassUtils.isPresent(DISPATCHER_SERVLET_CLASS_NAME, getClass().getClassLoader());
|
||||
if(webmvcPresent) {
|
||||
RootBeanDefinition beanDefinition = new RootBeanDefinition(CsrfRequestDataValueProcessor.class);
|
||||
BeanComponentDefinition componentDefinition =
|
||||
new BeanComponentDefinition(beanDefinition, REQUEST_DATA_VALUE_PROCESSOR);
|
||||
pc.registerBeanComponent(componentDefinition);
|
||||
}
|
||||
|
||||
csrfRepositoryRef = element.getAttribute(ATT_REPOSITORY);
|
||||
String matcherRef = element.getAttribute(ATT_MATCHER);
|
||||
|
||||
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(CsrfFilter.class);
|
||||
|
||||
if(!StringUtils.hasText(csrfRepositoryRef)) {
|
||||
RootBeanDefinition csrfTokenRepository = new RootBeanDefinition(HttpSessionCsrfTokenRepository.class);
|
||||
csrfRepositoryRef = pc.getReaderContext().generateBeanName(csrfTokenRepository);
|
||||
pc.registerBeanComponent(new BeanComponentDefinition(csrfTokenRepository, csrfRepositoryRef));
|
||||
}
|
||||
|
||||
builder.addConstructorArgReference(csrfRepositoryRef);
|
||||
|
||||
if(StringUtils.hasText(matcherRef)) {
|
||||
builder.addPropertyReference("requireCsrfProtectionMatcher", matcherRef);
|
||||
}
|
||||
|
||||
return builder.getBeanDefinition();
|
||||
}
|
||||
|
||||
BeanDefinition getCsrfAuthenticationStrategy() {
|
||||
BeanDefinitionBuilder csrfAuthenticationStrategy = BeanDefinitionBuilder.rootBeanDefinition(CsrfAuthenticationStrategy.class);
|
||||
csrfAuthenticationStrategy.addConstructorArgReference(csrfRepositoryRef);
|
||||
return csrfAuthenticationStrategy.getBeanDefinition();
|
||||
}
|
||||
|
||||
BeanDefinition getCsrfLogoutHandler() {
|
||||
BeanDefinitionBuilder csrfAuthenticationStrategy = BeanDefinitionBuilder.rootBeanDefinition(CsrfLogoutHandler.class);
|
||||
csrfAuthenticationStrategy.addConstructorArgReference(csrfRepositoryRef);
|
||||
return csrfAuthenticationStrategy.getBeanDefinition();
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,6 @@ import javax.servlet.http.HttpServletRequest;
|
||||
import org.springframework.beans.BeanMetadataElement;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.beans.factory.config.BeanReference;
|
||||
import org.springframework.beans.factory.config.BeanReferenceFactoryBean;
|
||||
import org.springframework.beans.factory.config.RuntimeBeanReference;
|
||||
import org.springframework.beans.factory.parsing.BeanComponentDefinition;
|
||||
import org.springframework.beans.factory.parsing.CompositeComponentDefinition;
|
||||
@@ -71,6 +70,7 @@ import org.springframework.security.web.servletapi.SecurityContextHolderAwareReq
|
||||
import org.springframework.security.web.session.ConcurrentSessionFilter;
|
||||
import org.springframework.security.web.session.SessionManagementFilter;
|
||||
import org.springframework.security.web.session.SimpleRedirectInvalidSessionStrategy;
|
||||
import org.springframework.security.web.util.AntPathRequestMatcher;
|
||||
import org.springframework.util.ClassUtils;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
import org.springframework.util.StringUtils;
|
||||
@@ -126,6 +126,9 @@ class HttpConfigurationBuilder {
|
||||
private BeanReference fsi;
|
||||
private BeanReference requestCache;
|
||||
private BeanDefinition addHeadersFilter;
|
||||
private BeanDefinition csrfFilter;
|
||||
private BeanMetadataElement csrfLogoutHandler;
|
||||
private BeanMetadataElement csrfAuthStrategy;
|
||||
|
||||
public HttpConfigurationBuilder(Element element, ParserContext pc,
|
||||
BeanReference portMapper, BeanReference portResolver, BeanReference authenticationManager) {
|
||||
@@ -152,6 +155,7 @@ class HttpConfigurationBuilder {
|
||||
sessionPolicy = SessionCreationPolicy.IF_REQUIRED;
|
||||
}
|
||||
|
||||
createCsrfFilter();
|
||||
createSecurityContextPersistenceFilter();
|
||||
createSessionManagementFilters();
|
||||
createWebAsyncManagerFilter();
|
||||
@@ -195,6 +199,12 @@ class HttpConfigurationBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
void setAccessDeniedHandler(BeanMetadataElement accessDeniedHandler) {
|
||||
if(csrfFilter != null) {
|
||||
csrfFilter.getPropertyValues().add("accessDeniedHandler", accessDeniedHandler);
|
||||
}
|
||||
}
|
||||
|
||||
// Needed to account for placeholders
|
||||
static String createPath(String path, boolean lowerCase) {
|
||||
return lowerCase ? path.toLowerCase() : path;
|
||||
@@ -298,6 +308,10 @@ class HttpConfigurationBuilder {
|
||||
BeanDefinitionBuilder sessionFixationStrategy = null;
|
||||
BeanDefinitionBuilder registerSessionStrategy;
|
||||
|
||||
if(csrfAuthStrategy != null) {
|
||||
delegateSessionStrategies.add(csrfAuthStrategy);
|
||||
}
|
||||
|
||||
if (sessionControlEnabled) {
|
||||
assert sessionRegistryRef != null;
|
||||
concurrentSessionStrategy = BeanDefinitionBuilder.rootBeanDefinition(ConcurrentSessionControlAuthenticationStrategy.class);
|
||||
@@ -541,6 +555,12 @@ class HttpConfigurationBuilder {
|
||||
requestCacheBldr = BeanDefinitionBuilder.rootBeanDefinition(HttpSessionRequestCache.class);
|
||||
requestCacheBldr.addPropertyValue("createSessionAllowed", sessionPolicy == SessionCreationPolicy.IF_REQUIRED);
|
||||
requestCacheBldr.addPropertyValue("portResolver", portResolver);
|
||||
if(csrfFilter != null) {
|
||||
BeanDefinitionBuilder requestCacheMatcherBldr = BeanDefinitionBuilder.rootBeanDefinition(AntPathRequestMatcher.class);
|
||||
requestCacheMatcherBldr.addConstructorArgValue("/**");
|
||||
requestCacheMatcherBldr.addConstructorArgValue("GET");
|
||||
requestCacheBldr.addPropertyValue("requestMatcher", requestCacheMatcherBldr.getBeanDefinition());
|
||||
}
|
||||
}
|
||||
|
||||
BeanDefinition bean = requestCacheBldr.getBeanDefinition();
|
||||
@@ -617,6 +637,20 @@ class HttpConfigurationBuilder {
|
||||
|
||||
}
|
||||
|
||||
private void createCsrfFilter() {
|
||||
Element elmt = DomUtils.getChildElementByTagName(httpElt, Elements.CSRF);
|
||||
if (elmt != null) {
|
||||
CsrfBeanDefinitionParser csrfParser = new CsrfBeanDefinitionParser();
|
||||
this.csrfFilter = csrfParser.parse(elmt, pc);
|
||||
this.csrfAuthStrategy = csrfParser.getCsrfAuthenticationStrategy();
|
||||
this.csrfLogoutHandler = csrfParser.getCsrfLogoutHandler();
|
||||
}
|
||||
}
|
||||
|
||||
BeanMetadataElement getCsrfLogoutHandler() {
|
||||
return this.csrfLogoutHandler;
|
||||
}
|
||||
|
||||
BeanReference getSessionStrategy() {
|
||||
return sessionStrategyRef;
|
||||
}
|
||||
@@ -668,6 +702,10 @@ class HttpConfigurationBuilder {
|
||||
filters.add(new OrderDecorator(addHeadersFilter, HEADERS_FILTER));
|
||||
}
|
||||
|
||||
if (csrfFilter != null) {
|
||||
filters.add(new OrderDecorator(csrfFilter, CSRF_FILTER));
|
||||
}
|
||||
|
||||
return filters;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,10 +137,11 @@ public class HttpSecurityBeanDefinitionParser implements BeanDefinitionParser {
|
||||
|
||||
AuthenticationConfigBuilder authBldr = new AuthenticationConfigBuilder(element, pc,
|
||||
httpBldr.getSessionCreationPolicy(), httpBldr.getRequestCache(), authenticationManager,
|
||||
httpBldr.getSessionStrategy(), portMapper, portResolver);
|
||||
httpBldr.getSessionStrategy(), portMapper, portResolver, httpBldr.getCsrfLogoutHandler());
|
||||
|
||||
httpBldr.setLogoutHandlers(authBldr.getLogoutHandlers());
|
||||
httpBldr.setEntryPoint(authBldr.getEntryPointBean());
|
||||
httpBldr.setAccessDeniedHandler(authBldr.getAccessDeniedHandlerBean());
|
||||
|
||||
authenticationProviders.addAll(authBldr.getProviders());
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
*/
|
||||
package org.springframework.security.config.http;
|
||||
|
||||
import org.springframework.beans.BeanMetadataElement;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.beans.factory.config.RuntimeBeanReference;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
|
||||
@@ -44,13 +45,15 @@ class LogoutBeanDefinitionParser implements BeanDefinitionParser {
|
||||
static final String ATT_DELETE_COOKIES = "delete-cookies";
|
||||
|
||||
final String rememberMeServices;
|
||||
private ManagedList logoutHandlers = new ManagedList();
|
||||
private ManagedList<BeanMetadataElement> logoutHandlers = new ManagedList<BeanMetadataElement>();
|
||||
|
||||
public LogoutBeanDefinitionParser(String rememberMeServices) {
|
||||
public LogoutBeanDefinitionParser(String rememberMeServices, BeanMetadataElement csrfLogoutHandler) {
|
||||
this.rememberMeServices = rememberMeServices;
|
||||
if(csrfLogoutHandler != null) {
|
||||
logoutHandlers.add(csrfLogoutHandler);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public BeanDefinition parse(Element element, ParserContext pc) {
|
||||
String logoutUrl = null;
|
||||
String successHandlerRef = null;
|
||||
@@ -111,7 +114,7 @@ class LogoutBeanDefinitionParser implements BeanDefinitionParser {
|
||||
return builder.getBeanDefinition();
|
||||
}
|
||||
|
||||
ManagedList getLogoutHandlers() {
|
||||
ManagedList<BeanMetadataElement> getLogoutHandlers() {
|
||||
return logoutHandlers;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ enum SecurityFilters {
|
||||
/** {@link WebAsyncManagerIntegrationFilter} */
|
||||
WEB_ASYNC_MANAGER_FILTER,
|
||||
HEADERS_FILTER,
|
||||
CSRF_FILTER,
|
||||
LOGOUT_FILTER,
|
||||
X509_FILTER,
|
||||
PRE_AUTH_FILTER,
|
||||
|
||||
@@ -281,7 +281,7 @@ http-firewall =
|
||||
|
||||
http =
|
||||
## Container element for HTTP security configuration. Multiple elements can now be defined, each with a specific pattern to which the enclosed security configuration applies. A pattern can also be configured to bypass Spring Security's filters completely by setting the "secured" attribute to "false".
|
||||
element http {http.attlist, (intercept-url* & access-denied-handler? & form-login? & openid-login? & x509? & jee? & http-basic? & logout? & session-management & remember-me? & anonymous? & port-mappings & custom-filter* & request-cache? & expression-handler? & headers?) }
|
||||
element http {http.attlist, (intercept-url* & access-denied-handler? & form-login? & openid-login? & x509? & jee? & http-basic? & logout? & session-management & remember-me? & anonymous? & port-mappings & custom-filter* & request-cache? & expression-handler? & headers? & csrf?) }
|
||||
http.attlist &=
|
||||
## The request URL pattern which will be mapped to the filter chain created by this <http> element. If omitted, the filter chain will match all requests.
|
||||
attribute pattern {xsd:token}?
|
||||
@@ -718,8 +718,18 @@ jdbc-user-service.attlist &=
|
||||
jdbc-user-service.attlist &=
|
||||
role-prefix?
|
||||
|
||||
csrf =
|
||||
## Element for configuration of the CsrfFilter for protection against CSRF. It also updates the default RequestCache to only replay "GET" requests.
|
||||
element csrf {csrf-options.attlist}
|
||||
csrf-options.attlist &=
|
||||
## The RequestMatcher instance to be used to determine if CSRF should be applied. Default is any HTTP method except "GET", "TRACE", "HEAD", "OPTIONS"
|
||||
attribute request-matcher-ref { xsd:token }?
|
||||
csrf-options.attlist &=
|
||||
## The CsrfTokenRepository to use. The default is HttpSessionCsrfTokenRepository
|
||||
attribute token-repository-ref { xsd:token }?
|
||||
|
||||
headers =
|
||||
## Element for configuration of the AddHeadersFilter. Enables easy setting for the X-Frame-Options, X-XSS-Protection and X-Content-Type-Options headers.
|
||||
## Element for configuration of the HeaderWritersFilter. Enables easy setting for the X-Frame-Options, X-XSS-Protection and X-Content-Type-Options headers.
|
||||
element headers {cache-control? & xss-protection? & hsts? & frame-options? & content-type-options? & header*}
|
||||
|
||||
hsts =
|
||||
@@ -783,7 +793,7 @@ header.attlist &=
|
||||
## The value for the header.
|
||||
attribute value {xsd:token}?
|
||||
header.attlist &=
|
||||
## Reference to a custom HeaderFactory implementation.
|
||||
## Reference to a custom HeaderWriter implementation.
|
||||
ref?
|
||||
|
||||
any-user-service = user-service | jdbc-user-service | ldap-user-service
|
||||
@@ -808,4 +818,4 @@ position =
|
||||
## The explicit position at which the custom-filter should be placed in the chain. Use if you are replacing a standard filter.
|
||||
attribute position {named-security-filter}
|
||||
|
||||
named-security-filter = "FIRST" | "CHANNEL_FILTER" | "CONCURRENT_SESSION_FILTER" | "SECURITY_CONTEXT_FILTER" | "LOGOUT_FILTER" | "X509_FILTER" | "PRE_AUTH_FILTER" | "CAS_FILTER" | "FORM_LOGIN_FILTER" | "OPENID_FILTER" |"BASIC_AUTH_FILTER" | "SERVLET_API_SUPPORT_FILTER" | "REMEMBER_ME_FILTER" | "ANONYMOUS_FILTER" | "EXCEPTION_TRANSLATION_FILTER" | "SESSION_MANAGEMENT_FILTER" | "FILTER_SECURITY_INTERCEPTOR" | "SWITCH_USER_FILTER" | "LAST"
|
||||
named-security-filter = "FIRST" | "CHANNEL_FILTER" | "CONCURRENT_SESSION_FILTER" | "HEADERS_FILTER" | "CSRF_FILTER" | "SECURITY_CONTEXT_FILTER" | "LOGOUT_FILTER" | "X509_FILTER" | "PRE_AUTH_FILTER" | "CAS_FILTER" | "FORM_LOGIN_FILTER" | "OPENID_FILTER" |"BASIC_AUTH_FILTER" | "SERVLET_API_SUPPORT_FILTER" | "REMEMBER_ME_FILTER" | "ANONYMOUS_FILTER" | "EXCEPTION_TRANSLATION_FILTER" | "SESSION_MANAGEMENT_FILTER" | "FILTER_SECURITY_INTERCEPTOR" | "SWITCH_USER_FILTER" | "LAST"
|
||||
|
||||
@@ -1025,6 +1025,7 @@
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
<xs:element ref="security:headers"/>
|
||||
<xs:element ref="security:csrf"/>
|
||||
</xs:choice>
|
||||
<xs:attributeGroup ref="security:http.attlist"/>
|
||||
</xs:complexType>
|
||||
@@ -2238,9 +2239,34 @@
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
</xs:attributeGroup>
|
||||
<xs:element name="csrf">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Element for configuration of the CsrfFilter for protection against CSRF. It also updates
|
||||
the default RequestCache to only replay "GET" requests.
|
||||
</xs:documentation>
|
||||
</xs:annotation>
|
||||
<xs:complexType>
|
||||
<xs:attributeGroup ref="security:csrf-options.attlist"/>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
<xs:attributeGroup name="csrf-options.attlist">
|
||||
<xs:attribute name="request-matcher-ref" type="xs:token">
|
||||
<xs:annotation>
|
||||
<xs:documentation>The RequestMatcher instance to be used to determine if CSRF should be applied. Default is
|
||||
any HTTP method except "GET", "TRACE", "HEAD", "OPTIONS"
|
||||
</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
<xs:attribute name="token-repository-ref" type="xs:token">
|
||||
<xs:annotation>
|
||||
<xs:documentation>The CsrfTokenRepository to use. The default is HttpSessionCsrfTokenRepository
|
||||
</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:attribute>
|
||||
</xs:attributeGroup>
|
||||
<xs:element name="headers">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Element for configuration of the AddHeadersFilter. Enables easy setting for the
|
||||
<xs:documentation>Element for configuration of the HeaderWritersFilter. Enables easy setting for the
|
||||
X-Frame-Options, X-XSS-Protection and X-Content-Type-Options headers.
|
||||
</xs:documentation>
|
||||
</xs:annotation>
|
||||
@@ -2479,6 +2505,8 @@
|
||||
<xs:enumeration value="FIRST"/>
|
||||
<xs:enumeration value="CHANNEL_FILTER"/>
|
||||
<xs:enumeration value="CONCURRENT_SESSION_FILTER"/>
|
||||
<xs:enumeration value="HEADERS_FILTER"/>
|
||||
<xs:enumeration value="CSRF_FILTER"/>
|
||||
<xs:enumeration value="SECURITY_CONTEXT_FILTER"/>
|
||||
<xs:enumeration value="LOGOUT_FILTER"/>
|
||||
<xs:enumeration value="X509_FILTER"/>
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package org.springframework.security.config
|
||||
|
||||
import groovy.xml.MarkupBuilder
|
||||
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.context.support.AbstractXmlApplicationContext
|
||||
import org.springframework.security.config.util.InMemoryXmlApplicationContext
|
||||
import org.springframework.security.core.context.SecurityContextHolder
|
||||
@@ -37,6 +39,12 @@ abstract class AbstractXmlConfigTests extends Specification {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
def mockBean(Class clazz, String id = clazz.simpleName) {
|
||||
xml.'b:bean'(id: id, 'class': Mockito.class.name, 'factory-method':'mock') {
|
||||
'b:constructor-arg'(value : clazz.name)
|
||||
}
|
||||
}
|
||||
|
||||
def bean(String name, Class clazz) {
|
||||
xml.'b:bean'(id: name, 'class': clazz.name)
|
||||
}
|
||||
|
||||
@@ -25,16 +25,18 @@ import org.springframework.mock.web.MockHttpServletRequest
|
||||
import org.springframework.mock.web.MockHttpServletResponse
|
||||
import org.springframework.security.authentication.AuthenticationManager
|
||||
import org.springframework.security.authentication.AuthenticationProvider
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
|
||||
import org.springframework.security.core.Authentication
|
||||
import org.springframework.security.core.authority.AuthorityUtils;
|
||||
import org.springframework.security.core.authority.AuthorityUtils
|
||||
import org.springframework.security.core.context.SecurityContextHolder
|
||||
import org.springframework.security.core.context.SecurityContextImpl
|
||||
import org.springframework.security.web.FilterChainProxy
|
||||
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor
|
||||
import org.springframework.security.web.context.HttpRequestResponseHolder
|
||||
import org.springframework.security.web.context.HttpSessionSecurityContextRepository
|
||||
import org.springframework.security.web.csrf.CsrfToken
|
||||
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository
|
||||
|
||||
import spock.lang.AutoCleanup
|
||||
import spock.lang.Specification
|
||||
@@ -50,11 +52,26 @@ abstract class BaseSpringSpec extends Specification {
|
||||
MockHttpServletRequest request
|
||||
MockHttpServletResponse response
|
||||
MockFilterChain chain
|
||||
CsrfToken csrfToken
|
||||
|
||||
def setup() {
|
||||
setupWeb(null)
|
||||
}
|
||||
|
||||
def setupWeb(httpSession = null) {
|
||||
request = new MockHttpServletRequest(method:"GET")
|
||||
if(httpSession) {
|
||||
request.session = httpSession
|
||||
}
|
||||
response = new MockHttpServletResponse()
|
||||
chain = new MockFilterChain()
|
||||
setupCsrf()
|
||||
}
|
||||
|
||||
def setupCsrf(csrfTokenValue="BaseSpringSpec_CSRFTOKEN") {
|
||||
csrfToken = new CsrfToken("X-CSRF-TOKEN","_csrf",csrfTokenValue)
|
||||
new HttpSessionCsrfTokenRepository().saveToken(csrfToken, request,response)
|
||||
request.setParameter(csrfToken.parameterName, csrfToken.token)
|
||||
}
|
||||
|
||||
AuthenticationManagerBuilder authenticationBldr = new AuthenticationManagerBuilder(ObjectPostProcessor.QUIESCENT_POSTPROCESSOR).inMemoryAuthentication().and()
|
||||
@@ -117,6 +134,10 @@ abstract class BaseSpringSpec extends Specification {
|
||||
authenticationProviders().find { provider.isAssignableFrom(it.class) }
|
||||
}
|
||||
|
||||
def getCurrentAuthentication() {
|
||||
new HttpSessionSecurityContextRepository().loadContext(new HttpRequestResponseHolder(request, response)).authentication
|
||||
}
|
||||
|
||||
def login(String username="user", String role="ROLE_USER") {
|
||||
login(new UsernamePasswordAuthenticationToken(username, null, AuthorityUtils.createAuthorityList(role)))
|
||||
}
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.config.annotation;
|
||||
|
||||
import org.springframework.context.ConfigurableApplicationContext
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.mock.web.MockFilterChain;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.core.context.SecurityContextHolder
|
||||
import org.springframework.security.web.FilterChainProxy;
|
||||
|
||||
import spock.lang.AutoCleanup
|
||||
import spock.lang.Specification
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
*/
|
||||
abstract class BaseWebSpecuritySpec extends BaseSpringSpec {
|
||||
FilterChainProxy springSecurityFilterChain
|
||||
MockHttpServletRequest request
|
||||
MockHttpServletResponse response
|
||||
MockFilterChain chain
|
||||
|
||||
def setup() {
|
||||
request = new MockHttpServletRequest(method:"GET")
|
||||
response = new MockHttpServletResponse()
|
||||
chain = new MockFilterChain()
|
||||
}
|
||||
|
||||
|
||||
def loadConfig(Class<?>... configs) {
|
||||
super.loadConfig(configs)
|
||||
springSecurityFilterChain = context.getBean(FilterChainProxy)
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -20,8 +20,7 @@ import javax.servlet.http.HttpServletResponse
|
||||
import org.springframework.beans.factory.annotation.Autowired
|
||||
import org.springframework.context.annotation.Configuration
|
||||
import org.springframework.core.annotation.Order
|
||||
import org.springframework.security.authentication.AuthenticationManager
|
||||
import org.springframework.security.config.annotation.BaseWebSpecuritySpec
|
||||
import org.springframework.security.config.annotation.BaseSpringSpec
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity
|
||||
import org.springframework.security.config.annotation.web.builders.WebSecurity
|
||||
@@ -34,7 +33,7 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
|
||||
* @author Rob Winch
|
||||
*
|
||||
*/
|
||||
public class SampleWebSecurityConfigurerAdapterTests extends BaseWebSpecuritySpec {
|
||||
public class SampleWebSecurityConfigurerAdapterTests extends BaseSpringSpec {
|
||||
def "README HelloWorld Sample works"() {
|
||||
setup: "Sample Config is loaded"
|
||||
loadConfig(HelloWorldWebSecurityConfigurerAdapter)
|
||||
|
||||
@@ -79,7 +79,8 @@ class WebSecurityConfigurerAdapterTests extends BaseSpringSpec {
|
||||
'Strict-Transport-Security': 'max-age=31536000 ; includeSubDomains',
|
||||
'Cache-Control': 'no-cache,no-store,max-age=0,must-revalidate',
|
||||
'Pragma':'no-cache',
|
||||
'X-XSS-Protection' : '1; mode=block']
|
||||
'X-XSS-Protection' : '1; mode=block',
|
||||
'X-CSRF-TOKEN' : csrfToken.token]
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
|
||||
@@ -0,0 +1,355 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.config.annotation.web.configurers
|
||||
|
||||
import javax.servlet.http.HttpServletResponse
|
||||
|
||||
import org.springframework.context.annotation.Configuration
|
||||
import org.springframework.security.config.annotation.BaseSpringSpec
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
|
||||
import org.springframework.security.web.access.AccessDeniedHandler
|
||||
import org.springframework.security.web.csrf.CsrfFilter;
|
||||
import org.springframework.security.web.csrf.CsrfTokenRepository;
|
||||
import org.springframework.security.web.servlet.support.csrf.CsrfRequestDataValueProcessor;
|
||||
import org.springframework.security.web.util.RequestMatcher;
|
||||
|
||||
import spock.lang.Unroll;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
*/
|
||||
class CsrfConfigurerTests extends BaseSpringSpec {
|
||||
|
||||
@Unroll
|
||||
def "csrf applied by default"() {
|
||||
setup:
|
||||
loadConfig(CsrfAppliedDefaultConfig)
|
||||
request.method = httpMethod
|
||||
clearCsrfToken()
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
response.status == httpStatus
|
||||
where:
|
||||
httpMethod | httpStatus
|
||||
'POST' | HttpServletResponse.SC_FORBIDDEN
|
||||
'PUT' | HttpServletResponse.SC_FORBIDDEN
|
||||
'PATCH' | HttpServletResponse.SC_FORBIDDEN
|
||||
'DELETE' | HttpServletResponse.SC_FORBIDDEN
|
||||
'INVALID' | HttpServletResponse.SC_FORBIDDEN
|
||||
'GET' | HttpServletResponse.SC_OK
|
||||
'HEAD' | HttpServletResponse.SC_OK
|
||||
'TRACE' | HttpServletResponse.SC_OK
|
||||
'OPTIONS' | HttpServletResponse.SC_OK
|
||||
}
|
||||
|
||||
def "csrf default creates CsrfRequestDataValueProcessor"() {
|
||||
when:
|
||||
loadConfig(CsrfAppliedDefaultConfig)
|
||||
then:
|
||||
context.getBean(CsrfRequestDataValueProcessor)
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
static class CsrfAppliedDefaultConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
}
|
||||
}
|
||||
|
||||
def "csrf disable"() {
|
||||
setup:
|
||||
loadConfig(DisableCsrfConfig)
|
||||
request.method = "POST"
|
||||
clearCsrfToken()
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
!findFilter(CsrfFilter)
|
||||
response.status == HttpServletResponse.SC_OK
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
static class DisableCsrfConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.csrf().disable()
|
||||
}
|
||||
}
|
||||
|
||||
def "csrf requireCsrfProtectionMatcher"() {
|
||||
setup:
|
||||
RequireCsrfProtectionMatcherConfig.matcher = Mock(RequestMatcher)
|
||||
RequireCsrfProtectionMatcherConfig.matcher.matches(_) >>> [false,true]
|
||||
loadConfig(RequireCsrfProtectionMatcherConfig)
|
||||
clearCsrfToken()
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
response.status == HttpServletResponse.SC_OK
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
response.status == HttpServletResponse.SC_FORBIDDEN
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
static class RequireCsrfProtectionMatcherConfig extends WebSecurityConfigurerAdapter {
|
||||
static RequestMatcher matcher
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.csrf()
|
||||
.requireCsrfProtectionMatcher(matcher)
|
||||
}
|
||||
}
|
||||
|
||||
def "csrf csrfTokenRepository"() {
|
||||
setup:
|
||||
CsrfTokenRepositoryConfig.repo = Mock(CsrfTokenRepository)
|
||||
loadConfig(CsrfTokenRepositoryConfig)
|
||||
clearCsrfToken()
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
1 * CsrfTokenRepositoryConfig.repo.loadToken(_) >> csrfToken
|
||||
response.status == HttpServletResponse.SC_OK
|
||||
}
|
||||
|
||||
def "csrf clears on logout"() {
|
||||
setup:
|
||||
CsrfTokenRepositoryConfig.repo = Mock(CsrfTokenRepository)
|
||||
1 * CsrfTokenRepositoryConfig.repo.loadToken(_) >> csrfToken
|
||||
loadConfig(CsrfTokenRepositoryConfig)
|
||||
login()
|
||||
request.method = "POST"
|
||||
request.servletPath = "/logout"
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
1 * CsrfTokenRepositoryConfig.repo.saveToken(null, _, _)
|
||||
}
|
||||
|
||||
def "csrf clears on login"() {
|
||||
setup:
|
||||
CsrfTokenRepositoryConfig.repo = Mock(CsrfTokenRepository)
|
||||
1 * CsrfTokenRepositoryConfig.repo.loadToken(_) >> csrfToken
|
||||
loadConfig(CsrfTokenRepositoryConfig)
|
||||
request.method = "POST"
|
||||
request.getSession()
|
||||
request.servletPath = "/login"
|
||||
request.setParameter("username", "user")
|
||||
request.setParameter("password", "password")
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
response.redirectedUrl == "/"
|
||||
1 * CsrfTokenRepositoryConfig.repo.saveToken(null, _, _)
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
static class CsrfTokenRepositoryConfig extends WebSecurityConfigurerAdapter {
|
||||
static CsrfTokenRepository repo
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.formLogin()
|
||||
.and()
|
||||
.csrf()
|
||||
.csrfTokenRepository(repo)
|
||||
}
|
||||
@Override
|
||||
protected void registerAuthentication(AuthenticationManagerBuilder auth)
|
||||
throws Exception {
|
||||
auth
|
||||
.inMemoryAuthentication()
|
||||
.withUser("user").password("password").roles("USER")
|
||||
}
|
||||
}
|
||||
|
||||
def "csrf access denied handler"() {
|
||||
setup:
|
||||
AccessDeniedHandlerConfig.deniedHandler = Mock(AccessDeniedHandler)
|
||||
1 * AccessDeniedHandlerConfig.deniedHandler.handle(_, _, _)
|
||||
loadConfig(AccessDeniedHandlerConfig)
|
||||
clearCsrfToken()
|
||||
request.method = "POST"
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
response.status == HttpServletResponse.SC_OK
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
static class AccessDeniedHandlerConfig extends WebSecurityConfigurerAdapter {
|
||||
static AccessDeniedHandler deniedHandler
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.exceptionHandling()
|
||||
.accessDeniedHandler(deniedHandler)
|
||||
}
|
||||
}
|
||||
|
||||
def "formLogin requires CSRF token"() {
|
||||
setup:
|
||||
loadConfig(FormLoginConfig)
|
||||
clearCsrfToken()
|
||||
request.setParameter("username", "user")
|
||||
request.setParameter("password", "password")
|
||||
request.servletPath = "/login"
|
||||
request.method = "POST"
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
response.status == HttpServletResponse.SC_FORBIDDEN
|
||||
currentAuthentication == null
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
static class FormLoginConfig extends WebSecurityConfigurerAdapter {
|
||||
static AccessDeniedHandler deniedHandler
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.formLogin()
|
||||
}
|
||||
}
|
||||
|
||||
def "logout requires CSRF token"() {
|
||||
setup:
|
||||
loadConfig(LogoutConfig)
|
||||
clearCsrfToken()
|
||||
login()
|
||||
request.servletPath = "/logout"
|
||||
request.method = "POST"
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then: "logout is not allowed and user is still authenticated"
|
||||
response.status == HttpServletResponse.SC_FORBIDDEN
|
||||
currentAuthentication != null
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
static class LogoutConfig extends WebSecurityConfigurerAdapter {
|
||||
static AccessDeniedHandler deniedHandler
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.formLogin()
|
||||
}
|
||||
}
|
||||
|
||||
def "csrf disables POST requests from RequestCache"() {
|
||||
setup:
|
||||
CsrfDisablesPostRequestFromRequestCacheConfig.repo = Mock(CsrfTokenRepository)
|
||||
loadConfig(CsrfDisablesPostRequestFromRequestCacheConfig)
|
||||
request.servletPath = "/some-url"
|
||||
request.requestURI = "/some-url"
|
||||
request.method = "POST"
|
||||
when: "CSRF passes and our session times out"
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then: "sent to the login page"
|
||||
1 * CsrfDisablesPostRequestFromRequestCacheConfig.repo.loadToken(_) >> csrfToken
|
||||
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 success because we don't want csrf attempts made prior to authentication to pass"
|
||||
1 * CsrfDisablesPostRequestFromRequestCacheConfig.repo.loadToken(_) >> csrfToken
|
||||
response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
|
||||
response.redirectedUrl == "/"
|
||||
}
|
||||
|
||||
def "csrf enables GET requests with RequestCache"() {
|
||||
setup:
|
||||
CsrfDisablesPostRequestFromRequestCacheConfig.repo = Mock(CsrfTokenRepository)
|
||||
loadConfig(CsrfDisablesPostRequestFromRequestCacheConfig)
|
||||
request.servletPath = "/some-url"
|
||||
request.requestURI = "/some-url"
|
||||
request.method = "GET"
|
||||
when: "CSRF passes and our session times out"
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then: "sent to the login page"
|
||||
1 * CsrfDisablesPostRequestFromRequestCacheConfig.repo.loadToken(_) >> csrfToken
|
||||
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 original URL since it was a GET"
|
||||
1 * CsrfDisablesPostRequestFromRequestCacheConfig.repo.loadToken(_) >> csrfToken
|
||||
response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
|
||||
response.redirectedUrl == "http://localhost/some-url"
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
static class CsrfDisablesPostRequestFromRequestCacheConfig extends WebSecurityConfigurerAdapter {
|
||||
static CsrfTokenRepository repo
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.authorizeRequests()
|
||||
.anyRequest().authenticated()
|
||||
.and()
|
||||
.formLogin()
|
||||
.and()
|
||||
.csrf()
|
||||
.csrfTokenRepository(repo)
|
||||
}
|
||||
@Override
|
||||
protected void registerAuthentication(AuthenticationManagerBuilder auth)
|
||||
throws Exception {
|
||||
auth
|
||||
.inMemoryAuthentication()
|
||||
.withUser("user").password("password").roles("USER")
|
||||
}
|
||||
}
|
||||
|
||||
def clearCsrfToken() {
|
||||
request.removeAllParameters()
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,8 @@ import org.springframework.security.web.authentication.AnonymousAuthenticationFi
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
|
||||
import org.springframework.security.web.authentication.logout.LogoutFilter
|
||||
import org.springframework.security.web.context.SecurityContextPersistenceFilter
|
||||
import org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter;
|
||||
import org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter
|
||||
import org.springframework.security.web.csrf.CsrfFilter
|
||||
import org.springframework.security.web.header.HeaderWriterFilter
|
||||
import org.springframework.security.web.savedrequest.RequestCacheAwareFilter
|
||||
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter
|
||||
@@ -107,17 +108,17 @@ class DefaultFiltersTests extends BaseSpringSpec {
|
||||
|
||||
def "FilterChainProxyBuilder ignoring resources"() {
|
||||
when:
|
||||
context = new AnnotationConfigApplicationContext(FilterChainProxyBuilderIgnoringConfig)
|
||||
loadConfig(FilterChainProxyBuilderIgnoringConfig)
|
||||
then:
|
||||
List<DefaultSecurityFilterChain> 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, LogoutFilter, RequestCacheAwareFilter,
|
||||
SecurityContextHolderAwareRequestFilter, AnonymousAuthenticationFilter, SessionManagementFilter,
|
||||
ExceptionTranslationFilter, FilterSecurityInterceptor ]
|
||||
List<DefaultSecurityFilterChain> 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 ]
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@@ -139,17 +140,16 @@ class DefaultFiltersTests extends BaseSpringSpec {
|
||||
|
||||
def "DefaultFilters.permitAll()"() {
|
||||
when:
|
||||
context = new AnnotationConfigApplicationContext(DefaultFiltersConfigPermitAll)
|
||||
loadConfig(DefaultFiltersConfigPermitAll)
|
||||
MockHttpServletResponse response = new MockHttpServletResponse()
|
||||
request = new MockHttpServletRequest(servletPath : uri, queryString: query, method:"POST")
|
||||
setupCsrf()
|
||||
springSecurityFilterChain.doFilter(request, response, new MockFilterChain())
|
||||
then:
|
||||
FilterChainProxy filterChain = context.getBean(FilterChainProxy)
|
||||
|
||||
expect:
|
||||
MockHttpServletResponse response = new MockHttpServletResponse()
|
||||
filterChain.doFilter(new MockHttpServletRequest(servletPath : uri, queryString: query), response, new MockFilterChain())
|
||||
response.redirectedUrl == null
|
||||
response.redirectedUrl == "/login?logout"
|
||||
where:
|
||||
uri | query
|
||||
"/logout" | null
|
||||
uri | query
|
||||
"/logout" | null
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
@@ -42,28 +42,16 @@ import org.springframework.security.web.authentication.ui.DefaultLoginPageViewFi
|
||||
*
|
||||
*/
|
||||
public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
|
||||
FilterChainProxy springSecurityFilterChain
|
||||
MockHttpServletRequest request
|
||||
MockHttpServletResponse response
|
||||
MockFilterChain chain
|
||||
|
||||
def setup() {
|
||||
request = new MockHttpServletRequest(method:"GET")
|
||||
response = new MockHttpServletResponse()
|
||||
chain = new MockFilterChain()
|
||||
}
|
||||
|
||||
def "http/form-login default login generating page"() {
|
||||
setup:
|
||||
loadConfig(DefaultLoginPageConfig)
|
||||
springSecurityFilterChain = context.getBean(FilterChainProxy)
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
findFilter(DefaultLoginPageViewFilter)
|
||||
response.getRedirectedUrl() == "http://localhost/login"
|
||||
when: "request the login page"
|
||||
setup()
|
||||
super.setup()
|
||||
request.requestURI = "/login"
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
@@ -73,10 +61,11 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
|
||||
<tr><td>User:</td><td><input type='text' name='username' value=''></td></tr>
|
||||
<tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
|
||||
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
|
||||
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
|
||||
</table>
|
||||
</form></body></html>"""
|
||||
when: "fail to log in"
|
||||
setup()
|
||||
super.setup()
|
||||
request.servletPath = "/login"
|
||||
request.method = "POST"
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
@@ -84,7 +73,7 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
|
||||
response.getRedirectedUrl() == "/login?error"
|
||||
when: "request the error page"
|
||||
HttpSession session = request.session
|
||||
setup()
|
||||
super.setup()
|
||||
request.session = session
|
||||
request.requestURI = "/login"
|
||||
request.queryString = "error"
|
||||
@@ -96,10 +85,11 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
|
||||
<tr><td>User:</td><td><input type='text' name='username' value=''></td></tr>
|
||||
<tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
|
||||
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
|
||||
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
|
||||
</table>
|
||||
</form></body></html>"""
|
||||
when: "login success"
|
||||
setup()
|
||||
super.setup()
|
||||
request.servletPath = "/login"
|
||||
request.method = "POST"
|
||||
request.parameters.username = ["user"] as String[]
|
||||
@@ -112,7 +102,6 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
|
||||
def "logout success renders"() {
|
||||
setup:
|
||||
loadConfig(DefaultLoginPageConfig)
|
||||
springSecurityFilterChain = context.getBean(FilterChainProxy)
|
||||
when: "logout success"
|
||||
request.requestURI = "/login"
|
||||
request.queryString = "logout"
|
||||
@@ -125,6 +114,7 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
|
||||
<tr><td>User:</td><td><input type='text' name='username' value=''></td></tr>
|
||||
<tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
|
||||
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
|
||||
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
|
||||
</table>
|
||||
</form></body></html>"""
|
||||
}
|
||||
@@ -144,7 +134,6 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
|
||||
def "custom logout success handler prevents rendering"() {
|
||||
setup:
|
||||
loadConfig(DefaultLoginPageCustomLogoutSuccessHandlerConfig)
|
||||
springSecurityFilterChain = context.getBean(FilterChainProxy)
|
||||
when: "logout success"
|
||||
request.requestURI = "/login"
|
||||
request.queryString = "logout"
|
||||
@@ -172,7 +161,6 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
|
||||
def "custom logout success url prevents rendering"() {
|
||||
setup:
|
||||
loadConfig(DefaultLoginPageCustomLogoutConfig)
|
||||
springSecurityFilterChain = context.getBean(FilterChainProxy)
|
||||
when: "logout success"
|
||||
request.requestURI = "/login"
|
||||
request.queryString = "logout"
|
||||
@@ -200,9 +188,8 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
|
||||
def "http/form-login default login with remember me"() {
|
||||
setup:
|
||||
loadConfig(DefaultLoginPageWithRememberMeConfig)
|
||||
springSecurityFilterChain = context.getBean(FilterChainProxy)
|
||||
when: "request the login page"
|
||||
setup()
|
||||
super.setup()
|
||||
request.requestURI = "/login"
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
@@ -213,6 +200,7 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
|
||||
<tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
|
||||
<tr><td><input type='checkbox' name='remember-me'/></td><td>Remember me on this computer.</td></tr>
|
||||
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
|
||||
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
|
||||
</table>
|
||||
</form></body></html>"""
|
||||
}
|
||||
@@ -234,7 +222,6 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
|
||||
def "http/form-login default login with openid"() {
|
||||
setup:
|
||||
loadConfig(DefaultLoginPageWithOpenIDConfig)
|
||||
springSecurityFilterChain = context.getBean(FilterChainProxy)
|
||||
when: "request the login page"
|
||||
request.requestURI = "/login"
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
@@ -244,6 +231,7 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
|
||||
<tr><td>Identity:</td><td><input type='text' size='30' name='openid_identifier'/></td></tr>
|
||||
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
|
||||
</table>
|
||||
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
|
||||
</form></body></html>"""
|
||||
}
|
||||
|
||||
@@ -262,7 +250,6 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
|
||||
def "http/form-login default login with openid, form login, and rememberme"() {
|
||||
setup:
|
||||
loadConfig(DefaultLoginPageWithFormLoginOpenIDRememberMeConfig)
|
||||
springSecurityFilterChain = context.getBean(FilterChainProxy)
|
||||
when: "request the login page"
|
||||
request.requestURI = "/login"
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
@@ -274,6 +261,7 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
|
||||
<tr><td>Password:</td><td><input type='password' name='password'/></td></tr>
|
||||
<tr><td><input type='checkbox' name='remember-me'/></td><td>Remember me on this computer.</td></tr>
|
||||
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
|
||||
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
|
||||
</table>
|
||||
</form><h3>Login with OpenID Identity</h3><form name='oidf' action='/login/openid' method='POST'>
|
||||
<table>
|
||||
@@ -281,6 +269,7 @@ public class DefaultLoginPageConfigurerTests extends BaseSpringSpec {
|
||||
<tr><td><input type='checkbox' name='remember-me'></td><td>Remember me on this computer.</td></tr>
|
||||
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
|
||||
</table>
|
||||
<input name="${csrfToken.parameterName}" type="hidden" value="${csrfToken.token}" />
|
||||
</form></body></html>"""
|
||||
}
|
||||
|
||||
|
||||
@@ -41,6 +41,7 @@ import org.springframework.security.web.authentication.logout.LogoutFilter
|
||||
import org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy
|
||||
import org.springframework.security.web.context.SecurityContextPersistenceFilter
|
||||
import org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter
|
||||
import org.springframework.security.web.csrf.CsrfFilter;
|
||||
import org.springframework.security.web.header.HeaderWriterFilter
|
||||
import org.springframework.security.web.savedrequest.RequestCacheAwareFilter
|
||||
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter
|
||||
@@ -64,7 +65,7 @@ class FormLoginConfigurerTests extends BaseSpringSpec {
|
||||
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, LogoutFilter, UsernamePasswordAuthenticationFilter,
|
||||
[WebAsyncManagerIntegrationFilter, SecurityContextPersistenceFilter, HeaderWriterFilter, CsrfFilter, LogoutFilter, UsernamePasswordAuthenticationFilter,
|
||||
RequestCacheAwareFilter, SecurityContextHolderAwareRequestFilter,
|
||||
AnonymousAuthenticationFilter, SessionManagementFilter, ExceptionTranslationFilter, FilterSecurityInterceptor ]
|
||||
|
||||
@@ -78,7 +79,7 @@ class FormLoginConfigurerTests extends BaseSpringSpec {
|
||||
!authFilter.requiresAuthentication(new MockHttpServletRequest(servletPath : "/login", method: "GET"), new MockHttpServletResponse())
|
||||
|
||||
and: "SessionFixationProtectionStrategy is configured correctly"
|
||||
SessionFixationProtectionStrategy sessionStrategy = ReflectionTestUtils.getField(authFilter,"sessionStrategy")
|
||||
SessionFixationProtectionStrategy sessionStrategy = ReflectionTestUtils.getField(authFilter,"sessionStrategy").delegateStrategies.find { SessionFixationProtectionStrategy }
|
||||
sessionStrategy.migrateSessionAttributes
|
||||
|
||||
and: "Exception handling is configured correctly"
|
||||
@@ -112,11 +113,13 @@ class FormLoginConfigurerTests extends BaseSpringSpec {
|
||||
def "FormLogin.permitAll()"() {
|
||||
when: "load formLogin() with permitAll"
|
||||
context = new AnnotationConfigApplicationContext(FormLoginConfigPermitAll)
|
||||
|
||||
then: "the formLogin URLs are granted access"
|
||||
FilterChainProxy filterChain = context.getBean(FilterChainProxy)
|
||||
MockHttpServletResponse response = new MockHttpServletResponse()
|
||||
filterChain.doFilter(new MockHttpServletRequest(servletPath : servletPath, requestURI: servletPath, queryString: query, method: method), response, new MockFilterChain())
|
||||
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
|
||||
|
||||
where:
|
||||
|
||||
@@ -47,8 +47,11 @@ class LogoutConfigurerTests extends BaseSpringSpec {
|
||||
def "invoke logout twice does not override"() {
|
||||
when:
|
||||
loadConfig(InvokeTwiceDoesNotOverride)
|
||||
request.method = "POST"
|
||||
request.servletPath = "/custom/logout"
|
||||
findFilter(LogoutFilter).doFilter(request,response,chain)
|
||||
then:
|
||||
findFilter(LogoutFilter).filterProcessesUrl == "/custom/logout"
|
||||
response.redirectedUrl == "/login?logout"
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
||||
@@ -39,35 +39,24 @@ import org.springframework.security.web.authentication.www.BasicAuthenticationFi
|
||||
*
|
||||
*/
|
||||
public class NamespaceHttpBasicTests extends BaseSpringSpec {
|
||||
FilterChainProxy springSecurityFilterChain
|
||||
MockHttpServletRequest request
|
||||
MockHttpServletResponse response
|
||||
MockFilterChain chain
|
||||
|
||||
def setup() {
|
||||
request = new MockHttpServletRequest()
|
||||
response = new MockHttpServletResponse()
|
||||
chain = new MockFilterChain()
|
||||
}
|
||||
|
||||
def "http/http-basic"() {
|
||||
setup:
|
||||
loadConfig(HttpBasicConfig)
|
||||
springSecurityFilterChain = context.getBean(FilterChainProxy)
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
response.status == HttpServletResponse.SC_UNAUTHORIZED
|
||||
when: "fail to log in"
|
||||
setup()
|
||||
login("user","invalid")
|
||||
super.setup()
|
||||
basicLogin("user","invalid")
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then: "unauthorized"
|
||||
response.status == HttpServletResponse.SC_UNAUTHORIZED
|
||||
response.getHeader("WWW-Authenticate") == 'Basic realm="Spring Security Application"'
|
||||
when: "login success"
|
||||
setup()
|
||||
login()
|
||||
super.setup()
|
||||
basicLogin()
|
||||
then: "sent to default succes page"
|
||||
!response.committed
|
||||
}
|
||||
@@ -86,9 +75,8 @@ public class NamespaceHttpBasicTests extends BaseSpringSpec {
|
||||
def "http@realm"() {
|
||||
setup:
|
||||
loadConfig(CustomHttpBasicConfig)
|
||||
springSecurityFilterChain = context.getBean(FilterChainProxy)
|
||||
when:
|
||||
login("user","invalid")
|
||||
basicLogin("user","invalid")
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then: "unauthorized"
|
||||
response.status == HttpServletResponse.SC_UNAUTHORIZED
|
||||
@@ -109,7 +97,6 @@ public class NamespaceHttpBasicTests extends BaseSpringSpec {
|
||||
def "http-basic@authentication-details-source-ref"() {
|
||||
when:
|
||||
loadConfig(AuthenticationDetailsSourceHttpBasicConfig)
|
||||
springSecurityFilterChain = context.getBean(FilterChainProxy)
|
||||
then:
|
||||
findFilter(BasicAuthenticationFilter).authenticationDetailsSource.class == CustomAuthenticationDetailsSource
|
||||
}
|
||||
@@ -128,20 +115,20 @@ public class NamespaceHttpBasicTests extends BaseSpringSpec {
|
||||
def "http-basic@entry-point-ref"() {
|
||||
setup:
|
||||
loadConfig(EntryPointRefHttpBasicConfig)
|
||||
springSecurityFilterChain = context.getBean(FilterChainProxy)
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
response.status == HttpServletResponse.SC_INTERNAL_SERVER_ERROR
|
||||
when: "fail to log in"
|
||||
setup()
|
||||
login("user","invalid")
|
||||
super.setup()
|
||||
basicLogin("user","invalid")
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then: "custom"
|
||||
response.status == HttpServletResponse.SC_INTERNAL_SERVER_ERROR
|
||||
when: "login success"
|
||||
setup()
|
||||
login()
|
||||
super.setup()
|
||||
basicLogin()
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then: "sent to default succes page"
|
||||
!response.committed
|
||||
}
|
||||
@@ -162,7 +149,7 @@ public class NamespaceHttpBasicTests extends BaseSpringSpec {
|
||||
}
|
||||
}
|
||||
|
||||
def login(String username="user",String password="password") {
|
||||
def basicLogin(String username="user",String password="password") {
|
||||
def credentials = username + ":" + password
|
||||
request.addHeader("Authorization", "Basic " + credentials.bytes.encodeBase64())
|
||||
}
|
||||
|
||||
@@ -36,6 +36,7 @@ import org.springframework.security.web.util.AnyRequestMatcher
|
||||
*
|
||||
*/
|
||||
public class NamespaceHttpHeadersTests extends BaseSpringSpec {
|
||||
|
||||
def "http/headers"() {
|
||||
setup:
|
||||
loadConfig(HeadersDefaultConfig)
|
||||
@@ -48,7 +49,8 @@ public class NamespaceHttpHeadersTests extends BaseSpringSpec {
|
||||
'Strict-Transport-Security': 'max-age=31536000 ; includeSubDomains',
|
||||
'Cache-Control': 'no-cache,no-store,max-age=0,must-revalidate',
|
||||
'Pragma':'no-cache',
|
||||
'X-XSS-Protection' : '1; mode=block']
|
||||
'X-XSS-Protection' : '1; mode=block',
|
||||
'X-CSRF-TOKEN' : csrfToken.token]
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@@ -68,7 +70,8 @@ public class NamespaceHttpHeadersTests extends BaseSpringSpec {
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
responseHeaders == ['Cache-Control': 'no-cache,no-store,max-age=0,must-revalidate',
|
||||
'Pragma':'no-cache']
|
||||
'Pragma':'no-cache',
|
||||
'X-CSRF-TOKEN' : csrfToken.token]
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@@ -88,7 +91,8 @@ public class NamespaceHttpHeadersTests extends BaseSpringSpec {
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
responseHeaders == ['Strict-Transport-Security': 'max-age=31536000 ; includeSubDomains']
|
||||
responseHeaders == ['Strict-Transport-Security': 'max-age=31536000 ; includeSubDomains',
|
||||
'X-CSRF-TOKEN' : csrfToken.token]
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@@ -107,7 +111,8 @@ public class NamespaceHttpHeadersTests extends BaseSpringSpec {
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
responseHeaders == ['Strict-Transport-Security': 'max-age=15768000']
|
||||
responseHeaders == ['Strict-Transport-Security': 'max-age=15768000',
|
||||
'X-CSRF-TOKEN' : csrfToken.token]
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@@ -128,7 +133,8 @@ public class NamespaceHttpHeadersTests extends BaseSpringSpec {
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
responseHeaders == ['X-Frame-Options': 'SAMEORIGIN']
|
||||
responseHeaders == ['X-Frame-Options': 'SAMEORIGIN',
|
||||
'X-CSRF-TOKEN' : csrfToken.token]
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@@ -150,7 +156,8 @@ public class NamespaceHttpHeadersTests extends BaseSpringSpec {
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
responseHeaders == ['X-Frame-Options': 'ALLOW-FROM https://example.com']
|
||||
responseHeaders == ['X-Frame-Options': 'ALLOW-FROM https://example.com',
|
||||
'X-CSRF-TOKEN' : csrfToken.token]
|
||||
}
|
||||
|
||||
|
||||
@@ -171,7 +178,8 @@ public class NamespaceHttpHeadersTests extends BaseSpringSpec {
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
responseHeaders == ['X-XSS-Protection': '1; mode=block']
|
||||
responseHeaders == ['X-XSS-Protection': '1; mode=block',
|
||||
'X-CSRF-TOKEN' : csrfToken.token]
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@@ -191,7 +199,8 @@ public class NamespaceHttpHeadersTests extends BaseSpringSpec {
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
responseHeaders == ['X-XSS-Protection': '1']
|
||||
responseHeaders == ['X-XSS-Protection': '1',
|
||||
'X-CSRF-TOKEN' : csrfToken.token]
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@@ -211,7 +220,8 @@ public class NamespaceHttpHeadersTests extends BaseSpringSpec {
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
responseHeaders == ['X-Content-Type-Options': 'nosniff']
|
||||
responseHeaders == ['X-Content-Type-Options': 'nosniff',
|
||||
'X-CSRF-TOKEN' : csrfToken.token]
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@@ -233,7 +243,8 @@ public class NamespaceHttpHeadersTests extends BaseSpringSpec {
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
responseHeaders == ['customHeaderName': 'customHeaderValue']
|
||||
responseHeaders == ['customHeaderName': 'customHeaderValue',
|
||||
'X-CSRF-TOKEN' : csrfToken.token]
|
||||
}
|
||||
|
||||
@Configuration
|
||||
@@ -245,4 +256,5 @@ public class NamespaceHttpHeadersTests extends BaseSpringSpec {
|
||||
.addHeaderWriter(new StaticHeadersWriter("customHeaderName", "customHeaderValue"))
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -71,23 +71,13 @@ import org.springframework.security.web.util.RequestMatcher
|
||||
*
|
||||
*/
|
||||
public class NamespaceHttpLogoutTests extends BaseSpringSpec {
|
||||
FilterChainProxy springSecurityFilterChain
|
||||
MockHttpServletRequest request
|
||||
MockHttpServletResponse response
|
||||
MockFilterChain chain
|
||||
|
||||
def setup() {
|
||||
request = new MockHttpServletRequest()
|
||||
response = new MockHttpServletResponse()
|
||||
chain = new MockFilterChain()
|
||||
}
|
||||
|
||||
def "http/logout"() {
|
||||
setup:
|
||||
loadConfig(HttpLogoutConfig)
|
||||
springSecurityFilterChain = context.getBean(FilterChainProxy)
|
||||
login()
|
||||
request.setRequestURI("/logout")
|
||||
request.servletPath = "/logout"
|
||||
request.method = "POST"
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
@@ -106,9 +96,9 @@ public class NamespaceHttpLogoutTests extends BaseSpringSpec {
|
||||
def "http/logout custom"() {
|
||||
setup:
|
||||
loadConfig(CustomHttpLogoutConfig)
|
||||
springSecurityFilterChain = context.getBean(FilterChainProxy)
|
||||
login()
|
||||
request.setRequestURI("/custom-logout")
|
||||
request.servletPath = "/custom-logout"
|
||||
request.method = "POST"
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
@@ -135,9 +125,9 @@ public class NamespaceHttpLogoutTests extends BaseSpringSpec {
|
||||
def "http/logout@success-handler-ref"() {
|
||||
setup:
|
||||
loadConfig(SuccessHandlerRefHttpLogoutConfig)
|
||||
springSecurityFilterChain = context.getBean(FilterChainProxy)
|
||||
login()
|
||||
request.setRequestURI("/logout")
|
||||
request.servletPath = "/logout"
|
||||
request.method = "POST"
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
|
||||
@@ -44,21 +44,9 @@ import org.springframework.security.web.authentication.WebAuthenticationDetailsS
|
||||
*
|
||||
*/
|
||||
public class NamespaceHttpOpenIDLoginTests extends BaseSpringSpec {
|
||||
FilterChainProxy springSecurityFilterChain
|
||||
MockHttpServletRequest request
|
||||
MockHttpServletResponse response
|
||||
MockFilterChain chain
|
||||
|
||||
def setup() {
|
||||
request = new MockHttpServletRequest()
|
||||
response = new MockHttpServletResponse()
|
||||
chain = new MockFilterChain()
|
||||
}
|
||||
|
||||
def "http/openid-login"() {
|
||||
when:
|
||||
loadConfig(OpenIDLoginConfig)
|
||||
springSecurityFilterChain = context.getBean(FilterChainProxy)
|
||||
then:
|
||||
findFilter(OpenIDAuthenticationFilter).consumer.class == OpenID4JavaConsumer
|
||||
when:
|
||||
@@ -66,7 +54,7 @@ public class NamespaceHttpOpenIDLoginTests extends BaseSpringSpec {
|
||||
then:
|
||||
response.getRedirectedUrl() == "http://localhost/login"
|
||||
when: "fail to log in"
|
||||
setup()
|
||||
super.setup()
|
||||
request.servletPath = "/login/openid"
|
||||
request.method = "POST"
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
@@ -89,7 +77,6 @@ public class NamespaceHttpOpenIDLoginTests extends BaseSpringSpec {
|
||||
def "http/openid-login/attribute-exchange"() {
|
||||
when:
|
||||
loadConfig(OpenIDLoginAttributeExchangeConfig)
|
||||
springSecurityFilterChain = context.getBean(FilterChainProxy)
|
||||
OpenID4JavaConsumer consumer = findFilter(OpenIDAuthenticationFilter).consumer
|
||||
then:
|
||||
consumer.class == OpenID4JavaConsumer
|
||||
@@ -117,7 +104,7 @@ public class NamespaceHttpOpenIDLoginTests extends BaseSpringSpec {
|
||||
then:
|
||||
response.getRedirectedUrl() == "http://localhost/login"
|
||||
when: "fail to log in"
|
||||
setup()
|
||||
super.setup()
|
||||
request.servletPath = "/login/openid"
|
||||
request.method = "POST"
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
@@ -165,13 +152,12 @@ public class NamespaceHttpOpenIDLoginTests extends BaseSpringSpec {
|
||||
def "http/openid-login custom"() {
|
||||
setup:
|
||||
loadConfig(OpenIDLoginCustomConfig)
|
||||
springSecurityFilterChain = context.getBean(FilterChainProxy)
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
response.getRedirectedUrl() == "http://localhost/authentication/login"
|
||||
when: "fail to log in"
|
||||
setup()
|
||||
super.setup()
|
||||
request.servletPath = "/authentication/login/process"
|
||||
request.method = "POST"
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
@@ -200,7 +186,6 @@ public class NamespaceHttpOpenIDLoginTests extends BaseSpringSpec {
|
||||
when:
|
||||
OpenIDLoginCustomRefsConfig.AUDS = Mock(AuthenticationUserDetailsService)
|
||||
loadConfig(OpenIDLoginCustomRefsConfig)
|
||||
springSecurityFilterChain = context.getBean(FilterChainProxy)
|
||||
then: "CustomWebAuthenticationDetailsSource is used"
|
||||
findFilter(OpenIDAuthenticationFilter).authenticationDetailsSource.class == CustomWebAuthenticationDetailsSource
|
||||
findAuthenticationProvider(OpenIDAuthenticationProvider).userDetailsService == OpenIDLoginCustomRefsConfig.AUDS
|
||||
|
||||
@@ -55,22 +55,10 @@ import org.springframework.test.util.ReflectionTestUtils
|
||||
*
|
||||
*/
|
||||
public class NamespaceHttpX509Tests extends BaseSpringSpec {
|
||||
FilterChainProxy springSecurityFilterChain
|
||||
MockHttpServletRequest request
|
||||
MockHttpServletResponse response
|
||||
MockFilterChain chain
|
||||
|
||||
def setup() {
|
||||
request = new MockHttpServletRequest()
|
||||
response = new MockHttpServletResponse()
|
||||
chain = new MockFilterChain()
|
||||
}
|
||||
|
||||
def "http/x509 can authenticate"() {
|
||||
setup:
|
||||
X509Certificate certificate = loadCert("rod.cer")
|
||||
loadConfig(X509Config)
|
||||
springSecurityFilterChain = context.getBean(FilterChainProxy)
|
||||
when:
|
||||
request.setAttribute("javax.servlet.request.X509Certificate", [certificate] as X509Certificate[] )
|
||||
springSecurityFilterChain.doFilter(request, response, chain);
|
||||
@@ -148,7 +136,6 @@ public class NamespaceHttpX509Tests extends BaseSpringSpec {
|
||||
setup:
|
||||
X509Certificate certificate = loadCert("rodatexampledotcom.cer")
|
||||
loadConfig(SubjectPrincipalRegexConfig)
|
||||
springSecurityFilterChain = context.getBean(FilterChainProxy)
|
||||
when:
|
||||
request.setAttribute("javax.servlet.request.X509Certificate", [certificate] as X509Certificate[] )
|
||||
springSecurityFilterChain.doFilter(request, response, chain);
|
||||
@@ -182,7 +169,6 @@ public class NamespaceHttpX509Tests extends BaseSpringSpec {
|
||||
setup:
|
||||
X509Certificate certificate = loadCert("rodatexampledotcom.cer")
|
||||
loadConfig(UserDetailsServiceRefConfig)
|
||||
springSecurityFilterChain = context.getBean(FilterChainProxy)
|
||||
when:
|
||||
request.setAttribute("javax.servlet.request.X509Certificate", [certificate] as X509Certificate[] )
|
||||
springSecurityFilterChain.doFilter(request, response, chain);
|
||||
@@ -216,7 +202,6 @@ public class NamespaceHttpX509Tests extends BaseSpringSpec {
|
||||
setup:
|
||||
X509Certificate certificate = loadCert("rodatexampledotcom.cer")
|
||||
loadConfig(AuthenticationUserDetailsServiceConfig)
|
||||
springSecurityFilterChain = context.getBean(FilterChainProxy)
|
||||
when:
|
||||
request.setAttribute("javax.servlet.request.X509Certificate", [certificate] as X509Certificate[] )
|
||||
springSecurityFilterChain.doFilter(request, response, chain);
|
||||
|
||||
@@ -81,8 +81,10 @@ public class NamespaceRememberMeTests extends BaseSpringSpec {
|
||||
when: "logout"
|
||||
super.setup()
|
||||
request.setSession(session)
|
||||
super.setupCsrf()
|
||||
request.setCookies(rememberMeCookie)
|
||||
request.requestURI = "/logout"
|
||||
request.servletPath = "/logout"
|
||||
request.method = "POST"
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
rememberMeCookie = getRememberMeCookie()
|
||||
then: "logout cookie expired"
|
||||
|
||||
@@ -41,7 +41,7 @@ class NamespaceSessionManagementTests extends BaseSpringSpec {
|
||||
when:
|
||||
loadConfig(SessionManagementConfig)
|
||||
then:
|
||||
findFilter(SessionManagementFilter).sessionAuthenticationStrategy instanceof SessionFixationProtectionStrategy
|
||||
findSessionAuthenticationStrategy(SessionFixationProtectionStrategy)
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
@@ -91,7 +91,7 @@ class NamespaceSessionManagementTests extends BaseSpringSpec {
|
||||
when:
|
||||
loadConfig(RefsSessionManagementConfig)
|
||||
then:
|
||||
findFilter(SessionManagementFilter).sessionAuthenticationStrategy == RefsSessionManagementConfig.SAS
|
||||
findFilter(SessionManagementFilter).sessionAuthenticationStrategy.delegateStrategies.find { it == RefsSessionManagementConfig.SAS }
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
@@ -110,7 +110,7 @@ class NamespaceSessionManagementTests extends BaseSpringSpec {
|
||||
when:
|
||||
loadConfig(SFPNoneSessionManagementConfig)
|
||||
then:
|
||||
findFilter(SessionManagementFilter).sessionAuthenticationStrategy.class == NullAuthenticatedSessionStrategy
|
||||
findFilter(SessionManagementFilter).sessionAuthenticationStrategy.delegateStrategies.find { it instanceof NullAuthenticatedSessionStrategy }
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
@@ -128,7 +128,7 @@ class NamespaceSessionManagementTests extends BaseSpringSpec {
|
||||
when:
|
||||
loadConfig(SFPMigrateSessionManagementConfig)
|
||||
then:
|
||||
findFilter(SessionManagementFilter).sessionAuthenticationStrategy.migrateSessionAttributes
|
||||
findSessionAuthenticationStrategy(SessionFixationProtectionStrategy).migrateSessionAttributes
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
@@ -145,7 +145,11 @@ class NamespaceSessionManagementTests extends BaseSpringSpec {
|
||||
when:
|
||||
loadConfig(SFPNewSessionSessionManagementConfig)
|
||||
then:
|
||||
!findFilter(SessionManagementFilter).sessionAuthenticationStrategy.migrateSessionAttributes
|
||||
!findSessionAuthenticationStrategy(SessionFixationProtectionStrategy).migrateSessionAttributes
|
||||
}
|
||||
|
||||
def findSessionAuthenticationStrategy(def c) {
|
||||
findFilter(SessionManagementFilter).sessionAuthenticationStrategy.delegateStrategies.find { it.class.isAssignableFrom(c) }
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
|
||||
@@ -26,6 +26,7 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
|
||||
import org.springframework.security.web.AuthenticationEntryPoint
|
||||
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
|
||||
import org.springframework.security.web.csrf.CsrfLogoutHandler;
|
||||
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter
|
||||
|
||||
/**
|
||||
@@ -59,7 +60,7 @@ class ServletApiConfigurerTests extends BaseSpringSpec {
|
||||
and: "requestFactory != null"
|
||||
filter.requestFactory != null
|
||||
and: "logoutHandlers populated"
|
||||
filter.logoutHandlers.collect { it.class } == [SecurityContextLogoutHandler]
|
||||
filter.logoutHandlers.collect { it.class } == [CsrfLogoutHandler, SecurityContextLogoutHandler]
|
||||
}
|
||||
|
||||
@CompileStatic
|
||||
|
||||
@@ -57,8 +57,11 @@ abstract class AbstractHttpConfigTests extends AbstractXmlConfigTests {
|
||||
}
|
||||
|
||||
List getFilters(String url) {
|
||||
def fcp = appContext.getBean(BeanIds.FILTER_CHAIN_PROXY);
|
||||
return fcp.getFilters(url)
|
||||
springSecurityFilterChain.getFilters(url)
|
||||
}
|
||||
|
||||
Filter getSpringSecurityFilterChain() {
|
||||
appContext.getBean(BeanIds.FILTER_CHAIN_PROXY)
|
||||
}
|
||||
|
||||
FilterInvocation createFilterinvocation(String path, String method) {
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
/*
|
||||
* Copyright 2002-2012 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
||||
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.config.http
|
||||
|
||||
import static org.mockito.Mockito.*
|
||||
import static org.mockito.Matchers.*
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse
|
||||
|
||||
import org.spockframework.compiler.model.WhenBlock;
|
||||
import org.springframework.mock.web.MockFilterChain
|
||||
import org.springframework.mock.web.MockHttpServletRequest
|
||||
import org.springframework.mock.web.MockHttpServletResponse
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.config.annotation.web.configurers.CsrfConfigurerTests.CsrfTokenRepositoryConfig;
|
||||
import org.springframework.security.config.annotation.web.configurers.CsrfConfigurerTests.RequireCsrfProtectionMatcherConfig
|
||||
import org.springframework.security.web.access.AccessDeniedHandler;
|
||||
import org.springframework.security.web.csrf.CsrfFilter
|
||||
import org.springframework.security.web.csrf.CsrfToken;
|
||||
import org.springframework.security.web.csrf.CsrfTokenRepository;
|
||||
import org.springframework.security.web.servlet.support.csrf.CsrfRequestDataValueProcessor
|
||||
import org.springframework.security.web.util.RequestMatcher
|
||||
|
||||
import spock.lang.Unroll
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Rob Winch
|
||||
*/
|
||||
class CsrfConfigTests extends AbstractHttpConfigTests {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest()
|
||||
MockHttpServletResponse response = new MockHttpServletResponse()
|
||||
MockFilterChain chain = new MockFilterChain()
|
||||
|
||||
def 'no http csrf filter by default'() {
|
||||
when:
|
||||
httpAutoConfig {
|
||||
}
|
||||
createAppContext()
|
||||
then:
|
||||
!getFilter(CsrfFilter)
|
||||
}
|
||||
|
||||
@Unroll
|
||||
def 'csrf defaults'() {
|
||||
setup:
|
||||
httpAutoConfig {
|
||||
'csrf'()
|
||||
}
|
||||
createAppContext()
|
||||
when:
|
||||
request.method = httpMethod
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
response.status == httpStatus
|
||||
where:
|
||||
httpMethod | httpStatus
|
||||
'POST' | HttpServletResponse.SC_FORBIDDEN
|
||||
'PUT' | HttpServletResponse.SC_FORBIDDEN
|
||||
'PATCH' | HttpServletResponse.SC_FORBIDDEN
|
||||
'DELETE' | HttpServletResponse.SC_FORBIDDEN
|
||||
'INVALID' | HttpServletResponse.SC_FORBIDDEN
|
||||
'GET' | HttpServletResponse.SC_OK
|
||||
'HEAD' | HttpServletResponse.SC_OK
|
||||
'TRACE' | HttpServletResponse.SC_OK
|
||||
'OPTIONS' | HttpServletResponse.SC_OK
|
||||
}
|
||||
|
||||
def 'csrf default creates CsrfRequestDataValueProcessor'() {
|
||||
when:
|
||||
httpAutoConfig {
|
||||
'csrf'()
|
||||
}
|
||||
createAppContext()
|
||||
then:
|
||||
appContext.getBean("requestDataValueProcessor",CsrfRequestDataValueProcessor)
|
||||
}
|
||||
|
||||
def 'csrf custom AccessDeniedHandler'() {
|
||||
setup:
|
||||
httpAutoConfig {
|
||||
'access-denied-handler'(ref:'adh')
|
||||
'csrf'()
|
||||
}
|
||||
mockBean(AccessDeniedHandler,'adh')
|
||||
createAppContext()
|
||||
AccessDeniedHandler adh = appContext.getBean(AccessDeniedHandler)
|
||||
request.method = "POST"
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
verify(adh).handle(any(HttpServletRequest),any(HttpServletResponse),any(AccessDeniedException))
|
||||
response.status == HttpServletResponse.SC_OK // our mock doesn't do anything
|
||||
}
|
||||
|
||||
def "csrf disables posts for RequestCache"() {
|
||||
setup:
|
||||
httpAutoConfig {
|
||||
'csrf'('token-repository-ref':'repo')
|
||||
'intercept-url'(pattern:"/**",access:'ROLE_USER')
|
||||
}
|
||||
mockBean(CsrfTokenRepository,'repo')
|
||||
createAppContext()
|
||||
CsrfTokenRepository repo = appContext.getBean("repo",CsrfTokenRepository)
|
||||
CsrfToken token = new CsrfToken("X-CSRF-TOKEN","_csrf", "abc")
|
||||
when(repo.loadToken(any(HttpServletRequest))).thenReturn(token)
|
||||
request.setParameter(token.parameterName,token.token)
|
||||
request.servletPath = "/some-url"
|
||||
request.requestURI = "/some-url"
|
||||
request.method = "POST"
|
||||
when: "CSRF passes and our session times out"
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then: "sent to the login page"
|
||||
response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
|
||||
response.redirectedUrl == "http://localhost/spring_security_login"
|
||||
when: "authenticate successfully"
|
||||
response = new MockHttpServletResponse()
|
||||
request = new MockHttpServletRequest(session: request.session)
|
||||
request.requestURI = "/j_spring_security_check"
|
||||
request.setParameter(token.parameterName,token.token)
|
||||
request.setParameter("j_username","user")
|
||||
request.setParameter("j_password","password")
|
||||
request.method = "POST"
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then: "sent to default success because we don't want csrf attempts made prior to authentication to pass"
|
||||
response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
|
||||
response.redirectedUrl == "/"
|
||||
}
|
||||
|
||||
def "csrf enables gets for RequestCache"() {
|
||||
setup:
|
||||
httpAutoConfig {
|
||||
'csrf'('token-repository-ref':'repo')
|
||||
'intercept-url'(pattern:"/**",access:'ROLE_USER')
|
||||
}
|
||||
mockBean(CsrfTokenRepository,'repo')
|
||||
createAppContext()
|
||||
CsrfTokenRepository repo = appContext.getBean("repo",CsrfTokenRepository)
|
||||
CsrfToken token = new CsrfToken("X-CSRF-TOKEN","_csrf", "abc")
|
||||
when(repo.loadToken(any(HttpServletRequest))).thenReturn(token)
|
||||
request.setParameter(token.parameterName,token.token)
|
||||
request.servletPath = "/some-url"
|
||||
request.requestURI = "/some-url"
|
||||
request.method = "GET"
|
||||
when: "CSRF passes and our session times out"
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then: "sent to the login page"
|
||||
response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
|
||||
response.redirectedUrl == "http://localhost/spring_security_login"
|
||||
when: "authenticate successfully"
|
||||
response = new MockHttpServletResponse()
|
||||
request = new MockHttpServletRequest(session: request.session)
|
||||
request.requestURI = "/j_spring_security_check"
|
||||
request.setParameter(token.parameterName,token.token)
|
||||
request.setParameter("j_username","user")
|
||||
request.setParameter("j_password","password")
|
||||
request.method = "POST"
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then: "sent to original URL since it was a GET"
|
||||
response.status == HttpServletResponse.SC_MOVED_TEMPORARILY
|
||||
response.redirectedUrl == "http://localhost/some-url"
|
||||
}
|
||||
|
||||
def "csrf requireCsrfProtectionMatcher"() {
|
||||
setup:
|
||||
httpAutoConfig {
|
||||
'csrf'('request-matcher-ref':'matcher')
|
||||
}
|
||||
mockBean(RequestMatcher,'matcher')
|
||||
createAppContext()
|
||||
RequestMatcher matcher = appContext.getBean("matcher",RequestMatcher)
|
||||
when:
|
||||
when(matcher.matches(any(HttpServletRequest))).thenReturn(false)
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
response.status == HttpServletResponse.SC_OK
|
||||
when:
|
||||
when(matcher.matches(any(HttpServletRequest))).thenReturn(true)
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
response.status == HttpServletResponse.SC_FORBIDDEN
|
||||
}
|
||||
|
||||
def "csrf csrfTokenRepository"() {
|
||||
setup:
|
||||
httpAutoConfig {
|
||||
'csrf'('token-repository-ref':'repo')
|
||||
}
|
||||
mockBean(CsrfTokenRepository,'repo')
|
||||
createAppContext()
|
||||
CsrfTokenRepository repo = appContext.getBean("repo",CsrfTokenRepository)
|
||||
CsrfToken token = new CsrfToken("X-CSRF-TOKEN","_csrf", "abc")
|
||||
when(repo.loadToken(any(HttpServletRequest))).thenReturn(token)
|
||||
request.setParameter(token.parameterName,token.token)
|
||||
request.method = "POST"
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
response.status == HttpServletResponse.SC_OK
|
||||
when:
|
||||
request.setParameter(token.parameterName,token.token+"INVALID")
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
response.status == HttpServletResponse.SC_FORBIDDEN
|
||||
}
|
||||
|
||||
def "csrf clears on login"() {
|
||||
setup:
|
||||
httpAutoConfig {
|
||||
'csrf'('token-repository-ref':'repo')
|
||||
}
|
||||
mockBean(CsrfTokenRepository,'repo')
|
||||
createAppContext()
|
||||
CsrfTokenRepository repo = appContext.getBean("repo",CsrfTokenRepository)
|
||||
CsrfToken token = new CsrfToken("X-CSRF-TOKEN","_csrf", "abc")
|
||||
when(repo.loadToken(any(HttpServletRequest))).thenReturn(token)
|
||||
request.setParameter(token.parameterName,token.token)
|
||||
request.method = "POST"
|
||||
request.setParameter("j_username","user")
|
||||
request.setParameter("j_password","password")
|
||||
request.requestURI = "/j_spring_security_check"
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
verify(repo).saveToken(eq(null),any(HttpServletRequest), any(HttpServletResponse))
|
||||
}
|
||||
|
||||
def "csrf clears on logout"() {
|
||||
setup:
|
||||
httpAutoConfig {
|
||||
'csrf'('token-repository-ref':'repo')
|
||||
}
|
||||
mockBean(CsrfTokenRepository,'repo')
|
||||
createAppContext()
|
||||
CsrfTokenRepository repo = appContext.getBean("repo",CsrfTokenRepository)
|
||||
CsrfToken token = new CsrfToken("X-CSRF-TOKEN","_csrf", "abc")
|
||||
when(repo.loadToken(any(HttpServletRequest))).thenReturn(token)
|
||||
request.setParameter(token.parameterName,token.token)
|
||||
request.method = "POST"
|
||||
request.requestURI = "/j_spring_security_logout"
|
||||
when:
|
||||
springSecurityFilterChain.doFilter(request,response,chain)
|
||||
then:
|
||||
verify(repo).saveToken(eq(null),any(HttpServletRequest), any(HttpServletResponse))
|
||||
}
|
||||
}
|
||||
@@ -275,9 +275,7 @@ class SessionManagementConfigTests extends AbstractHttpConfigTests {
|
||||
httpAutoConfig {
|
||||
'session-management'('session-authentication-strategy-ref':'ss')
|
||||
}
|
||||
xml.'b:bean'(id: 'ss', 'class': Mockito.class.name, 'factory-method':'mock') {
|
||||
'b:constructor-arg'(value : SessionAuthenticationStrategy.class.name)
|
||||
}
|
||||
mockBean(SessionAuthenticationStrategy,'ss')
|
||||
createAppContext()
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* Copyright 2002-2013 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.security.config.annotation.web.configurers;
|
||||
|
||||
import static org.fest.assertions.Assertions.assertThat;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.powermock.api.mockito.PowerMockito.spy;
|
||||
import static org.powermock.api.mockito.PowerMockito.when;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.powermock.core.classloader.annotations.PrepareForTest;
|
||||
import org.powermock.modules.junit4.PowerMockRunner;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
/**
|
||||
* @author Rob Winch
|
||||
*
|
||||
*/
|
||||
@RunWith(PowerMockRunner.class)
|
||||
@PrepareForTest({ClassUtils.class})
|
||||
public class CsrfConfigurerNoWebMvcTests {
|
||||
ConfigurableApplicationContext context;
|
||||
|
||||
@After
|
||||
public void teardown() {
|
||||
if(context != null) {
|
||||
context.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void missingDispatcherServletPreventsCsrfRequestDataValueProcessor() {
|
||||
spy(ClassUtils.class);
|
||||
when(ClassUtils.isPresent(eq("org.springframework.web.servlet.DispatcherServlet"), any(ClassLoader.class))).thenReturn(false);
|
||||
|
||||
loadContext(CsrfDefaultsConfig.class);
|
||||
|
||||
assertThat(context.containsBeanDefinition("requestDataValueProcessor")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findDispatcherServletPreventsCsrfRequestDataValueProcessor() {
|
||||
loadContext(CsrfDefaultsConfig.class);
|
||||
|
||||
assertThat(context.containsBeanDefinition("requestDataValueProcessor")).isTrue();
|
||||
}
|
||||
|
||||
@EnableWebSecurity
|
||||
@Configuration
|
||||
static class CsrfDefaultsConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
}
|
||||
}
|
||||
|
||||
private void loadContext(Class<?> configs) {
|
||||
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
|
||||
annotationConfigApplicationContext.register(configs);
|
||||
annotationConfigApplicationContext.refresh();
|
||||
this.context = annotationConfigApplicationContext;
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,8 @@ import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextImpl;
|
||||
import org.springframework.security.web.context.HttpRequestResponseHolder;
|
||||
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
|
||||
import org.springframework.security.web.csrf.CsrfToken;
|
||||
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
|
||||
|
||||
@@ -94,6 +96,8 @@ public class SessionManagementConfigurerServlet31Tests {
|
||||
request.setMethod("POST");
|
||||
request.setParameter("username", "user");
|
||||
request.setParameter("password", "password");
|
||||
CsrfToken token = new HttpSessionCsrfTokenRepository().generateAndSaveToken(request, response);
|
||||
request.setParameter(token.getParameterName(),token.getToken());
|
||||
when(ReflectionUtils.findMethod(HttpServletRequest.class, "changeSessionId")).thenReturn(method);
|
||||
|
||||
loadConfig(SessionManagementDefaultSessionFixationServlet31Config.class);
|
||||
|
||||
Reference in New Issue
Block a user