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('<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86e7e2e2f4e3f5f5c6e3fee7ebf6eae3a8e5e9eb" rel="noreferrer noopener nofollow">[email protected]</a>')
google_calendar = googleapiclient.discovery.build('calendar', 'v3', credentials=delegated_credentials)
events = google_calendar.events().list(
calendarId='<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="650401011700161625001d04081509004b060a08" rel="noreferrer noopener nofollow">[email protected]</a>',
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}')
域范围授权
已开启。服务帐户客户端 ID 在 GSuite 中的适当范围内进行授权。
服务帐户适用于普通凭据。它仅不适用于委派凭据。
我在我们的域中尝试了不同的 API(范围)和不同的用户。
我有一位同事尝试从头开始编写示例,他得到了同样的结果。
最佳答案
我认为您的问题是您在调用Calendar API之前没有授权您的凭据。但我在自己的实现中使用了一些差异
使用以下导入语句
from oauth2client.service_account import ServiceAccountCredentials from apiclient import discovery
授权凭据并在构建服务时将其作为
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('<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="244540405641575764415c45495448410a474b49" rel="noreferrer noopener nofollow">[email protected]</a>')
delegated_http = delegated_credentials.authorize(httplib2.Http())
google_calendar = discovery.build('calendar', 'v3', http=delegated_http)
events = google_calendar.events().list(
calendarId='<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="472623233522343407223f262a372b226924282a" rel="noreferrer noopener nofollow">[email protected]</a>',
maxResults=10
).execute()
我还建议在 API 调用中设置 calendarId='primary'
,以便您始终返回当前已为其委派凭据的用户的主日历。
有关使用 ServiceAccountCredentials
进行身份验证的更多信息,请参阅以下链接:http://oauth2client.readthedocs.io/en/latest/source/oauth2client.service_account.html
关于python - Google 服务帐户无法模拟 GSuite 用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49374112/