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

How to explain TypeScript generics in a simple way

Table of contents Overview What are Generics Buil...

Common methods of Vue componentization: component value transfer and communication

Related knowledge points Passing values ​​from pa...

A brief discussion on the font settings in web pages

Setting the font for the entire site has always b...

DOM operation table example (DOM creates table)

1. Create a table using HTML tags: Copy code The ...

Vite2.0 Pitfalls

Table of contents Vite project build optimization...

A collection of common uses of HTML meta tags

What is a mata tag The <meta> element provi...

Detailed explanation of Vue custom instructions

Table of contents Vue custom directive Custom dir...

Detailed explanation of the 14 common HTTP status codes returned by the server

HTTP Status Codes The status code is composed of ...

Summary of Form Design Techniques in Web Design

“Inputs should be divided into logical groups so ...

Detailed explanation of the integer data type tinyint in MySQL

Table of contents 1.1Tinyint Type Description 1.2...

IIS 7.5 uses URL Rewrite module to achieve web page redirection

We all know that Apache can easily set rewrites f...

React example of how to get the value of the input box

React multiple ways to get the value of the input...

MySQL account password modification method (summary)

Preface: In the daily use of the database, it is ...