FastAPI-Azure-Auth is a Python library that provides an easy and secure implementation of Azure Entra ID (formerly Azure Active Directory) authentication and authorization for FastAPI APIs. It supports B2C, single-tenant, and multi-tenant applications. The library is actively maintained, with frequent updates, and is currently at version 5.2.0.
pip install fastapi-azure-auth uvicornVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates setting up a FastAPI application with single-tenant Azure Entra ID authentication. It uses Pydantic-settings to manage configuration from environment variables (or a .env file) and protects an endpoint using the `SingleTenantAzureAuthorizationCodeBearer` scheme. Remember to configure your Azure App Registration with the appropriate Redirect URIs, such as `http://localhost:8000/oauth2-redirect`.
Ensure your Azure App Registration is configured to issue v2 tokens. You can typically change this in the application manifest within the Azure portal.
Upgrade Pydantic to version 2.x. Review your Pydantic models for any breaking changes introduced in Pydantic v2 (e.g., `Config` class to `model_config`, field definitions).
Replace `raise InvalidAuth(detail="...")` with `raise InvalidAuthHttp(detail="...", request=request)` or `raise InvalidAuthWebSocket(detail="...", websocket=websocket)` as appropriate.
Ensure the redirect URI in your Azure App Registration (e.g., `http://localhost:8000/oauth2-redirect`) is an exact match for what your FastAPI application exposes. Consistently use either `localhost` or `127.0.0.1`.
It is generally recommended to disable Azure Easy Auth on the backend API service and rely solely on `fastapi-azure-auth` for token validation, ensuring CORS and token scopes are correctly configured.
Ensure that the Azure App Registration for the client application has the necessary *application permissions* (app roles), not just delegated permissions, and that these have been granted by an admin. The scope should typically be `api://{APP_CLIENT_ID}/.default`.