Security News
pnpm 10.0.0 Blocks Lifecycle Scripts by Default
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
fastapi-microsoft-identity
Advanced tools
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 Microsoft Identity for FastAPI library with pip:
pip install fastapi-microsoft-identity
The library can now support both Azure AD and Azure AD B2C authentication for FastAPI applications
First create an Azure Active Directory Application Registration
in the Azure AD portal using the following steps:
App Registrations
-> New Registration
.Register
.Client ID
and Tenant ID
from the Application Registration
Overview page.Expose API
tab.Set
next to the Application ID URI field.access_as_user
.Admin and User
for consentState
is set to EnabledThe scope should look like this:
api://279cfdb1-0000-0000-0000-291dcd4b561a/access_as_user
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.
Based on user feedback, the library now provides a helper function to access the token claims.
token_claims = authservice.get_token_claims(request)
# do something with the claims
First create an Azure AD B2C App Registration
in the B2C portal using the following steps:
App Registrations
-> New registration
.Supported account types
choose Accounts in any identity provider or organizational directory(for authenticating user with user flows).Permissions
Register
.Client ID
and Tenant ID
from the App Registration
Overview page.Expose API
tab.Set
next to the Application ID URI field.access_as_user
.State
is set to Enabled<your-tenant>
ignoring the .onmicrosoft.com.
. eg. cmatb2cdevIn your FastAPI application, you need to initialize the authentication library using the following values:
Client ID
Tenant ID
Domain Name
Sign up & Sign In User Flow
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_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_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:
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:
roles
or scp
claim was present in the tokenRequires Python 3.x
MIT
If you encounter bugs or have suggestions, please open an issue.
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.
The fastapi_microsoft_identity
was written by Christos Matskas <christos.matskas@microsoft.com>
.
FAQs
Azure AD authentication for Fast API
We found that fastapi-microsoft-identity demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
Product
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
Research
Security News
Socket researchers have discovered multiple malicious npm packages targeting Solana private keys, abusing Gmail to exfiltrate the data and drain Solana wallets.