Skip to main content

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

Project description

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

Checked with mypy Code style: black Checked with Pylint

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. Includes a pydantic setting class for easy and secure configuration from your ENV (or .env)

Installation

With pipenv (really, don't use anything else...)

pipenv install fastapi_msal

Prerequisets

As part of your fastapi application the following packages should be included
TL;DR: If you just wish to install it all use

pipenv install "fastapi_msal[full]"
  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

  3. python-dotenv
    Used by pydantic settings management to read configuration from a ".env" file (Optional but recommended)

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, client_config

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=client_config.client_credential")  # don't do this in production!
msal_auth = MSALAuthorization()
app.include_router(msal_auth.router)


@app.get("/users/me", response_model=UserInfo, response_model_exclude_none=True)
async def read_users_me(current_user: UserInfo = Depends(msal_auth.get_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. And if you will try out the API you wrote - it will work for you and present the user info Me Page Image

TODO List

  • Add support for local/redis session cache

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_msal-0.0.3.tar.gz (268.0 kB view details)

Uploaded Source

Built Distribution

fastapi_msal-0.0.3-py3-none-any.whl (17.1 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_msal-0.0.3.tar.gz.

File metadata

  • Download URL: fastapi_msal-0.0.3.tar.gz
  • Upload date:
  • Size: 268.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: python-requests/2.25.1

File hashes

Hashes for fastapi_msal-0.0.3.tar.gz
Algorithm Hash digest
SHA256 14526cbc2ecda2b0da81317f2cd453d41f2f5dd0f0830924377fd69c3cab99d5
MD5 1510daedf824d3084b38485cb1401b33
BLAKE2b-256 20747a259c065cfc97cdb90c4afc88f509a84504b940a9a2cf83c071ff1b357e

See more details on using hashes here.

File details

Details for the file fastapi_msal-0.0.3-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_msal-0.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 36b0530507d6157b471e6c4e589d7df52caff6524cc2444c29b6f2d3f8a20694
MD5 829b66745bc02de2c9b812bb3fd85b41
BLAKE2b-256 5d5636426f8e080457ebd029a8c58a3d55e73cfe8e64fb1df16e93c052dbff04

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page