NodeJS how to set csrf token correctly?

感情迁移 提交于 2019-12-12 03:56:43

问题


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

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.

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.

But the django rest-auth still reports fail like:

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


回答1:


JiPanNYC, maybe you forgot to add

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

in your settings.py



来源:https://stackoverflow.com/questions/42101642/nodejs-how-to-set-csrf-token-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!