Google OAuth2授权重定向URI不匹配

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

Google OAuth2 authorization redirect_uri_mismatch

问题

我尝试使用Python通过Google进行身份验证,但我收到400错误(重定向URI不匹配)

但在Google控制台中,我设置了另一个重定向URI

我的credentials.json也有另一个重定向URI

我不明白为什么生成了错误的授权URL:

请访问此URL以授权此应用程序:https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=19********8-m5k0j08t3u36bsed38kv60qmjpaj9pn3.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A34161%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdocuments.readonly&state=q5LBokF7CxHKJH67TsxLni2b0VaSQ6&access_type=offline

我的代码:

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/documents.readonly']

# The ID of a sample document.
DOCUMENT_ID = '13GMqNrDu604Cd8U_N5E6gPkL9rSJZSgRSDZHtg16Kao'


def test():
    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('docs', 'v1', credentials=creds)

        # Retrieve the documents contents from the Docs service.
        document = service.documents().get(documentId=DOCUMENT_ID).execute()

        print('The title of the document is: {}'.format(document.get('title')))
    except HttpError as err:
        print(err)
英文:

I try to auth through google with python, but i get 400 error (redirect URI mismatch)

Google OAuth2授权重定向URI不匹配

but in google console I set another redirect uri

Google OAuth2授权重定向URI不匹配

my credentials.json also has another redirection uri

{
    "web": {
        "client_id": "...",
        "project_id": "resume-hub",
        "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": [
            "https://example.com/"
        ]
    }
}

I don't understand why generated wrong url to authorize:

Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=19********8-m5k0j08t3u36bsed38kv60qmjpaj9pn3.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A34161%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdocuments.readonly&state=q5LBokF7CxHKJH67TsxLni2b0VaSQ6&access_type=offline

my code:

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/documents.readonly']

# The ID of a sample document.
DOCUMENT_ID = '13GMqNrDu604Cd8U_N5E6gPkL9rSJZSgRSDZHtg16Kao'


def test():
    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('docs', 'v1', credentials=creds)

        # Retrieve the documents contents from the Docs service.
        document = service.documents().get(documentId=DOCUMENT_ID).execute()

        print('The title of the document is: {}'.format(document.get('title')))
    except HttpError as err:
        print(err)

答案1

得分: 1

图书馆会根据您的应用程序以及它如何运行您的代码自动创建重定向URI。您的代码正在本地主机上以http运行,因此它从localhost http发送。

您之所以收到重定向不匹配的错误是因为您没有将其添加为云控制台中的有效重定向URI。

老实说,您的代码是为已安装的应用程序设计的,您应该创建本机客户端而不是Web应用程序客户端,那么您就不会遇到这个问题。

英文:

the library automatically creates the redirect URI based upon your application and how its running your code is running on local host as http so it's sending from localhost http

you are getting redirect mismatched because you haven't added that as a valid redirect URI in cloud console.

Tbh your code is designed for a installed app you should have created native client not a web app client then you wouldn't have this issue

huangapple
  • 本文由 发表于 2023年7月20日 21:01:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76730179.html
匿名

发表评论

匿名网友

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

确定