CSRF protection for SFRA storefront forms
Key Takeaway
In SFRA, add csrfProtection.generateToken to the GET route that renders a form. Add csrfProtection.validateAjaxRequest to the POST route that receives the form's AJAX submission, so a request without a valid CSRF token is rejected.
Cross-site request forgery (CSRF) protection lets the server reject a storefront form submission that doesn't carry a valid token. In SFRA, you add the protection to controller routes as middleware. Without middleware, the dw.web.CSRFProtection script class generates and validates tokens directly.
Synchronizer tokens
B2C Commerce protects forms with synchronizer tokens, which are a best practice for protecting against CSRF attacks. The flow runs in this order:
- The server generates a unique token for the shopper's session.
- The token goes into the form.
- The form sends the token back when the shopper submits it.
- The server checks the token and can reject a submission that doesn't carry a valid one.
Each token is tied to the shopper's session. A token is valid for 60 minutes after the server creates it.