NodeJS如何正确设置csrf令牌? [英] NodeJS how to set csrf token correctly?

查看:713
本文介绍了NodeJS如何正确设置csrf令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是这个问题的延续:





我认为是我没有不能正确设置cookie。我试图删除app.use(csrf({cookie:true}))),但是它显示了错误配置的错误。



在fiddler中,我可以看到cookie中有两个令牌,一个是默认的,一个是由res.cookie('csrfmiddlewaretoken',req。 csrfToken()); ,如何以正确的方式设置cookie?



更新:



我想出了一种暴力的方法将_csrf的名称更改为csrfmiddlewaretoken。

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

然后,在fiddler中,我看到的值是一样的。





但是django rest-auth仍然报告失败,如:



也许这不是名字。我还在研究....

解决方案

JiPanNYC,也许你忘了添加

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

}

在您的settings.py


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....

解决方案

JiPanNYC, maybe you forgot to add

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

in your settings.py

这篇关于NodeJS如何正确设置csrf令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆