Have a refresh_token
Use Store optimization to encapsulate local storage tokens & TOKEN expiration handling
No refresh_token
Active intervention of Token invalidation
If the back-end interface is not doing the processing, active intervention is an easy way to do it
In the request interceptor, the timestamp is used to determine whether a timeout has occurred for logout and other operations
1. Byjs-cookie
Access token and timestamp
src/utils/auth.js
import Cookies from 'js-cookie'
const TokenKey = 'hr-jean-token' // Create a unique key--token
const TimeKey = 'hr-jean-time' // Set a unique key-- timestamp
export function getToken() {
return Cookies.get(TokenKey)
}
export function setToken(token) {
return Cookies.set(TokenKey, token)
}
export function removeToken() {
return Cookies.remove(TokenKey)
}
// Access timestamp
export function getTimeStamp() {
return Cookies.get(TimeKey)
}
export function setTimeStamp() {
// Save to the present time
return Cookies.set(TimeKey, Date.now())
}
Copy the code
2. Click login and save the token and timestamp
src/store/modules/user.js
// Defining the login action also requires parameters that are passed when the action is called
// Async is an asynchronous function -> is essentially a promise
async login(context, data) {
// The result is the token after the response interceptor
const result = await login(data) // This is actually a promise result
// Axios adds a layer of data by default
// Indicates that the login interface was successfully called, which means that your username and password are correct
// Now there is a user token
// Actions Change state must be done via mutations
context.commit('setToken', result)
// Write the timestamp
setTimeStamp() // Write the current latest time to the cache
}
Copy the code
3. Perform timeout interception in axios request interceptor
import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Message } from 'element-ui'
import { getTimeStamp } from '@/utils/auth'
const TimeOut = 3600 // Define the timeout
const service = axios.create({
// When NPM run dev =>.evn.development => / API => cross-domain proxy
baseURL: process.env.VUE_APP_BASE_API, // npm run dev => /api npm run build => /prod-api
timeout: 5000 // Set the timeout period
})
// Request interceptor
service.interceptors.request.use(config= > {
// config is the requested configuration information
/ / into the token
if (store.getters.token) {
// It is only necessary to check if the timestamp times out if there is a token
if (IsCheckTimeOut()) {
// If it is true, it is expired
// The token is not used because it timed out
store.dispatch('user/logout') // Log out
// Jump to the login page
router.push('/login')
return Promise.reject(new Error('Token timed out'))
}
config.headers['Authorization'] = `Bearer ${store.getters.token}`
}
return config // It must be returned
}, error= > {
return Promise.reject(error) }) ... Omit other code// Whether timeout occurs
// Whether the timeout logic (current time - time in cache) is greater than the time difference
function IsCheckTimeOut() {
var currentTime = Date.now() // The current timestamp
var timeStamp = getTimeStamp() // Cache timestamp
return (currentTime - timeStamp) / 1000 > TimeOut
}
export default service
Copy the code
Passive handling of Token invalidation
There’s active processing and there’s passive processing, where the back end tells us we’ve timed out, and we’re forced to react, and if the back end interface doesn’t process, active intervention is an easy way to do that
The token timeout error code is 10002
1. In axiosThe response
In interceptorerror
Do timeout intercept processing
src/utils/request.js
error => {
// Error message response object
// Check whether the token expires
/ / way
// if (error.response && error.response.status === 401) {}
2 / / way
if (error.response && error.response.data && error.response.data.code === 10002) {
// When the value equals 10002, the backend tells me that the token has timed out
store.dispatch('user/logout') // Logout action deletes the token
router.push('/login')}else {
Message.error(error.message) // An error message is displayed
}
return Promise.reject(error)
}
Copy the code