HTTPS 监听器,但 FastAPI 和 Cloud Run 中的 HTTP URL

问题描述 投票:0回答:1

我创建了一个 FastAPI 应用程序,我可以在

https://cloudrundomain.app/docs
访问 Swagger UI 自动文档。当我使用 Swagger UI 发送 HTTPS 请求时,
request.headers.get("X-Forwarded-Proto")
是 HTTPS,但
request.url
http://cloudrundomain
(我问题的根源是
HTTPException
是 HTTP,但我认为它从那里开始)。

我认为这不是一个好主意,但我尝试做你可以在下面看到的事情。触发“将方案修改为 HTTPS 以避免混合内容问题”,但重定向失败。

@app.middleware("http")
async def force_https(request: Request, call_next):
   # Check the X-Forwarded-Proto header to determine if the request is HTTP
   forwarded_proto = request.headers.get("X-Forwarded-Proto")

   if forwarded_proto == "http":
       print("Redirect to HTTPS")
       return RedirectResponse(url=f"https://{request.url.hostname}{request.url.path}")

   # Ensure URLs are constructed using HTTPS
   # Modify request.url to use HTTPS if necessary
   if forwarded_proto == "https" and request.url.scheme == "http":
       print("Modify the scheme to HTTPS to avoid mixed content issues")
       return RedirectResponse(url=f"https://{request.url.hostname}{request.url.path}")

   # Proceed with the request if it's already HTTPS or after the redirect
   response = await call_next(request)
   return response 
python https fastapi google-cloud-run
1个回答
0
投票

我参考这个GitHub问题找到了解决方案:https://github.com/encode/uvicorn/issues/369.

更具体地说,我改变了启动 FastAPI Web 应用程序的方式。之前我用过:

fastapi  run --workers 4 app/main.py

我通过以下命令切换为直接使用 Uvicorn:

uvicorn your_app:app --host 0.0.0.0 --port 8000 --proxy-headers --forwarded-allow-ips "*"

© www.soinside.com 2019 - 2024. All rights reserved.