Korzystanie z OAuth2 z kontem serwisowym na gdata w Pythonie

Chcę użyć data.photos.service.PhotosService do push and pull photos from Picasa. Mam plik klucza serwisowego XXXXXXXX-privatekey.p12 z konsoli Google i próbuję teraz uwierzytelnić za pomocą wspomnianego klucza z google.

Dokumentacja OAUTH2 używająca appengine doprowadziła mnie do przekonania, że użycie następujących elementów byłoby przydatne:

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'[email protected]', u'email': u'[email protected]'}

Problem polega na tym, że albo metoda 1 używając SetOAuthInputParameters zwraca nieprawidłowy token, albo Metoda 2 zwraca 403 restricted.

Jestem u kresu rozumu czytając przez góry Kod, że wszystkie zrobić regularne 3 legged oauth, gdy naprawdę i naprawdę nie chcę tego zrobić w ten sposób. Jakieś pomysły/artykuły, których jeszcze nie widziałem?

Author: poolie, 2013-04-16

2 answers

Użyj gdata.gauth.OAuth2TokenFromCredentials.

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

OAuth2TokenFromCredentials został zaprojektowany, aby pomóc ci używać apiclient i gdata w tym samym czasie. Pod pokrywami używa poświadczeń, aby upewnić się, że posiada informacje auth potrzebne do wykonywania wywołań gdata.

Uwaga, jeśli nadal masz 403, może to być coś zupełnie innego. Korzystałem z konta serwisowego, aby uzyskać dostęp do danych użytkownika i dostawałem 403, ponieważ nie sprecyzowałem poprawnie użytkownika w / Align = "center" bgcolor = "# e0ffe0 " / cesarz chin / / align = center /

UPDATE: oto podstawowy wzór, którego użyłem:

from oauth2client.client import SignedJwtAssertionCredentials
credentials = SignedJwtAssertionCredentials(
    "[email protected]",
    open("keyfile").read(),
    scope=(
        "https://www.googleapis.com/auth/drive",
        "https://spreadsheets.google.com/feeds",
        "https://docs.google.com/feeds"
    ), # For example.
    sub="[email protected]"
)
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
Author: David K. Hess,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-14 14:32:42

Jeśli używasz MFA na swoim koncie google, musisz użyć metody uwierzytelniania ekranu zgody. Z API Picassa nie działa tak, jak jest, ponieważ API żądania jest nieco inny.

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
Author: tardyp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-08 20:55:34