Mohit Bhardwaj
Mohit Bhardwaj

Reputation: 10083

how to pass csrf token in all views in express, nodejs

I have a NodeJS app built using ExpressJS. After a security review, I was suggested to implement CSRF on all forms and ajax submissions. For this, I used csurf package. For this, we need to pass CSRF token in every form page, then return it with form submission data.

First, I tried doing this individually for pages that contained forms. But later I realised that I had a search form in my page header, which appears on all of the pages. Now, is there any way I can pass the CSRF token, to all my views, without passing it explicitly for each request. Here's a general code I use for rendering my form pages. I use Jade/Pug for rendering:

router.get('/createcampaign', checkUserSession, middleWare2, middleware3, function(req, res){
    var pageInfo = {};
    pageInfo.title = 'Create New Campaign';
    pageInfo.projects = req.projects;
    pageInfo.session = req.session;
    pageInfo.bodyid = 'createcampaign';
    pageInfo.project_id = req.flash('project_id');
    pageInfo.bodyclass = 'bluebody';
    pageInfo.account = req.account;
    pageInfo.grammars = req.grammars;
    pageInfo.csrfToken = req.csrfToken; //Here I pass csrfToken to view

    res.render( 'users/createcampaign', pageInfo );
});//createcampaign get route

As you can see, I need to pass csrfToken with view context object. How can I pass it globally so it will be passed to all views?

Also, is it safe security wise, to send this csrfToken on all pages and use it wherever required?

Thanks.

Upvotes: 1

Views: 3267

Answers (1)

Yves Kipondo
Yves Kipondo

Reputation: 5603

create a middleware that will pass a token to the token property to the request object
var csrf = require('csurf')   
app.use(csrf())
app.use(function(request,response,next){
    app.locals._token = request.csrfToken()
    next() 
})

and you can use the variable _token in your view

Upvotes: 5

Related Questions