How to convert the expires token to a date

Asked

Viewed 36 times

-2

Hello, I am starting my walk with Python and JWT, I am authenticating myself in an external API and I have as return the Token and the "expires_in", however the value comes in a format I need to convert to date and so find out when my Token will expire to be able to renew it. how can I convert the value below to a valid date using Python.

  "expires_in": 1209599

1 answer

1


The key expires_in is not a "Registered Claim", I mean, there is no standardization and you need to find out who generated this number to know what it means. Below I first explain the standard JWT date values and then create an example if this number is the number of seconds after created until the token expires.


If you check the RFC7519 that formalizes the JWT you will see in Session 4.1 "Registered Claims" that the Claims iat (issued at), exp (expiration time) and nbf (not before) are data of the type NumericDate.

To understand what the guy is NumericDate just see at the end of sitting 2 of the same document:

A JSON Numeric value Representing the number of Seconds from 1970-01-01T00:00:00Z UTC until the specified UTC date/time.

Free translation:

A numeric JSON value representing the number of seconds since 1970-01-01T00:00:00Z UTC to specified date/time.

I mean, it’s a number of seconds since Unix Epoch and can be calculated using the datetime.utcfromtimestamp:

from datetime import datetime

datetime.utcfromtimestamp(1622950200)
# datetime.datetime(2021, 6, 6, 3, 30)

Using the above function for the value 1209599 that you use in your example will give 1970-01-14 23:59:59 UTC.. then your example value is not the standard normally used by JWT. If this number represents the amount of seconds from a given time (in this case 13 days 23:59:59 timedelta and validate the token:

from datetime import datetime, timedelta

expires_in = 1209599
initial_datetime = datetime(2021, 6, 6)  # valor apenas para exemplo
expire_datetime = initial_datetime + timedelta(seconds=expires_in)
# datetime.datetime(2021, 6, 19, 23, 59, 59)

# agora bastaria testar se `expire_datetime` já passou
if expire_datetime > datetime.now():
    # Token expirado

Remembering that this example is to understand how to do this at hand, but the JWT standard already has the club iat to inform the datetime that the token was created and the club exp to say which datetime expires the token. So you could use some library already ready for this and make these checks automatically for you.

  • Hello Fernando, Thank you so much for the help, I discovered here that the value I reported was actually time in seconds, which gives about 13 days, I will use the code that passed from example to validate whether my token has expired or not.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.