尾部斜杠 returns 非 ssl link 的 FastAPI 重定向

FastAPI redirection for trailing slash returns non-ssl link

运行 当我们调用端点并且由于缺少尾部斜杠而发生重定向时出现问题。如下图所示,当向 https://.../notifications 发出请求时,FastAPI 服务器会重定向到 http://...通知/

我怀疑这是一个应用程序配置问题,而不是服务器配置问题。有人知道如何解决这个问题吗?

这是因为您的应用程序不信任反向代理的 header 覆盖方案(在处理 TLS 请求时传递的 X-Forwarded-Proto header)。

有几种方法可以解决这个问题:

  • 如果您是 运行 直接来自 uvicorn 服务器的应用程序,请尝试使用标志 --forwarded-allow-ips '*'.

  • 如果你是 运行 gunicorn 你也可以设置标志 --forwarded-allow-ips="*".

  • 在任一应用程序中,您还可以使用 FORWARDED_ALLOW_IPS 环境变量。

重要提示: * 应仅用作测试,因为它会使您的应用程序信任 X-Forwarded-* header 来自任何来源。我建议您阅读 uvicorn's docs and gunicorn's docs 以更深入地了解在此标志中设置的内容以及原因。

我在使用 FastAPI 和 react-admin 时遇到了这个问题。

一种解决方法是更改​​ FastAPI 应用程序,使其不进行重定向,而是将两个 URL 视为有效的 API 端点(带斜线和不带斜线)。

您可以使用 malthunayan 编写的这段代码来更改 APIRouter:

的行为
from typing import Any, Callable

from fastapi import APIRouter as FastAPIRouter
from fastapi.types import DecoratedCallable


class APIRouter(FastAPIRouter):
    def api_route(
        self, path: str, *, include_in_schema: bool = True, **kwargs: Any
    ) -> Callable[[DecoratedCallable], DecoratedCallable]:
        if path.endswith("/"):
            path = path[:-1]

        add_path = super().api_route(
            path, include_in_schema=include_in_schema, **kwargs
        )

        alternate_path = path + "/"
        add_alternate_path = super().api_route(
            alternate_path, include_in_schema=False, **kwargs
        )

        def decorator(func: DecoratedCallable) -> DecoratedCallable:
            add_alternate_path(func)
            return add_path(func)

        return decorator

来源:https://github.com/tiangolo/fastapi/issues/2060#issuecomment-834868906

(你也可以在这个GitHub问题中看到其他类似的解决方案)


另一种解决方法是添加:

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">

到前端的index.html文件。它会将所有请求从 http 升级到 https(当本地 运行 时也是如此,因此它可能不是最佳解决方法)