Rest-auth still reports the error of “CSRF cookie

2019-09-15 05:28发布

问题:

I tried to implement an authentication(login/registration) function using Django rest-auth package.

url(r'^rest-auth/', include('rest_auth.urls')),
url(r'^rest-auth/registration/', include('rest_auth.registration.urls')),

But when I tried to post the rest-auth urls, it gave me the error:

However, in Nodejs I've already set the csrf token using the 'csurf' package,

const cookieParser = require('cookie-parser');
const csrf = require('csurf');
const app = new Express();
app.use(cookieParser());
app.use(csrf({ cookie: true }));

Also, I can see the csrf token using Fiddler:

Could you help me figure out where is the bug?

回答1:

The token in your request is currently named _csrf. It needs to be called csrfmiddlewaretoken for Django to pick it up.



回答2:

Thanks to Raphael Gomes. I made some progress on this. I changed my server.js file as:

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();
});

And in the Fiddler,

I can see 2 csrfs there, one default and one set by me. I tried to remove app.use(csrf({ cookie: true })); but then it shows csrf misconfigued. Anyway, at least csrfmiddlewaretoken works in this way.

Then the authentication result is like:

It says this csrf token is not valid. I think that's because I used the req.csrfToken(). I am still researching that how to set the correct csrf token.