How do I generate CSRF tokens in Express?

后端 未结 4 1286
北海茫月
北海茫月 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 13:51

    Add the token to dynamic helpers.

    app.dynamicHelpers({
      token: function(req, res) {
        return req.session._csrf;
      }
    });
    

    Reference it in your jade template.

    input(type='hidden', value=token)
    

    Source: http://senchalabs.github.com/connect/middleware-csrf.html

    0 讨论(0)
  • 2021-02-03 13:58

    If you also want to set a secure cookie for your CSRF token that can be read by your frontend (angular for example), you can do this:

    app.use csrf()
    
    app.use (req, res, next) ->
      res.cookie('XSRF-TOKEN', req.csrfToken(), {secure: true})
    next()
    
    0 讨论(0)
  • 2021-02-03 14:06

    Dynamic helpers has been removed from Express since 3.x.

    The new usage would be app.use(express.csrf());, which comes from Connect.

    0 讨论(0)
  • 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!! :)

    0 讨论(0)
提交回复
热议问题