python-social-auth无法获得正确的Google OAuth2详细信息

时间:2015-01-30 14:21:58

标签: django python-2.7 django-socialauth google-login python-social-auth

我想在Django中使用Google Plus登录的python-social-auth功能登录用户。从我的网站登录时,一切正常,并将正确的详细信息添加到数据库中。

但是,我也希望从我的Android应用程序进行身份验证。用户登录应用程序,然后将访问令牌发送到django API,该API根据以下代码处理登录过程,改编自the documentation

@csrf_exempt
@serengeti_api_request
@psa('social:complete')
def login_social_token(request, backend):
    # Ensure the token has been specified.
    token = request.META.get('HTTP_ACCESSTOKEN')
    if token is None:
        raise SerengetiApiRequestException('Access token is missing!')

    # Login the user for this session
    user = request.backend.do_auth(token)
    if user is None:
        raise SerengetiApiRequestException('Could not authenticate user!')

    login(request, user)

    # Store the email address if one has been specified (e.g. Twitter)
    email = request.META.get('HTTP_EMAIL')
    if email is not None:
        user.email = email
        user.save()

    # Prepare the parameters to be returned
    response = dict({
        'id': user.id,
        'first_name': user.first_name,
        'last_name': user.last_name,
        'api_key': request.session.session_key,
    })

    # Return a 200 status code to signal success.
    return HttpResponse(json.dumps(response, indent=4), status=200)

从网站登录时,social_auth_usersocialauth表包含:

id | provider      | uid       | extra_data
==========================================
10 | google-oauth2 | <myemail> | {"token_type": "Bearer", "access_token": "<token>", "expires": 3600}

但是,使用上述函数从应用程序登录时,操作完成正常,但表中的条目如下所示:

id | provider      | uid     | extra_data
=========================================
10 | google-oauth2 | <empty> | {"access_token": "", "expires": null}

此外,auth_user表格包含username,而不是Google Plus用户名,而eeed494412obfuscated48bc47dd9b字段为空。

我做错了什么,如何获得与网站相同的功能?

我想提一下,我已经从Android应用程序实施了Facebook和Twitter身份验证,它调用了上述功能并存储了正确的详细信息,只有Google Plus导致了问题。

4 个答案:

答案 0 :(得分:3)

我有一个使用google oauth2身份验证的项目(实际上没有运行)。我在这里留下我的配置文件,所以它对你有用(我只使用oauth2所以有些东西可能会有所不同):

AUTHENTICATION_BACKENDS = (
    'social.backends.google.GoogleOAuth2',  # /google-oauth2
    'django.contrib.auth.backends.ModelBackend',
)
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'your google oauth 2 key'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'your secret google oauth 2 key'

SOCIAL_AUTH_PIPELINE = (
    'social.pipeline.social_auth.social_details',
    'social.pipeline.social_auth.social_uid',
    'social.pipeline.social_auth.auth_allowed',
    'social.pipeline.social_auth.associate_by_email',
    'social.pipeline.social_auth.social_user',
    'social.pipeline.user.get_username',
    'social.pipeline.user.create_user',
    'social.pipeline.social_auth.associate_user',
    'social.pipeline.social_auth.load_extra_data',
    'social.pipeline.user.user_details'
)

我也附上了视图(注意我正在使用django rest框架)。

class ObtainAuthToken(APIView):
    permission_classes = (permissions.AllowAny,)
    serializer_class = AuthTokenSerializer
    model = Token

    # Accept backend as a parameter and 'auth' for a login / pass
    def post(self, request, backend):

        if backend == 'auth':  # For admin purposes
            serializer = self.serializer_class(data=request.DATA)
            if serializer.is_valid():
                token, created = Token.objects.get_or_create(user=serializer.object['user'])
                return Response({'token': token.key})
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

        else:
            # Here we call PSA to authenticate like we would if we used PSA on server side.
            user = register_by_access_token(request, backend)

            # If user is active we get or create the REST token and send it back with user data
            if user and user.is_active:
                token, created = Token.objects.get_or_create(user=user)
                return Response({'id': user.id, 'name': user.username, 'token': token.key})
            else:
                return Response("Bad Credentials, check the Access Token and/or the UID", status=403)


@strategy('social:complete')
def register_by_access_token(request, backend):
    # This view expects an access_token GET parameter
    token = request.GET.get('access_token')
    backend = request.strategy.backend
    user = backend.do_auth(access_token=token, backend=backend)
    if user:
        # login(request, user) #Only useful for web..
        return user
    else:
        return None

并在urls.py中:

urlpatterns = patterns(
    '',
    url(r'^login/(?P<backend>[\w-]+)$', ObtainAuthToken.as_view(), ),
)

很抱歉附加所有这些代码而没有提供具体答案,但需要更多数据,因为错误可能来自许多来源(错误的api密钥,糟糕的设置配置,管道......)。我希望代码有所帮助。

答案 1 :(得分:3)

只想分享另一种方法。此示例非常原始,并未涵盖所有情况(例如,身份验证失败)。但是,它应该足够深入了解如何完成OAuth2身份验证。

获取客户ID

从OAuth2服务提供商(例如Google)获取客户ID,并配置重定向网址。

我假设你已经这样做了。

创建登录/注册链接

您需要在视图中生成登录/注册链接。它应该是这样的:

https://accounts.google.com/o/oauth2/auth?response_type=code&client_id={{CLIENT_ID}}&redirect_uri={{REDIRECT_URL}}&scope=email

将{{CLIENT_ID}}和{{REDIRECT_URL}}替换为您在上一步中获得的详细信息。

创建新视图

urls.py中添加以下内容:

url(r'^oauth2/google/$', views.oauth2_google),

views.py创建方法:

def oauth2_google(request):

    # Get the code after a successful signing
    # Note: this does not cover the case when authentication fails
    CODE = request.GET['code']

    CLIENT_ID = 'xxxxx.apps.googleusercontent.com' # Edit this
    CLIENT_SECRET = 'xxxxx' # Edit this
    REDIRECT_URL = 'http://localhost:8000/oauth2/google' # Edit this

    if CODE is not None:
        payload = {
            'grant_type': 'authorization_code', 
            'code': CODE, 
            'redirect_uri': REDIRECT_URL, 
            'client_id': CLIENT_ID, 
            'client_secret': CLIENT_SECRET
            }

        token_details_request = requests.post('https://accounts.google.com/o/oauth2/token', data=payload)
        token_details = token_details_request.json()
        id_token = token_details['id_token']
        access_token = token_details['access_token']

        # Retrieve the unique identifier for the social media account
        decoded = jwt.decode(id_token, verify=False)
        oauth_identifier = decoded['sub']

        # Retrieve other account details
        account_details_request = requests.get('https://www.googleapis.com/plus/v1/people/me?access_token=' + access_token)
        account_details = account_details_request.json()
        avatar = account_details['image']['url']

        # Check if the user already has an account with us
        try:
            profile = Profile.objects.get(oauth_identifier=oauth_identifier)
            profile.avatar = avatar
            profile.save()
            user = profile.user
        except Profile.DoesNotExist:
            user = User.objects.create_user()           
            user.save()
            profile = Profile(user=user, oauth_identifier=oauth_identifier, avatar=avatar)
            profile.save()

        user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(request, user)

        return redirect('/')

您可能需要以下导入:

from django.shortcuts import redirect
import jwt # PyJWT==0.4.1
import requests # requests==2.5.0
import json

答案 2 :(得分:1)

我终于弄明白了。根据{{​​3}},我还需要在Android应用中发出请求时请求this article in the Android's Google Plus documentation。添加后,python-social-auth代码设法将电子邮件正确存储在uid字段中。这允许它识别同一用户是否从网站或应用程序登录,这是我需要的。这是我使用的范围字符串:

String scopes = "oauth2:" + Plus.SCOPE_PLUS_LOGIN + " https://www.googleapis.com/auth/plus.profile.emails.read";

但是,extra_data字段仍包含我上面提到的值。我认为这也是因为需要请求离线访问,这样Google Plus就可以将丢失的字段传回python-django-authplus.profile.emails.read scope

答案 3 :(得分:0)

我遇到了同样的问题。你的谷歌用户没有设置extra_fields的原因是因为python-social-auth调用谷歌服务器设置这些东西,但如果你只是用access_token拨打谷歌,它就赢了#39 ;足以让Google返回refresh_token和所有其他auth相关字段。您可以通过手动设置来破解它,但随后您最终会使用与客户端相同的访问权限和刷新令牌。 Google建议您使用客户端生成具有所需范围的新授权令牌,然后将该身份验证令牌发送到服务器,然后服务器会将其转换为访问和刷新令牌。请参阅此处了解详细信息(这是一个涉及阅读的内容):https://developers.google.com/identity/protocols/CrossClientAuth

如果您真的致力于在python-social-auth的范围内做到这一点,我建议您制作一个自定义身份验证后端,将其称为GoogleOAuth2AuthorizationCodeAuth({{3} })。

懒惰且可能易于破解和粗暴的方法是将access_token发布到我的服务器以Google用户身份登录(您似乎正在正常运行),然后再获取另一个用户来自客户端的授权令牌,以便发布到单独的端点,然后我将处理转换为连接到用户配置文件的另一个凭据模型对象。

在DjangoRestFramework中:

class GoogleAuthorizationCodeView(APIView):
    def post(self, request, format=None):
        credentials = flow.step2_exchange(code)
        saved_creds = GoogleCredentials.objects.create(credentials=credentials)
        return Response(status=status.HTTP_201_CREATED)