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

Rog*_*ger 3 python google-app-engine oauth

这是此问题的后续问题:

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

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

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

任何人都可以对此有所了解吗?

Rog*_*ger 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)
Run Code Online (Sandbox Code Playgroud)

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

libraries:
- name: pycrypto
  version: "latest"
Run Code Online (Sandbox Code Playgroud)