尝试通过p12访问Google Directory API会导致未经授权的错误

时间:2017-05-10 05:08:28

标签: python-2.7 google-api-client google-authentication google-directory-api google-python-api

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(
    'googleapptara@tara1-167105.iam.gserviceaccount.com',
    '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('tara.gurung@orgemail.net)

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

在这里,我正在尝试使用 p12 安全文件执行服务器到服务器身份验证并尝试抓取域中的所有用户。

我已成功通过3legs身份验证获取用户列表,方法是通过同一帐户中的浏览器进行授权

但是这样会给我带来以下错误。

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">

设置完成:

  1. 我在管理控制台中拥有超级管理员级别访问权限。

  2. 我也补充说 范围通过安全&gt; showmore&gt; advance&gt; manageipclient&gt;授权 添加了用户ID和范围

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

  3. 在服务控制台中添加了用户权限并成为了所有者。

  4. Admin SDK已启用

  5. 我到底错过了什么。为什么它说我无权访问资源/ api

1 个答案:

答案 0 :(得分:2)

我看到你正在使用delegated_credentials。你用过吗??

更改以下行:

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

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