Cross Site Request Forgery Nodejs

Posted By : Sakshi Gadia | 19-Apr-2018

Attackers perform requests on behalf of users in your application without noticing them. For example change the user’s email address, home address, password, or purchase something etc.

 

How to protect?

We can protect ourselves from this attack by using Node.js CSRF protection middleware. When the browser gets a page from the server, it sends a CSRF token as a cookie. When the browser page action to POST request, it will send the CSRF(Cross Site Request Forgery) token as a cookie.

 

Installation

It can be accessed by:  

 
var csrf = require('csurf')

 

Forms will need to include a hidden CSRF field to allow the POST request to be accepted by the server:

 
 
<input type="hidden" name="_csrf" value="${req.csrfToken()}" />

Set token secret for the user should be stored in a cookie or in req.session. Set cookie true.

 
const csrf = require('csurf');
const cookieParser = require('cookie-parser');

const csrfMiddleware = csrf({
  cookie: true
});

Example of csrf token post back:

 
const express = require('express');
const bodyParser = require('body-parser');
const csrf = require('csurf');
const cookieParser = require('cookie-parser');

const app = express();

const csrfMiddleware = csrf({
  cookie: true
});

app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(cookieParser());
app.use(csrfMiddleware);

app.get('/', (req, res) => {
  res.send(`
    <h1>Hello World</h1>
    <form action="http://localhost:3000/main" method="POST">
      <div>
        <label for="message">Your message</label>
        <input id="message" name="message" type="text" />
      </div>
      <input type="submit" value="Submit" />
      <input type="hidden" name="_csrf" value="${req.csrfToken()}" />
    </form>
  `);
});

app.post('/main', (req, res) => {
  console.log(`Message received: ${req.body.message}`);
  res.send(`CSRF token used: ${req.body._csrf}, Message received: ${req.body.message}`);
});

app.listen(3000, () => {
  console.log(`Listening on http://localhost:3000`);
});

 

 

 

 

 

 

 

 

 

 

About Author

Author Image
Sakshi Gadia

An experienced MEAN Stack developer having good knowledge in Nodejs, MongoDb. Apart from these in my spare time, I enjoy playing chess and ready to learn new technologies.

Request for Proposal

Name is required

Comment is required

Sending message..