如果令牌已过期则注销 [英] Logout if token is expired

查看:124
本文介绍了如果令牌已过期则注销的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个由许多API请求组成的React应用程序.该应用程序的结构是

I'm working on a react application that consists of many API requests. The structure of the application is

登录时,我收到响应令牌,并将令牌保存在本地存储中以供其他API请求使用.

When logging in, I'm receiving a token on response and I'm saving the token in my local storage to be used in other API requests.

此令牌每30分钟过期一次,如果我在30分钟后发出API请求,则请求中的状态为401.我正在使用这种401状态注销并清除本地存储中的令牌数据.

This token is expired every 30 minutes and if I do an API request after 30 minutes, I'm receiving a status of 401 in my request. I'm using this 401 status to do my logging out and clearing token data in local storage.

示例请求

export function stationDailyUsage(data) {
    return dispatch => {
        dispatch(dailyUsageLoading());
        axios.get(`${API_URL}/Dashboard/DailyUsage?type=${data.type}&date=${data.date}`, {
            headers: {
                'Authorization': `Bearer ${token}`
            },
        })
            .then(res => {
                if (res.data.success === true) {
                    dispatch(dailyUsageSuccess(res.data));
                } else {
                    console.log("error");
                }
            })
            .catch(function (error) {
                if(error.response.status === 401){
                    dispatch(logout());
                }
              });
    }
}

所以要以这种方式注销,我必须对我使用的每个API(大约40个API)进行此检查.这是遵循的最佳方法,还是有一种更好的注销方法?我已经读过关于axios interceptors的信息,但是不清楚如何在我的系统中实现它.任何帮助将不胜感激.

So to logout this way I have to do this check for every API I use (Around 40 APIs ). Is this the best approach to follow or is there a better way to handle the logout. I've read about axios interceptors but was not clear about how to implement it in my system. Any help is greatly appreciated.

推荐答案

将此代码放在项目的初始化或加载部分中,然后运行一次 那么每次您调用axios时,此代码都会检查错误

Put this code in your project initialize or loading section, and run it once then every time you call axios this code will check errors

在此处更改变量并使用它

Change your variable here and use it

  // Add a request interceptor
  axios.interceptors.request.use((config) => {
    let token = localStorage.getItem("token");
    if (token) {
      config.headers.credentials = 'include';
      config.headers.Authorization = `Bearer ${token}`;
      config.headers['Access-Control-Allow-Origin'] = '*';
      config.headers['Content-Type'] = 'application/json';
    }

    return config;
  }, (error) => {
    alert('interceptor request has error');
    return Promise.reject(error);
  });

  // Add a response interceptor
  axios.interceptors.response.use((response) => {
    return response;
  }, (error) => {

    if (error.response && error.response.data && error.response.data.error &&
      (error.response.data.session === false || error.response.data.session === "false")) {
      localStorage.removeItem("userId"); // <-- add your var
      window.location = "/";   // <-- add your path
    }
    else if (error.response && error.response.data && error.response.data.error && error.response.data.error.message) {
      toastMessage(error.response.data.error.message, 1);
    }
    else
      if (error.response && error.response.status === 401) {
        localStorage.removeItem("userId"); // <-- add your var
        window.location = "/";  // <-- add your path
      } else
        return Promise.reject(error);
  });

这篇关于如果令牌已过期则注销的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆