Rest-auth still reports the error of “CSRF cookie

2019-09-15 04:47发布

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: screenshot from chrome console

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: screenshot from fiddler

Could you help me figure out where is the bug?

2条回答
The star\"
2楼-- · 2019-09-15 05:23

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

查看更多
萌系小妹纸
3楼-- · 2019-09-15 05:36

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, enter image description here

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: enter image description here

enter image description here

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.

查看更多
登录 后发表回答