fastapi中的重定向uri不匹配

2024-05-14 20:48:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望大家都好。我正在尝试在我的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 dashboard中的URL配置

enter image description here

我在下面提到的错误

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

Tags: andclientidgetasyncreturn错误google
3条回答

问题可能出在process_login()函数中,该函数在/callback api中的verify_和_process()函数中被调用

让我们看看PrimeSoLogin()函数(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}"

我猜(重定向uri不匹配)错误是因为您在GoogleSSO()调用中使用了HTTP重定向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://")

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

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

is not

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

它们是两个不同的URL

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

顺便问一下,你是否在谷歌云(https://developers.google.com/identity/sign-in/web/sign-in)中注册了你的应用程序?因为您使用“客户机id”和“客户机机密”作为参数

这是因为每次运行应用程序时,重定向URI中的端口号都在更改。 因此,每次运行时,它都会变成:

http://localhost:65280/
http://localhost:65230/
http://localhost:63280/

等等。我还没有解决办法。我自己现在正在做

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

  1. 修复url@app1.get(“/google/callback/”)#添加/

相关问题 更多 >

    热门问题