【问题标题】:Renaming Spring csrf token variable重命名 Spring csrf 令牌变量
【发布时间】:2015-09-26 09:37:33
【问题描述】:

我的应用程序在另一个门户应用程序下运行。两者都是在 spring 中实现的,并且都使用 csrf 安全性。

我的需要基本上是更改 csrf 令牌在会话中的命名方式,因此两个令牌都可以正常工作而不会发生冲突。到目前为止,我尝试的是创建另一个令牌存储库并尝试更改安全配置类中的参数名称和会话属性名称。

final HttpSessionCsrfTokenRepository tokenRepository = new HttpSessionCsrfTokenRepository();
tokenRepository.setHeaderName("TOOLBIZ-CSRF-TOKEN");
tokenRepository.setParameterName("toolbiz_csfr");
//tokenRepository.setSessionAttributeName("toolbiz_csrf");

当我提出请求时,Spring 不太喜欢这种新设置,并且日志会生成以下行:

Invalid CSRF token found

我还应该做些什么?我错过了什么吗?

【问题讨论】:

    标签: java spring spring-security csrf csrf-protection


    【解决方案1】:

    这对我有用:-

    @Configuration
    @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
    public class OptosoftWebfrontSecurity extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/assets/**").permitAll()
                .anyRequest().authenticated().and().formLogin().and()
                .httpBasic().disable()
                .addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class)
                .csrf().csrfTokenRepository(csrfTokenRepository());
    }
    
    private CsrfTokenRepository csrfTokenRepository() {
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        repository.setHeaderName("X-XSRF-TOKEN");
        repository.setParameterName("_csrf");
        return repository;
    }
    
    }
    

    还有过滤器:-

    public class CsrfHeaderFilter extends OncePerRequestFilter {
        @Override
        protected void doFilterInternal(HttpServletRequest request,
                HttpServletResponse response, FilterChain filterChain)
                throws ServletException, IOException {
            CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class
                    .getName());
            if (csrf != null) {
                Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
                String token = csrf.getToken();
                if (cookie == null || token != null
                        && !token.equals(cookie.getValue())) {
                    cookie = new Cookie("XSRF-TOKEN", token);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
            filterChain.doFilter(request, response);
        }
    }
    

    您是否覆盖了 WebSecurityConfigurerAdapter#configure 方法?

    【讨论】:

      【解决方案2】:

      请记住在重命名标题之前删除您拥有的所有旧 cookie。我遇到了同样的问题,一切都设置得很好,但是浏览器中的旧 cookie 导致过滤功能基本上没用。

      【讨论】:

        猜你喜欢
        • 2014-03-03
        • 2015-01-08
        • 2017-09-07
        • 1970-01-01
        • 2012-03-06
        • 2019-12-30
        • 2019-07-20
        • 1970-01-01
        • 2017-10-27
        相关资源
        最近更新 更多