I've been using flask-jwt-extended
for my application and one of the problems I had was logging a session out and making sure the token is not usable anymore.
I've based my solution on the Blacklist and Token Revoking documentation page with a custom RevokedToken
model:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class RevokedToken(db.Model):
"""
Model is used as a storage to keep invalid/revoked tokens.
Currently used for log out functionality.
"""
__tablename__ = 'revoked_tokens'
id = db.Column(db.Integer, primary_key=True)
jti = db.Column(db.String(120))
@classmethod
def is_jti_blacklisted(cls, jti):
query = cls.query.filter_by(jti=jti).first()
return bool(query)
Logout resource:
class LogoutResource(Resource):
@jwt_required
def post(self):
jti = get_raw_jwt()['jti']
# invalidate access token
revoked_token = RevokedToken(jti=jti)
session.add(revoked_token)
session.commit()
return {}, 200
And the token_in_blacklist_loader()
jwt
function:
from flask_jwt_extended import JWTManager
jwt = JWTManager(app)
@jwt.token_in_blacklist_loader
def check_if_token_in_blacklist(decrypted_token):
jti = decrypted_token['jti']
return models.RevokedToken.is_jti_blacklisted(jti)
This looks straightforward enough, but, as we are talking about authentication, I thought I would ask if anyone sees any flaws or potential improvements to this approach?