title: Django Expire token Authentication
body: <p>I am working on expiring a django Token for this I am following this <a href="https://medium.com/@yerkebulan199/django-rest-framework-drf-token-authentication-with-expires-in-a05c1d2b7e05" rel="nofollow noreferrer">https://medium.com/@yerkebulan199/django-rest-framework-drf-token-authentication-with-expires-in-a05c1d2b7e05</a></p>
  <p>and my accounts/authentication.py file is like</p>
  <pre><code>from rest_framework.authentication import TokenAuthentication
  from rest_framework.authtoken.models import Token
  from rest_framework.exceptions import AuthenticationFailed
  
  from datetime import timedelta
  from django.utils import timezone
  from django.conf import settings
  
  
  # this return left time
  def expires_in(token):
      time_elapsed = timezone.now() - token.created
      left_time = timedelta(seconds=settings.TOKEN_EXPIRED_AFTER_SECONDS) - time_elapsed
      return left_time
  
  
  # token checker if token expired or not
  def is_token_expired(token):
      return expires_in(token) &lt; timedelta(seconds=0)
  
  
  # if token is expired new token will be established
  # If token is expired then it will be removed
  # and new one with different key will be created
  def token_expire_handler(token):
      is_expired = is_token_expired(token)
      if is_expired:
          token.delete()
          token = Token.objects.create(user=token.user)
      return is_expired, token
  
  
  # ________________________________________________
  # DEFAULT_AUTHENTICATION_CLASSES
  class ExpiringTokenAuthentication(TokenAuthentication):
      &quot;&quot;&quot;
      If token is expired then it will be removed
      and new one with different key will be created
      &quot;&quot;&quot;
  
      def authenticate_credentials(self, key):
          try:
              token = Token.objects.get(key=key)
          except Token.DoesNotExist:
              raise AuthenticationFailed(&quot;Invalid Token&quot;)
  
          if not token.user.is_active:
              raise AuthenticationFailed(&quot;User is not active&quot;)
  
          is_expired, token = token_expire_handler(token)
          if is_expired:
              raise AuthenticationFailed(&quot;The Token is expired&quot;)
  
          return (token.user, token)
  </code></pre>
  <p>and I have added in settings.py like this</p>
  <pre><code>REST_FRAMEWORK = {
      'DEFAULT_AUTHENTICATION_CLASSES': (
          'accounts.authentication.ExpiringTokenAuthentication',
      ),
      'DEFAULT_PERMISSION_CLASSES': (
          'rest_framework.permissions.IsAuthenticated',
      )
  }
  
  TOKEN_EXPIRED_AFTER_SECONDS = 10
  </code></pre>
  <p>Still token is not renewing , I have checked this authentication class is not triggering .</p>