首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在python中对gdata使用带有服务帐户的OAuth2

在python中对gdata使用带有服务帐户的OAuth2
EN

Stack Overflow用户
提问于 2013-04-16 07:26:37
回答 2查看 6.7K关注 0票数 8

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

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

代码语言:javascript
运行
复制
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 restricted

当我真的真的不想这样做的时候,我却无计可施地阅读了堆积如山的代码,这些代码都是常规的3条腿的oauth。有什么想法/文章我还没看过吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-08-22 23:01:55

使用gdata.gauth.OAuth2TokenFromCredentials。

代码语言:javascript
运行
复制
auth2token = gdata.gauth.OAuth2TokenFromCredentials(credentials)
gd_client = auth2token.authorize(gd_client)

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

请注意,如果你仍然得到403,它可能是完全不同的东西。我使用一个服务帐户来访问用户的数据,并得到了403,因为我没有在SignedJwtAssertionCredentials调用中正确地指定用户。

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

代码语言:javascript
运行
复制
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)
票数 19
EN

Stack Overflow用户

发布于 2017-09-09 04:55:35

如果您在google帐户上使用MFA,则需要使用同意屏幕身份验证方法。对于Picassa API,它不能按原样工作,因为请求API略有不同。

代码语言:javascript
运行
复制
import gdata.gauth
import os
import pickle
import gdata.photos.service

clientid='xxx'  # https://console.developers.google.com/apis/credentials
clientsecret='xxx'
Scope='https://picasaweb.google.com/data/'
User_agent='myself'

def GetAuthToken():
    if os.path.exists(".token"):
        with open(".token") as f:
            token = pickle.load(f)
    else:
        token = gdata.gauth.OAuth2Token(client_id=clientid,client_secret=clientsecret,scope=Scope,user_agent=User_agent)
        print token.generate_authorize_url(redirect_uri='urn:ietf:wg:oauth:2.0:oob')
        code = raw_input('What is the verification code? ').strip()
        token.get_access_token(code)
        with open(".token", 'w') as f:
            pickle.dump(token, f)
    return token


token = GetAuthToken()

gd_client = gdata.photos.service.PhotosService()
old_request = gd_client.request


def request(operation, url, data=None, headers=None):
    headers = headers or {}
    headers['Authorization'] = 'Bearer ' + token.access_token
    return old_request(operation, url, data=data, headers=headers)


gd_client.request = request
photos = gd_client.GetUserFeed(kind='photo', limit='10')
for photo in photos.entry:
    print 'Recently added photo title:', photo.title.text
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16026286

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档