Implementing Csurf Middleware in Node.js

Csurf module in Node.js prevents the Cross-Site Request Forgery(CSRF) attack on an application. By using this module, when a browser renders up a page from the server, it sends a randomly generated string as a CSRF token. Therefore, when the POST request is performed, it will send the random CSRF token as a cookie. The token sent will be different for each request since they are generated randomly.

Prerequisites

  • An IDE of your choice
  • NodeJs and NPM installed and setup in your system.
  • Basic knowledge of Node.js modules and Embedded JavaScript(ejs).

Installation:

  1. First, we need to initialize our application with package.json file. Therefore, write the following command in the terminal:
    npm init
  2. After, the pakage.json is created, its time to install our dependencies. Therefore, Install the required dependencies by the following command:
    npm install body-parser cookie-parser express csurf --save

    Cookie-parser is used to parse the incoming cookies. Body-parser is used to parse the incoming form data that we will be creating in a HTML file.

  3. Create a file and named as app.js and write the following code for requiring module:
    Filename: app.js

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

    Here, csrf will act as a middleware for generating and validating CSRF cookies. This middleware will add a function for generating cookies. This function will be passed to requests through a hidden form field. This created cookie will be then validated when the users send requests. The middleware populates req.csrfToken().

  4. Now after we have required all the modules, now let’s write down the full code as shown below:
    Filename: app.js



    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    const express = require('express');
    const csrf = require('csurf');
    const cookieParser = require('cookie-parser');
    const bodyParser = require('body-parser');
       
    var csrfProtection = csrf({ cookie: true });
    var parseForm = bodyParser.urlencoded({ extended: false });
       
    var app = express();
    app.set('view engine','ejs')
       
    app.use(cookieParser());
       
    app.get('/form', csrfProtection, function (req, res) {
      // pass the csrfToken to the view
      res.render('login', { csrfToken: req.csrfToken() });
    });
       
    app.post('/process', parseForm, 
          csrfProtection, function (req, res) {
      res.send('Successfully Validated!!');
    });
       
    app.listen(3000, (err) => {
       if (err) console.log(err);
       console.log('Server Running');
    });

    chevron_right

    
    

    In the above code, after importing the modules, we set up the route middlewares and pass the validation method as cookie instead of token. Body-parser is used to parse the data coming from the form. Since, cookie is used as the validation method, therefore, cookie-parser is used. Now, in the GET request, we are rendering the passed cookie value to the view. In the POST request, we are first validating the cookie and if validated, then we are sending a message.

  5. Now, create a folder and named as view and create a file and name it as login.ejs and write the following code in it:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <html>
    <head>
          <title>Csurf Middleware</title>
    </head>
    <body>
        <form action="process" method="POST">
           <input type="hidden" name="_csrf" 
                    value="<%= csrfToken %>">
           <input type="text" name="myname">
           <input type="submit" value="Submit">
        </form>
    </body>
    </html>

    chevron_right

    
    

The above code example will run just as a simple application but there will be an added extra security measure for preventing CSRF.

Steps to run this program:

  1. Make sure you have installed express, csurf, cookie-parser, body-parser module with following command:
    npm install express
    npm install express
    npm install csurf
    npm install cookie-parser
    npm install body-parser
  2. Run index.js file with following command:
    node index.js
  3. Open the browser and go to http://localhost:3000/form, then you will see the form with an input field as shown below:
  4. After submitting the form, you will see the following output:
    Successfully Validated!!

Conclusion: Csurf is a very useful node module for preventing Cross-Site Request Forgery attack.




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.