發表文章

目前顯示的是 3月, 2021的文章

設定密碼保護你的 FastAPI Docs|抬升 Raise

圖片
這篇文章要教你如何透過權限控管,保護 FastAPI 生成的 API 文件,讓使用者需要經過授權才能進去 FastAPI 是一個 Python 的後端框架,具有自動生成 API 文件頁面 的特色,幫助開發者可以快速開發並測試 API。 然而,這些文件會隨著伺服器的部署,一同被公開到網路上。如果你想要避免閒雜人等進入 API 文件,可以參考以下的步驟: 1. 關閉預設 API Docs 透過在創建 App 時加上以下變數,可以關閉預設 API 文件功能。 from fastapi import FastAPI app = FastAPI(docs_url=None, redoc_url=None, openapi_url = None) 2. 新增 HTTP Basic Auth 帳號密碼驗證 透過下列程式,我們新增一個驗證物件供 API 使用。 只要在建立 API 時加上這個物件,就會需要經過帳號密碼驗證才能使用該 API import secrets from fastapi import Depends, FastAPI, HTTPException, status from fastapi.security import HTTPBasic, HTTPBasicCredentials security = HTTPBasic() def get_current_username(credentials: HTTPBasicCredentials = Depends(security)): correct_username = secrets.compare_digest(credentials.username, "user") correct_password = secrets.compare_digest(credentials.password, "password") if not (correct_username and correct_password): raise HTTPExcept...