这是 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/