How to secure Single Page Apps (SPA) against CSRF
masterTo avoid Cross-Site Request Forgery (CSRF) vulnerabilities, avoid using cookies as the sole method for identifying a user on the server. Instead, use a custom HTTP header to pass an authentication token.
The Recommended Workflow:
- Initial Load: The server returns the web page and JavaScript application.
- Token Retrieval: The JavaScript application reads the authentication token from a cookie (which is safe because malicious sites cannot access your domain's cookies via JS).
- Authenticated Requests: For every subsequent request to protected data, the JavaScript application manually includes that token in a custom HTTP header.
- Server Validation: The server validates the user based on the token in the custom header rather than the cookie itself.
- Error Handling: If the server returns a
401 (Unauthorized)response, the JavaScript application should trigger the login flow.
Security Note: Always use HTTPS to ensure tokens are encrypted in transit. Configure your cookies to only be sent over HTTPS to prevent accidental transmission over unencrypted connections.