ilhank
ilhank

Reputation: 148

Handling access tokens expire time

I am consuming some web API methods in my MVC projects. What I am doing is creating an API handling class. I am planning to get access token in the constructor of this class and then attaching it to my webapihandler object in the constructor again. Then I will consume several API calls which is fine. However, I think I have to control the expire time of the token before every call and if it is expired then I have to create one. I do not know how to check the expiry time of a token.

This is the first time I am dealing with tokens in such a way and any help is appreciated.

Upvotes: 1

Views: 5826

Answers (1)

gMoney
gMoney

Reputation: 235

You want to save the access_token, refresh_token, token_expire_time and last_write in the database. the last_write is the time the access token was created and the token_expire_time should be how long until the access token expires in minutes or seconds for time accuracy.

from there you just compare the (last_write time + token_expire_time ) to the time now.

Remember to always use DateTime.UtcNow when comparing and saving the time in the database or else timezones with throw it off and it wont refresh properly.

Here is an example

Database Class

public class Token
{
    public int Id { get; set; }

    public string AccessToken { get; set; }

    public string RefreshToken { get; set; }

    public DateTime LastWrite { get; set; }

    public int Expiration { get; set; }
}

Function to check refresh:

// call this to get the token before making API call
public static async Task<string> GetAccessToken(Token token)
{
     string accessToken;
     if (token.LastWrite.AddSeconds(token.Expiration) <= DateTime.UtcNow)
     {
        // refresh and update the database with the new tokens/expiration
     }
     else
     {
          accessToken = token.AccessToken;
     }
     return accessToken;
}

Upvotes: 1

Related Questions