FastAPI authentication with Microsoft Identity
The Microsoft Identity library for Python's FastAPI provides Azure Active Directory token authentication and authorization through a set of convenience functions. It enables any FastAPI applications to authenticate with Azure AD to validate JWT tokens and API permissions
Install the package
Install the Microsoft Identity for FastAPI library with pip:
pip install fastapi-microsoft-identity
Prerequisites
- An Azure Active Directory Get one FREE
- Or an Azure Active Directory B2C, through a FREE Azure subscription Get your Free sub
- Python 3.11 or later
Usage
1. Azure AD Authentication
The library can now support both Azure AD and Azure AD B2C authentication for FastAPI applications
1.1 Azure AD App Registration Configuration
First create an Azure Active Directory Application Registration in the Azure AD portal using the following steps:
- Sign in to your Azure AD Tenant (link)
- Navigate to
App Registrations->New Registration. - Enter a name for your application.
- Leave everything else as default.
- Click
Register. - Copy the
Client IDandTenant IDfrom theApplication RegistrationOverview page. - Navigate to the
Expose APItab. - Click
Setnext to the Application ID URI field. - Click Add a scope
- Give the scope a name like
access_as_user. - Select
Admin and Userfor consent - Provide meaningful descriptions for the admin and user consents
- Ensure
Stateis set to Enabled - Client Add scope
- Give the scope a name like
The scope should look like this:
api://279cfdb1-0000-0000-0000-291dcd4b561a/access_as_user
1.2 Using the Microsoft Identity for FastAPI library
In your FastAPI application, you need to initialize the authentication library using the Client ID and Tenant ID values from the Application Registration Overview page.
initialize(tenant_id, client_id)
You can now decorate any API endpoint with the requires_auth decorator as per the example below
from fastapi_microsoft_identity import requires_auth, validate_scope, AuthError
expected_scope = "<your expected scope e.g access_as_user>"
@router.get('/api/weather/{city}')
@requires_auth
async def weather(request: Request, loc: Location = Depends(), units: Optional[str] = 'metric'):
try:
validate_scope(expected_scope, request)
return await openweather_service.get_report_async(loc.city, loc.state, loc.country, units)
except AuthError as ae:
return fastapi.Response(content=ae.error_msg, status_code=ae.status_code)
except ValidationError as ve:
return fastapi.Response(content=ve.error_msg, status_code=ve.status_code)
except Exception as x:
return fastapi.Response(content=str(x), status_code=500)
The requires_auth decorator will check if the JWT Access Token in the request is a valid token and then raise an AuthError (HTTP 401) if the token is invalid (expired, not right audience etc).
The library also provides a helper function: validate_scope that can be used to validate the scope of the JWT token.
validate_scope(expected_scope, request)
The validate_scope method will throw an AuthError (HTTP 403) if the token doesn't contain the right scope / api permission.
1.3 Accessing the token claims
Based on user feedback, the library now provides a helper function to access the token claims.
Inside an endpoint protected by requires_auth / requires_b2c_auth, the verified claims are available on the request:
token_claims = request.state.token_claims
get_token_claims(request) is also available, but it returns the claims without verifying the token, so only use it on protected endpoints.
1.4 Validating one of several scopes
validate_scope accepts a single scope or a list. The check passes if the token has any of them, either as a delegated scope (scp) or as an app role (roles):
validate_scope(["access_as_user", "app.weather.read"], request)
1.5 Multi-tenant applications
To accept tokens from any Azure AD tenant, pass multitenant=True. Signing keys come from the common endpoint. The issuer is still validated against the token's own tid claim, so you can restrict access to specific tenants with allowed_tenants:
initialize(tenant_id, client_id, multitenant=True, allowed_tenants=["<tenant-guid>", "<tenant-guid>"])
1.6 How validation works
- Tokens must be RS256-signed by a key from the tenant's JWKS endpoint, and must include valid
exp,audandissclaims.nbfis checked when it's present. - The accepted audiences are
<client_id>andapi://<client_id>. - Signing keys are cached for an hour by default (
initialize(..., jwks_cache_ttl=3600)). A token with an unknownkidtriggers a refresh, so key rollover is picked up, but at most once a minute. - The protected endpoint must declare a
request: Requestparameter. Bothasync defand regulardefendpoints work. - Failures return
401with aWWW-Authenticate: Bearerheader, or503if the signing keys can't be retrieved.
2. Azure AD B2C Authentication
2.1 Create your Azure AD B2C Application Registration
First create an Azure AD B2C App Registration in the B2C portal using the following steps:
- Sign in to your Azure portal, search for your B2C tenant and navigate to the B2C portal
- Navigate to
App Registrations->New registration. - Enter a name for your application.
- Under
Supported account typeschoose Accounts in any identity provider or organizational directory(for authenticating user with user flows). - Make sure the Grant admin consent to openid and offline_access is checked. under
Permissions - Click
Register. - Copy the
Client IDandTenant IDfrom theApp RegistrationOverview page. - Navigate to the
Expose APItab. - Click
Setnext to the Application ID URI field. - Click Add a scope
- Give the scope a name like
access_as_user. - Provide meaningful descriptions for the admin consent name and description
- Ensure
Stateis set to Enabled - Client Add scope
- Give the scope a name like
- From the B2C overview pane, copy the domaain name like this
<your-tenant>ignoring the.onmicrosoft.com.. eg. cmatb2cdev
2.2 Using the Microsoft Identity for FastAPI library with Azure AD B2C
In your FastAPI application, you need to initialize the authentication library using the following values:
Client IDTenant IDDomain NameSign up & Sign In User Flow
The issuer and signing keys are read from the user flow's OpenID Connect metadata (https://<domain>.b2clogin.com/<domain>.onmicrosoft.com/<policy>/v2.0/.well-known/openid-configuration).
You need to make sure that both your Fast API and the API clients use the same B2C User flow to authenticate and acquire tokens.
You can read more about Azure AD User Flows and Policies here
initialize(tenant_id, client_id, b2c_policy_name, b2c_domain_name)
You can now decorate any API endpoint with the requires_b2c_auth decorator as per the example below
from fastapi_microsoft_identity import requires_b2c_auth, validate_scope, AuthError
expected_scope = "<your expected scope e.g access_as_user>"
@router.get('/api/weather/{city}')
@requires_b2c_auth
async def weather(request: Request, loc: Location = Depends(), units: Optional[str] = 'metric'):
try:
validate_scope(expected_scope, request)
return await openweather_service.get_report_async(loc.city, loc.state, loc.country, units)
except AuthError as ae:
return fastapi.Response(content=ae.error_msg, status_code=ae.status_code)
except ValidationError as ve:
return fastapi.Response(content=ve.error_msg, status_code=ve.status_code)
except Exception as x:
return fastapi.Response(content=str(x), status_code=500)
The requires_auth decorator will check if the JWT Access Token in the request is a valid token and then raise an AuthError (HTTP 401) if the token is invalid (expired, not right audience etc).
The library also provides a helper function: validate_scope that can be used to validate the scope of the JWT token.
validate_scope(expected_scope, request)
The validate_scope method takes 2 parameters:
- expected_scope: The scope that the token should have (this can also be an app permission).
- request: The FastAPI Request object.
The method works out wether the access token contain an app permission (role) or a scope and then validate the claim.
If neither is present, the method throws an AuthError (HTTP 403) for the following reasons:
- no
rolesorscpclaim was present in the token - the token doesn't contain the right scope / api permission
Compatibility
Requires Python 3.11+. Version 0.2.0 replaced python-jose with PyJWT. The public API is unchanged.
Development
pip install -e ".[dev]"
pytest
The tests sign tokens with a locally generated key, so they don't need network access or real Azure tokens.
Licence
MIT
Provide feedback
If you encounter bugs or have suggestions, please open an issue.
Contributing
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.
This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.
Authors
The fastapi_microsoft_identity was written by Christos Matskas <christos.matskas@microsoft.com>.
Metadata
Release files for fastapi-microsoft-identity 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| fastapi_microsoft_identity-0.2.0.tar.gz | 11.7 kB | With provenance | Details for fastapi_microsoft_identity-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| fastapi_microsoft_identity-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for fastapi_microsoft_identity-0.2.0-py3-none-any.whl |
Total release size: 21.9 kB
Release files / fastapi_microsoft_identity-0.2.0.tar.gz
| Download URL | fastapi_microsoft_identity-0.2.0.tar.gz |
|---|---|
| Size | 11.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
4bb725395e35614a4cf43446849a067b8c4598699b13ba409153f39382db2e80
|
|
BLAKE2b-256 checksum How to use checksums |
2eaf1d47d55a1b69ee24c28e70edbb85b196d1e9536547c03eecc928f97e5851
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.
Transparency logRelease files / fastapi_microsoft_identity-0.2.0-py3-none-any.whl
| Download URL | fastapi_microsoft_identity-0.2.0-py3-none-any.whl |
|---|---|
| Size | 10.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
76193396ebc288c6fa531757df42f40c45675325ae3a37866d3700b95ff1a23c
|
|
BLAKE2b-256 checksum How to use checksums |
30a14e9f0f7eb591357eaaf3a794c39160b57c8264637bd8569e2ab8d9fec0ad
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.
Transparency logSecurity for fastapi-microsoft-identity 0.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for fastapi_microsoft_identity-0.2.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.