javascript - How to use Express JS 4.0's csurf? - Stack Overflow

I have been checking csurf's wiki, but it is empty. This module adds a csrfToken() function to use

I have been checking csurf's wiki, but it is empty. This module adds a csrfToken() function to user requests, but then, how should I use it?

Can someone give a code example with explanations? What should I do on user side? What should I do on server-side?

I have been checking csurf's wiki, but it is empty. This module adds a csrfToken() function to user requests, but then, how should I use it?

Can someone give a code example with explanations? What should I do on user side? What should I do on server-side?

Share Improve this question asked May 28, 2014 at 16:56 Jérôme VerstryngeJérôme Verstrynge 59.7k97 gold badges295 silver badges466 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

The csurf middleware is designed to reject requests that contain a payload (body parameters, for example) if it doesn't have a valid token. Here's how you would use it:

app.use(require('body-parser')());
app.use(require('cookie-parser')('YOUR SECRET GOES HERE'));
app.use(require('express-session')());

app.use(require('csurf')());

app.get('/some-form', function(req, res){
    res.send('<form action="/process" method="POST">' +
        '<input type="hidden" name="_csrf" value="' + req.csrfToken() + '">' +
        'Favorite color: <input type="text" name="favoriteColor">' +
        '<button type="submit">Submit</button>' +
        '</form>');
});

app.post('/process', function(req, res){
    res.send('<p>Your favorite color is "' + req.body.favoriteColor + '".');
});

Try taking out the req.csrfToken() (or replacing it with something else); you will find that the form no longer works.

Note that you need sessions for csurf to work. If you want understand the reasons you would use csurf, see the Wikipedia article on cross-site request forgery (CSRF).

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745374585a4624944.html

相关推荐

  • javascript - How to use Express JS 4.0&#39;s csurf? - Stack Overflow

    I have been checking csurf's wiki, but it is empty. This module adds a csrfToken() function to use

    7小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信