on
XSRF (CSRF) Protection - Synchronizer Token Pattern
Introduction
This is the most popular implementation to prevent Cross-site Request Forgery (CSRF), and it makes use of a challenge token that is associated with a particular user which is used as a hidden value in every state changing form which is present on the web application.
How?
This token, called a CSRF Token or a Synchronizer Token, works as follows:
- The web server generates a token
- The form is submitted by the user
- The token is included in the POST data at submit time.
- The web application compares the token generated by the web application with the token sent in through the request
- If these tokens match, the request is valid, as it has been sent through the actual form in the web application.
- If there is no match, the request will be considered as illegal and will be rejected.
CSRF Token generation function for a particular user session
The token is set as a hidden input on the protected form via an AJAX request to the remote site's token endpoint.
AJAX request to the token endpoint
HTML Form using POST method
Form handler function
CSRF Token validated
CSRF endpoint is a 404[/caption]
CSRF Validation Failed
Conclusion
For the anti-CSRF mechanism to be implemented properly, it will also need to be cryptographically secure (openssl_random_pseudo_bytes(30)), so that the token itself cannot be easily guessed.
This protects the form against Cross-site Request Forgery (CSRF) attacks, because an attacker crafting a request will also need to guess the anti-CSRF token for them to successfully trick a victim into sending a valid request. And, this token is invalidated after some time when the user logs out.