fastapi_auth
v1.0.5
基於API密鑰的FastApi的身份驗證軟件包,專注於簡單性和易用性:
sqlite或postgres數據庫後端的API密鑰安全性,與標題和查詢參數一起工作example.env文件以顯示如何使用環境變量。README.md以反映更改。mysql數據庫後端的支持。 pip install fastapi_auth2
from fastapi import Depends , FastAPI
from fastapi_auth import api_key_router , api_key_security
app = FastAPI (
description = "FastAPI Auth is a package that provides authentication based API security with FastAPI and Postgres Database, SQLite Database or MongoDB Database" ,
title = "FastAPI Auth Example" ,
version = 1.0 ,
)
app . include_router ( api_key_router , prefix = "/auth" , tags = [ "_auth" ])
@ app . get ( "/unsecure" )
async def unsecure_endpoint ():
return { "message" : "This is a unsecure endpoint" }
@ app . get ( "/secure" , dependencies = [ Depends ( api_key_security )])
async def secure_endpoint ():
return { "message" : "This is a secure endpoint" }結果應用是:

啟動API,並檢查日誌是否通過環境變量提供一個自動生成的秘密密鑰。

轉到您的API上的/docs ,並在Authorize/Secret header框中通知此秘密密鑰。所有管理員端點僅支持標頭安全性,以確保共享URL時不會無意間共享秘密密鑰。

然後,您可以使用/auth/new生成新的API密鑰。

最後,您可以使用此API鍵來訪問安全端點。

當然,您可以通過Python自動化API密鑰requests並直接查詢端點。
如果這樣做,則可以使用環境變量FASTAPI_AUTH_HIDE_DOCS隱藏API文檔中的端點。
環境變量:
FASTAPI_AUTH_SECRET :秘密管理員密鑰
FASTAPI_AUTH_HIDE_DOCS :是否從文檔中隱藏與API密鑰相關的終點
FASTAPI_AUTH_DB_LOCATION :本地sqlite數據庫文件的位置
sqlite.dbFASTAPI_AUTH_AUTOMATIC_EXPIRATION :持續時間,直到API鍵被視為過期
DATABASE_MODE :如果設置為postgres ,則軟件包將使用Postgres數據庫代替SQLITE
URI :Postgres數據庫的位置
postgresql://postgres:postgres@localhost:5432/postgres默認情況下DEV_MODE設置為False時使用有關更多信息,請參見CONTIBUTING.md 。
poetry install
poetry shellpre-commit installpytest隨附的Docker映像在localhost:8080 ,帶有秘密鍵TEST_SECRET 。運行它:
docker-compose build && docker-compose up