Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
914 views
in Technique[技术] by (71.8m points)

python - Received error "Not Authorized to access this resource/api" when trying to use Google Directory API and Service Account Authentication

I'm really struggling with trying to use Service Account authentication to use the Google Directory API (Admin SDK).

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.

Here is the code:

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

I tried using the following API as well:

service = build("groupssettings", "v1", http=http)

But this returns an error as well - "Backend Error".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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='[email protected]'
)

where [email protected] is a super administrator in your Google Apps account.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...