python-3.x 将Swagger API的OAuth2 Login与Firebase auth集成

wwwo4jvm  于 4个月前  发布在  Python
关注(0)|答案(1)|浏览(83)
class AuthenticationMiddleware(BaseHTTPMiddleware):
    """Middleware to authenticate requests using Firebase Auth.
    """

    async def dispatch(self, request: Request, call_next: Callable):
        # This is where you can modify the request if needed
        path = request.url.path
        # Exclude specific paths from middleware
        if path in [
            "/health",
            "/auth/login",
            "/docs",
            "/openapi.json",
        ]:
            return await call_next(request)  # Continue with the request

        headers = request.headers
        token = headers.get("Authorization")

        if not token:
            raise HTTPException(status_code=401, detail="Authorization token is missing")

        try:
            # Verify and decode the token using Firebase Admin SDK
            user_info = auth.verify_id_token(token)
            # Check if the token is still valid
            if user_info.get("exp") < time.time():
                raise HTTPException(status_code=401, detail="Token expired")
            # If the token is valid, you can access user information
            request.state.user = user_info
            return await call_next(request)  # Continue with the request

        except Exception as err:
            raise HTTPException(status_code=401, detail="Invalid token") from err

字符串
我在上面写了一个中间件--它基本上试图从头文件中找到firebase token。我在这里看到的问题是,对于任何使用token的API,我需要使用postman/thudnerclient。
我对将用户友好的OAuth2登录直接集成到Swagger UI中以简化测试很感兴趣。我偶然发现了关于简单OAuth2的FastAPI文档(https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/#see-it-in-action),我想知道是否有一种方法可以将其应用于我的Firebase身份验证中间件。
有人能指导我将OAuth2登录整合到FastAPI的Swagger UI中,允许直接在Swagger界面中进行无缝令牌测试吗?

fsi0uk1n

fsi0uk1n1#

您可以执行以下操作

from fastapi.security import OAuth2AuthorizationCodeBearer

oauth2_code_bearer = OAuth2AuthorizationCodeBearer(
    authorizationUrl="https://accounts.google.com/o/oauth2/v2/auth",
    tokenUrl="https://oauth2.googleapis.com/token",
    scopes={"openid": "email"}, # or whatever you want
)

# use as dependency
async def auth_required(
    oauth2_code_bearer: HTTPAuthorizationCredentials = Security(oauth2_code_bearer),
) -> None:
    ...

字符串
您需要从Google Cloud Console传递client_idclient_secret。但是还没有proper token refresh,并且您不能在配置代码AFAICT中指定client_idclient_secret
您还可以从starlette.middleware.authentication.AuthenticationMiddleware而不是BaseHTTPMiddleware继承身份验证中间件,以使用request.user

相关问题