五、认证


返回

5.1 定义认证类

  • utils/auth.py:定义认证类的authenticate方法

    from rest_framework.authentication import BaseAuthentication
    from rest_framework.exceptions import AuthenticationFailed
    from Login.models import User
    
    
    class MyAuth(BaseAuthentication):
        def authenticate(self, request):
            # 过滤OPITIONS请求
            if request.method == "OPTIONS":
                return None, None
            token = request.META.get("HTTP_AUTHENTICATION", "")
            if not token:
                raise AuthenticationFailed("没有携带token")
            # 通过token获取用户id
            user_id = '通过token获取用户id'.get(str(token))
            if user_id is None:
                raise AuthenticationFailed("token过期")
            user_obj = User.objects.filter(id=user_id).first()
            return user_obj, token
        
    

5.2 全局认证

  • settings.py

    # DRF配置
    REST_FRAMEWORK = {
        "DEFAULT_AUTHENTICATION_CLASSES": ["utils.auth.MyAuth", ]
    }
    
    

5.3 局部认证

  • views.py

    from rest_framework.views import APIView
    from utils.auth import MyAuth
    
    
    class TestView(APIView):
        authentication_classes = [MyAuth, ]  # 局部认证
    
        def get(self, request):
            pass
            
    

5.4 利用框架

  • 提供了四种认证类

    from rest_framework.authentication import TokenAuthentication
    from rest_framework.authentication import SessionAuthentication
    from rest_framework.authentication import RemoteUserAuthentication
    from rest_framework.authentication import BasicAuthentication
    
返回