Search code examples
pythonflaskjwttoken

how to refresh JWT


I'm a beginer at flask and I wanna secure my app with JWT. I use pyjwt python library. Is it possible to refresh jwt in pyjwt? Lots of information about flask-jwt-extended but nothing about pyjwt.


Solution

  • PyJWT is a Python library which allows you to encode and decode JSON Web Tokens

    This library is not ready for user sessions. You should implement refreshing logic by yourself:

    import jwt
    from datetime import datetime, timedelta, timezone
    
    payload = {"username": "john", "session_id": "abc"}
    
    # add token expiration time (5 seconds):
    payload["exp"] = datetime.now(tz=timezone.utc) + timedelta(seconds=5)
    
    # this token is valid for 5 seconds
    token = jwt.encode(payload, "some_secret_phrase", algorithm="HS256")
    
    # get token data:
    decoded_payload = jwt.decode(token, "some_secret_phrase", algorithms=["HS256"])
    
    # if we run ↑this↑ after 5 seconds jwt.exceptions.ExpiredSignatureError: Signature has expired will be raised
    # in other case we will get decoded data:
    # {'username': 'john', 'session_id': 'abc', 'exp': 1650187206}
    
    # now we should update 'exp' for 5 seconds again
    decoded_payload['exp'] = datetime.now(tz=timezone.utc) + timedelta(seconds=5)
    
    # and generate new token
    new_token = jwt.encode(payload, "some_secret_phrase", algorithm="HS256")
    
    # after receiving this new token client will be able to use it for 5 seconds before another refreshing process
    

    My example is super simple, insecure and just demonstrate how token may be refreshed. You have to use more complicated logic and refresh tokens for real web applications.