nginx FastAPI:SAML-SSO-在https://containerip/而不是https接收到响应:

vdgimpew  于 2023-08-03  发布在  Nginx
关注(0)|答案(1)|浏览(107)

我面临着一个反向代理与nginx和FastAPI,同时集成SAML SSO与OneLogin。我得到ERROR:routers.auth:Errors occurred: ['invalid_response'],后面跟着The response was received at https://containerip/ instead of https:myserverurl
这是我的nginx配置

server {
    listen              443 ssl http2;
    listen              [::]:443 ssl http2;
    server_name         $hostname ;


    # SSL
    ssl_certificate     /etc/nginx/ssl/localhost.crt;
    ssl_certificate_key /etc/nginx/ssl/localhost.key;

    # security
    include             nginxconfig.io/security.conf;

    # restrict methods
    if ($request_method !~ ^(GET|POST)$) {
        return '405';
    }
    
    # New location for FastAPI-App
    location / {
        proxy_pass http://fastapi:5000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    
    }

字符串
下面是我准备auth请求的方式:

async def prepare_fastapi_request(request):
    # Convert FastAPI request to a format compatible with python3-saml    
    form_data = await request.form()
    server_port = request.url.port
    if server_port is None:
        server_port = "443" if request.url.scheme == "https" else "80"
    rv = {
        "https": "on" if request.url.scheme == "https" else "off",
        "http_host": request.client.host,
        "server_port": server_port,
        "script_name": request.url.path,
        "get_data": { },
        # "post_data": await request.form(),  # Changed this
        "post_data": { },  # Use this instead
    }
    if (request.query_params):
        rv["get_data"] = request.query_params,
    if "SAMLResponse" in form_data:
        SAMLResponse = form_data["SAMLResponse"]
        rv["post_data"]["SAMLResponse"] = SAMLResponse
    if "RelayState" in form_data:
        RelayState = form_data["RelayState"]
        rv["post_data"]["RelayState"] = RelayState
    return rv


这是在服务器上运行我的docker容器的CMD:
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "5000", "--proxy-headers", "--forwarded-allow-ips", "*"]
我尝试了使用代理头,X转发,代理重定向的解决方案,但似乎没有任何工作,我还将RelayState更改为服务器上托管的服务的URL。

pb3skfrl

pb3skfrl1#

通过更改以下函数解决了问题

async def prepare_fastapi_request(request):

headers = request.headers
forwarded_host = headers.get("x-forwarded-host")
server_port = headers.get("x-forwarded-port")

rv = {
    "https": "on" if request.url.scheme == "https" else "off",
    "http_host": forwarded_host,
    "server_port": server_port,
    "script_name": request.url.path,
    "get_data": request.query_params,
    "post_data": await request.form(),  # Changed this
    #"post_data": { },  # Use this instead
}

return rv

字符串

相关问题