Benjo
Benjo

Reputation: 41

@JWT_Required decorator Exception Handling

I am using an auth API using JWT and it works great. This API is being used to authorize users for my web app. For this to work, I store JWT access_tokens as cookie manually with Flask. I secure my resource with @JWT_required decorator and if I try to access a secure resource with a valid token everything works fine. However, if the access token is missing or invalid/expired I get a JSON saying:

{
      "message": "Missing cookie \"access_token_cookie\""
}

This is obvious the right message but rather then showing a JSON I want to redirect to the appropriate statuscode error page that is provided by Flask - in this case 401.

@app.route('/dashbord')
@jwt_required
def dashbord():
    return render_template('dashbord.html', title='Home')

My goal is to redirect to appropriate error page 404, 403, 401 if anything is wrong with the access token.

THE SOLUTION:

@jwt.unauthorized_loader
def my_invalid_token_callback(expired_token):
    return render_template('401.html', title='Home')

Upvotes: 2

Views: 3457

Answers (2)

Nathan Wailes
Nathan Wailes

Reputation: 12222

Here's the solution Benjo posted at the bottom of his question:

@jwt.unauthorized_loader
def my_invalid_token_callback(expired_token):
    return render_template('401.html', title='Home')

Upvotes: 1

vimalloc
vimalloc

Reputation: 4167

Here is the documentation for changing the results for invalid tokens: https://flask-jwt-extended.readthedocs.io/en/stable/changing_default_behavior.html#changing-callback-functions

Upvotes: 0

Related Questions