
Security News
Browserslist-rs Gets Major Refactor, Cutting Binary Size by Over 1MB
Browserslist-rs now uses static data to reduce binary size by over 1MB, improving memory use and performance for Rust-based frontend tools.
aad_fastapi middleware backend helper for bearer verification with FastAPI and Azure AD
This package allows you to protect easily your Web API, using Azure AD.
It has been created specifically for FAST API, delivering a new middleware in the pipeline to authenticate and authorize any http requests, if needed.
To install with pip
:
> python -m pip install aad_fastapi
Once configured in Azure AD (see sections below), just add an authentication middleware with the AadBearerBackend
:
from aad_fastapi import (
AadBearerBackend,
AadUser,
authorize,
oauth2_scheme,
AzureAdSettings
)
# App Registration settings for protecting all the APIs.
api_options = AzureAdSettings()
api_options.client_id = environ.get("API_CLIENT_ID")
api_options.domain = environ.get("DOMAIN")
api_options.scopes = environ.get("SCOPES")
# App Registration setting for authentication SWAGGER WEB UI AUTHENTICATION.
web_ui_client_id = environ.get("CLIENT_ID") # Client ID
web_ui_scopes = environ.get("SCOPES") # Client ID
# pre fill client id
swagger_ui_init_oauth = {
"usePkceWithAuthorizationCodeGrant": "true",
"clientId": web_ui_client_id,
"appName": "B-ID",
"scopes": web_ui_scopes,
}
# Create a FasAPI instance
app = FastAPI(swagger_ui_init_oauth=swagger_ui_init_oauth)
# Add the bearer middleware, protected with Api App Registration
app.add_middleware(AuthenticationMiddleware, backend=AadBearerBackend(api_options))
Once configured, you can add authentication dependency injection to your routers:
# These routers needs an authentication for all its routes using Web App Registration
app.include_router(engines.router, dependencies=[Depends(oauth2_scheme(options=api_options))])
Or directly to your web api route:
@app.get("/user")
async def user(request: Request, token=Depends(oauth2_scheme(options=api_options))):
return request.user
It's important to have the Request
object set as the first parameter for your endpoint
if you are inspecting the
request.user
object, you will find all the user's property retrieved from Azure AD.
You can specify scopes and / or roles, using decorators, to be checked before accessing your web api:
@app.get("/user_with_scope")
@authorize("user_impersonation")
async def user_with_scope(
request: Request, token=Depends(oauth2_scheme(options=api_options))
):
# code here
@app.get("/user_with_scope_and_roles")
@authorize("user_impersonation", "admin-role")
async def user_with_scope_and_roles(
request: Request, token=Depends(oauth2_scheme(options=api_options))
):
# code here
The @authorize
decorator is capable of specifying multiple roles as a list of string, which will be checked against the user's roles.
If all the roles are found, the user is authorized.
To require the user to have at least one of the specified roles, you can use the role_requirement
parameter with the
value RoleRequirement.ANY
:
@app.get("/user_with_scope_and_roles_any")
@authorize("user_impersonation", roles=["admin","superuser"], role_requirement=RoleRequirement.ANY)
async def user_with_scope_and_roles_any(
request: Request, token=Depends(oauth2_scheme(options=api_options))
):
# code here
NOTE:
RoleRequirement.ALL
is the default behavior and does not need to be specified.
There are two applications to register:
The Web API application does not need to allow user to authenticate. The main purpose of this application is to protect our Web API.
py-api
.Set
next to the Application ID URI to generate a URI that is unique for this app.user_impersonation
.The Client application will allow the user to authenticate, and will expose a scope to the Web Api application.
py-web
.Do not activate the implicit flow, as we are using the new Authorization Code Flow with PKCE (https://oauth.net/2/pkce/)
In the app's registration screen, click on the Certificates & secrets blade in the left to open the page where we can generate secrets and upload certificates.
In the Client secrets section, click on New client secret:
sample
in our sample),In the app's registration screen, click on the API permissions blade in the left to open the page where we add access to the APIs that your application needs.
py-api
.For a middle tier Web API to be able to call a downstream Web API, the middle tier app needs to be granted the required permissions as well. However, since the middle tier cannot interact with the signed-in user, it needs to be explicitly bound to the client app in its Azure AD registration. This binding merges the permissions required by both the client and the middle tier Web API and presents it to the end user in a single consent dialog. The user then consent to this combined set of permissions.
To achieve this, you need to add the Application Id of the client app (py-web
in our sample), in the Manifest of the Web API in the knownClientApplications
property. Here's how:
py-api
app registration, and select Expose an API section.py-web
applicationuser_impersonation
Open the project in VS Code and configure correctly the .devcontainer/devcontainer.json file:
TENANT_ID={GUID} # The tenant id where you've created the application registrations
SUBSCRIPTION_ID= {GUID} # Your subscription id
DOMAIN={domain}.onmicrosoft.com # the domain name
AUTHORITY=https://login.microsoftonline.com/{tenant_id} # Authority used to login in Azure AD
# App Registration information for Web Authentication
CLIENT_ID={GUID} # This client id is the authentication client id used by the user (from `py-web` application registration)
CLIENT_SECRET= {PWD} # you
SCOPES=https://{domain}.onmicrosoft.com/{client_id}/user_impersonation : # Scope exposed to the `py-web` application
API_URL=http://localhost:8000
VAULT_NAME={Vault Name} # Optional : Key vault used to store the secret
VAULT_SECRET_KEY={Vault key} # Optional : Key vault secret's key
# App Registration information for Api Protection
API_CLIENT_ID={GUID} # Client id for the web api protection (from `py-api` application registration)
The solutions provides a launch.json
example (in the /.vscode folder) that you can use to launch the demo.
You don't need to fill the secret textbox when trying to authenticate your user, since we are using the PKCE method
FAQs
aad_fastapi middleware backend helper for bearer verification with FastAPI and Azure AD
We found that aad-fastapi demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers 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
Browserslist-rs now uses static data to reduce binary size by over 1MB, improving memory use and performance for Rust-based frontend tools.
Research
Security News
Eight new malicious Firefox extensions impersonate games, steal OAuth tokens, hijack sessions, and exploit browser permissions to spy on users.
Security News
The official Go SDK for the Model Context Protocol is in development, with a stable, production-ready release expected by August 2025.