django Token权限认证

django Token权限认证
  • 重写rest_framework中的TokenAuthentication,设置token的过期时间
  1. users.models.py

    # Create your models here.
    from rest_framework.authtoken.models import Token
    
    
    class PrivateToken(Token):
        """
        继承Token模型,方便后期扩展
        """
    
        class Meta:
            verbose_name = 'Private Token'
    
  2. users.authentication.py

    from datetime import timedelta
    
    from django.conf import settings
    from django.utils import timezone
    from django.utils.translation import ugettext_lazy as _
    from rest_framework import authentication, exceptions
    from users.models import PrivateToken
    
    
    class PrivateTokenAuthentication(authentication.TokenAuthentication):
        """
        API接口Token认证
        """
        model = PrivateToken
    
        def authenticate_credentials(self, key):
            model = self.get_model()
            try:
                token = model.objects.select_related('user').get(key=key)
            except model.DoesNotExist:
                raise exceptions.AuthenticationFailed(_('Invalid token.'))
    
            if not token.user.is_active:
                raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))
    
            if timezone.now() > (token.created + timedelta(seconds=settings.TOKEN_EXPIRATION)):
                raise exceptions.AuthenticationFailed(_('Token has expired'))
            return (token.user, token)
    
  3. settings.py

    REST_FRAMEWORK = {
        # Use Django's standard `django.contrib.auth` permissions,
        # or allow read-only access for unauthenticated users.
        'EXCEPTION_HANDLER': 'common.views.exception_handler',
        'DEFAULT_PERMISSION_CLASSES': (
            'rest_framework.permissions.IsAuthenticated',
        ),
        'DEFAULT_RENDERER_CLASSES': (
            'rest_framework.renderers.JSONRenderer',
            'rest_framework.renderers.BrowsableAPIRenderer',
        ),
        'DEFAULT_PARSER_CLASSES': (
            'rest_framework.parsers.JSONParser',
            'rest_framework.parsers.FormParser',
            'rest_framework.parsers.MultiPartParser',
            'rest_framework.parsers.FileUploadParser',
        ),
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'users.authentication.PrivateTokenAuthentication',  # 这里添加
            # 'users.authentication.SessionAuthentication',
        ),
        'DEFAULT_FILTER_BACKENDS': (
            'django_filters.rest_framework.DjangoFilterBackend',
            'rest_framework.filters.SearchFilter',
            'rest_framework.filters.OrderingFilter',
        ),
        'ORDERING_PARAM': "order",
        'SEARCH_PARAM': "search",
        'DATETIME_FORMAT': '%Y-%m-%d %H:%M:%S %z',
        'DATETIME_INPUT_FORMATS': ['%Y-%m-%d %H:%M:%S %z'],
        'PAGINATE_BY': 10,
        'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
        'PAGE_SIZE': 15
    }
    
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值