axios拦截器中判断token是否过期并处理登录状态

前言

网上搜索到的常见处理方式是在axios响应拦截器中获取401状态码后,使用refresh token发送请求,获取新的token。考虑到设置的refresh token也会过期,以及为了减少请求错误,因此在请求拦截器中对token是否过期进行预先判断。

思路

首先判断access token是否过期,未过期则添加到headers。如果access已过期,再判断refresh token是否过期,未过期则发送请求获取新的access token,过期则退出登录。

解决方案

import dayjs from "dayjs";
import jwt_decode from "jwt-decode";
import store from "@/store";

const storage = localStorage;

const axiosInstance = axios.create({
    baseURL: 'http://localhost:8000',
    withCredentials: true,
});

axiosInstance.interceptors.request.use(
    async config => {
        const token = store.state.auth.token;
        const isAccessExpired = token ? dayjs.unix(jwt_decode(token).exp).diff(dayjs()) < 1 : true;
        const refresh = storage.getItem('refresh.myBlog');
        const isRefreshExpired = refresh ? dayjs.unix(jwt_decode(refresh).exp).diff(dayjs()) < 1 : true;

        if (token !== null) {
            if (!isAccessExpired) {
                // token 未过期,添加到 headers
                config.headers.Authorization = `Bearer ${token}`
            } else {
                // token 过期,判断 refresh 是否过期
                if (!isRefreshExpired) {
                    // refresh 未过期,获取新的 access
                    const response = await axios.post(
                        `${baseURL}/api/token/refresh/`,
                        {refresh: refresh}
                    )
                    store.commit('auth/SET_TOKEN', response);
                    config.headers.Authorization = `Bearer ${store.state.auth.token}`
                } else {
                    // refresh 过期,退出登录
                    store.commit('auth/REMOVE_TOKEN'); 
                }
            }
        }

        return config;
    },
    error => {
        return Promise.reject(error.response);
    }
)

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值