使用谷歌API令牌[Django和AllAuth]

5
我在我的Django应用程序中使用AllAuth来管理用户身份验证。我的用户可以连接他们的Google账户并获取一个带有适当范围的Google API令牌。
我想使用该令牌访问Google API(在我的情况下是日历v3),因为我的用户已经使用OAuth2在我的网站上进行了登录,并授予了我对日历API的访问权限。
谷歌只在他们的网站上提供完整的流程(从身份验证到API),是否有一种方法来实现我的想法,或者它根本不可能?
我尝试过 drive = build('calendar', 'v3', credentials=credentials) 如此说此处,但“credentials”需要成为oauth2client的一部分,而不仅仅是一个简单的字符串令牌。
感谢您宝贵的时间。
Simon

1
您可以使用有效的访问令牌(以及可能的刷新令牌和刷新URI)授权http客户端,并将其提供给客户端库,而不是凭据对象。或者,您可以使用令牌和刷新URI构建凭据对象。无论哪种方式,您都需要将其传递给build命令。 - tehhowch
1
还可以参见AccessTokenCredentials,以及Credentials构造函数:https://oauth2client.readthedocs.io/en/latest/_modules/oauth2client/client.html#OAuth2Credentials - tehhowch
@Simon,你找到解决方案了吗?你能告诉我如何获取Google的访问令牌吗? - Muhammad Usama Mashkoor
@usama 很遗憾我刚刚放弃了这个项目,转而去做其他事情了。抱歉!希望你能找到答案——如果找到了,请在这里发布! - Simon
1个回答

3
我知道这是一个老问题,但最终我找到了适合我的解决方案。在使用allauth成功进行身份验证后,我执行以下操作来获取客户端令牌,然后构建服务。
    from googleapiclient.discovery import build
    from google.oauth2.credentials import Credentials
    from allauth.socialaccount.models import SocialToken, SocialApp

    ...    

    # request is the HttpRequest object
    token = SocialToken.objects.get(account__user=request.user, account__provider='google')

    credentials = Credentials(
        token=token.token,
        refresh_token=token.token_secret,
        token_uri='https://oauth2.googleapis.com/token',
        client_id='client-id', # replace with yours 
        client_secret='client-secret') # replace with yours 

    service = build('calendar', 'v3', credentials=credentials)

确保根据https://django-allauth.readthedocs.io/en/latest/configuration.html的说明,将SOCIALACCOUNT_STORE_TOKENS = True设置为True,否则您将没有任何SocialToken对象。

你把那段代码放在哪里?那是一个视图吗?能否分享更深入的代码,因为我正在寻找相同的解决方案! - Shadi Almosri
是的,它在我的views.py文件的方法中。 - ayrunn
SocialToken不存在,我该如何获取它? - AgentNirmites

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接