【问题标题】:Spring Security CSRF support for manual security configurationSpring Security CSRF 支持手动安全配置
【发布时间】: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 &lt;bean class="package.WebSecurityConfig"/&gt;,但在创建应用程序上下文时从不调用 WebSecurityConfigurerAdapter.configure 方法。

如何在此处添加 CSRF 保护?是否也需要手动插入 CSRFFilter?

【问题讨论】:

    标签: java spring-security csrf


    【解决方案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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-18
      • 1970-01-01
      • 2021-08-19
      • 1970-01-01
      • 2014-02-19
      • 2012-12-28
      • 2021-11-17
      相关资源
      最近更新 更多