收到错误“未授权访问此资源/api";尝试使用Google Directory API和服务帐户身份验证时
我真的很努力尝试使用服务帐户身份验证来使用Google Directory API(Admin SDK).
I'm really struggling with trying to use Service Account authentication to use the Google Directory API (Admin SDK).
使用基于客户端的三足式OAuth可以正常工作(在这里进行了测试- https://developers.google.com/admin-sdk/directory/v1/reference/members/insert ),但是我正在使用的服务帐户的权限委派有问题.在Google Apps管理下,我启用了使用API的功能,并按照指示将服务帐户添加到了允许的OAuth客户端列表中.
Using client based three legged OAuth this works (tested here - https://developers.google.com/admin-sdk/directory/v1/reference/members/insert) but there's a problem with the permission delegation to the service account I am using. Under the Google Apps administration, I enabled using APIs and added the service account to the list of allowed OAuth clients as instructed.
这是代码:
import httplib2
import sys
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
credentials = SignedJwtAssertionCredentials(
'<KEY>@developer.gserviceaccount.com',
'<KEY DATA>',
scope='https://www.googleapis.com/auth/apps.groups.settings https://www.googleapis.com/auth/admin.directory.group https://www.googleapis.com/auth/admin.directory.group.member'
)
http = httplib2.Http()
http = credentials.authorize(http)
service = build("admin", "directory_v1", http=http)
groups = service.groups()
g = groups.get(groupKey="<GROUP NAME>").execute()
最终,我收到以下错误消息:
Eventually, I get the following error:
apiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/admin/directory/v1/groups/<GROUP NAME>?alt=json returned "Not Authorized to access this resource/api">
我也尝试使用以下API:
I tried using the following API as well:
service = build("groupssettings", "v1", http=http)
但这也会返回一个错误-后端错误".
But this returns an error as well - "Backend Error".
即使您使用的是服务帐户,在具有适当管理员权限的实例中,仍然需要代表Google Apps用户执行操作.尝试做:
Even though you're using a Service Account you still need to act on behalf of a Google Apps user in the instance that has the proper admin permissions. Try doing:
credentials = SignedJwtAssertionCredentials(
'<KEY>@developer.gserviceaccount.com',
'<KEY DATA>',
scope='https://www.googleapis.com/auth/apps.groups.settings https://www.googleapis.com/auth/admin.directory.group https://www.googleapis.com/auth/admin.directory.group.member',
sub='super-admin@yourdomain.com'
)
其中super-admin@yourdomain.com是您Google Apps帐户中的超级管理员.
where super-admin@yourdomain.com is a super administrator in your Google Apps account.