【问题标题】:How to retrieve query parameter from URL after RedirectResponse in FastAPI?如何在 FastAPI 中的 RedirectResponse 之后从 URL 检索查询参数?
【发布时间】:2022-11-27 05:25:40
【问题描述】:

我正在实施一个 oauth 授权代码流程。

我想要的是检索重定向后在 url 中显示的 code。我进行了研究,但没有发现真正有用的东西。我认为如果我可以在RedirectResponse 之后获取浏览器中的当前 url,然后我可以使用 urllib.parse 之类的 python 模块提取它的 code 参数。或者,FastApi 是否有办法帮助我在RedirectResponse 之后获取该网址?我在他们的文档中看到了 Background Tasks,但我不知道这是否真的可以帮助我在重定向后检索 url。在看到this 后,我尝试使用selenium 库,但它打开了一个新窗口,当我尝试应用 cmets 中建议的 driver.get('put_your_site_name') 时,它花费的时间太长了。

这是代码摘录,它将我重定向到浏览器中的 url,并将代码作为参数:

from uuid import uuid4

from oauthlib.oauth2 import WebApplicationClient

from fastapi import APIRouter, Request, Response

from fastapi.responses import RedirectResponse



router = APIRouter()

@router.get("/install/")
async def install(request: Request) -> Response:
    """Trigger the client identification process."""
    client_id = "xxx"
    client = WebApplicationClient(client_id)
    state = str(uuid4())

    authorization_url = f"https://api-url.com/auth/authorize?client_id={client_id}"
    url = client.prepare_request_uri(
        authorization_url,
        redirect_uri="http://127.0.0.1:8000/callback/",
        scope=["read:user"],
        state=state,
    )

    return RedirectResponse(url=url)

通过以上,我被重定向到以授权代码作为参数的回调 url:http://127.0.0.1:8000/callback/?code=random-string-xyz。 我还发现 this 与我正在寻找的非常接近,只是我试图仅在重定向后获取当前路径。

我还检查了 FastApi query parameters 部分并尝试了以下内容:

import typing
from uuid import uuid4

from oauthlib.oauth2 import WebApplicationClient

from fastapi import APIRouter, Request, Response

from fastapi.responses import RedirectResponse



router = APIRouter()

@router.get("/install/")
async def install(request: Request, code : typing.Optional[str] = None) -> Response:
    """Trigger the client identification process."""
    client_id = "xxx"
    client = WebApplicationClient(client_id)
    state = str(uuid4())

    authorization_url = f"https://api-url.com/auth/authorize?client_id={client_id}"
    url = client.prepare_request_uri(
        authorization_url,
        redirect_uri="http://127.0.0.1:8000/callback/",
        scope=["read:user"],
        state=state,
    )


    print("\n code : ", code, "\n")
    return RedirectResponse(url=url)

输出:code : None,我猜是因为代码是在重定向后返回的吗?

我如何以编程方式获取该 url 以检索 code?或者,也许您还有其他方法可以得到它..?

【问题讨论】:

  • 我的不好,这很明显。我没有很注意。这可以通过回调端点上的查询参数轻松完成。解决了。
  • 你好,没有忽略你的评论。正想再看一遍,没看到。真的不想添加任何信息,因为我想做的事情并不那么复杂。我是那个没有注意的人。谢谢@Chris。

标签: python redirect oauth fastapi


【解决方案1】:

您应该改为检索 /callback 端点内的 code 值,而不是 /install,因为根据您的问题中提供的链接,这是您被重定向到的端点:

http://127.0.0.1:8000/callback/?code=random-string-xyz
                     ^^^^^^^^^

在 FastAPI 中,您可以通过在端点中声明参数来获取查询参数。根据documentation

当您声明不属于的其他函数参数时 路径参数,它们是自动地解释为“查询” 参数。

例子:

@router.get("/callback")
async def install(code : str = None):
    # ...

或者,您可以use Starlette's Request object directly(也可以参见 Starlette 的documentation),如this answerherehere 中所述。

【讨论】:

    猜你喜欢
    • 2022-12-04
    • 2018-05-07
    • 2018-12-23
    • 2023-02-14
    • 2020-08-01
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-16
    相关资源
    最近更新 更多