如何使用刷新令牌刷新访问令牌?

时间:2020-04-01 07:54:03

标签: javascript reactjs jwt token access-token

访问令牌过期时,我有问题,想用令牌刷新它。我有两种方法,一种显示帐户并使用axios帖子,另一种刷新令牌。

export const add_account = account=>{
    var token=localStorage.getItem("access_token")
      var decoded=jwt_decode(token);
        var time_exp=decoded.exp;
        if(time_exp<new Date().getTime()/1000) {
            refreshToken();
        }
    return axios.post("http://localhost:5000/accounts",{
        acc_name:account.name,
        acc_pass:account.pass,
        acc_host:account.host,
        acc_description:account.description
   }, {headers: {
    'Authorization': `Bearer ${localStorage.getItem('access_token')}`
        }}).then(res=>{
        return res.data
    })
}

第二种方法是刷新方法,我在调试中注意到首先要刷新令牌功能,然后在该功能中输入 .then(res => ....,然后返回到第一个函数过程,返回axios.post并查看access_token已过期。此后,返回refreshToken()并设置本地存储access_token。

export const refreshToken=()=>{
return axios.post("http://localhost:5000/refresh",null,{headers: {
'Authorization': `Bearer ${localStorage.getItem("refresh_token")}`
    }}).then(res=>{
        localStorage.setItem('access_token',res.data['access_token']);
        return res.data;
}).catch(e=>{
    console.log(e)
})

}

1 个答案:

答案 0 :(得分:1)

在我看来,refreshToken函数与登录函数并行运行,因为您不必等到refreshToken函数完成。您可以尝试将第一个更改为异步功能,然后等待结果。

export const add_account = async account=>{
    var token=localStorage.getItem("access_token")
      var decoded=jwt_decode(token);
        var time_exp=decoded.exp;
        if(time_exp<new Date().getTime()/1000) {
           await refreshToken();
        }

    return axios.post("http://localhost:5000/accounts",{
        acc_name:account.name,
        acc_pass:account.pass,
        acc_host:account.host,
        acc_description:account.description
   }, {headers: {
    'Authorization': `Bearer ${localStorage.getItem('access_token')}`
        }}).then(res=>{
        return res.data
    })
}

也许也可以使用then语法而不是async await在样式上更有意义,但是随后您必须指定两条执行路径(一条带有refreshToken,另一条不带),这似乎很麻烦。