我将djangorestframework
和django-rest-auth
用于身份验证api。我想使用created
的{{1}}字段来检查令牌到期。因此,我需要在过期检查后删除过期的令牌,但是调用rest_framework.authtoken.models.Token
方法不会删除令牌对象!
delete()
settings.py
INSTALLED_APPS = [
...
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
...
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'users.authentication.ExpirationAuth',
),
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle'
),
'DEFAULT_THROTTLE_RATES': {
'anon': '50/hour',
'user': '100/hour'
}
}
users.authentication.py
如果令牌已过期,我会收到一条消息from rest_framework.authentication import TokenAuthentication, exceptions
from django.utils.timezone import get_current_timezone
from datetime import datetime, timedelta
from config import constants
current_timezone = get_current_timezone()
class ExpirationAuth(TokenAuthentication):
""" Custom authentication with expiration token """
def authenticate_credentials(self, key):
model = self.get_model()
try:
token = model.objects.get(key=key)
except model.DoesNotExist:
raise exceptions.AuthenticationFailed('Invalid token.')
if self.expired(token):
token.delete()
raise exceptions.AuthenticationFailed('Token has expired.')
if not token.user.is_active:
raise exceptions.AuthenticationFailed('User inactive or deleted.')
return token.user, token
@staticmethod
def expired(token) -> bool:
return token.created < (datetime.now(current_timezone) - timedelta(hours=constants.token_expiration_hours))
,但此令牌仍在数据库中。