Flask JWT extend validity of token on each request

Viewed 14046

Scenario

A logged in user will have a token expiry of 24 hours. Within that period, all request with @jwt_required decorator will have the current access token's expiry extended by another 24 hours. There is a maximum validity of 168(24 * 7) hours.

It is possible to use access_token and refresh_token.

ret = {
        'access_token': create_access_token(identity=username, fresh=True),
        'refresh_token': create_refresh_token(identity=username)
    }

But that means every API call from my applicatino will be two requests: 1. Actual HTTP Request 2. Refresh the auth token

@app.route('/refresh', methods=['POST'])
@jwt_refresh_token_required
def refresh():
    current_user = get_jwt_identity()
    ret = {
        'access_token': create_access_token(identity=current_user)
    }
    return jsonify(ret), 200

Is there a way to implicitly extend an auth token?

2 Answers
app = Flask(__name__)

app.config["JWT_SECRET_KEY"] = "super-secret"  # Change this!
app.config["JWT_ACCESS_TOKEN_EXPIRES"] = timedelta(hours=1)
app.config["JWT_REFRESH_TOKEN_EXPIRES"] = timedelta(days=30)
jwt = JWTManager(app)

change time according to your requirement

Related