google-app-engine – 在python中的gdata上使用OAuth2和服务帐户

我想使用data.photos.service.PhotosService从Picasa中推送和拉取照片.我从Google控制台获得了一个服务密钥文件XXXXXXXX-privatekey.p12,现在我正在尝试使用谷歌的密钥进行身份验证.

使用appengine的OAUTH2文档让我相信使用以下内容是有用的:

f = file(settings.SITE_ROOT + '/aurora/' + settings.PRIVATE_KEY, 'rb')
key = f.read()
f.close()

credentials = SignedJwtAssertionCredentials(settings.SERVICE_ACCOUNT_NAME, key, scope = 'http://picasaweb.google.com/data https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile')
http = httplib2.Http()
http = credentials.authorize(http)
service = build("oauth2", "v2", http=http)
user_info = None
try:
  user_info = service.userinfo().get().execute()
  # neither of these two methods work
  #gd_client.SetOAuthInputParameters(signature_method = gdata.auth.OAuthSignatureMethod.RSA_SHA1, consumer_key = "asdfasdfasdf.apps.googleusercontent.com", rsa_key = key, two_legged_oauth = True, requestor_id = user_info.get('email'))
  #gd_client.auth_token = gdata.gauth.TwoLeggedOAuthRsaToken(consumer_key = user_info.get('email'), rsa_private_key = key, requestor_id = user_info.get('email'))
except errors.HttpError, e:
  logging.error('An error occurred: %s', e)

user_inf0 = {u'verified_email': True, u'id': u'1234', u'name': u'asdfasdfasdf@developer.gserviceaccount.com', u'email': u'asdfasdfasdf@developer.gserviceaccount.com'}

问题是使用SetOAuthInputParameters的方法1返回无效标记,或方法2返回403限制.

当我真的并且真的不想这样做的时候,我正在通过大量的代码来阅读所有常规的3条腿的oauth.我还没有看到任何想法/文章?

最佳答案
使用gdata.gauth.OAuth2TokenFromCredentials.

auth2token = gdata.gauth.OAuth2TokenFromCredentials(credentials)
gd_client = auth2token.authorize(gd_client)

OAuth2TokenFromCredentials旨在帮助您同时使用apiclient和gdata.在幕后,它使用凭据确保它具有执行gdata调用所需的身份验证信息.

注意,如果你仍然得到403,那么它可能完全不同.我使用服务帐户访问用户的数据并获得403,因为我没有在SignedJwtAssertionCredentials调用中正确指定用户.

更新:这是我使用的基本模式:

from oauth2client.client import SignedJwtAssertionCredentials
credentials = SignedJwtAssertionCredentials(
    "XXXXXXXXXXX@developer.gserviceaccount.com",
    open("keyfile").read(),
    scope=(
        "https://www.googleapis.com/auth/drive",
        "https://spreadsheets.google.com/feeds",
        "https://docs.google.com/feeds"
    ), # For example.
    sub="user@gmail.com"
)
http = httplib2.Http()
http = credentials.authorize(http) # Not needed? See comment below.
auth2token = gdata.gauth.OAuth2TokenFromCredentials(credentials)
gd_client = gdata.photos.service.PhotosService() # For example.
gd_client = auth2token.authorize(gd_client)

转载注明原文:google-app-engine – 在python中的gdata上使用OAuth2和服务帐户 - 代码日志