跳转到主要内容

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

项目描述


FastAPI-Azure-Auth

Azure AD身份验证,为FastAPI应用程序简化。

Python version FastAPI Version Package version
Codecov Pre-commit Black mypy isort

🚀 描述

FastAPI是一个现代、快速(高性能)的基于Python的Web框架,用于构建API,基于标准的Python类型提示。

在Intility,我们使用FastAPI为内部(单租户)和面向客户(多租户)API。此包使我们的开发者(以及您 😊)能够在不担心身份验证和授权的情况下创建功能。

此外,我们正在招聘!

📚 资源

文档包含如何配置Azure AD和FastAPI以用于单租户和多租户应用程序以及B2C应用程序的完整教程。它包括如何将您的API锁定到特定范围、租户、角色等示例。对于初学者,强烈建议您按照文档中的描述设置应用程序,然后根据需要稍后进行调整。

MIT许可证 | 文档 | GitHub

⚡ 设置

这是一个简短的介绍,旨在让您了解此包的功能和使用方法。对于更深入的教程和设置参考,您应阅读文档

1. 安装此库

pip install fastapi-azure-auth
# or
poetry add fastapi-azure-auth

2. 配置您的FastAPI应用程序

在您的FastAPI应用程序初始化中包含swagger_ui_oauth2_redirect_urlswagger_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

配置SingleTenantAzureAuthorizationCodeBearerMultiTenantAzureAuthorizationCodeBearerB2CMultiTenantAuthorizationCodeBearer

# 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按钮,可以用来进行认证。authorize

用户可以根据您的配置选择要认证的哪个范围。scopes

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源分发

fastapi_azure_auth-5.0.1.tar.gz (14.1 kB 查看散列)

上传时间

构建分发

fastapi_azure_auth-5.0.1-py3-none-any.whl (14.2 kB 查看哈希值)

上传时间: Python 3

由以下支持

AWSAWS云计算和安全赞助商DatadogDatadog监控FastlyFastlyCDNGoogleGoogle下载分析MicrosoftMicrosoftPSF赞助商PingdomPingdom监控SentrySentry错误记录StatusPageStatusPage状态页面