I am implementing CSRF protection using Spring security as per the doc
One question I have is: When this token will get invalidated by the Spring security? Does the token gets invalidated for each request submit?
A CSRF token is not an access token and does not have a lifetime like bearer tokens do. They are generated using session information. CSRF adds additional information to your requests that lets the server verify the requests comes from an authorized location. They don't have to be session-related.
Make sure tokens can't be reused. Expire them after a short amount of time. Verify the received token is the same as the set token in a safe way, for example, compare hashes. Do not send CSRF tokens in HTTP GET requests.
To protect MVC applications, Spring adds a CSRF token to each generated view. This token must be submitted to the server on every HTTP request that modifies state (PATCH, POST, PUT and DELETE — not GET). This protects our application against CSRF attacks since an attacker can't get this token from their own page.
Each HTTP request requires, besides our session cookie, a secure random generated value called a CSRF token. Server store this token on the server end and also passes it to the client.
By default the CSRF token is stored in the HTTP session and is generated on a per-session basis. See the official Spring Security documentation for more details. Therefore, the default lifecycle of CSRF tokens is the session duration.
Like everything else in Spring Security, the storage and retrieval of CSRF tokens can be customized to suit individual needs. The way to do that would involve creating an implementation for CsrfTokenRepository
. Custom implementations could change the token on a per request basis, store the token in a relational database, and so on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With