Cross-Site Request Forgery (CSRF) tricks a user into submitting a request they didn’t intend. Protecting your forms against this attack is simple if you generate and verify tokens properly.
1. Generating a token
Create a random token, store it in the session, and embed it into your form as a hidden input. Never reuse the same token across multiple requests.
2. Verifying the token
When processing the request, compare the submitted token to the one in the session. If they differ or are missing, deny the request.
3. Rotate tokens
After a successful submission, rotate the token so an attacker can’t replay it. This limits the lifetime of any leaked tokens.