how to check Microsoft graph api Access token expiresOn

Subasri 25 Reputation points
2023-12-11T08:42:30.04+00:00
static bool IsTokenExpired(string accessToken)
{
    var tokenHandler = new JwtSecurityTokenHandler();
    var jsonToken = tokenHandler.ReadToken(accessToken) as JwtSecurityToken;

    if (jsonToken == null)
    {
        // Invalid token format
        return true;
    }

    DateTime expiresOn = jsonToken.ValidTo;

    if (expiresOn < DateTime.UtcNow)
    {
        // Token has expired
        MessageBox.Show("Token has Expired");
        return true;
    }

    // Token is still valid
    return false;
}
Microsoft Security Microsoft Graph
Developer technologies C#
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Sourabh Gupta 800 Reputation points Microsoft External Staff
    2024-01-13T17:18:09.8633333+00:00

    Hi Subasri, Thanks for reaching out.

    The simplest approach is to use the MSAL SDK and let it handle the cache/refresh of tokens. Alternatively, I would recommend simply trying to acquire a token, and upon failure (typically AADSTS700020) initiate a user action to re-acquire a token. The reasoning is that tokens can become invalid due to circumstances beyond your control (certificate revocation, conditional access policy, multi-factor requirement). Simply checking the token expiration does not guarantee a successful result if you use the token. However, The default lifetime of an access token is variable. When issued, the Microsoft identity platform assigns a random value ranging between 60-90 minutes (75 minutes on average) as the default lifetime of an access token. while access token is expired you can get new access token by this Microsoft API.

    data = {
       "grant_type": "refresh_token",
       "client_id": "Your Client_id",
       "client_secret": "Your Client_secret",
       "refresh_token": refresh_token
    }
    response = requests.post('https://login.microsoftonline.com/consumers/oauth2/v2.0/token', data)
    
    

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    2 people found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.