Notes on CSRF token
02/11/2025
What is CSRF?
- Cross-Site Request Forgery (CSRF) is a type of security vulnerability where an attacker tricks a user's browser into making unwanted requests to a website where the user is already authenticated.
- One possible scenario of how could it work:
- The victim logs in to a legitimate website (for example a bank account) and receives a valid session cookie
- Without logging out, the victim visits another malicious website that is controlled by the attacker
- The malicious website triggers a request to the legitimate website
- The request contains the cookies that are associated to the legitimate website
- The browser attaches them automatically and the legitimate website can't distinguish between the real and forged requests
What is a CSRF token?
- CSRF token is a security measure to prevent the above
- It generates a unique, random token for each user session
- The user then needs to include this token in each submission or request
- The backend then validates that incoming token
- CSRF token is:
- unique for each user session
- unpredictable and randomly generated
- validated on the server side
- securely transmitted over HTTPS (at least it should be)
- hard for the malicious sites to replicate
CSRF token lifecycle
- server generates a token at the beginning of the user's session; it should use state-of-art algorithms and random number generators
- the token is then sent to user in requests as a hidden field, it should be single-use and have an appropriate expiration date
- the user should send it back with every request to the server
- server verifies that the token is valid before doing anything else
- if the token is invalid, the server rejects the request
Cookies?
- Common practices:
- CSRF tokens are often sent as a cookie, it is both helpful and secure
- the JavaScript client then scrapes them and send them back
- this approach makes the token available throughout the application
- it also prevents the attack as the attacker can't access the session cookies