Node.js - csurf invalid csrf token

冷暖自知 提交于 2021-01-29 18:57:47

问题


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

--- Server side ---

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 }));

--- Client side ---

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.


回答1:


You need to add it in your app.js below the cookieParser like so:

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

You are successfully sending a CSRF token to the frontend in your /csrfToken but then your app is generating a new token in your /post.

Here is the link to the respective documentation.




回答2:


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.

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));

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



来源:https://stackoverflow.com/questions/60915619/node-js-csurf-invalid-csrf-token

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