CSRF
CSRF in JavaScript
Vulnerability: Cross-Site Request Forgery (CSRF)
Vulnerable Code:
javascriptCopy code// No CSRF token validation
fetch('/update-profile', {
method: 'POST',
body: JSON.stringify({ email: '[email protected]' })
});Reason for vulnerability: The code performs a sensitive action without validating a CSRF token, making it susceptible to CSRF attacks.
Fixed Code:
javascriptCopy code// Fetch CSRF token from meta tag
const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
fetch('/update-profile', {
method: 'POST',
headers: {
'CSRF-Token': token,
'Content-Type': 'application/json'
},
body: JSON.stringify({ email: '[email protected]' })
});Reason for fix: Including a CSRF token in the request header ensures that the request is legitimate and not forged by an attacker.
Vulnerable Code
Reason for Vulnerability:
This endpoint doesn't implement any CSRF protection, allowing attackers to trick users into making unintended transfers.
Fixed Code:
Reason for Fix:
The fixed code implements a custom CSRF token validation. A more robust solution would be to use Spring Security's built-in CSRF protection.
Vulnerable Code:
Reason for Vulnerability:
This Flask route doesn't implement any CSRF protection, allowing attackers to trick users into changing their email without their knowledge.
Fixed Code:
Reason for Fix:
The fixed code implements CSRF protection using Flask-WTF's CSRFProtect and custom token validation.
JavaScript Example
Vulnerable Code:
Reason for Vulnerability:
The API endpoint doesn't implement any CSRF protection, making it vulnerable to cross-site requests.
Fixed Code:
Reason for Fix:
The fixed code implements CSRF protection using the csurf middleware for Express.js and includes the CSRF token in API requests.
Last updated