fastapi-jwt-auth icon indicating copy to clipboard operation
fastapi-jwt-auth copied to clipboard

Revoke both access and refresh token on single api call

Open kounelios13 opened this issue 4 years ago • 2 comments

Hello . I am trying to implement a route for logging out a user . When a user logs out I want to revoke their access token and their refresh tokens. From the documentation thought the only way I see is this

1 endpoint for revoking the access token

1 endpoint for revoking refresh tokens

Is there anyway that I can use both tokens at the same request to do this without doing 2 separate api calls?

kounelios13 avatar Apr 01 '22 09:04 kounelios13

I'm trying to figure out the same thing. You can only have one Authorization header per request, so you can only send the Access or the Refresh token, not both. So I think that means that you need to keep track of every single token (jti) you issue. So you could make the logout method accept any valid token, then it would look up in the DB for all the other tokens issued for that user and add them all to the denylist. This would be like a super-logout, log out of all sessions across even from multiple devices. Or you could remember each access,refresh pair and deny both when provided with either.

EnigmaCurry avatar Apr 13 '22 01:04 EnigmaCurry

Oh if you switch to using JWT cookies (https://indominusbyte.github.io/fastapi-jwt-auth/usage/jwt-in-cookies/) then it sends both the access_token_cookie and the refresh_token_cookie

So I think this should work:

from fastapi import Cookie

...

@router.post("/logout")
def logout(
    Authorize: AuthJWT = Depends(),
    access_token_cookie: str = Cookie(None),
    refresh_token_cookie: str = Cookie(None),
):
    Authorize.jwt_required()
    access_jti = Authorize.get_jti(access_token_cookie)
    refresh_jti = Authorize.get_jti(refresh_token_cookie)
    denylist.add(access_jti)
    denylist.add(refresh_jti)
    Authorize.unset_jwt_cookies()
    return {"detail": "Successfully logged out"}

EnigmaCurry avatar Apr 13 '22 01:04 EnigmaCurry