Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to check if oauth token is expired or not?

I am accessing web api using oauth token.

Token expires after 1 hour. But I want to add functionality to generate new token when it expires.

I found that in case of expired token it sends StatusCode as unauthorized.

Please let me know if its the only statuscode which tells about expiration of token.

like image 543
Gaurav123 Avatar asked Apr 01 '16 06:04

Gaurav123


Video Answer


2 Answers

Resurrecting this post once again and taking @Lavandysh's solution and pulling in the System.IdentityModel.Tokens.Jwt class; call this method to have an idea if the token is even valid anymore before the request:

    public bool _isEmptyOrInvalid (string token)
    {
        if (string.IsNullOrEmpty(token))
        {
            return true;
        }

        var jwtToken = new JwtSecurityToken(token);
        return (jwtToken == null) || (jwtToken.ValidFrom > DateTime.UtcNow) || (jwtToken.ValidTo < DateTime.UtcNow);
    }
like image 121
vandsh Avatar answered Oct 13 '22 01:10

vandsh


The easiest way is to just try to call the service with it. It will reject it if it is expired and then you can request a new one.

You can also keep the time you received the token and use the expires_in to calculate when it will approximately expire. Then you request a new token before making a new request after the expiration date.

like image 29
Patrick Hofman Avatar answered Oct 13 '22 01:10

Patrick Hofman