首页 文章

Google API授权(服务帐户)错误:HttpAccessTokenRefreshError:unauthorized_client:请求中未经授权的客户端或范围

提问于
浏览
1

我在凭据选项卡中的开发者控制台我单击 Create credentials 下拉菜单并选择 Help me choose . 我点击我想要使用的API( YouTube Analytics API ),我将从( Other non-UI (e.g. cron job, daemon) )调用,我将访问哪些数据( Application Data ),然后我是否使用Google App Engine( no ) . 我点击按钮查看我需要的凭据,它告诉我 You alread have credentials that are suitable for this purpose .

我有 Service account 用于连接Google Search Console API以访问我公司拥有的多个网站的数据 . 因为我们有多个站点,所以我根据我的电子邮件地址使用委派凭据 . 这是我用于对Search Console API进行身份验证的代码:

from httplib2 import Http
from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build

scopes = ['https://www.googleapis.com/auth/webmasters.readonly']
credentials = ServiceAccountCredentials.from_json_keyfile_name('keyfile.json', scopes=scopes)

delegated_credentials = credentials.create_delegated('<my-email>')
http_auth = delegated_credentials.authorize(Http())

webmasters_service = build('webmasters', 'v3', http=http_auth)

现在,我'm trying to use a similar approach with the YouTube Analytics API but I'm收到此错误: HttpAccessTokenRefreshError: unauthorized_client: Unauthorized client or scope in request. . 这是我的代码:

from httplib2 import Http
from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build

START_DATE = "2016-09-01"
END_DATE = "2016-09-30"

scopes = ['https://www.googleapis.com/auth/yt-analytics.readonly']
credentials = ServiceAccountCredentials.from_json_keyfile_name('keyfile.json', scopes=scopes)

delegated_credentials = credentials.create_delegated('<my-email>')
http_auth = delegated_credentials.authorize(Http())

youtube_service = build('youtubeAnalytics', 'v1', http=http_auth)

analytics_query_response = youtube_service.reports().query(
    ids="channel==<my-youtube-channel-id>",
    metrics="views",
    start_date=START_DATE,
    end_date=END_DATE
).execute()

keyfile.json 与我用于连接到Search Console API的文件(包含服务帐户凭据)相同 . 我甚至尝试创建一个新的服务帐户并使用这些凭据,但我没有在开发者控制台中启用所有YouTube API .

Do you have any idea why I'm getting the HttpAccessTokenRefreshError: unauthorized_client: ... error?

编辑:以前我使用OAuth ID而不是服务帐户,当我运行脚本时,会显示一个浏览器选项卡,我必须选择一个帐户 . 我收到了两个选项:一个是我的电子邮件,另一个是我作为经理添加的YouTube帐户 . 你是否认为我收到了这个错误,因为我正在使用我的电子邮件地址生成凭据(而不是YouTube帐户)?

edit2:YouTube帐户似乎不属于我们Google Apps域的范畴 . 因此,这可能就是为什么我无法授权使用我的电子邮件地址,即使我已经成为该YouTube帐户的管理员,并使用该电子邮件地址 .

1 回答

  • 2

    我在documentation上发现您无法在YouTube Analytics API中使用服务帐户 .

    这里说:

    服务帐户流支持不访问用户信息的服务器到服务器交互 . 但是,YouTube Analytics API不支持此流程 . 由于无法将服务帐户与YouTube帐户相关联,因此尝试使用此流程授权请求会产生错误 .

    我也在这个由Google员工回答的问题中找到了它 .

    有关更多信息,请查看SO question .

相关问题