title: Spring Security: Custom CSRF Implementation by extending CsrfRepository
body: <p>I am trying to create a customized CSRF implementation in my Spring Boot application by implementing the <code>CsrfRepository</code> interface provided by Spring Security.</p>
  
  <p>Below is how my custom repository looks like:</p>
  
  <pre><code>public class CustomCookieCsrfTokenRepository implements CsrfTokenRepository {
  
      static final String DEFAULT_CSRF_COOKIE_NAME = "XSRF-TOKEN";
  
      static final String DEFAULT_CSRF_PARAMETER_NAME = "_csrf";
  
      static final String DEFAULT_CSRF_HEADER_NAME = "X-XSRF-TOKEN";
  
      @Override
      public CsrfToken generateToken(HttpServletRequest request) {
          return new DefaultCsrfToken(this.DEFAULT_CSRF_HEADER_NAME, this.DEFAULT_CSRF_PARAMETER_NAME, createNewToken());
      }
  
      @Override
      public void saveToken(CsrfToken token, HttpServletRequest request, HttpServletResponse response) {
          String tokenValue = token == null ? "" : token.getToken();
          Cookie cookie = new Cookie(this.DEFAULT_CSRF_COOKIE_NAME, tokenValue);
          cookie.setSecure(request.isSecure());
          response.addCookie(cookie);
      }
  
      @Override
      public CsrfToken loadToken(HttpServletRequest request) {
          Cookie cookie = WebUtils.getCookie(request, this.DEFAULT_CSRF_COOKIE_NAME);
          if (cookie == null) {
              return null;
          }
          String token = cookie.getValue();
          if (!StringUtils.hasLength(token)) {
              return null;
          }
          return new DefaultCsrfToken(this.DEFAULT_CSRF_HEADER_NAME, this.DEFAULT_CSRF_PARAMETER_NAME, token);
      }
  
      private String createNewToken() {
          String unsignedToken = UUID.randomUUID().toString();
          return RSAUtil.signMessage(unsignedToken, privateKey);
      }
  }
  </code></pre>
  
  <p><strong>QUESTION</strong>: As you can see, I want to sign my cookie value using a private key and validate it using a public key. The question is where should this verification logic take place? I am guessing <code>loadToken()</code> method can have the logic to validate the signature. Is this the correct place or should it take place elsewhere?</p>
  
  <p>Can someone provide some snippets or samples on how and where to handle this?</p>