且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-07 20:28:27

经过一番挖掘,我发现了一个。从这里我创建了以下简单的示例,创建一个JWT来访问日历API:

  import httplib2 
import pprint
$ b $ from apiclient.discovery import build $ b $ from oauth2client.client import SignedJwtAssertionCredentials

#从Google提供的私钥文件中获取私钥。
f = file(your_private_key_file.p12,rb)
key = f.read()
f.close()

#创建JWT
credentials = SignedJwtAssertionCredentials(
xxxxxxxxxx@developer.gserviceaccount.com,key,
scope =https://www.googleapis.com/auth/calendar


#创建一个授权http实例
http = httplib2.Http()
http = credentials.authorize(http)

#创建一个服务调用日历API
service = build(calendar,v3,http = http)

#列出所有日历。
lists = service.calendarList()。list(pageToken = None).execute(http = http)
pprint.pprint(lists)

为了在Google App Engine上工作,您需要为您的应用程序启用PyCrypto。这意味着将以下内容添加到 app.yaml 文件中:

 库:
- 名称:pycrypto
版本:latest


This is a follow-up question for this question:

I have successfully created a private key and have read the various pages of Google documentation on the concepts of server to server authentication.

I need to create a JWT to authorize my App Engine application (Python) to access the Google calendar and post events in the calendar. From the source in oauth2client it looks like I need to use oauth2client.client.SignedJwtAssertionCredentials to create the JWT.

What I'm missing at the moment is a stylised bit of sample Python code of the various steps involved to create the JWT and use it to authenticate my App Engine application for Google Calendar. Also, from SignedJwtAssertionCredentials source it looks like I need some App Engine compatible library to perform the signing.

Can anybody shed some light on this?

After some digging I found a couple of samples based on the OAuth2 authentication. From this I cooked up the following simple sample that creates a JWT to access the calendar 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)

For this to work on Google App Engine you will need to enable PyCrypto for your app. This means adding the following to your app.yaml file:

libraries:
- name: pycrypto
  version: "latest"