3
votes

I'm using Simple JWT to use JWT tokens in my Django rest API. It works great but I would like to be able to blacklist a token when a user logs out. In the documentation, it is said:

If the blacklist app is detected in INSTALLED_APPS, Simple JWT will add any generated refresh or sliding tokens to a list of outstanding tokens. It will also check that any refresh or sliding token does not appear in a blacklist of tokens before it considers it as valid. The Simple JWT blacklist app implements its outstanding and blacklisted token lists using two models: OutstandingToken and BlacklistedToken. Model admins are defined for both of these models. To add a token to the blacklist, find its corresponding OutstandingToken record in the admin and use the admin again to create a BlacklistedToken record that points to the OutstandingToken record.

However, I didn't find any code example and I'm not sure how this should be implemented. An example would be greatly appreciated.

2
Have you got any solution?bharatk
Unfortunately noqwertzuiop
I keep getting TokenError(_('Token is invalid or expired')) with token.blacklist() utility as mentioned on the docs.Jay Modi
@qwertzuiop token_blacklist is only blacklisting refresh tokens. I am not able to find a way to blacklist jwt access token as well.DHS

2 Answers

1
votes

Simple JWT only blacklists refresh tokens. This can be done by setting:


INSTALLED_APPS = (
    ...
    'rest_framework_simplejwt.token_blacklist',
    ...
}

and then running migrate.

So, i would suggest, inorder to logout user:

  • Delete both, refresh & access tokens from the client. Also, keep access token expiry as short as possible.

  • Black-list the refresh token by creating an api end-point.

    urls.py

    path('/api/logout', views.BlacklistRefreshView.as_view(), name="logout"),
    

    views.py

    from rest_framework_simplejwt.tokens import RefreshToken
    
    class BlacklistRefreshView(APIView):
        def post(self, request)
            token = RefreshToken(request.data.get('refresh'))
            token.blacklist()
            return Response("Success")
    

This will make sure that the refresh token cannot be used again to generate a new token (if at all someone has acquired it). Also, since access token has short life, it will be invalidated soon hopefully.

0
votes

I was getting the same error:

TokenError(_('Token is invalid or expired'))

because of passing the access token in:

token = RefreshToken(access_token)

while I should pass in the refresh token.