brett
brett

Reputation: 351

Managed Identity token checking expiration

I have a Azure Managed Identity Access token that I am trying to cache. I am unsure about the correct way to check if the token is expired. I am caching the expires_on property, which Micrososft explains as "The timespan when the access token expires. The date is represented as the number of seconds from "1970-01-01T0:0:0Z UTC."

Does this mean the expires_on property from the token is already in Utc format? I am not sure it's ok to check date time in Utc and compare it directly with it. My huge fear is that if my logic is wrong I am going to return an expired token over and over - breaking the app.

My current check is:

var tokenExp = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
tokenExp = tokenExp.AddSeconds(Int32.Parse(cachedExpiresOn));  // cachedExpiresOn is "1588350330"

if (tokenExp > DateTime.UtcNow)
{
  // return cached token
} else 
{
  // fetch token and cache
}

Upvotes: 0

Views: 1355

Answers (1)

Joy Wang
Joy Wang

Reputation: 42043

Per my test, your solution should work.

But actually you could use the code below to check it directly.

var jwthandler = new JwtSecurityTokenHandler();
var jwttoken = jwthandler.ReadToken("<your access_token>");
var expDate = jwttoken.ValidTo;
if (expDate < DateTime.UtcNow)
     Console.WriteLine("Expired");
else
     Console.WriteLine("Not expired");

enter image description here

Upvotes: 2

Related Questions