Back to All Questions
Question 69 of 100
API Security Testing
Advanced
Q69: What is CSRF? How Can APIs Prevent It?
🛡️Core Concept
What is CSRF? How Can APIs Prevent It?
Key Takeaways & Architecture Summary
- ✓CSRF stands for Cross-Site Request Forgery; malicious request exploits.
- ✓Forces a browser to execute unauthorized actions on a logged-in site.
- ✓APIs prevent CSRF using Anti-CSRF Tokens or SameSite cookie configurations.
Direct Answer Summary
CSRF (Cross-Site Request Forgery) is a vulnerability where an attacker tricks a user's browser into executing state-changing requests (like money transfers) on an active, authenticated application. APIs prevent CSRF by enforcing custom headers, using cryptographic anti-CSRF tokens, or setting authentication cookies to `SameSite=Strict`.
⚠️ Senior Engineering Warning (Red Flag)
Do not rely on CORS to prevent CSRF. CORS blocks domains from reading the response payload but cannot prevent the browser from submitting the request and mutating data on the server.
💡 STAR Architectural Explanation & Pro Tip
Modern stateless APIs that rely on JWT tokens stored in localStorage are naturally immune to CSRF because browsers do not append localStorage variables automatically to outbound requests.
RestAssuredTest.java
Rest-Assured + Java// Express CSRF prevention middleware setup
const csrf = require('csurf');
app.use(csrf({ cookie: true })); // Enforces CSRF token validation