我在尝试获取用于获取刷新令牌的认证代码时遇到了访问被阻止的错误。

huangapple go评论71阅读模式
英文:

I am getting Access blocked error while trying to get athentication code which i will use to get refresh token?

问题

这是我尝试的内容:
我将OAuth Consent Screen的状态从测试更改为发布,并且应用范围是external,然后我创建了OAuth客户端ID令牌,然后我尝试了这段代码,但当我尝试对应用进行身份验证时,它会出现错误。

from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

SCOPES = ['https://www.googleapis.com/auth/drive']

CLIENT_SECRETS_FILE = 'client.json'

REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES, redirect_uri=REDIRECT_URI)
auth_url, _ = flow.authorization_url(prompt='consent')
print(f'请访问此URL以授权应用程序:{auth_url}')
auth_code = input('输入授权码:')
flow.fetch_token(code=auth_code)
creds = flow.credentials
print(f'访问令牌:{creds.token}')
print(f'刷新令牌:{creds.refresh_token}')

你能看出如何在Python中实现它并解决此错误吗?

英文:

here is what is tried
I changed the status of O Auth Consent screen from testing to publish and the app scope is external then i created the O Auth client Id token and then i tried this code but this is giving error when i try to authenticate to the app.

from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

SCOPES = ['https://www.googleapis.com/auth/drive']

CLIENT_SECRETS_FILE = 'client.json'

REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES, redirect_uri=REDIRECT_URI)
auth_url, _ = flow.authorization_url(prompt='consent')
print(f'Please go to this URL to authorize the application: {auth_url}')
auth_code = input('Enter the authorization code: ')
flow.fetch_token(code=auth_code)
creds = flow.credentials
print(f'Access token: {creds.token}')
print(f'Refresh token: {creds.refresh_token}')

Can you spot how to do it in python and solve this error.

答案1

得分: 1

你不能使用 urn:ietf:wg:oauth:2.0:oob,因为它已经停用。

你最好按照官方的快速入门来操作。

此示例将使用 creds = flow.run_local_server(port=0) 来打开授权屏幕,而不是要求你点击链接,因为这样可能会返回 404 错误,因为你没有本地 Web 服务器在运行。

from __future__ import print_function

import os.path

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

# 如果要修改这些范围,请删除 token.json 文件。
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']

def main():
    """展示了 Drive v3 API 的基本用法。
    打印用户可以访问的前 10 个文件的名称和 ID。
    """
    creds = None
    # 文件 token.json 存储了用户的访问令牌和刷新令牌,在第一次授权流完成后会自动生成。
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # 如果没有(有效的)凭据可用,让用户登录。
    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)
        # 保存凭据以备下次运行使用
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

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

        # 调用 Drive v3 API
        results = service.files().list(
            pageSize=10, fields="nextPageToken, files(id, name)").execute()
        items = results.get('files', [])

        if not items:
            print('未找到文件。')
            return
        print('文件:')
        for item in items:
            print(u'{0} ({1})'.format(item['name'], item['id']))
    except HttpError as error:
        # TODO(开发者)- 处理来自 Drive API 的错误。
        print(f'发生错误:{error}')

if __name__ == '__main__':
    main()
英文:

you cant use urn:ietf:wg:oauth:2.0:oob, this was discontinued.

You would have better luck following the official QuickStart

This sample will use creds = flow.run_local_server(port=0) to open the consent screen for you rather then asking you to click a link which will probably return a 404 error because you don't have a local web server running.

from __future__ import print_function
import os.path
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
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']
def main():
"""Shows basic usage of the Drive v3 API.
Prints the names and ids of the first 10 files the user has access to.
"""
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'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# 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.json', 'w') as token:
token.write(creds.to_json())
try:
service = build('drive', 'v3', credentials=creds)
# Call the Drive v3 API
results = service.files().list(
pageSize=10, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
print('No files found.')
return
print('Files:')
for item in items:
print(u'{0} ({1})'.format(item['name'], item['id']))
except HttpError as error:
# TODO(developer) - Handle errors from drive API.
print(f'An error occurred: {error}')
if __name__ == '__main__':
main()

huangapple
  • 本文由 发表于 2023年3月1日 16:09:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75600994.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定