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