Spring正在为每个请求而不是每个会话生成CSRF令牌,想要按会话生成

时间:2019-04-24 07:13:56

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

我正在使用Spring Security生成CSRF令牌并将其发送到Cookie中的客户端。目前,每次请求后令牌都会更改,但我希望spring为整个会话生成一个令牌。我不确定这是否是因为我的代码。这是我的代码:

protected static class SecurityConfiguration extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .httpBasic().and()
      .authorizeRequests()
        .antMatchers("/**").permitAll().and().
         .csrf().csrfTokenRepository(csrfTokenRepository()).and()
      .addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class);
  }

private CsrfTokenRepository csrfTokenRepository() {
  HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
  repository.setHeaderName("X-XSRF-TOKEN");
  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);
  }
}

0 个答案:

没有答案