python-2.7 – 尝试通过p12访问Google Directory 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">

设置完成:

>我在管理控制台中有超级管理员级别的访问权限.
>我还补充说
范围通过安全> showmore> advance> manageipclient>授权
添加了用户ID和范围

https://www.googleapis.com/auth/admin.directory.user.readonly
https://www.googleapis.com/auth/admin.directory.user
>在服务控制台中添加了用户权限并成为所有者.
> Admin SDK已启用

我到底在哪里错过了这些东西.为什么它说我无权访问资源/ api

最佳答案
我看到你正在使用delegated_credentials.你用过吗?

更改以下行:

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

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

转载注明原文:python-2.7 – 尝试通过p12访问Google Directory API会导致未经授权的错误 - 代码日志