Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using csurf with session in express

I'm writing a single page application with MEAN stack, and using express-session with redis for session management.

I want to use scrf token in my client's cookies.

the problem is when I add csurf middleware, it set a session with name csrfSecret in redis, but how can I send it in cookie to client?

middlewares :

 app.use(csrf({}));

 app.use(function(req, res, next) {
     res.cookie('csrf-token', req.csrfToken());
     return next();
 });

and csrf-token is sending to client but it don't do anything.and I receive 403 error from module.

thank you for any answer or idea.

like image 770
Elyas74 Avatar asked Oct 26 '25 12:10

Elyas74


1 Answers

If you want to create a csrf cookie in the client you have to use the following:

app.use(csrf({ cookie: true })

This will create a token in the client. If you do not pass any options to the csrf function it will use req.session. If you want to save the cookie client-side, remember that you will need to use cookie-parser module.

You can find more information in the github link to the project: https://github.com/expressjs/csurf

like image 130
Jose Miguel Colella Avatar answered Oct 28 '25 03:10

Jose Miguel Colella



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!