34. What is CSRF protection and how do you defend against it?

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:

  1. 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>
  1. Referer Checking: Verify the referer header to ensure the request comes from a trusted source.
  2. Session Lifespan Limitation: Shorten session lifespans to reduce the risk of CSRF token exploitation.
  3. 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.

devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.