python - failedPrecondition when using google Oauth2 Service Account -
there're 3 types of google api client_id:
1. web application
2. service account
3. installed application
i have used 3. installed application
successfullly base on oauth2client, failed on 2. service account
. wanna access own gmail inbox oauth2.0 credentials
.
import imaplib import json import urllib2 oauth2client.client import signedjwtassertioncredentials httplib2 import http apiclient.discovery import build import os reldir = os.path.dirname(os.path.relpath(__file__)) client_secret_file = os.path.join(reldir, 'gmail_service.json') oauth_scope = "https://mail.google.com" gmail_address = 'my_gmail_address@gmail.com' def jwt_oauth2(): ''' https://developers.google.com/identity/protocols/oauth2serviceaccount ''' open(client_secret_file) f: data = json.loads(f.read()) private_key = data['private_key'] client_email = data['client_email'] credentials = signedjwtassertioncredentials( client_email, private_key, scope=oauth_scope) http_auth = credentials.authorize(http()) try: gmail_service = build('gmail', 'v1', http=http_auth) threads = gmail_service.users().messages().list(userid='me').execute() except exception e: return e
i got exception same question. encounter exception while trying add sub=gmail_address
credentials:
accesstokenrefresherror: unauthorized_client: unauthorized client or scope in request.
i'm trying figure out problem, credentials
without sub
:
>>> credentials = signedjwtassertioncredentials( client_email, private_key, scope=oauth_scope) >>> http = credentials.authorize(http()) >>> credentials.access_token >>> credentials.refresh(http) >>> credentials.access_token u'ya29.pagjjddcxjwsihfn6hku1yakdwn7xmjbks5o76pmrpe1hw1bbgwfzifjp81ade55almvgjv-ybyiyq' >>> gmail_service = build('gmail', 'v1', http=http) >>> request = gmail_service.users().messages().list(userid='me') >>> response = request.execute() { "error": { "errors": [ { "domain": "global", "reason": "failedprecondition", "message": "bad request" } ], "code": 400, "message": "bad request" } }
try use credentials
sub
:
>>> credentials = signedjwtassertioncredentials( client_email, private_key, scope=oauth_scope, sub=gmail_address) >>> http = credentials.authorize(http()) >>> credentials.access_token >>> credentials.refresh(http) accesstokenrefresherror: unauthorized_client: unauthorized client or scope in request.
i found similar question google oauth2 service account http/rest authentication, don't know node.js
. appreciated.
you should use sub field specify account want impersonate.
say, using service account, want details of user user@domain.com, sub field should populated as:
sub: user@domain.com
you should make sure have given service account access users in domain. refer - https://developers.google.com/drive/web/delegation
Comments
Post a Comment