如何在代码中使用python-social-auth通过访问令牌进行身份验证

8 投票
2 回答
7429 浏览
提问于 2025-04-30 16:03

我有一个REST API,需要通过Facebook登录API来验证用户。访问令牌应该在手机应用里获取(我想是这样),然后再发送到服务器。所以我在一个旧教程里找到了一些代码,但我搞不定。以下是代码:

from social.apps.django_app.utils import strategy
from django.contrib.auth import login
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view, permission_classes
from rest_framework import permissions, status
from django.http import HttpResponse as Response


@strategy()
def auth_by_token(request, backend):
    user=request.user
    user = backend.do_auth(
        access_token=request.DATA.get('access_token'),
        user=user.is_authenticated() and user or None
        )
    if user and user.is_active:
        return user
    else:
        return None



@csrf_exempt
@api_view(['POST'])
@permission_classes((permissions.AllowAny,))
def social_register(request):
    auth_token = request.DATA.get('access_token', None)
    backend = request.DATA.get('backend', None)
    if auth_token and backend:
        try:
            user = auth_by_token(request, backend)
        except Exception, err:
            return Response(str(err), status=400)
        if user:
            login(request, user)
            return Response("User logged in", status=status.HTTP_200_OK)
        else:
            return Response("Bad Credentials", status=403)
    else:
        return Response("Bad request", status=400)

当我尝试发送带参数的POST请求时,出现了这个错误:

'unicode' object has no attribute 'do_auth'

我在官方文档里找到一个例子,它使用了@psa('social:complete')这个装饰器:

from django.contrib.auth import login

from social.apps.django_app.utils import psa

# Define an URL entry to point to this view, call it passing the
# access_token parameter like ?access_token=<token>. The URL entry must
# contain the backend, like this:
#
#   url(r'^register-by-token/(?P<backend>[^/]+)/$',
#       'register_by_access_token')

@psa('social:complete')
def register_by_access_token(request, backend):
    # This view expects an access_token GET parameter, if it's needed,
    # request.backend and request.strategy will be loaded with the current
    # backend and strategy.
    token = request.GET.get('access_token')
    user = backend.do_auth(request.GET.get('access_token'))
    if user:
        login(request, user)
        return 'OK'
    else:
        return 'ERROR'

但是如果我需要在请求体中传递后端名称呢?

暂无标签

2 个回答

3

现在,你可以使用这个库 https://github.com/PhilipGarnero/django-rest-framework-social-oauth2,通过第三方的访问令牌(比如 Facebook、Google、Github 等)来验证你的 Django REST 框架用户。这意味着你可以让用户用他们在这些平台上的账号登录你的应用。

6

应该是 request.backend.do_auth(request.GET.get('access_token'))

我已经更新了文档,里面有正确的代码片段 http://psa.matiasaguirre.net/docs/use_cases.html#signup-by-oauth-access-token https://python-social-auth.readthedocs.io/en/latest/use_cases.html#signup-by-oauth-access-token

撰写回答