Google Docs API授权报错Error 400: redirect_uri_mismatch求助
问题:Google Docs API授权时出现Error 400: redirect_uri_mismatch
我开发了一款可从图片提取文本并写入新Google文档的应用,已下载并配置好credentials.json文件,但调用API进行授权时出现以下错误:
访问被阻止:此应用的请求无效
email@gmail.com(非真实邮箱)
无法登录,因为此应用发送了无效请求。您可以稍后重试或联系开发者了解此问题。了解有关此错误的更多信息
如果您是此应用的开发者,请查看错误详情。
Error 400: redirect_uri_mismatch
相关代码如下:
import streamlit as st from PIL import Image import pytesseract import cv2 import tempfile import numpy as np from Functionalities.camera_input import get_camera_input from Functionalities.upload_input import get_uploaded_input from Functionalities.text_extraction import get_text_from_image from Functionalities.docs_api import create_blank_document 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 st.title('Make notes on the go...') use_camera = st.checkbox("Use Camera") if use_camera: image_file = get_camera_input() else: image_file = get_uploaded_input() col1, col2 = st.columns(2) show_image = col1.checkbox("Show Image") show_text = col2.checkbox("Show Text") image_container = st.container() if show_image: with image_container: if image_file is not None: st.image(image_file) else: st.write("No image available") if show_text: img_to_text = get_text_from_image(image_file) if img_to_text is not None: extracted_text = st.text_area("Extracted Text:", img_to_text, height=200) # User options for writing to documents (implementation not included here) write_to_options = st.selectbox("Write To:", ("New Document", "Existing Document")) if write_to_options == "New Document": credentials = 'credentials.json' if not credentials: st.write("Please authorize your Google account to write to Docs:") # Implement OAuth flow using google-auth-oauthlib to obtain credentials if credentials: doc_title = st.text_input("New Document Title:") if st.button("Create and Write"): # Implement create_blank_google_doc function using the obtained credentials doc_id = create_blank_document(credentials, doc_title) # if doc_id: # # Call append_text_to_google_doc function using the obtained credentials # # append_text_to_google_doc(credentials, doc_id, extracted_text) # # st.success(f"Text appended to new document: {doc_title}") else: st.write("Existing Document functionality not implemented yet.") else: st.write("No image selected or text extraction failed.")
# CREDENTIALS_FILE = 'credentials.json' # DOC_TITLE = "My New Document" 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 def create_blank_document(CREDENTIALS_FILE, DOC_TITLE): SCOPES = ['https://www.googleapis.com/auth/documents'] # Initialize credentials flow flow = InstalledAppFlow.from_client_secrets_file(CREDENTIALS_FILE, SCOPES) # Get user credentials credentials = flow.run_local_server(port=0) # Build the Docs service object service = build('docs', 'v1', credentials=credentials) # Create a new document body body = { 'title': DOC_TITLE } # Create the document document = service.documents().create(body=body).execute() print(f"Doc created with ID: {document.get('id')}")
解决方案:修复redirect_uri_mismatch错误
redirect_uri_mismatch错误是因为Google Cloud控制台中配置的授权重定向URI,和应用实际请求中使用的URI不一致导致的,按以下步骤修复:
确认应用实际使用的重定向URI
调用flow.run_local_server(port=0)时,系统会随机分配可用端口,格式为http://localhost:<随机端口>/。启动授权流程时,查看浏览器地址栏的redirect_uri参数,或控制台输出,确认具体URI。在Google Cloud控制台配置匹配的重定向URI
- 进入Google Cloud控制台,打开你的项目,导航到「API和服务」→「凭据」页面。
- 找到对应
credentials.json的OAuth客户端ID(类型为「桌面应用」)。 - 编辑该客户端ID,在「已授权的重定向URI」中添加以下内容:
- 若使用固定端口,添加
http://localhost:8080/(示例端口) - 若使用随机端口,添加
http://localhost/(部分环境支持通配端口) - 也可直接添加你看到的具体随机端口URI,比如
http://localhost:54321/
- 若使用固定端口,添加
- 保存配置,等待5-10分钟让设置生效。
代码优化:指定固定端口避免随机端口问题
修改create_blank_document函数中的授权代码,指定固定端口:def create_blank_document(CREDENTIALS_FILE, DOC_TITLE): SCOPES = ['https://www.googleapis.com/auth/documents'] flow = InstalledAppFlow.from_client_secrets_file(CREDENTIALS_FILE, SCOPES) # 指定固定端口8080,和控制台配置的URI保持一致 credentials = flow.run_local_server(port=8080) service = build('docs', 'v1', credentials=credentials) body = {'title': DOC_TITLE} document = service.documents().create(body=body).execute() print(f"Doc created with ID: {document.get('id')}")额外检查
- 确认
credentials.json中的client_id和client_secret与Google Cloud控制台的客户端信息完全一致。 - 若使用Streamlit,注意其默认运行端口为8501,避免OAuth端口和它冲突。
- 确认
内容的提问来源于stack exchange,提问作者Avishkar Borkar
相关产品推荐
相关产品推荐

