python - 使用 OAuth 2.0 和 Google API 的服务器到服务器身份验证示例

标签 python google-app-engine oauth

这是 this question 的后续问题:

我已成功创建私钥并阅读了有关服务器到服务器身份验证概念的 Google 文档的各个页面。

我需要创建一个 JWT 来授权我的 App Engine 应用程序 (Python) 访问 Google 日历并在日历中发布事件。从 oauth2client 的源代码看来,我需要使用 oauth2client.client.SignedJwtAssertionCredentials 来创建 JWT。

我现在缺少的是创建 JWT 并使用它来验证我的 Google 日历 App Engine 应用程序所涉及的各个步骤的程式化示例 Python 代码。此外,从 SignedJwtAssertionCredentials 来源看来,我需要一些与 App Engine 兼容的库来执行签名。

任何人都可以阐明这一点吗?

最佳答案

经过一番挖掘,我发现了一个 couple of samples基于 OAuth2 身份验证。由此我编写了以下简单示例,创建了一个 JWT 来访问日历 API:

import httplib2
import pprint

from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials

# Get the private key from the Google supplied private key file.
f = file("your_private_key_file.p12", "rb")
key = f.read()
f.close()

# Create the JWT
credentials = SignedJwtAssertionCredentials(
  "xxxxxxxxxx@developer.gserviceaccount.com", key,
  scope="https://www.googleapis.com/auth/calendar"
)

# Create an authorized http instance
http = httplib2.Http()
http = credentials.authorize(http)

# Create a service call to the calendar API
service = build("calendar", "v3", http=http)

# List all calendars.
lists = service.calendarList().list(pageToken=None).execute(http=http)
pprint.pprint(lists)

要使其在 Google App Engine 上运行,您需要为您的应用启用 PyCrypto。这意味着将以下内容添加到您的 app.yaml 文件中:

libraries:
- name: pycrypto
  version: "latest"

关于python - 使用 OAuth 2.0 和 Google API 的服务器到服务器身份验证示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19407600/

相关文章:

python - 祖先索引消耗的存储空间更少吗?大约会消耗多少存储空间?

java - 如何使用 Grails oauth 插件获取访问 token ?

c# - 使用 oauth 访问 gmail 的电子邮件

python - PyCharm docker 调试错误

python - numpy库如何实现n维数组?

python - 查询奇怪的行为。 Google App Engine 数据存储

android - Android 应用程序上的 Oauth 2

python - 定期抓取雅虎财经

python - python中的条件统计摘要数据框

java - 将 App Engine 数据存储区低级 API 与 Java 结合使用