python google_auth_oauthlib带外(OOB)错误

q5iwbnjs  于 2022-12-02  发布在  Python
关注(0)|答案(1)|浏览(192)

我尝试运行一个内部应用程序(这是一个简单的脚本),并使用OAuth和python进行身份验证。但在运行脚本后,当我点击链接对用户进行身份验证时,我遇到了以下错误:
已阻止带外(OOB)流以保护用户安全。请按照下面的开发人员文档中链接的带外(OOB)流迁移指南将您的应用迁移到其他方法。要求详细信息:用户名:
下面是我的代码:

# More code

import google_auth_oauthlib.flow

# More code

scopes = ["https://www.googleapis.com/auth/youtube.upload"]

# More code

def upload():
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    # os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    client_secrets_file = os.path.abspath(os.path.join(os.path.dirname(__file__), "client_secrets.json"))

    api_service_name = "youtube"
    api_version = "v3"

    # Get credentials and create an API client
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes)
    credentials = flow.run_console()

还有我的client_secrets.json

{
    "installed": {
        "client_id": "**********",
        "project_id": "MY-PROJECT-ID",
        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
        "token_uri": "https://oauth2.googleapis.com/token",
        "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
        "client_secret": "*****",
        "redirect_uris": [
            "http://localhost:3000"
        ]
    }
}

但检索要进行身份验证的代码的URL仍为:https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=*********&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.upload&state=******&prompt=consent&access_type=offline
正如你所看到的,url仍然使用oob,我没有找到任何方法来使它改为使用localhost。
我运行的pip库版本:

pip list
oauthlib                 3.2.2
requests-oauthlib        1.3.1
google-api-python-client 2.66.0
google-auth              2.14.1
google-auth-httplib2     0.1.0
google-auth-oauthlib     0.7.1
googleapis-common-protos 1.57.0
http-client              0.1.22
httplib2                 0.21.0

并使用python 3.10.7

  • 我已经检查了此文档,对于桌面应用程序,它只是说“使用回环URL”:https://developers.google.com/identity/protocols/oauth2/resources/oob-migration
  • 我也读了这篇文章来正确使用地址环回,但没有成功:https://developers.google.com/identity/protocols/oauth2/native-app#handlingresponse
  • 我尝试运行一个用python -m http.server 3000启动的本地Web服务器来侦听环回上的事件,但没有成功

你有什么想法如何使这工作?非常感谢!

rqqzpn5f

rqqzpn5f1#

首先,请确保您已经更新了客户端库。我不确定您运行的是哪个版本,但库大约一年前就已修复。
然后拆下端口。

"redirect_uris":["http://localhost"]

第三次
如果这不起作用,这里是我的视频样本。插入它应该开箱即用。

#   To install the Google client library for Python, run the following command:
#   pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

from __future__ import print_function

import os.path

import google.auth.exceptions
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/youtube']

def main():

    """Shows basic usage of the YouTube v3 API.
    Uploads a private video to YouTube
    """
    creds = None
    # The file token.json 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.json'):
        try:
            creds = Credentials.from_authorized_user_file('token.json', SCOPES)
            creds.refresh(Request())
        except google.auth.exceptions.RefreshError as error:
            # if refresh token fails, reset creds to none.
            #creds = None
            print(f'An error occurred: {error}')
    # 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(
                'C:\YouTube\dev\credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        service = build('youtube', 'v3', credentials=creds)

        body = dict(
            snippet=dict(
                title="Test",
                description="test",
                tags="tes"
            ),
            status=dict(
                privacyStatus="private"
            )
        )

        media = MediaFileUpload("dummyvideo.mkv", chunksize=-1, resumable=True)

        results = service.videos().insert(
                part=",".join(body.keys()),
                body=body,
                media_body=media).execute()
        print(F'video ID: {results.get("id")}')

    except HttpError as error:
        # TODO(developer) - Handle errors from drive API.
        print(f'An error occurred: {error}')

if __name__ == '__main__':
    main()

google api python客户端的版本

我正在运行这些版本的相关google apis python库。

pip list

google-api-core          2.10.1
google-api-python-client 2.62.0
requests-oauthlib        1.3.1

我认为oauthlib可能也是其中的一部分。

相关问题