Search code examples
flaskjwtflask-jwt-extended

How can I make sure a JWT doesn't expire on the user


So I'm able to create aa JWT on login using flask-jwt-extended

I set the expiration to 5 minutes. So I have routes in my VueJS app and when they are called(beforeeach) I make a call to "/api/check" to make sure that the token is valid.

All other API calls are via axios to the backend.

What I'm not understanding that since the cookie is HTTP only I can't check the expiation with javascript...does that mean I have to ping the backend every X minutes along with with every axios call to refresh the cookie then make the actual API call?

Seems like a lot of overhead. Lots of code out there on the nuts and bolts however not much on the actual steps behind the issue I'm having...understanding...

Thanks


Solution

  • You could have the backend automatically refresh the cookie if it is close to expiring without having to do anything extra on the frontend. Something like this (untested)

    @app.after_request
    def refresh_jwt_if_near_expiring(response):
        expires_time = get_raw_jwt().get('exp')
        if not expires_time:
            return response
        
        # Change the time delta based on your app and exp config. 
        target_time = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
        if (target_time > expires_time):
            access_token = create_access_token(identity=get_jwt_identity())
            set_access_cookies(response, access_token)
    
        return response
    

    Then if the user is inactive for X many minutes they get logged out, otherwise they keep getting a new token as needed. If they do wait too long and get logged out, the backend returns a 401 and your frontend can prompt them to log in again.