Как использовать обменный токен с OAuth2 - social-auth-app-django

Я пытаюсь реализовать аутентификацию OAuth2, используя social-auth-app-django.

Мой бэкенд может обмениваться маркером авторизации, который я получаю от фронтенда с помощью SDK провайдеров, в качестве примера я приведу Apple: Мое приложение для iOS получает токен авторизации от пользователя, используя "Sign in with Apple". Затем я отправляю этот токен в бэкенд, чтобы я мог обменяться им с помощью этого представления:

@api_view(http_method_names=['POST'])
@permission_classes([AllowAny])
@psa()
def exchange_token_view(request, backend):
    
    serializer = SocialSerializer(data=request.data)
    if serializer.is_valid(raise_exception=True):
        print("Backend:", backend)
        print("Token:", serializer.validated_data['access_token'])

        # set up non-field errors key
        # http://www.django-rest-framework.org/api-guide/exceptions/#exception-handling-in-rest-framework-views
        try:
            nfe = "non_field_errors"
        except AttributeError:
            nfe = 'non_field_errors'

        try:
            # this line, plus the psa decorator above, are all that's necessary to
            # get and populate a user object for any properly enabled/configured backend
            # which python-social-auth can handle.
            user = request.backend.do_auth(serializer.validated_data['access_token'])
        except HTTPError as e:
            # An HTTPError bubbled up from the request to the social auth provider.
            # This happens, at least in Google's case, every time you send a malformed
            # or incorrect access key.
            return Response(
                {'errors': {
                    'token': 'Invalid token',
                    'detail': str(e),
                }},
                status=status.HTTP_400_BAD_REQUEST,
            )

        if user:
            if user.is_active:
                token, _ = Token.objects.get_or_create(user=user)
                print()
                return Response({'token': token.key})
            else:
                # user is not active; at some point they deleted their account,
                # or were banned by a superuser. They can't just log in with their
                # normal credentials anymore, so they can't log in with social
                # credentials either.
                return Response(
                    {'errors': {nfe: 'This user account is inactive'}},
                    status=status.HTTP_400_BAD_REQUEST,
                )
        else:
            # Unfortunately, PSA swallows any information the backend provider
            # generated as to why specifically the authentication failed;
            # this makes it tough to debug except by examining the server logs.
            return Response(
                {'errors': {nfe: "Authentication Failed"}},
                status=status.HTTP_400_BAD_REQUEST,
            )

Затем это представление отправляет обратно на фронт вот такой токен:

f3f2de271ve1ef3a1b477b0d1b97252d117b9ca7

Но я не понимаю, как я должен использовать этот токен. Он хранится в таблице под названием authtoken_token в моей базе данных. Как я могу использовать этот токен для выполнения запросов к моим представлениям и доступа к данным пользователя? Что мне нужно сделать в моих представлениях Django, чтобы принять этот токен в качестве аутентификации?

Вернуться на верх