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

how to refresh access token with refresh token?

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

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=>..然后回到第一个函数过程 return axios.post 并看到 access_token 是 expired.after 回到 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)
})

}

在我看来,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,一条不带),这看起来很复杂。