在fastapi中重定向uri不匹配

问题描述

希望大家一切都好。我正在尝试在我的 fastapi 应用程序上实现 google sso。输入用户凭据后,它在重定向时被重定向,我收到此错误

google_sso = GoogleSSO("client-id","client-secret","http://127.0.0.1:8000/google/callback/")

@app1.get("/google/login")
async def google_login():
    """Generate login url and redirect"""
    return await google_sso.get_login_redirect()


@app1.get("/google/callback")
async def google_callback(request: Request):
    """Process login response from Google and return user info"""
    user = await google_sso.verify_and_process(request)
    print("Hellooooooooooooooo")
    print(user,"11111111111111")
    return {
        "id": user.id,"picture": user.picture,"display_name": user.display_name,"email": user.email,"provider": user.provider,}

我在下面的屏幕截图中分享了 google 仪表板中的 URL 配置

enter image description here

我在下面提到的错误

oauthlib.oauth2.rfc6749.errors.CustomOAuth2Error: (redirect_uri_mismatch) Bad Request

解决方法

  1. 尝试使用 127.0.0.1:8000/google/callback #remove /

  1. 修复网址@app1.get("/google/callback/") #add /
,

问题可能出在 process_login() 函数中,该函数在您的 /callback api 中的 verify_and_process() 函数中被调用。

让我们来看看 process_login() 函数(https://tomasvotava.github.io/fastapi-sso/sso/base.html#fastapi_sso.sso.base.SSOBase.verify_and_process)的内部:

async def process_login(self,code: str,request: Request) -> Optional[OpenID]:
"""This method should be called from callback endpoint to verify the user and request user info endpoint.
This is low level,you should use {verify_and_process} instead.
"""
url = request.url
current_url = str(url).replace("http://","https://")
current_path = f"https://{url.netloc}{url.path}"

我猜 (redirect_uri_mismatch) 错误是因为您在 GoogleSSO() 调用中使用了 HTTP redirect_url:

google_sso = GoogleSSO("client-id","client-secret","http://127.0.0.1:8000/google/callback/")

在 process_login() 函数内,您请求的 url 内的重定向 url 的 HTTP 被替换为 HTTPS:

url = request.url    
current_url = str(url).replace("http://","https://")

替换后,您的重定向网址不匹配,因为

https://127.0.0.1:8000/google/callback/ 

is not

http://127.0.0.1:8000/google/callback/

它们是两个不同的网址。

解决方案可能是您通过自签名证书使用 HTTPS 保护您的服务器。 (那个很简单:https://dev.to/rajshirolkar/fastapi-over-https-for-development-on-windows-2p7d

顺便说一句。您是否在谷歌云 (https://developers.google.com/identity/sign-in/web/sign-in) 中注册了您的应用?因为您使用“client-id”和“client-secret”作为参数。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...