我遇到了Directory API +服务帐户(Google API)的问题。这是我目前的设置:
网页上有OAuth2登录链接,如下所示:https://accounts.google.com/o/oauth2/auth?access_type=offline&state=%2Fprofile&redirect_uri=##REDIR##&response_type=code&client_id=##CLIENTID##&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fadmin.directory.user.readonly
用户登录,授权应用代表他们以只读模式访问Directory API。
然后,我尝试使用目录API检索给定用户的域的用户(通过知道其电子邮件地址)。
Python代码:
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
import httplib2
CLIENT_ID = "xzxzxzxzxzxz.apps.googleusercontent.com"
APP_EMAIL = "xzxzxzxzxzxz@developer.gserviceaccount.com"
SCOPES = ('https://www.googleapis.com/auth/admin.directory.user.readonly')
f = file('key.p12', 'rb')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(APP_EMAIL, key, SCOPES, sub="user@example.com")
http = httplib2.Http()
http = credentials.authorize(http)
directory_service = build('admin', 'directory_v1', http=http)
users = directory_service.users().list(domain="example.com").execute()
print users
我还尝试将sub="user@example.com"
设置为应用所有者,例如sub="appowner@company.com"
,但无济于事。
我尝试的另一件事是根本不使用模拟(即删除sub = xx部分),这导致我出现此错误:
apiclient.errors.HttpError:https://www.googleapis.com/admin/directory/v1/users?domain = example.com& salt = json返回"未授权访问此资源/ api&# 34;>
使用模仿总能让我知道这一点。我已经证实它与我试图调用的范围和api有关:
oauth2client.client.AccessTokenRefreshError:access_denied
现在,实际问题:
我应该使用服务帐户吗?对我来说,这是最方便的方式,因为我不必存储可能完全过时的令牌。
如果服务帐户是可行的方式,我在使用它的方式上做错了什么?使用Google Apps管理员帐户(通过OAuth网络登录)或应用程序所有者帐户进行模拟似乎不起作用。