Node.js-csurf无效的csrf令牌 [英] Node.js - csurf invalid csrf token

查看:75
本文介绍了Node.js-csurf无效的csrf令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用npm模块csurf生成令牌.首先,我从服务器获取令牌,然后将其用于/register请求.当我用邮递员复制相同的步骤时,它似乎可以工作,但不幸的是在应用程序中没有.那里总是抛出令牌无效的错误消息

I'm using the npm module csurf for generating a token. First I get the token from the server, which I then use for the /register request. When I'm reproducing the same steps with postman, it seems to work, but unfortunately not in the application. There it always throws the error message that the token is invalid

-服务器端---

csrfProtection.js

import csrf from 'csurf';

export default csrf({
  cookie: true
});

router.js

import csrfProtection from './../../config/csrfProtection'
router.get('/csrfToken', csrfProtection, async (req, res, next) => {
  return res.send(req.csrfToken());
});

router.post(
  '/register',
  validationHelper({ validation: registerUserValidation }),
  csrfProtection,
  async (req, res, next) => {
    return res.send('user registered');
  }
);

app.js

const app = express();

app.use(cookieParser());
app.use(
  cors()
);
app.use(compression());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

-客户端---

const token = await this.$axios.$get('/csrfToken')
// token has the value 1KFmMJVz-dspX9TJo8oRInPzgDA1VY28uqQw

    await this.$axios.$post(
      '/register',
      {
        name: 'test456',
        email: 'test@gmail.com',
        password: '123456789'
      },
      {
        headers: {
          'csrf-token': token
        }   
      }
    )

有人遇到过同样的问题吗?前端和后端托管在不同的域中.

Someone experienced the same problem? Frontend and backend are hosted on different domains.

推荐答案

最近解决了有关csrf令牌403的类似问题.在get csrf调用之后发生的每个发布请求都会生成一个新的CSRF令牌.

Recently fixed a similar issue regarding 403 for csrf token. A new CSRF token is generated for every post request that happens after the get csrf call.

我发现这是一个CORS问题.我通过添加以下代码进行修复:

I found that this is a CORS issue. I fixed by adding below code:

import cors from 'cors';
const allowedOrigins = ['http://localhost:3000', 'http://localhost'];
const corsoptions: cors.CorsOptions = {
  allowedHeaders: ["Origin", "X-Requested-With", "Cookie", "Content-Type", "Accept", "X-Access-Token", "Authorization"],
  credentials: true,
  methods: "GET,PATCH,POST,DELETE",
  origin: function (origin, callback) {
    // allow requests with no origin 
    // (like mobile apps or curl requests)
    if (!origin) return callback(null, true);
    if (allowedOrigins.indexOf(origin) === -1) {
      var msg = 'The CORS policy for this site does not ' +
        'allow access from the specified Origin.';
      return callback(new Error(msg), false);
    }
    return callback(null, true);
  },
  preflightContinue: false,
};

export const handleCors = (router: Router) =>
  router.use(cors(corsoptions));

请参阅cors软件包 https://www.npmjs.com/package/cors"

Please refer to cors package https://www.npmjs.com/package/cors"

这篇关于Node.js-csurf无效的csrf令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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