[英]FastAPI: security with firebase token
我正在按照本教程創建一個 api 后端。
我使用 firebase 身份驗證:
Authorization
header( Bearer xxx
)中發送令牌本教程展示了如何使用密碼執行此操作:
# creating a dependency
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
async def get_current_user(token: str = Depends(oauth2_scheme)):
user = fake_decode_token(token)
return user
但是由於我使用的是 firebase,因此沒有/token
用於獲取帶密碼的令牌。
我可以通過創建自定義依賴項來解析令牌,例如:
async def parse_token(auth_token:str = Header(...)):
token = auth_token.split(' ')[1]
return token
async def get_current_user(token: str = Depends(parse_token)):
# check the token with firebase auth
user = auth.verify_id_token(token)
return user
但現在我必須檢查所有內容並手動返回異常。
有沒有 FastAPI 方法可以做到這一點?
簡單地忽略它。
/token
端點用於驗證和生成令牌(成功嘗試時)。 它只是一個登錄頁面/表單。 您只需跳過該部分並使用將執行檢查的依賴項。
當然,您必須遵循OAuth2Password
內容的相同名稱和位置。
請記住,HTTP 是無狀態的,令牌用於記住用戶已經提供了身份證明。 如果你有一個有效的令牌,你也可以在另一台機器上交換它並使用它(除非有一些安全 cookie 並且與機器相關的信息存儲在 cookie 中)。
如果繼續學習鏈接的教程,您將獲得帶有身份驗證的最終代碼。 只需在從前端到后端的請求的"Authorization: Bearer {token}"
中提供 firebase 令牌,它就會起作用。
在文檔鏈接下方。
https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/
我有類似的用例,在谷歌搜索時我遇到了這個問題。 但這對我沒有太大幫助。 經過進一步研究,我發現了這篇很有幫助的文章。 只需按如下方式創建依賴項;
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi import Depends, HTTPException, status, Response
from firebase_admin import auth, credentials
import firebase_admin
cred = credentials.Certificate('./account_key.json')
firebase_admin.initialize_app(cred)
def get_user(res: Response, cred: HTTPAuthorizationCredentials=Depends(HTTPBearer(auto_error=False))):
if cred is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Bearer authentication required",
headers={'WWW-Authenticate': 'Bearer realm="auth_required"'},
)
try:
decoded_token = auth.verify_id_token(cred.credentials)
except Exception as err:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=f"Invalid authentication credentials. {err}",
headers={'WWW-Authenticate': 'Bearer error="invalid_token"'},
)
res.headers['WWW-Authenticate'] = 'Bearer realm="auth_required"'
return decoded_token
然后添加對您要保護的端點的依賴,如下所示
async def hello_user(user = Depends(get_user))
這與 Swagger 端點很好地集成,然后您可以根據您的請求接收idToken
並根據需要使用它們。 非常感謝海報
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.