Search code examples
node.jsdjangoauthenticationcookiescsrf

NodeJS how to set csrf token correctly?


This is a continuation of this question: Rest-auth still reports the error of "CSRF cookie not set", but I've set the csrf

The code I used for server.js is:
const cookieParser = require('cookie-parser');
const csrf = require('csurf');
app.use(cookieParser());
app.use(csrf({ cookie: true }));
app.use(function (req, res, next) {
  res.cookie('csrfmiddlewaretoken', req.csrfToken());
  next();
});

However, the result is enter image description here

enter image description here

The reason I think is that I didn't set the cookie correctly. I tried to remove app.use(csrf({ cookie: true }));, but then it shows an error of csrf misconfigured. enter image description here

In fiddler, I can see there are two tokens in the cookie, one default, one set by res.cookie('csrfmiddlewaretoken', req.csrfToken());, how can I set the cookie in the correct way?

UPDATE:

I kind of figured out a brute-force way to change the name of _csrf to csrfmiddlewaretoken.

app.use(function (req, res, next) {
  res.cookie('csrfmiddlewaretoken', req.cookies._csrf);
  next();
})

Then, in fiddler, I see the value are same.

enter image description here

But the django rest-auth still reports fail like: enter image description here

Maybe that's not about the name. I am still researching....


Solution

  • JiPanNYC, maybe you forgot to add

    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework.authentication.SessionAuthentication',
            'rest_framework.authentication.TokenAuthentication',
        )
    }
    

    in your settings.py