CSRF (Cross-Site Request Forgery) is an attack that forces a user to perform unwanted actions in an application in which they are authenticated. CSRF attacks can lead to unauthorized data changes, administrative actions, or other harmful operations.
Methods of CSRF protection:
- CSRF Tokens: Use unique CSRF tokens that are generated for each user session and verified for each authenticated operation.
<form method="post" action="/submit"> <input type="hidden" name="csrf_token" value="UNIQUE_TOKEN"> <!-- other form fields --> <input type="submit" value="Submit"> </form>
- Referer Checking: Verify the referer header to ensure the request comes from a trusted source.
- Session Lifespan Limitation: Shorten session lifespans to reduce the risk of CSRF token exploitation.
- SameSite Cookies: Set the
SameSite
attribute for cookies to restrict them from being sent to third-party sites.
Set-Cookie: sessionId=abc123; SameSite=Strict;
Example of implementing CSRF tokens in Node.js using Express:
const express = require('express'); const csrf = require('csurf'); const bodyParser = require('body-parser'); const app = express(); const csrfProtection = csrf({ cookie: true }); const parseForm = bodyParser.urlencoded({ extended: false }); app.use(require('cookie-parser')()); app.use(csrfProtection); app.get('/form', (req, res) => { res.send(`<form method="post" action="/submit"> <input type="hidden" name="_csrf" value="${req.csrfToken()}"> <input type="submit" value="Submit"> </form>`); }); app.post('/submit', parseForm, csrfProtection, (req, res) => { res.send('Form data is valid'); }); app.listen(3000, () => console.log('Server running on port 3000'));
CSRF protection is crucial for ensuring the security of web applications and protecting users from potential attacks.