Get expire time of OAuth session

23,921

Solution 1

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 :-)

Solution 2

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

Solution 3

You can use DateTimeOffset.FromUnixTimeSeconds:

   var jwtExpValue = long.Parse(principal.Claims.FirstOrDefault(x => x.Type == "exp").Value);
   DateTime expirationTime = DateTimeOffset.FromUnixTimeSeconds(jwtExpValue).DateTime;
Share:
23,921
Nando
Author by

Nando

Updated on September 17, 2020

Comments

  • Nando
    Nando over 3 years

    To grant or revoke access to my webapis, I use OAuth password- and tokenrefreshworkflow.

    If I understand everything correctly the workflow should be something like this:

    1. Authenticate with username / password / client id
    2. Retrieve accestoken, refreshtoken and expire date
    3. Start timeout in client to refresh your token after expired token time
    4. Go on with bullet 2 -> and so on..

    The progress above works fine so far. My problem is, that I don't get the expire time out of the users principle after the authentication request. So if I work with stateles webclients, I need to renew my token every request to retrieve a new expire date, even if the users token is valid :/

    What I want is something like a /api/session/information service, that provides general information about the current session of an authenticated user.

    How do I retrieve my expire date =)

    [HttpGet]
    [ActionName("information")]
    public HttpResponseMessage Information(BaseRequest request)
    {
    
        var p = Request.GetRequestContext().Principal;
    
        /* here i need help =) */
    }
    
  • Nando
    Nando about 10 years
    So if I understand you correctly henrik, I need to store the expiry date in a claim and calc the time difs by hand? There is no way Oauth is telling me, how long my token is valid?
  • Henrik N.
    Henrik N. about 10 years
    Yes, in most applications consuming OAuth2 tokens the EXP is required. So if you have access to your token, you know how long it lives. Since the token is the only authentication/authorization you normally send to an endpoint, this info must be present, but you could also return at as a "bonus info" to the client requesting the token. Sort of "Expires in 20 minutes".
  • Henrik N.
    Henrik N. about 10 years
    For server side I can very much recommend the JWTSecurityTokenHandler from Microsoft (NuGet).
  • DanielV
    DanielV over 4 years
    is it possible to read the token's expiry date without its secret?
  • Quan
    Quan almost 4 years
    FYI, in version 6.7.1 of System.IdentityModel.Tokens.Jwt, we may call handler.ReadJwtToken(tokenString) without the need to cast to JwtSecurityToken.