IndominusByte / fastapi-jwt-auth

FastAPI extension that provides JWT Auth support (secure, easy to use, and lightweight)
http://indominusbyte.github.io/fastapi-jwt-auth/
MIT License
644 stars 150 forks source link

Allow using sql for token blacklist #49

Closed SelfhostedPro closed 3 years ago

SelfhostedPro commented 3 years ago

Hey, I was wondering if I'd be able to store blacklist tokens in an sqlite database? I see instructions for redis but I'm already using a db anyways for user management and would like to store them in a table there. If you need any help with this, let me know. I'm happy to contribute.

SelfhostedPro commented 3 years ago

As a note, the reason I'm implementing this is for integrating API keys into my apps so other apps can talk to it easily. If there's a better way than using a jwt token as the API key, I'm all ears.

SelfhostedPro commented 3 years ago

This is possible using something like the following setup: Crud function:

def blacklist_login_token(Authorize, db: Session):
    jti = Authorize.get_raw_jwt()['jti']
    _exp = Authorize.get_raw_jwt()['exp']
    exp = datetime.fromtimestamp(_exp)
    access = TokenBlacklist(jti=jti, expires=exp, revoked=True)
    db.add(access)
    db.commit()
    return

model:

class TokenBlacklist(Base):
    __tablename__ = "jwt_token_blacklist"
    jti = Column(String, primary_key=True, index=True)
    expires = Column(DateTime, nullable=True)
    revoked = Column(Boolean, nullable=False)

main.py:

@AuthJWT.token_in_denylist_loader
def check_if_token_in_denylist(decrypted_token):
    db = SessionLocal()
    jti = decrypted_token['jti']
    entry = db.query(TokenBlacklist).filter(TokenBlacklist.jti == jti).first()
    if entry:
        return True