Reputation: 1
Currently I am using JWT (rest_framework_simplejwt) with Django Rest Framework. The database table containing tokens got bigger and bigger. Is there any way to delete all expired access tokens from the database? I mean all expired Outstanding_Tokens and Blacklisted_Tokens related to them.
I tried running the following command from django shell but didn't work:
from rest_framework_simplejwt.tokens import AccessToken
AccessToken.objects.filter(expires__lt=datetime.now()).delete()
==>
AttributeError: type object 'AccessToken' has no attribute 'objects'
Thanks a lot for your help!
Upvotes: 0
Views: 2318
Reputation: 2769
The short answer:
JWT Tokens are not stored in the database. Thus you do not need to delete any tokens. There isn't any django models declared in simplejwt.
The long answer:
AccessToken
is only an object not a django model. Thus it does not support what you are trying to do. JWT is a type of token that the expiry date and the additional data are encrypted with a passphrase where only server side knows. Frontend will have this encrypted data with user information but cannot read it. Whenever the request is made its way to backend, it's being decrypted and with the information you may authorize user.
JWT tokens are not being stored anywhere. Unless the expiry date not passed the token remains valid. In some cases you want existing tokens to be invalidated. Then you need to store these tokens, if these tokens(blacklist) are used, you need to refuse them. simplejwt
app also provides a blacklist app which handles the blacklist operation. If you are referring to them there are 2 models. Then to delete those you might need to use the following code:
from rest_framework_simplejwt.token_blacklist.models import \
OutstandingToken, BlacklistedToken
BlacklistedToken.objects.filter(token__expires_at__lt=datetime.now()).delete()
OutstandingToken.objects.filter(expires_at__lt=datetime.now()).delete()
Upvotes: 4