Cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

How often should I refresh tokens?

ANSWERED

I am developing a clock face which requests WebAPI data through a companion app. I can refresh OAuth tokens manually, by calling a function in the companion App.

What is the recommended practice when it comes to refreshing tokens automatically? I mean, should I do it every X hours? Before every request to the WebAPI? After?

 

Also, does a token refresh count against the rate limit?

 

Thanks!

Best Answer
0 Votes
1 BEST ANSWER

Accepted Solutions

So, it turns out I found an answer to my question, which I've put to test since yesterday and it is working fine:

 

Whenever I get new OAuth data, I save it using a function that also saves the timestamp for when it was acquired:

function saveOauthData(oauthData) {
  settingsStorage.setItem("oauth", oauthData);
  settingsStorage.setItem("oauthtimestamp", Date.now());
}

 

Then, before making requests, I use a function to evaluate if what I have stored is expired. When it is, I proceed to refresh tokens before doing the request to the WebAPI:

function isTokenValid() {

  let now = parseInt(Date.now()/1000);
  let oauthtimestamp = parseInt(Number(settingsStorage.getItem("oauthtimestamp"))/1000) || 0;
  let expiresin = JSON.parse(settingsStorage.getItem("oauth")).expires_in || 0;
  let secondsleft = expiresin-(now-oauthtimestamp);
  
  if (secondsleft <= 0) {
    console.log ("The access_token has expired " + secondsleft*-1 + " seconds ago.");
    return false;
  }

  console.log ("The access_token is still valid. " + secondsleft + " seconds left.");
  return true;

}

 

View best answer in original post

Best Answer
0 Votes
1 REPLY 1

So, it turns out I found an answer to my question, which I've put to test since yesterday and it is working fine:

 

Whenever I get new OAuth data, I save it using a function that also saves the timestamp for when it was acquired:

function saveOauthData(oauthData) {
  settingsStorage.setItem("oauth", oauthData);
  settingsStorage.setItem("oauthtimestamp", Date.now());
}

 

Then, before making requests, I use a function to evaluate if what I have stored is expired. When it is, I proceed to refresh tokens before doing the request to the WebAPI:

function isTokenValid() {

  let now = parseInt(Date.now()/1000);
  let oauthtimestamp = parseInt(Number(settingsStorage.getItem("oauthtimestamp"))/1000) || 0;
  let expiresin = JSON.parse(settingsStorage.getItem("oauth")).expires_in || 0;
  let secondsleft = expiresin-(now-oauthtimestamp);
  
  if (secondsleft <= 0) {
    console.log ("The access_token has expired " + secondsleft*-1 + " seconds ago.");
    return false;
  }

  console.log ("The access_token is still valid. " + secondsleft + " seconds left.");
  return true;

}

 

Best Answer
0 Votes