Search code examples
pythonweb2py

Web2py JWT based authentication - refresh token


I am trying to achieve token based authentication, for some REST APIs built on Web2py. I am using version 2.14.6(stable). As mentioned in the documentation, I followed the steps and was able to authenticate and retrieve data from the authentication protected resources using JWT. I have done the following steps:

from gluon.tools import AuthJWT

myjwt = AuthJWT(auth, secret_key='secret', user_param="email")

def login_take_token():
    return myjwt.jwt_token_manager()

@myjwt.allows_jwt()
@auth.requires_login()
def get_my_service():
    my_code

So with this configuration, I am able to get a token when made a call to function "login_take_token" and also get the required data from "get_my_service". Below are the service calls:

/app/controller/login_take_token?email=abc.com&password=abc123

This returns us a token say

/app/controller/get_my_service?_token=<TOKEN_RECEIVED>

This returns us the required expected data on successful login.

My question is, as explained in the web2py docs , if the token is expired than we can use the token and make a call to login_take_token to get a new active token. But this below call does not return any token, but only returns 400 Bad Request, with the output "Token is expired".

/app/controller/login_take_token?_token=<TOKEN_RECEIVED>

How should the call be made with the old token(expired) to get a new token.

Regards


Solution

  • By default, verify_expiration=True, which means you can neither authenticate nor refresh a token if the current token is already expired. If you want to allow refresh with an expired token, you can conditionally change verify_expiration when a refresh is requested (while still checking expiration for authentication):

    def login_take_token():
        myjwt.verify_expiration = False # This will allow refresh with an expired token.
        return myjwt.jwt_token_manager()
    

    Note, there is an additional argument, refresh_expiration_delta, which defaults to 60 * 60 (i.e., 60 minutes). If the time since the original token was issued is greater than refresh_expiration_delta, the refresh request will be denied and it will be necessary to re-authenticate to get a new token.

    So, with the default expiration of 5 minutes and the default refresh expiration delta of 60 minutes, you can get up to 12 refresh tokens before you will be forced to re-authenticate (assuming you request a refresh exactly every 5 minutes). You can, of course, set refresh_expiration_delta to a higher value if you want to extend the period for issuing refresh tokens.