Analysis of 2 Token Reasons and Sample Code in Web Project Development

Analysis of 2 Token Reasons and Sample Code in Web Project Development

insert image description here

question:

There are 2 tokens in the project, one with a validity period of 2 hours (referred to as: short token), and the other with a validity period of 14 days (referred to as: long token).
Why use 2 tokens?

answer:

1. Based on security considerations and to prevent token leakage, all requests in server resources can only use short tokens, and short tokens are only valid for 2 hours;

  • This method still cannot completely solve the problem of preventing Token leakage, but it can only improve the security of preventing Token leakage to a certain extent;
  • The only function of a long token is to use it to request a new short token when the short token expires.

Only in this interface can you send requests using long Token.

2. To improve the user experience, do not directly ask users to exit the page they are operating

import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
import { getToken, setToken } from './token'
import router from '../router/index.js'
import { Toast } from 'vant'
Vue.use(VueAxios, axios)
const instance = axios.create({
  baseURL: 'base URL',
  timeout: 100000
})
// Add request interceptor instance.interceptors.request.use(
  function (config) {
    // Add token uniformly
    getToken() && (config.headers['Authorization']= `Bearer ${getToken().token}`)
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)
//Add response interceptor/**
 * 1.if 401 else don't care* 2.if there is a token else jump to the login page* 3.try-catch use refresh_token to get the token, if successful else refresh_token is invalid, jump to the login page* 4.Save the obtained token, update, and continue to perform the user's desired operation*/
instance.interceptors.response.use(
  function (response) {
    return response
  },
  async function (error) {
    if (401 === error.response.status) {
      setTimeout('console.clear()', 2000)
      if (getToken()) {
        try {
          // Logged in, but the short T expired, use the long T to get the short T (refresh user token)
          let res = await axios({
            url: 'base address/v1_0/authorizations',
            method: 'PUT',
            headers:{Authorization : `Bearer ${getToken().refresh_token}`}
          })
          // Update short T
          let token = getToken()
          token.token = res.data.data.token
          setToken(token)
          // Continue user operation return instance(error.config)
        } catch (error) {
          // Long T fails, jump to login page Toast.fail('Please log in first')
          router.push({ path: '/login' })
        }
      } else {
        // Not logged in, jump to the login page Toast.fail('Please log in first')
        router.push({ path: '/login' })
      }
    }
    return Promise.reject(error)
  }
)
export default instance

The above is the detailed content of the analysis of the reasons and sample codes of 2 Tokens in web project development. For more information about web project development, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • How to get token in Vue and write it into header
  • Example code for token verification based on Vue
  • The ssm project implements user login persistence (token)
  • Detailed explanation of the simple practice of using token authentication in Vue project
  • After successful login verification in Vue, the token is saved, and each request carries and verifies the token operation
  • Vue interceptor handles token expiration

<<:  Dockerfile text file usage example analysis

>>:  Summary of MySQL database like statement wildcard fuzzy query

Recommend

Detailed tutorial on building Gitlab server on CentOS8.1

There is no need to say much about the difference...

100-1% of the content on the website is navigation

Website, (100-1)% of the content is navigation 1....

MySQL 8.0.13 decompression version installation graphic tutorial under Windows

This article shares with you the MySQL 8.0.13 ins...

How to install redis5.0.3 in docker

1. Pull the official 5.0.3 image [root@localhost ...

Design perspective technology is an important capital of design ability

A design soldier asked: "Can I just do pure ...

MySQL GROUP_CONCAT limitation solution

effect: The GROUP_CONCAT function can concatenate...

How to add Nginx proxy configuration to allow only internal IP access

location / { index index.jsp; proxy_next_upstream...

Use iptables and firewalld tools to manage Linux firewall connection rules

Firewall A firewall is a set of rules. When a pac...

Shell script nginx automation script

This script can satisfy the operations of startin...

Docker Compose installation methods in different environments

1. Online installation Currently only tried the L...

JavaScript determines whether the browser is IE

As a front-end developer, I can’t avoid IE’s pitf...