【问题标题】:how to refresh access token with refresh token?如何使用刷新令牌刷新访问令牌?
【发布时间】:2020-07-12 21:57:39
【问题描述】:

当访问令牌过期并想用令牌刷新它时遇到问题。我有两种方法,一种显示帐户并使用 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=>.... 然后返回到第一个函数进程返回 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)
})

}

【问题讨论】:

    标签: javascript reactjs jwt token access-token


    【解决方案1】:

    在我看来,refreshToken 函数与您的 login 函数并行运行,因为您不必等到 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,一个不带),这看起来很复杂。

    【讨论】:

      猜你喜欢
      • 2019-06-29
      • 2022-10-31
      • 2014-09-13
      • 2016-09-23
      • 1970-01-01
      • 2020-06-12
      • 1970-01-01
      • 2016-08-13
      • 2012-09-29
      相关资源
      最近更新 更多