Search code examples
python-2.7google-api-clientgoogle-authenticationgoogle-directory-apigoogle-python-api

Trying to Access Google Directory API via p12 throws not authorized error


from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import json
import base64
import httplib2

f = file('tara1-553d334b8702.p12', 'rb')
key = f.read()
f.close()

credentials = ServiceAccountCredentials.from_p12_keyfile(
    '[email protected]',
    'tara1-554d335b8702.p12',
    private_key_password='notasecret',
    scopes=['https://www.googleapis.com/auth/admin.directory.user.readonly','https://www.googleapis.com/auth/admin.directory.user'] 
)

delegated_credentials=credentials.create_delegated('[email protected])

http = httplib2.Http()
http = credentials.authorize(http)


DIRECOTORY = build('admin', 'directory_v1', credentials=credentials)
maxResults=10,orderBy='email').execute()
results = DIRECOTORY.users().list(domain='domainnamehere.net').execute()
users = results.get('users', [])

print users

Here ,I am trying to do the server to server authentication using the p12 security file and trying to grab all the users in the domain.

I have successfully fetched the users list by 3legs authentication,by authorizing from the browswer in the same account

But this way it's throwing me the following errors.

File "testing.py", line 41, in <module>
    results = DIRECOTORY.users().list(domain='domainemailhere.net').execute()
  File "/home/tara/taraproject/scripttesting/virtualenvforGapi/local/lib/python2.7/site-packages/oauth2client/_helpers.py", line 133, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/home/tara/taraproject/scripttesting/virtualenvforGapi/local/lib/python2.7/site-packages/googleapiclient/http.py", line 840, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/admin/directory/v1/users?domain=nepallink.net&alt=json returned "Not Authorized to access this resource/api">

SETUP DONE:

  1. I have a super admin level access in the admin console.

  2. I have also added the scope via security>showmore>advance>manageipclient>authorize Added the user id and scope

    https://www.googleapis.com/auth/admin.directory.user.readonly https://www.googleapis.com/auth/admin.directory.user

  3. Added the users permission in service console and made a owner.

  4. Admin SDK is Enabled

Where exactly am I missing the things. Why does it says I have no authority to access the resources/api


Solution

  • I see you are using delegated_credentials. Have you used it??

    Change following line:

    DIRECOTORY = build('admin', 'directory_v1', credentials=credentials)
    

    to

    DIRECOTORY = build('admin', 'directory_v1', credentials=delegated_credentials)