首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >谷歌服务帐户不能冒充GSuite用户

谷歌服务帐户不能冒充GSuite用户
EN

Stack Overflow用户
提问于 2018-03-19 23:38:48
回答 1查看 1.4K关注 0票数 2
代码语言:javascript
代码运行次数:0
运行
复制
from google.oauth2 import service_account
import googleapiclient.discovery

SCOPES = ['https://www.googleapis.com/auth/calendar']
SERVICE_ACCOUNT_FILE = 'GOOGLE_SECRET.json'

credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)

delegated_credentials = credentials.with_subject('address@example.com')

google_calendar = googleapiclient.discovery.build('calendar', 'v3', credentials=delegated_credentials)

events = google_calendar.events().list(
    calendarId='address@example.com',
    maxResults=10
).execute()

上述守则的结果是:

代码语言:javascript
代码运行次数:0
运行
复制
google.auth.exceptions.RefreshError: ('unauthorized_client: Client is unauthorized to retrieve access tokens using this method.', '{\n  "error" : "unauthorized_client",\n  "error_description" : "Client is unauthorized to retrieve access tokens using this method."\n}')

Domain-wide delegation接通了。在GSuite中使用适当的作用域授权服务帐户客户端ID。

服务帐户适用于正常凭据。它仅不适用于委托凭据。

我尝试过不同的API(作用域)和我们域中的不同用户。

我有一位同事试图从零开始对一个样本进行编码,他得到了同样的东西。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-20 09:44:21

我认为您的问题是在调用日历API之前没有授权您的凭据,但是在我自己的实现中有一些不同之处

  • 使用以下导入语句 从oauth2client.service_account导入ServiceAccountCredentials从apiclient导入发现
  • 使用from_json_keyfile_name方法
  • 授权凭据,并在构建服务时将其作为http参数传递

尝试对代码进行以下修改:

代码语言:javascript
代码运行次数:0
运行
复制
from apiclient import discovery
from oauth2client.service_account import ServiceAccountCredentials
import httplib2

SCOPES = ['https://www.googleapis.com/auth/calendar']
SERVICE_ACCOUNT_FILE = 'GOOGLE_SECRET.json'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)

# Use the create_delegated() method and authorize the delegated credentials
delegated_credentials = credentials.create_delegated('address@example.com')  
delegated_http = delegated_credentials.authorize(httplib2.Http())
google_calendar = discovery.build('calendar', 'v3', http=delegated_http)

events = google_calendar.events().list(
    calendarId='address@example.com',
    maxResults=10
).execute()

我还建议在API调用中设置calendarId='primary',以便始终返回当前具有委派凭据的用户的主日历。

有关使用ServiceAccountCredentials进行身份验证的更多信息,请参见以下链接:account.html

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49374112

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档