'Which mechanism to use for CSRF token handling with spring security

I am new to web security and implementation of same using spring-security. One important concept is prevention from CSRF using CSRF token. Spring security has provided two ways to manage CSRF token

  • CookieCsrfTokenRepository
  • HttpSessionCsrfTokenRepository

However I am not able to understand which one should be used as I can see cons in both the approach.

  • CookieCsrfTokenRepository is asking to set HTTP only property to false in cookie so that javascript can read it and add the same to in further request. However as per my understanding, setting http only as false is not recommended as malicious script can also read the cookie and share the same token in the forged request.
  • HttpSessionCsrfTokenRepository is storing the csrf token in session. In this case, we need to introduce session stickiness or session replication in case of distributed environment however recommendation is to go for stateless application.

So please some let me know if my above understanding is correct or not. If correct, which option do we need to select for csrf token implementation.



Solution 1:[1]

However as per my understanding, setting http only as false is not recommended as malicious script can also read the cookie and share the same token in the forged request.

I believe this would be true if a) you have an XSS vulnerability on your site or b) you did not set the Domain of the cookie. The rest of your question seems opinion-based to me.

however recommendation is to go for stateless application.

Note: The following is simply my opinion on the matter, as it's difficult to argue for/against statelessness in general.

This is an example where security requires state, so to protect the csrf token and avoid your concern with cookies, you need state on the server and should choose session.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Steve Riesenberg