3

in my app.py I initialized flask-jwt-extended as follow:

# Setup the Flask-JWT-Extended extension
app.config['RESTPLUS_MASK_SWAGGER'] = False # remove default X-Fields field in swagger
app.config['JWT_SECRET_KEY'] = 'super-secret'  # Change this!
app.config['JWT_BLACKLIST_ENABLED'] = True
app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access', 'refresh']
jwt = JWTManager(app)

then I create token in login with snippet:

            expires = datetime.timedelta(minutes=10)
            access_token = create_access_token(identity=payload['email'], fresh=True, expires_delta=expires)
            refresh_token = create_refresh_token(identity=payload['email'])

strangely if I add decorator @jwt.token_in_blacklist_loader to a certain endpoint I always received "Token has been revoked" error message.

@jwt.token_in_blacklist_loader
@api.route('/')
class UserList(Resource):
    @jwt_required
    @api.doc('list_users')
    @api.marshal_list_with(user)
    def get(self):
        '''Get all users'''
        users = UserApi.query.all()
        return users

As far as I know this decorator is to check whether or not the token is blacklisted and I just create a new token from login, what is the best practice to create a new token & check whether the token is blacklisted or not?

Gerry
  • 101
  • 1
  • 7

2 Answers2

5

From the documentation of flask-jwt-extended:

This decorator sets the callback function that will be called when a protected endpoint is accessed and will check if the JWT has been been revoked. By default, this callback is not used.

HINT: The callback must be a function that takes one argument, which is the decoded JWT (python dictionary), and returns True if the token has been blacklisted (or is otherwise considered revoked), or False otherwise.

The token_in_blacklist_loader decorator use to set the callback function when a protected endpoint is accessed. You should use this decorator on the function that checks your token wether blacklisted or not. The simple example using memory for saving blacklisted tokens:

blacklist = set()
@jwt.token_in_blacklist_loader
def check_if_token_in_blacklist(decrypted_token):
    jti = decrypted_token['jti']
    return jti in blacklist

For further information check the sample here: https://flask-jwt-extended.readthedocs.io/en/stable/blacklist_and_token_revoking/

Nur Faizin
  • 171
  • 6
1

Did you remember to add the newly generated access_token (from the refresh_token) to the Blacklist database? All tokens absent from Blacklist db are assumed to be revoked...

  • 2
    Please turn this into an assertive answer, to avoid that you are instead asking a question. Consider making a conditional answer like "If the problem is ... then the solution is to ...". – Yunnosch Jul 13 '20 at 11:18