Spring Security CSRF 支持手动安全配置
Posted
技术标签:
【中文标题】Spring Security CSRF 支持手动安全配置【英文标题】:Spring Security CSRF support for manual security configuration 【发布时间】:2015-11-25 21:42:59 【问题描述】:我正在处理复杂的手动安全配置(Spring 3.4、Spring Security 3.2)。过滤器链已经手动配置了httpSessionContextIntegrationFilter
和我们配置的其他bean。
<bean id="filterChainProxy" class="org.springframework.security.web.FilterChainProxy">
<security:filter-chain-map path-type="ant" request-matcher="ant">
<security:filter-chain pattern="/**" filters="httpSessionContextIntegrationFilter, ... beans ...,filterInvocationInterceptor"/>
</security:filter-chain-map>
</bean>
现在,我需要添加 CSRF 保护。我无法添加 http 和 csrf 标签,因为 http 正在复制手动配置。相反,我尝试在 Java 中配置它,但 Java 配置没有添加 CSRF 过滤器。
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
...
我在应用程序上下文中声明了 bean <bean class="package.WebSecurityConfig"/>
,但在创建应用程序上下文时从不调用 WebSecurityConfigurerAdapter.configure 方法。
如何在此处添加 CSRF 保护?是否也需要手动插入 CSRFFilter?
【问题讨论】:
【参考方案1】:如果这个link 回答了您的问题,请从它中提取。
import my.filter.CsrfTokenGeneratorFilter;
import org.springframework.security.web.csrf.CsrfFilter;
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
@Override
protected void configure(HttpSecurity http) throws Exception
http.addFilterAfter(new CsrfTokenGeneratorFilter(), CsrfFilter.class);
/**
* Filter which adds CSRF information as response headers.
*
* @author Patrick Grimard
* @since 12/31/2013 4:48 PM
*/
public final class CsrfTokenGeneratorFilter extends OncePerRequestFilter
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException
CsrfToken token = (CsrfToken) request.getAttribute("_csrf");
// Spring Security will allow the Token to be included in this header name
response.setHeader("X-CSRF-HEADER", token.getHeaderName());
// Spring Security will allow the token to be included in this parameter name
response.setHeader("X-CSRF-PARAM", token.getParameterName());
// this is the value of the token to be included as either a header or an HTTP parameter
response.setHeader("X-CSRF-TOKEN", token.getToken());
filterChain.doFilter(request, response);
【讨论】:
以上是关于Spring Security CSRF 支持手动安全配置的主要内容,如果未能解决你的问题,请参考以下文章