轻松安全地实现Azure AD,适用于您的FastAPI API
项目描述

FastAPI-Azure-Auth
Azure AD身份验证,为FastAPI应用程序简化。
🚀 描述
FastAPI是一个现代、快速(高性能)的基于Python的Web框架,用于构建API,基于标准的Python类型提示。
在Intility,我们使用FastAPI为内部(单租户)和面向客户(多租户)API。此包使我们的开发者(以及您 😊)能够在不担心身份验证和授权的情况下创建功能。
此外,我们正在招聘!
📚 资源
该文档包含如何配置Azure AD和FastAPI以用于单租户和多租户应用程序以及B2C应用程序的完整教程。它包括如何将您的API锁定到特定范围、租户、角色等示例。对于初学者,强烈建议您按照文档中的描述设置应用程序,然后根据需要稍后进行调整。
⚡ 设置
这是一个简短的介绍,旨在让您了解此包的功能和使用方法。对于更深入的教程和设置参考,您应阅读文档。
1. 安装此库
pip install fastapi-azure-auth
# or
poetry add fastapi-azure-auth
2. 配置您的FastAPI应用程序
在您的FastAPI应用程序初始化中包含swagger_ui_oauth2_redirect_url
和swagger_ui_init_oauth
。
# file: main.py
app = FastAPI(
...
swagger_ui_oauth2_redirect_url='/oauth2-redirect',
swagger_ui_init_oauth={
'usePkceWithAuthorizationCodeGrant': True,
'clientId': settings.OPENAPI_CLIENT_ID,
},
)
3. 设置CORS
确保您已为本地环境(如https://#:8000
)启用了CORS。
4. 配置FastAPI-Azure-Auth
配置SingleTenantAzureAuthorizationCodeBearer
、MultiTenantAzureAuthorizationCodeBearer
或B2CMultiTenantAuthorizationCodeBearer
# file: demoproj/api/dependencies.py
from fastapi_azure_auth.auth import SingleTenantAzureAuthorizationCodeBearer
azure_scheme = SingleTenantAzureAuthorizationCodeBearer(
app_client_id=settings.APP_CLIENT_ID,
tenant_id=settings.TENANT_ID,
scopes={
f'api://{settings.APP_CLIENT_ID}/user_impersonation': 'user_impersonation',
}
)
或对于多租户应用程序
# file: demoproj/api/dependencies.py
from fastapi_azure_auth.auth import MultiTenantAzureAuthorizationCodeBearer
azure_scheme = MultiTenantAzureAuthorizationCodeBearer(
app_client_id=settings.APP_CLIENT_ID,
scopes={
f'api://{settings.APP_CLIENT_ID}/user_impersonation': 'user_impersonation',
},
validate_iss=False
)
为了验证iss
,配置一个iss_callable
。
5. 配置依赖项
使用Security()
或Depends()
将azure_scheme
添加为您的视图/路由器的依赖项。
# file: main.py
from demoproj.api.dependencies import azure_scheme
app.include_router(api_router, prefix=settings.API_V1_STR, dependencies=[Security(azure_scheme, scopes=['user_impersonation'])])
6. 启动时加载配置
可选但推荐。
# file: main.py
@app.on_event('startup')
async def load_config() -> None:
"""
Load OpenID config on startup.
"""
await azure_scheme.openid_config.load_config()
📄 示例OpenAPI文档
您的OpenAPI文档将获得一个Authorize
按钮,可以用来进行认证。
用户可以根据您的配置选择要认证的哪个范围。
项目详情
fastapi_azure_auth-5.0.1.tar.gz 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 32c64007ef22b937867f32fa44f08325ec51deb54f6c9e8220ee9bdf6173f4c5 |
|
MD5 | 5c2cb6007b47aa0a3c67935f0f6e7efa |
|
BLAKE2b-256 | 82a9e71702178b6a81ffc613276c4d0eec19283db8986465a2e20b0622ea92f9 |
fastapi_azure_auth-5.0.1-py3-none-any.whl 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 6d390f194c4059a3523d7cd41b58e41b4a37504eca19bfa74fdbe97bec146741 |
|
MD5 | 3ef4bf3e6b7f84ebbfe1afb8f992ef1c |
|
BLAKE2b-256 | 2d811b49c95fa75d5945019e797538b439623ebd53d8ae5c3e8440a22f837d04 |