I know this is an old post, but there is a more direct way. If you decode the token from Base64 format you can see what the expiration date is, then you can compare it with the date right now.
If you want to check if this method works you can use this website to decode the token.
Now, in C# you run against some difficulties since the token contains '.' that cannot be decoded and if you only take out the middle part between the two points the length becomes invalid (it should always be a multitude of 4). To make the middle part have a correct length you can add '=' signs until it is a multitude of 4.
In the end I compare the date with the current dat plus a minute. Because I don't want a token that will expire in a second to be considered valid. You might want to adjust that time to suit your purposes.
So here's my code:
/***
* Check if the string token is expired by decoding it from the Base64 string
* Some adjustements to the string are necessairy since C# can only decode certain strings.
* It cannot handle '.' and requires a string has a length that is a multitude of 4.
* The information we are interrested in is found between the dots.
*
* The token that is given as a parameter should have approximately the following structure:
* ddddddddddddddddddddd.ddddddddddddddddddddddddddddddddddddd.dddddddddddddddddddddddddddd
* And should be a valid Oauth token that may or may not be expired
*/
public static bool isExpired(String token)
{
if (token == null || ("").Equals(token))
{
return true;
}
/***
* Make string valid for FromBase64String
* FromBase64String cannot accept '.' characters and only accepts stringth whose length is a multitude of 4
* If the string doesn't have the correct length trailing padding '=' characters should be added.
*/
int indexOfFirstPoint = token.IndexOf('.') + 1;
String toDecode = token.Substring(indexOfFirstPoint, token.LastIndexOf('.') - indexOfFirstPoint);
while (toDecode.Length % 4 != 0)
{
toDecode += '=';
}
//Decode the string
string decodedString = Encoding.ASCII.GetString(Convert.FromBase64String(toDecode));
//Get the "exp" part of the string
String beginning = "\"exp\":\"";
int startPosition = decodedString.LastIndexOf(beginning) + beginning.Length;
decodedString = decodedString.Substring(startPosition);
int endPosition = decodedString.IndexOf("\"");
decodedString = decodedString.Substring(0, endPosition);
long timestamp = Convert.ToInt64(decodedString);
DateTime date = new DateTime(1970, 1, 1).AddMilliseconds(timestamp);
DateTime compareTo = DateTime.Now.AddMinutes(1);
int result = DateTime.Compare(date, compareTo);
return result < 0;
}