Registry / azure / fastapi-azure-auth

fastapi-azure-auth

JSON →
library5.2.0pypypiunverified

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 uvicorn
INSTALL
IMPORT
SIG · FASTAPI-AZURE-AUTH
F
fastapi-azure-auth
azurepythonv5.2.0
Install
5.2s avg
Import
1150ms
Disk
51MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v5.2.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
installs and imports cleanly · install 0.0s · import 1.194s · 51.9MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 5.2s · import 1.106s · 51MB
51MB installed
● package 51MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

FastAPI
from fastapi import FastAPI
Security
from fastapi import Security
Depends
from fastapi import Depends
SingleTenantAzureAuthorizationCodeBearer
from fastapi_azure_auth.auth import SingleTenantAzureAuthorizationCodeBearer
MultiTenantAzureAuthorizationCodeBearer
from fastapi_azure_auth.auth import MultiTenantAzureAuthorizationCodeBearer
B2CMultiTenantAuthorizationCodeBearer
from fastapi_azure_auth.auth import B2CMultiTenantAuthorizationCodeBearer
User
from fastapi_azure_auth.user import User
BaseSettings
from pydantic_settings import BaseSettings
SettingsConfigDict
from pydantic_settings import SettingsConfigDict

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`.

import os from fastapi import FastAPI, Depends, HTTPException, status from pydantic import AnyHttpUrl from pydantic_settings import BaseSettings, SettingsConfigDict from fastapi_azure_auth import SingleTenantAzureAuthorizationCodeBearer from fastapi_azure_auth.user import User class Settings(BaseSettings): BACKEND_CORS_ORIGINS: list[str | AnyHttpUrl] = ['http://localhost:8000'] TENANT_ID: str = os.environ.get('TENANT_ID', '') APP_CLIENT_ID: str = os.environ.get('APP_CLIENT_ID', '') OPENAPI_CLIENT_ID: str = os.environ.get('OPENAPI_CLIENT_ID', '') SCOPE_DESCRIPTION: str = os.environ.get('SCOPE_DESCRIPTION', 'user_impersonation') model_config = SettingsConfigDict( env_file='.env', env_file_encoding='utf-8', case_sensitive=True ) @property def SCOPE_NAME(self) -> str: return f'api://{self.APP_CLIENT_ID}/{self.SCOPE_DESCRIPTION}' @property def SCOPES(self) -> dict: return {self.SCOPE_NAME: self.SCOPE_DESCRIPTION} settings = Settings() # Configure Azure AD authentication scheme azure_scheme = SingleTenantAzureAuthorizationCodeBearer( app_client_id=settings.APP_CLIENT_ID, tenant_id=settings.TENANT_ID, scopes=settings.SCOPES, ) app = FastAPI( swagger_ui_oauth2_redirect_url='/oauth2-redirect', swagger_ui_init_oauth={ 'usePkceWithAuthorizationCodeGrant': True, 'clientId': settings.OPENAPI_CLIENT_ID, 'scopes': settings.SCOPE_NAME, }, ) @app.get("/authenticated-hello") async def authenticated_hello(user: User = Depends(azure_scheme)): if not user: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated") return {"message": f"Hello, {user.name}! Your roles: {user.roles}"} # To run: uvicorn main:app --reload # Make sure to set TENANT_ID, APP_CLIENT_ID, OPENAPI_CLIENT_ID in your .env file or environment variables. # Also configure your Azure App Registration with the correct Redirect URIs (e.g., http://localhost:8000/oauth2-redirect).
Debug
Known issues
breakingAzure Entra ID (formerly Active Directory) v1 token support has been dropped. All new and existing projects should migrate to v2 tokens.
fix
Ensure your Azure App Registration is configured to issue v2 tokens. You can typically change this in the application manifest within the Azure portal.
affects: >=5.0.0
breakingPydantic v1 support has been dropped. Your project must use Pydantic v2 or later.
fix
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).
affects: >=5.0.0
breakingThe `InvalidAuth` exception class now requires both `detail` and `request` objects. For HTTP or WebSocket contexts, it's recommended to explicitly use `InvalidAuthHttp` or `InvalidAuthWebSocket` respectively.
fix
Replace `raise InvalidAuth(detail="...")` with `raise InvalidAuthHttp(detail="...", request=request)` or `raise InvalidAuthWebSocket(detail="...", websocket=websocket)` as appropriate.
affects: >=5.0.0
gotchaA common 'redirect URI mismatch' error can occur if the redirect URI configured in Azure Entra ID does not exactly match the one used by your application. This includes differences between 'localhost' and '127.0.0.1'.
fix
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`.
affects: All versions
gotchaIntegrating Azure Easy Auth (App Service Authentication/Authorization) directly with `fastapi-azure-auth` in a 2-tier application can lead to conflicts, as Easy Auth's flow might interfere with the library's custom token validation logic.
fix
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.
affects: All versions
gotchaWhen using the client_credentials flow, 'Invalid audience' errors can occur if application permissions (app roles) are not correctly configured and granted by an administrator or the API's owner. Delegated permissions are not sufficient for application-only authentication.
fix
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`.
affects: All versions
Upgrade
Version history
5.2.0latest on PyPI · released Jul 25, 2025
Audit
Dependencies
fastapirequiredThe core web framework this library integrates with.
cryptographyrequiredUsed for cryptographic operations, specified as a direct dependency.
httpxrequiredAn HTTP client for making requests, specified as a direct dependency.
pyjwtrequiredReplaced 'python-jose' for JWT handling in version 4.4.0.
pydantic-settingsrequiredRecommended for managing application settings, especially for loading from .env files.
uvicornrequiredAn ASGI server to run the FastAPI application.
Agent activity
28 hits · last 30 days
node
26
OpenAI (training)
1
Resources
fastapi-azure-auth — pip install fastapi-azure-auth · libregistry