Using OAuth2 with service account on gdata in python

不想你离开。 提交于 2019-11-30 00:55:44

Use gdata.gauth.OAuth2TokenFromCredentials.

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

OAuth2TokenFromCredentials is designed to help you use apiclient and gdata at the same time. Under the covers, it uses the credentials for making sure it has the auth information it needs to perform gdata calls.

Note, if you still get 403, it may be something else entirely. I was using a service account to access a user's data and was getting 403 because I hadn't spec'd the user properly in the SignedJwtAssertionCredentials call.

UPDATE: Here's the basic pattern I used:

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)

If you are using MFA on your google account, you need to use the consent screen authentication method. With Picassa API, it does not work as is, as the request API is slightly different.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!