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.
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With