How do I generate CSRF tokens in Express?

后端 未结 4 1287
北海茫月
北海茫月 2021-02-03 13:25

newbie. I\'m using ExpressJS/Node. Here\'s my config stuff:

var express = require(\'express\'),
app = express.createServer(),
jade=require(\'jade\');
// Configu         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-03 14:14

    In Express 4.x this middleware is removed. For Express 4.x you can do it as follows

    var csrf = require('csurf');
    app.use(csrf());
    

    Ah!! you need to register the csrf middleware after your session and cookieParser middleware.

    Inside Route Or Ctrl

    res.render('someform', { csrf: req.csrfToken() });
    

    or You can set a local variable also like so

    app.use(function(req, res, next){
      res.locals.csrf = req.csrfToken();
    });
    

    Then in view

    input(type="hidden", name="_csrf", value="#{csrf}")
    

    You are done!! :)

提交回复
热议问题