尝试授权

时间:2016-08-09 00:46:40

标签: google-admin-sdk

我正在使用Google Admin SDK Reports V1 Api从Google Apps管理面板收集所有管理活动。

我的Google Api python客户端最近更新为版本"google-api-python-client (1.5.1)"

以前我使用以下内容:

from oauth2client.client import SignedJwtAssertionCredentials

serviceAccountEmail = "blahblablah1233324@developer.gserviceaccount.com"
key = "google-apps-file.p12"
scopes = ['https://www.googleapis.com/auth/admin.reports.audit.readonly']


credentials = SignedJwtAssertionCredentials(
    serviceAccountEmail, key, scope=scopes, sub=userEmail)

然后Google放弃了对SignedJwtAssertionCredentials的支持。所以我改用了这个。

from oauth2client.service_account import ServiceAccountCredentials

serviceAccountEmail = "blahblablah1233324@developer.gserviceaccount.com"
key = "google-apps-file.p12"
scopes = ['https://www.googleapis.com/auth/admin.reports.audit.readonly']

credentials = ServiceAccountCredentials.from_p12_keyfile(
    serviceAccountEmail, key, scopes=scopes)`

好的,这应该是一个相对容易的小代码更改,但是当我运行代码时,我得到以下错误。

  File "/usr/local/lib/python2.7/site-packages/oauth2client/util.py", line 137, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/googleapiclient/http.py", line 832, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 401 when requesting https://www.googleapis.com/admin/reports/v1/activity/users/all/applications/admin?alt=json returned "Access denied. You are not authorized to read activity records.">

所以没有权限更改,我注意到的一件事是原始代码要求sub=userEmail(这是一个模拟帐户,该帐户将拥有对Google Apps域的特定管理员权限。)

我会得到401,但新文档中没有提到sub=userEmail参数。

1 个答案:

答案 0 :(得分:0)

我意识到自己错过了什么。

最初我有

 f = open(serviceAccountKeyLocation, 'rb')
 key = f.read()
 f.close()
 # Packaging up the auth parameters to pass along with the request.

 credentials = SignedJwtAssertionCredentials(serviceAccountEmail, key, scope=scopes, sub=userEmail)
 http = credentials.authorize(http)
 return http

然后我做了一些阅读和进一步的研究。

然后用它替换它。

credentials = ServiceAccountCredentials.from_p12_keyfile(serviceAccountEmail, 
                                                             serviceAccountKeyLocation,
                                                             scopes=scopes)
delegate_credentials = credentials.create_delegated(userEmail) # this fixes the sub user
http = delegate_credentials.authorize(http)
return http

我运行的Google Api python客户端的版本仍在使用from oauth2client.client import SignedJwtAssertionCredentials,而新的更新版本使用from oauth2client.service_account import ServiceAccountCredentials