title: Spring is generating CSRF token per request instead of per session, want to generate per session
body: <p>I am using spring security to generate CSRF token and send it over to client in Cookie. Currently the token is getting changed after every request but I want spring to generate a single token for the whole session. I am not sure if this is because of my code.  Here is my code : </p>
  
  <pre><code>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;
  }
  }
  </code></pre>
  
  <p>This is my filter : </p>
  
  <pre><code>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 &amp;&amp; !token.equals(cookie.getValue())) {
          cookie = new Cookie("XSRF-TOKEN", token);
          cookie.setPath("/");
          response.addCookie(cookie);
        }
      }
      filterChain.doFilter(request, response);
    }
  }
  </code></pre>