egg.js The frame post request reported an error of invalid CSRF token security verification, which has been solved

It has to be said that Alibaba’s egg framework is quite good, with its own security verification.

Problem: get request is normal, post request background will report such an error.

" nodejs.ForbiddenError : invalid csrf token"

There is an official explanation for this problem. Click to jump to the official safety explanation of egg. There is not too much explanation here

Method 1: in the confit.default.js Add the following code to turn off security verification (not recommended)

config.security = {
    csrf: {
      enable: false,
    },
  };

Method 2: when the front-end initializes the interface, let the front-end get to request an interface first, and the background returns a secret key to the front-end. Let the front-end put it in the headers request header when the post request is made, and the egg will automatically verify the secret key, and the request will succeed only if the verification is successful.

1. Egg background code, get interface returns secret key: 2

async index() {
    const { ctx } = this;
    ctx.body = {
      csrf:ctx.csrf
    };
}

The following two methods are demonstrated. The postman test is as follows. At the same time, if a request is made in the front end, a secret key pair will be generated in the cookies. As shown in the figure below, the secret key will change after each request, so the CSRF obtained in the front end should be put in the headers request header in a global way.

2. Front end secret key request: 2

axios.post('apis/add', data,{headers:{'x-csrf-token': headData}})

The postman test is as follows: directly copy CSRF

OK, successful request, perfect solution, start moving bricks


Read More: