亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Node.js - csurf 無效的 csrf 令牌

Node.js - csurf 無效的 csrf 令牌

慕的地8271018 2022-06-05 16:59:21
我正在使用 npm 模塊 csurf 來生成令牌。首先,我從服務器獲取令牌,然后將其用于 /register 請求。當我使用郵遞員復制相同的步驟時,它似乎可以工作,但不幸的是不在應用程序中。那里總是拋出令牌無效的錯誤消息- - 服務器端 - -csrfProtection.jsimport csrf from 'csurf';export default csrf({  cookie: true});路由器.jsimport 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');  });應用程序.jsconst 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: '[email protected]',        password: '123456789'      },      {        headers: {          'csrf-token': token        }         }    )有人遇到過同樣的問題嗎?前端和后端托管在不同的域上。
查看完整描述

2 回答

?
茅侃侃

TA貢獻1842條經驗 獲得超22個贊

最近修復了有關 csrf 令牌的 403 的類似問題。在 get csrf 調用之后發生的每個發布請求都會生成一個新的 CSRF 令牌。


我發現這是一個 CORS 問題。我通過添加以下代碼來修復:


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"


查看完整回答
反對 回復 2022-06-05
?
慕尼黑的夜晚無繁華

TA貢獻1864條經驗 獲得超6個贊

您需要在下面添加它,app.js如下所示cookieParser

app.use(cookieParser())
app.use(csrfProtection)

您已成功將 CSRF 令牌發送到您的前端,/csrfToken但隨后您的應用程序正在您的/post.

這是相應文檔的鏈接。


查看完整回答
反對 回復 2022-06-05
  • 2 回答
  • 0 關注
  • 218 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號