Get expire time of OAuth session

You can use DateTimeOffset.FromUnixTimeSeconds:

   var jwtExpValue = long.Parse(principal.Claims.FirstOrDefault(x => x.Type == "exp").Value);
   DateTime expirationTime = DateTimeOffset.FromUnixTimeSeconds(jwtExpValue).DateTime;

Your access token (JWT?) should contain an expiry claim. In JWT it is "exp", which shows the number of seconds since 1970-1-1. In javascript you can get a date from this like this:

new Date(<exp> * 1000);

In .Net / C# you would be able to do the same:

var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return epoch.AddSeconds(<exp>);

Is that what you are looking for? Otherwise let me know. Happy to help :-)


Just to expand on Henrik N.'s answer a little. If you're in C# then you can use JWTSecurityTokenHandler within System.IdentityModel.Tokens.Jwt (Nuget: Install-Package System.IdentityModel.Tokens.Jwt) to read the token and the resulting JwtSecurityToken object gives you some handy properties, one of which is ValidTo which converts the exp claim into a DateTime object for you E.g.:

var tokenString = GetTokenString(); // Arbitrary method to get the token
var handler = new JwtSecurityTokenHandler();
var token = handler.ReadToken(tokenString) as JwtSecurityToken;
var tokenExpiryDate = token.ValidTo;

// If there is no valid `exp` claim then `ValidTo` returns DateTime.MinValue
if(tokenExpiryDate == DateTime.MinValue) throw new Exception("Could not get exp claim from token");

// If the token is in the past then you can't use it
if(tokenExpiryDate < DateTime.UtcNow) throw new Exception($"Token expired on: {tokenExpiryDate}");

// Token is valid