I wrote a django that uses the TokenAuthentication verification of the django rest framework. When logging out, delete the previous token and recreate the token. Now I want to use django_cron to achieve token expiration and log out.How do I get current user information in Django Cron?
Asked
Active
Viewed 751 times
0
-
I propose using [simple-jwt](https://www.django-rest-framework.org/api-guide/authentication/#json-web-token-authentication). It offers expiration by default and you can add tokens to a blacklist after expiring. [settings are](https://django-rest-framework-simplejwt.readthedocs.io/en/latest/settings.html#settings) – Klim Bim Nov 24 '21 at 08:09
-
I know JWT and other ways to make token expire. If I want to use TokenAuthentication of django rest framework and use django_cron to realize token expiration and log in again, can you teach me? – Lee Nov 24 '21 at 08:16
1 Answers
0
you can follow this one https://django-cron.readthedocs.io/en/latest/installation.html and inside
from rest_framework.authtoken.models import Token
from datetime import timedelta, datetime
class MyCronJob(CronJobBase):
RUN_EVERY_MINS = 120 # every 2 hours
Expiration = timedelta(days=1) # whate ever you want or get from settings.py
now = datetime.now()
schedule = Schedule(run_every_mins=RUN_EVERY_MINS)
code = 'my_app.my_cron_job' # a unique code
def do(self):
tokens = Token.objects.filter(created__lt=now-Expiration)
# now to expires it you need to delete it
tokens.delete()
this just idea how to work with you

Mohamed Beltagy
- 593
- 4
- 8
-
I have read this document, but I don’t know how to get the information of the currently logged in user here,can you touch me? – Lee Nov 24 '21 at 09:46
-
# logout class LogoutView(APIView): # permission_classes permission_classes = [IsAuthenticated] def delete(self, request, *args, **kwargs): Token.objects.filter(user=request.user).delete() Token.objects.get_or_create(user=request.user) – Lee Nov 24 '21 at 09:52
-
to be clear what are you want, are you want to check every user separately so as to delete the token automatically??? – Mohamed Beltagy Nov 24 '21 at 10:43
-
-
as example you can get token from user and try to get it from db if found check expiration – Mohamed Beltagy Nov 24 '21 at 10:44
-
I want to know how to use django_cron to get the current user's information or get the token. – Lee Nov 25 '21 at 01:32