How to use Express JS 4.0 csurf?

I checked the csurf wiki but it is empty. This module adds the csrfToken() function to user requests, but then, how do I use it?

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

+6
source share
1 answer

The csurf designed to reject requests containing a payload (for example, body parameters) if it does not have a valid token. Here's how you 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 to take out req.csrfToken() (or replace it with something else); You will find that the form no longer works.

Note that you need csurf sessions to work. If you want to understand the reasons why you would use csurf , see the Wikipedia Article on Cross-Site Request Forgery (CSRF) .

+5
source

Source: https://habr.com/ru/post/969993/


All Articles