无需每次身份验证即可使用 Google Api 的任何方式?

Posted

技术标签:

【中文标题】无需每次身份验证即可使用 Google Api 的任何方式?【英文标题】:Any way to use Google Api without every-time authentication? 【发布时间】:2020-12-29 10:28:48 【问题描述】:

我尝试在 PC 上的自动运行中使用 Python 上的 API。但我不能,因为每次程序启动时,它都会询问我授权码。 这是我的代码:

client_secret_file = "client_secret.json"
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes)
    credentials = flow.run_console()
    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials)

有什么帮助吗?谢谢

【问题讨论】:

您只访问自己的帐户吗?您不会访问其他用户的帐户吗? 【参考方案1】:

因为您使用的是 YouTube API,所以您不能使用服务帐户,您需要使用 Oauth2。

Oauth2 可以返回称为刷新令牌的东西,如果您存储此令牌,您的代码可以在下次运行时访问刷新令牌并使用刷新令牌请求新的访问令牌,这样就不需要询问您每次运行以访问您的数据时。

# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
    with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            'credentials.json', SCOPES)
        creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open('token.pickle', 'wb') as token:
        pickle.dump(creds, token)

我知道的唯一包含刷新令牌的官方示例是否在这里 Python quickstart 您需要为 YouTube 更改它,但验证代码确实是您所需要的,只需将其插入您的代码,您应该是 GTG

【讨论】:

【参考方案2】:

您可以使用Service Account 实现此目的。

https://googleapis.dev/python/google-api-core/latest/auth.html#service-accounts

服务帐号在技术上由开发者预先授权。

如果 API 不支持服务帐户(在某些情况下),那么您可以尝试 oauth2 在您同意询问帐户所有者是否可以访问的地方

【讨论】:

我用的是python API,不好意思之前没说 更新了python Google API的服务账户详情链接 作者似乎正在使用 YouTube API,youtube api 不支持服务帐户。这个答案无济于事。

以上是关于无需每次身份验证即可使用 Google Api 的任何方式?的主要内容,如果未能解决你的问题,请参考以下文章