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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With