1.TokenViewBase调用TokenObtainSerializer里面的validate()方法 class TokenViewBase(generics.GenericAPIView): def post(self, request: Request, *args, **kwargs) -> Response: serializer = self.get_serializer(data=request.data) try: serializer.is_valid(raise_exception=True)# 调用serializer.validate() except TokenError as e: raise InvalidToken(e.args[0]) return Response(serializer.validated_data, status=status.HTTP_200_OK)
2.调用from django.contrib.auth import authenticate 里面的认证方法 class TokenObtainSerializer(serializers.Srializer): def validate(self, attrs: Dict[str, Any]) -> Dict[Any, Any]: authenticate_kwargs = { # 获取用户名和密码 self.username_field: attrs[self.username_field], "password": attrs["password"], } try: authenticate_kwargs["request"] = self.context["request"] except KeyError: pass self.user = authenticate(**authenticate_kwargs) #调用认证方法 return {} @classmethod def get_token(cls, user: AuthUser) -> Token: return cls.token_class.for_user(user) # type: ignore
3. 拉取settings.py里面配置的AUTHENTICATION_BACKENDS:认证类,并调用里面的authenticate()方法
def authenticate(request=None, **credentials): for backend, backend_path in _get_backends(return_tuples=True): try: user = backend.authenticate(request, **credentials) except PermissionDenied: break if user is None: continue user.backend = backend_path return user
def _get_backends(return_tuples=False): backends = [] for backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) backends.append((backend, backend_path) if return_tuples else backend) if not backends: raise ImproperlyConfigured( "No authentication backends have been defined. Does " "AUTHENTICATION_BACKENDS contain anything?" ) return backends
ModelBackend里面有一个authenicate方法也可以选择复写其他类里面得authnicate方法
from django.contrib.auth.backends import ModelBackend def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) if username is None or password is None: return try: user = UserModel._default_manager.get_by_natural_key(username) except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user