0

I'm attempting to use the apiclient to interface with my Google Apps for Education account. I'm using a Service Account as the final goal is to tie this in with our existing in-house system (i.e. server-based system with console access).

My code is:

from httplib2 import Http
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials

import pprint

with open('/path/mykey.p12') as f:
    key = f.read()

client_email = "my_email@developer.gserviceaccount.com"

scope = ['https://www.googleapis.com/auth/admin.directory.user', 'https://www.googleapis.com/auth/admin.directory.group']

http = Http()
credentials = SignedJwtAssertionCredentials(client_email, key, scope=scope)
credentials.authorize(http)

admin = build('admin', 'directory_v1', http=http)
users = admin.users.list(domain="mydomain.edu").execute(http=http)
pprint.pprint(users)

and when I run my code, I get the following traceback:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/home/ajford/.virtualenvs/aosa_usertools/local/lib/python2.7/site-packages/oauth2client/util.py", line 135, in positional_wrap
per
    return wrapped(*args, **kwargs)
  File "/home/ajford/.virtualenvs/aosa_usertools/local/lib/python2.7/site-packages/googleapiclient/http.py", line 723, in execute
    raise HttpError(resp, content, uri=self.uri)
HttpError: <HttpError 403 when requesting https://www.googleapis.com/admin/directory/v1/users?domain=mydomain.edu&alt=json returned "Not Authorized to access this resource/api">

I've entered my API access info on the security page in the Apps Admin Console. I've tried adding sub=superadmin@mydomain.edu. I've made sure Admin SDK is enabled on my project in the Developer's Console. I've made sure my user account under the domain has the appropriate roles under Admin Roles (in case that made a difference).

I've tried my test query under the API Explorer, and it works just fine.

I'm at a loss for where to go from here. Any suggestions?

tehhowch
  • 9,645
  • 4
  • 24
  • 42
A.Ford
  • 1,024
  • 8
  • 10
  • Why do you need to use a service account? – Jay Lee Feb 14 '15 at 19:26
  • @Jay Lee The final product will be run in the background async on a server. I would prefer not to have someone have to log in periodically. Or am I misunderstanding how the web token system works? – A.Ford Feb 14 '15 at 22:04

2 Answers2

1

You don't need to use a service account. Use the installed application flow and get a refresh token. The authorization will last as long as it's not revoked. Only the access token expires and it can be renewed by the refresh token. Access token refreshes are handled automatically by the client library so less work for you.

Jay Lee
  • 13,415
  • 3
  • 28
  • 59
0

Shouldn't the statement

users = admin.users.list(domain="mydomain.edu").execute(http=http)

be

users = admin.users().list(domain="mydomain.edu").execute(http=http)