Skip to main content

This is a patched version compatible with pydantic 2.0

Forked from https://github.com/dudil/fastapi_msal

FastAPI/MSAL - MSAL (Microsoft Authentication Library) plugin for FastAPI

FastAPI - https://github.com/tiangolo/fastapi FastAPI is a modern, fast (high-performance), web framework for building APIs based on standard Python type hints.

MSAL for Python - https://github.com/AzureAD/microsoft-authentication-library-for-python The Microsoft Authentication Library for Python enables applications to integrate with the Microsoft identity platform. It allows you to sign in users or apps with Microsoft identities and obtain tokens to call Microsoft APIs such as Microsoft Graph or your own APIs registered with the Microsoft identity platform. It is built using industry standard OAuth2 and OpenID Connect protocols

The fastapi_msal package was built to allow quick "out of the box" integration with MSAL. As a result the pacage was built around simplicity and ease of use on the expense of flexability and versatility.

Features

  1. Includes Async implementation of MSAL confidential client class utilizaing Starlette threadpool model.
  2. Use pydantic models to translate the MSAL objects to data objects which are code and easy to work with.
  3. Have a built-in router which includes the required paths for the authentication flow.
  4. Include a dependency class to authenticate and secure your application APIs
  5. Includes a pydantic setting class for easy and secure configuration from your ENV (or .env or secrets directory)
  6. Full support with FastAPI swagger documentations and authentication simulation

Installation

pip install "fastapi_msal_patched"

Prerequisets

  1. Python 3.7 and above
  2. As part of your fastapi application the following packages should be included:
    (if you use the [full] method it is not required.)
    1. python-multipart, From FastAPI documentation: This is required since OAuth2 (Which MSAL is based upon) uses "form data" to send the credentials.

    2. itsdangerous Used by Starlette session middleware

Usage

  1. Follow the application registration process with the microsoft identity platform. Finishing the processes will allow you to retrieve your app_code and app_credentials (app_secret) As well as register your app callback path with the platform.

  2. Create a new main.py file and add the following lines. Make sure to update the lines with the information retrieved in the previous step

import uvicorn
from fastapi import FastAPI, Depends
from starlette.middleware.sessions import SessionMiddleware
from fastapi_msal import MSALAuthorization, UserInfo, MSALClientConfig

client_config: MSALClientConfig = MSALClientConfig()
client_config.client_id = "The Client ID rerived at step #1"
client_config.client_credential = "The Client secret retrived at step #1"
client_config.tenant = "Your tenant id"

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="SOME_SSH_KEY_ONLY_YOU_KNOW")  # replace with your own!!!
msal_auth = MSALAuthorization(client_config=client_config)
app.include_router(msal_auth.router)


@app.get("/users/me", response_model=UserInfo, response_model_exclude_none=True, response_model_by_alias=False)
async def read_users_me(current_user: UserInfo = Depends(msal_auth.scheme)) -> UserInfo:
    return current_user


if __name__ == "__main__":
    uvicorn.run("main:app", host="localhost", port=5000, reload=True)
  1. Run your app
(pipenv shell)$ python main.py
INFO:     Uvicorn running on http://localhost:5000 (Press CTRL+C to quit)
INFO:     Started reloader process [12785] using statreload
INFO:     Started server process [12787]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
  1. Browse to http://localhost:5000/docs - this is the API docs generated by FastAPI (totaly cool!) Document Page Image

  2. Using the "built-in" authenticaiton button (the little lock) you will be able to set the full authentication process Authorize Page Image (Igonre the cline_id and client_secret - they are not relevant for the process as you already set them)

  3. After you complete the process you will get a confirmation popup Token Page Image

  4. Trying out the ME api endpoint Me Page Image

Working Example/Template

If you wish to try out a working example, clone the following project and adjust it to your needs: https://github.com/dudil/ms-identity-python-webapp

NB! Make sure you are using the fastapi_msal branch!!!

TODO List

  • Add support for local/redis session cache
  • Add Tests
  • Proper Documentation

Metadata

Release files for fastapi_msal_patched 0.2.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastapi_msal_patched 0.2.1
File Size Uploaded Provenance Actions
fastapi_msal_patched-0.2.1.tar.gz 19.8 kB Without provenance Details for fastapi_msal_patched-0.2.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fastapi_msal_patched 0.2.1
File Interpreter ABI Platform Actions
fastapi_msal_patched-0.2.1-py3-none-any.whl Python 3 none any Details for fastapi_msal_patched-0.2.1-py3-none-any.whl

Total release size: 39.3 kB

Release files / fastapi_msal_patched-0.2.1.tar.gz

Download URL fastapi_msal_patched-0.2.1.tar.gz
Size 19.8 kB
Tags Source
SHA-256 checksum
How to use checksums
4ec017dc74b489b11d0875ae1bc79b375152482d89997111e7590242b08814b7
BLAKE2b-256 checksum
How to use checksums
155ca72b2b224244776f1ee9d7edabcce29c8db915b65b9e58d78eae133744f6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via python-requests/2.31.0

Release files / fastapi_msal_patched-0.2.1-py3-none-any.whl

Download URL fastapi_msal_patched-0.2.1-py3-none-any.whl
Size 19.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
753a61c29260a70ff13954a9ad36172ef90c834c9b18ba90221a18706763270c
BLAKE2b-256 checksum
How to use checksums
bc8647cd37db940aaa9ea08dfb5d4aae23c1c68c88fc4690b11410100d71472f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via python-requests/2.31.0

Security for fastapi_msal_patched 0.2.1

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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

Release history Release notifications | RSS feed

This release

0.2.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page