The use of JWT (JSON web token) with separation of front end and back end

Time:2020-10-22

preface

Because the JWT technology is used in the project developed by ourselves, the front end adopts theVue.jsFramework, the back end adoptsCodeIgniterThis article helps friends who use the same technology stack.

The specific ideas are as follows:
Store the JWT token generated by the back-end into localstorage. When the front-end switches the route (refresh the page), it takes this token when it requests through Ajax and submits it to the back-end to judge whether the current token is valid, and the back-end returns the result.

JWT has many uses, which can be used for background permission restriction and interface security verification.

Using the tutorial

front end Vue.js

vue-router

When logging in, thetokenDepositlocalStorage

useVue-RouterJudge whether it exists or nottokenThere is no jump to login

//JWT user authority verification to determine whether token is in localstorage
router.beforeEach(({name}, from, next) => {
  //Get JWT token
  if (localStorage.getItem('JWT_TOKEN')) {
    //Login if the user is on the page
    if (name === 'login') {
      next('/');
    } else {
      next();
    }
  } else {
    if (name === 'login') {
      next();
    } else {
      next({name: 'login'});
    }
  }
});

axios

Axios global configuration interceptor
Each request to the back end to carry header information

staysrc/main.jsAdd the following code:

//HTTP request interceptor
axios.interceptors.request.use(
  config => {
    if ( localStorage.JWT_ Token) {// judge whether there is a token. If there is a token, a token is added to each HTTP header
      config.headers.Authorization = `token ${localStorage.JWT_TOKEN}`;
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  });

//HTTP response interceptor
axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (error.response) {
      console.log('axios:' + error.response.status);
      switch (error.response.status) {
        case 401:
          //Return to 401 to clear the token information and jump to the login page
          store.commit('LOG_OUT');
          router.replace({
            path: 'login',
            query: {redirect: router.currentRoute.fullPath}
          });
      }
    }
    return  Promise.reject ( error.response.data ); // returns the error information returned by the interface
  });

Vue.prototype.$http = axios;

Back end CodeIgniter

The back-end controller receives the request header information, verifies the validity of the token, and returns 401 status code if it is invalid

$header = $this->input->get_ request_ Header ('authorization ', true); // get request header authorization
    List ($token) = sscanf ($header, 'token% s'); // extract token
    if ($header != '' && jwt_helper::validate($token)) {
        $userid = jwt_ Helper:: decode ($header) - > userid; // decode the token and extract the userid field
        // do something
    } else {
        show_ Error ("permission denied", 401, "please check your token."); // 401 error
    }

Here we provide our own encapsulated JWT helper class and JWT library usage methods and files, which can access GitHub
Warehouse: https://github.com/52admln/JW…

Security

For reference: http://www.cnblogs.com/xiekel… Among themSecurity issues of token authentication based on JWT