为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕田峪4524236 2022-06-09 19:10:12
当访问令牌过期并想用令牌刷新它时出现问题。我有两种方法,一种显示帐户并使用 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)})
查看完整描述

1 回答

?
凤凰求蛊

TA贡献1825条经验 获得超4个赞

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


查看完整回答
反对 回复 2022-06-09
  • 1 回答
  • 0 关注
  • 496 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号