How to use Express JS 4.0's csurf?
Asked Answered
M

1

8

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?

Mail answered 28/5, 2014 at 16:56 Comment(0)
R
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).

Rumery answered 29/5, 2014 at 6:14 Comment(6)
in app.post i have to check csrfToken or not?Whimsical
No, Paresh, the csurf middleware handles that for you. If the _csrf field isn't present and correct, it will be rejected before your +post+ handler.Rumery
Thanks for quick reply. I am return index.html from express.js with _csrf token in cookie and front side in angular i get cookie and set in with in form tag with _csrf and set token from cookie to hidden and now i press submit but token always return EBADCSRFTOKEN. Where i am wrong please tell me.Whimsical
I am checking in req.body csrf token is present and i am also check browser cookie value it is match with passed value but it still reject the requestWhimsical
I can't really tell from your description, Paresh. Maybe try asking a new question with your application file and form source?Rumery
I am just host the site tranquil-earth-4097.herokuapp.com/login. here you can see in inspect element > resource > cookie here cookie is stored successfully. now i am post my code of index.js. Please see thise bin pastebin.com/Uvkj4ZH4. Thanks for helping me. @Ethan BrownWhimsical

© 2022 - 2024 — McMap. All rights reserved.