【问题标题】:Django Expire token AuthenticationDjango过期令牌身份验证
【发布时间】:2021-01-10 19:10:01
【问题描述】:

我正在为此努力使 django 令牌过期 我正在关注此https://medium.com/@yerkebulan199/django-rest-framework-drf-token-authentication-with-expires-in-a05c1d2b7e05

我的 accounts/authentication.py 文件就像

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) < 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):
    """
    If token is expired then it will be removed
    and new one with different key will be created
    """

    def authenticate_credentials(self, key):
        try:
            token = Token.objects.get(key=key)
        except Token.DoesNotExist:
            raise AuthenticationFailed("Invalid Token")

        if not token.user.is_active:
            raise AuthenticationFailed("User is not active")

        is_expired, token = token_expire_handler(token)
        if is_expired:
            raise AuthenticationFailed("The Token is expired")

        return (token.user, token)

我已经像这样在settings.py中添加了

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'accounts.authentication.ExpiringTokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

TOKEN_EXPIRED_AFTER_SECONDS = 10

仍然令牌没有更新,我检查了这个身份验证类没有触发。

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    expires_in 函数旁边试试

    time_elapsed = token.created - timezone.now()
    

    因为 time_elapsed 应该是 才能得到 left_time

    【讨论】:

    • 没有问题,这个文件甚至不能正常工作,并且令牌即使过期也能正常工作。
    • 身份验证类工作正常,但错误在 expires_in 函数中
    猜你喜欢
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-27
    • 2022-11-28
    • 2020-09-29
    • 2016-01-23
    • 2023-03-16
    相关资源
    最近更新 更多