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 git+https://github.com/dudil/fastapi_msal.git#egg=fastapi_msal

Prerequisets

As part of your fastapi application the following packages will also be included
(They are not required by fastpi_msal directly hence they are listed here)

  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. You will need to 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. Add the file fastapi_msal.env with the following configuration.
    NB! make sure to add all ".env" to your gitignore!!!

CLIENT_ID="THE-APP-CLIENT-ID"
CLIENT_CREDENTIAL="THE-APP-CLIENT-CREDENTIAL/SECRET"
TENANT="YOUR-TENANT-NAME"
POLICY="ONE-OF: AAD_MULTI\AAD_SINGLE\B2C_1_LOGIN\B2C_1_PROFILE"
SCOPES=["OPTIONAL-SCOPES"]

The policy configuration will be used according to your application target identity platform. If you are writing your own tenant graph-api application, you will select AAD_SINGLE.
If you wish to log-in your users to AAD B2C you should select B2C_1_LOGIN.

  1. Include the following line in your app main file:
import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse, PlainTextResponse
from starlette.middleware.sessions import SessionMiddleware
from fastapi_msal import MSALAuthorization, MSALClientConfig, UserInfo 

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="SOME_SSH_KEY_ONLY_YOU_KNOW")
msal_config = MSALClientConfig()
msal_auth = MSALAuthorization(client_config=msal_config)
app.include_router(msal_auth.router)

@app.get("/", response_class=PlainTextResponse)
async def index(request: Request):
    token: Optional[str] = request.session.get("AuthToken", None)
    if not token:
        return RedirectResponse(request.url_for(name="login"))
    user: UserInfo = await msal_auth.handler.parse_id_token(token=token)
    return f"Hi There {user.display_name}!"

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.1.tar.gz (24.9 kB view details)

Uploaded Source

Built Distribution

fastapi_msal-0.0.1-py3-none-any.whl (16.2 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for fastapi_msal-0.0.1.tar.gz
Algorithm Hash digest
SHA256 ea08aaf6ee684c9345334a245deacbd58479d768b1559d2700526615ebbad697
MD5 0852472be2d8eb8a96216dfc8b48003e
BLAKE2b-256 7a98ec0546afe5023c8201aff9e2f4fe70b537f7144322255085f7a7abcf4453

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for fastapi_msal-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 bdc1a9f97ed8c1e812e5aea5a86dafb24c4fd08d14b290f77739ba1552770151
MD5 e4c1f32b778c6320f53e1c23a75867d8
BLAKE2b-256 4632b340d78e831372abc32d35a6349f44483db8d181ce6a80c3f69355fda4e3

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