Open In App

Implementing Csurf Middleware in Node.js

Improve
Improve
Like Article
Like
Save
Share
Report

Csurf middleware 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.

Steps to set up the Application and Installing Required Modules 

Step 1: First, we need to initialize our application with a package.json file. Therefore, write the following command in the terminal:  

npm init

Step 2: After the package.json is created, it’s time to install our dependencies. Therefore, Install the required dependencies by the following command: 

npm install body-parser cookie-parser express csurf --save

Here,

  • 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 an HTML file.

Updated dependencies in the package.json file.

"dependencies": {
"body-parser": "^1.20.2",
"cookie-parser": "^1.4.6",
"csurf": "^1.11.0",
"express": "^4.18.2"
}

Steps to Implement Csurf Middleware in NodeJS:

Step 1: Create a file named app.js and import the required Modules.

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

  • 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(). 

Step 2: After Importing all the required modules, set up the route middleware and pass the validation method as a cookie instead of a token. Body-parser is used to parse the data coming from the form. Since a 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. 

Step 3: Now, create a folder and named as view and create a file and name it login.ejs, and create a simple form as given below:

<form action="process" method="POST">
<input type="hidden" name="_csrf"
value="<%= csrfToken %>">
<input type="text" name="myname">
<input type="submit" value="Submit">
</form>

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

Csurf Middleware Complete Example:

This example demonstrate a basic implementation of Csurf Middleware in Node.js.

HTML




<!-- Filename - login.ejs -->
<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>


Javascript




// Filename - app.js
 
const express = require('express');
const csrf = require('csurf');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
 
let csrfProtection = csrf({ cookie: true });
let parseForm = bodyParser.urlencoded({ extended: false });
 
let 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');
});


Steps to run this program: Run the app.js file with the following command:  

node app.js

Open the browser and go to http://localhost:3000/form, then you will see the form with an input field as shown below: 

After submitting the form, you will see the following output: 

Successfully Validated!!

Conclusion:

Implementing csurf middleware in Node.js strengthens security by guarding against Cross-Site Request Forgery attacks. By generating and validating tokens, it protects sensitive user data, ensuring a robust defense. This proactive measure bolsters overall application integrity, providing a reliable shield against potential security vulnerabilities and unauthorized requests.



Last Updated : 29 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads