How To Revoke a JWT Token ? #3580
-
API URL : Request Headers
Request Body {
"token": "JWT_TOKEN_HERE"
}Response For success {
"success": true,
"msg": "Token revoked"
}Response for unknown token {
"success": false,
"msg": "User is not logged on"
}The Login code : @router.post("/users/login")
def login(request: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(configuration.get_db)):
user: schemas.User = db.query(models.User).filter(
models.User.email == request.username).first()
if not user:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail=f"Invalid Credentials")
if not Hash.verify(user.password, request.password):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail=f"Incorrect password")
access_token = create_access_token(
data={"sub": user.email}
)
# generate JWT token and return
return {"access_token": access_token, "token_type": "bearer"} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
|
you can set the sub as None and issue a new token. |
Beta Was this translation helpful? Give feedback.
-
|
If you want to securely revoke tokens, you have to maintain a 'blacklist' in some cache (in-memory, redis). By doing so, you can check if the token was blacklisted before trying to validate it. To avoid this problem altogether, don't put any 'mutable' data in the JWT (ex. user roles). Put that in a server side session instead, where you can modify it and the changes would be instant. Ex. if you gave a user 'admin' access via JWT, then when you revoke that access, the old JWT is going to still work until it expires. Solution would be to blacklist JWTs. But when using server side sessions, you can simply change their role that's cached server-side. No need to revoke JWT cause it only contains their user_id in the sub for example. In case you really want to revoke it, you have to blacklist on top of that. Check this out btw: |
Beta Was this translation helpful? Give feedback.
you can set the sub as None and issue a new token.
It'll same as token expired or user is not logged in.