在授予对子应用程序的访问权限之前进行 FastAPI 身份验证检查

FastAPI auth check before granting access to sub-applications

我正在将 Flask 应用程序安装为我的根 FastAPI 应用程序中的子应用程序,如 documentation

中所述

现在我想使用 HTTPAuthorizationCredentials 依赖项添加身份验证层,如 this tutorial

中所述

tutorial code

我该怎么做?

最好,我希望对我的 Flask 子应用程序的任何类型的访问尝试首先通过在我的 FastAPI 根应用程序中实现的有效令牌身份验证过程。这可能吗?

您可以使用自定义 WSGIMiddleware 并授权调用其中的 Flask 应用程序,如下所示:

from fastapi import FastAPI, Depends, HTTPException
from fastapi.middleware.wsgi import WSGIMiddleware
from flask import Flask, escape, request
from starlette.routing import Mount
from starlette.types import Scope, Receive, Send

flask_app = Flask(__name__)

def authenticate(authorization: str = Header()):
    # Add logic to authorize user
    if authorization == "VALID_TOKEN":
        return
    else:
        raise HTTPException(status_code=401, detail="Not Authorized")

class AuthWSGIMiddleware(WSGIMiddleware):

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        _, authorization = next((header for header in scope['headers'] if header[0] == b'authorization'), (b'authorization', "" ))
        authenticate(authorization.decode('utf-8'))
        await super().__call__(scope, receive, send)

routes = [
            Mount("/v1", AuthWSGIMiddleware(flask_app)),
        ]

# OR Optionally use this as you were doing
# The above one is preferred as per starlette docs
# app.mount("/v1", WSGIMiddleware(flask_app))


@flask_app.route("/")
def flask_main():
    name = request.args.get("name", "World")
    return f"Hello, {escape(name)} from Flask!"

app = FastAPI(routes=routes, dependencies=[Depends(authenticate)])


@app.get("/v2")
def read_main():
    return {"message": "Hello World"}

对于您正在查看的教程,您可以将我示例中 AuthWSGIMiddleware->__call__() 中的调用 authenticate 函数替换为

AuthHandler().decode_toke(authorization)