使用OAuth 2.0与Google API进行服务器到服务器身份验证的示例

3
这是一个关于这个问题的后续提问:
我已经成功创建了私钥,并阅读了Google文档中有关服务器对服务器身份验证概念的各种页面。
我需要创建一个JWT来授权我的App Engine应用程序(Python)访问Google日历并在日历中发布事件。从oauth2client源代码中看,我需要使用oauth2client.client.SignedJwtAssertionCredentials来创建JWT。
我目前缺少的是一个样式化的Python示例代码,展示创建JWT和将其用于为Google Calendar认证我的App Engine应用程序的各个步骤。此外,从SignedJwtAssertionCredentials源代码中看,我需要一些与App Engine兼容的库来执行签名操作。
谁能为此提供一些帮助?
1个回答

8

经过一些调查,我找到了几个基于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"

感谢pycrypto库的技巧。我无法让SignedJwtAssertionCredentials正常工作 >_< - Depado

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