Monday, March 08, 2021

Mitigate ExpressJS CSRF using csurf npm module tutorial

Cross-Site Request Forgery attack is a prominent and classic web-based attack where you can request sensitive actions on behalf of the users and that may cause severe damage to the user data. To overcome such request forgery issues, a CSRF token is added explicitly to the request header or in the cookie or post request body which is then decoded on the server-side and validated against the session.

Mitigate ExpressJS CSRF using csurf npm module tutorial
Mitigate ExpressJS CSRF using csurf npm module tutorial


> npm install csurf


We've imported csrf module and initialized the csurf module with a cookie as a false option by default. This would start accepting the Anti-CSRF tokens either via header or request body which effectively prevents csrf attacks instead of sending cookies.

var csurf = require('csurf')

var csrfProtection = csrf({ cookie: false })

CSRF Token Generation

As the client-side API requires attaching the ant-csrf token, We need to send out the csrf token by generating it and responding via GET API. Either one can respond with render function or directly with JSON/XML based response to the frontend client.

app.get('/form', function (req, res) {
  // pass the csrfToken to the view
  res.render('send', { csrfToken: req.csrfToken() })

CSRF Validation Middleware

As the validation of the CSRF token happens in the server, ensure to install body-parser to parse any tokens passed via body part or access the token directly via header. Add the middleware above all request routes to have seamless verification of the token before executing the actual route.


Error Handling

To efficiently respond to the API client or frontend service, I would strongly recommend adding an error handling layer before the request route with a specific format response by which clients can easily parse and understand the error message thrown from the server.

app.use(function (err, req, res, next) {
  if (err.code !== 'EBADCSRFTOKEN') return next(err)
  // handle CSRF token errors here
  res.json({err: "CSRF ERROR"}) // respond with JSON response
Thus, We have successfully added CSRF validation logic as middleware to verify the request before being executed. For bugs/hugs, feel free to comment below. Share is care.


Post a Comment

feel free to post your comments! Don't Spam here!