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()
上述代码的结果是:
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
已开启。服务帐户客户端ID已在GSuite中使用适当的范围进行授权。
服务帐户适用于普通凭据。它仅适用于委派凭据。
我在我们的域中尝试过不同的API(范围)和不同的用户。
我让一位同事尝试从头开始编写样本,他得到了同样的东西。
答案 0 :(得分:2)
我认为您的问题在于,您在拨打Calendar API之前未授权您的凭据,但您在我自己的实施中使用了一些差异
from oauth2client.service_account import ServiceAccountCredentials
和from apiclient import discovery
from_json_keyfile_name
方法http
参数传递尝试对您的代码进行此修改:
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
进行身份验证的详细信息,请参阅以下链接:http://oauth2client.readthedocs.io/en/latest/source/oauth2client.service_account.html