【问题标题】:Using refresh token with Google directory service API将刷新令牌与 Google 目录服务 API 结合使用
【发布时间】:2014-11-07 03:37:27
【问题描述】:

有没有办法通过 Google 目录服务 API 使用刷新令牌? 我找不到任何示例如何做到这一点(我正在使用 Python)。 我正在寻找类似于以下代码的东西(这适用于 Google Adwords API),并预先设置了凭据:

oauth2_client = oauth2.GoogleRefreshTokenClient(
    CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN)

adwords_client = adwords.AdWordsClient(
    DEVELOPER_TOKEN, oauth2_client, USER_AGENT, CLIENT_CUSTOMER_ID)

self.managed_customer_service = adwords_client.GetService(
    'ManagedCustomerService', version='v201402')

对于 Directory API,我只找到了以下代码 sn-p,但我不知道如何使用刷新令牌:

flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
print 'Go to the following link in your browser: ' + authorize_url
code = raw_input('Enter verification code: ').strip()
credentials = flow.step2_exchange(code)

# Create an httplib2.Http object and authorize it with our credentials
http = httplib2.Http()
http = credentials.authorize(http)

self.directory_service = build('admin', 'directory_v1', http=http)

我的最终目标是仅使用刷新令牌授权我的应用程序,而无需每次打开浏览器、登录并获取新令牌。

【问题讨论】:

    标签: python google-api google-admin-sdk google-directory-api


    【解决方案1】:

    如果您使用 Storage 对象,Python 客户端库可以自动存储、加载和刷新凭据。 Gmail API Python Quickstart sample 展示了如何使用文件存储,它将凭据保存到磁盘。以下是相关的代码行:

    from oauth2client.file import Storage
    from oauth2client.tools import run
    
    ...
    
    # Location of the credentials storage file
    STORAGE = Storage('gmail.storage')
    
    ...
    
    # Try to retrieve credentials from storage or run the flow to generate them
    credentials = STORAGE.get()
    if credentials is None or credentials.invalid:
      credentials = run(flow, STORAGE, http=http)
    

    客户端库中内置了additional storage classes,或者你可以扩展Storage base class来实现你自己的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-17
      • 2016-01-26
      • 1970-01-01
      • 2015-02-03
      • 2016-08-03
      • 2020-02-06
      • 2019-06-29
      • 2017-03-21
      相关资源
      最近更新 更多