简体   繁体   中英

how to refresh access token with refresh token?

I have problem when access token expire and want to refresh it with token. I have two methods, one which shows accounts and use axios post and another one which refresh token.

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
    })
}

Second method is refresh method and I notice in debug that first go to refresh token function and when entered in that function go to .then(res=> .... and after that go back to first function process return axios.post and see that access_token is expired.after that go back to refreshToken() and than set local storage 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)
})

}

It looks to me that the refreshToken function runs parallel to your login function because you do not wait till the refreshToken function is finished. You could try to change the first one to an async function and await the result.

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
    })
}

Maybe it would make more sense stylewise to also use the then syntax instead of async await, but then you would have to specify two paths of execution (one with refreshToken and one without), which seems convoluted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM