1

I want to determine whether a JWT access token is valid or not by comparing its exp time with the current time. Now, the type of exp is string and of 10 digits like 1613576582. How do I compare with the current time as in datetime.datetime.now().time()?

I tried doing this:

import jwt
import datetime
from django.conf import settings

access_token = request.COOKIES.get('access')
if access_token:
    access_token = request.COOKIES.get('access')
    key = settings.SECRET_KEY
    decoded_access_token = jwt.decode(access_token, key, algorithms=["HS256"])    # not working in login
    current_time = datetime.datetime.now().time()
    token_exp_time = decoded_access_token['exp']
    if token_exp_time < current_time:
        print('expired')

But it's saying:

TypeError: '<' not supported between instances of 'int' and 'datetime.time'

But again the output of datetime.datetime.now().time() is 21:11:10.024584. So how do I compare it with the int format of access token exp?

forest
  • 1,312
  • 3
  • 20
  • 47
  • 1
    you either convert the `exp`, which is UNIX epoch time, to a timestamp or the current time to UNIX epoch time (seconds since 1970-1-1 00:00:00 UTC), see: https://stackoverflow.com/questions/6999726/how-can-i-convert-a-datetime-object-to-milliseconds-since-epoch-unix-time-in-p – jps Feb 17 '21 at 16:15
  • Got it working with the second answer in that link. – forest Feb 17 '21 at 16:53

1 Answers1

3

pyjwt checks if it has expired for you when you decode, read the documentation here.

As taken from the documentation, you just need to catch the jwt.ExpiredSignatureError and do whatever you need to do there:

try:
    jwt.decode(access_token, key, algorithms=["HS256"])
except jwt.ExpiredSignatureError:
    # Signature has expired
    print("expired")
Jason Rebelo Neves
  • 1,131
  • 10
  • 20