Django rest framework token认证

1.utils文件中,设置auth.py

from rest_framework import exceptions
from api import models
from rest_framework.authentication import BaseAuthentication


class FirstAuthtication(BaseAuthentication):
    def authenticate(self,request):
        pass

    def authenticate_header(self, request):
        pass

class Authtication(BaseAuthentication):
    def authenticate(self,request):
        token = request._request.GET.get('token')
        token_obj = models.UserToken.objects.filter(token=token).first()
        if not token_obj:
            raise exceptions.AuthenticationFailed('用户认证失败')
        # 在rest framework内部会将整个两个字段赋值给request,以供后续操作使用
        return (token_obj.user, token_obj)

    def authenticate_header(self, request):
        return 'Basic realm="api"'

2.settings.pu文件:

REST_FRAMEWORK = {
    # 全局使用的认证类
    "DEFAULT_AUTHENTICATION_CLASSES":['utils.auth.FirstAuthtication','utils.auth.Authtication', ],
    "UNAUTHENTICATED_USER":None, # 匿名,request.user = None
    "UNAUTHENTICATED_TOKEN":None,# 匿名,request.auth = None
}

3.登录时免除认证

class LoginView(APIView):
    authentication_classes = []
    def post(self,request, *args, **kwargs):
        ret={'code':1000, 'msg':None}
        ....

猜你喜欢

转载自blog.csdn.net/weixin_40744265/article/details/82493057