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界面中进行无缝令牌测试吗?
1条答案
按热度按时间fsi0uk1n1#
您可以执行以下操作
字符串
您需要从Google Cloud Console传递
client_id
和client_secret
。但是还没有proper token refresh,并且您不能在配置代码AFAICT中指定client_id
和client_secret
您还可以从
starlette.middleware.authentication.AuthenticationMiddleware
而不是BaseHTTPMiddleware
继承身份验证中间件,以使用request.user