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 Lint & Security Download monthly

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"

Or if you wish to have all the required packages straight forward

pip install "fastapi_msal[full]"

Prerequisets

  1. Python 3.9 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 register your app callback path with the platform, as well as to retrieve your application client_id, tenant_id and client_credential (client secrets) - see images below:

Client and tenant ID page

Client secrets page

  1. 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 retrieved at step #1"
client_config.client_credential = "The client_credential retrieved at step #1"
client_config.tenant = "Your tenant_id retrieved at step #1"

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!!!

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

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_msal-2.1.7-py3-none-any.whl (23.2 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: fastapi_msal-2.1.7.tar.gz
  • Upload date:
  • Size: 18.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for fastapi_msal-2.1.7.tar.gz
Algorithm Hash digest
SHA256 0262bb1d1d174f850ef1e41dab622d90eedcc49782b1c364329b24c84f55b484
MD5 28c14494c31ce2cf41dcaa90e3a9c02b
BLAKE2b-256 0a2e0c9860401a1064baef037eaa91220f012ab16d489bd6c62808b7a8f2e19b

See more details on using hashes here.

Provenance

The following attestation bundles were made for fastapi_msal-2.1.7.tar.gz:

Publisher: publish.yml on dudil/fastapi_msal

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

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

File metadata

  • Download URL: fastapi_msal-2.1.7-py3-none-any.whl
  • Upload date:
  • Size: 23.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for fastapi_msal-2.1.7-py3-none-any.whl
Algorithm Hash digest
SHA256 0d8638068ca70217d134c45d177d19569ee6d8dc4676d949d895b18488acb711
MD5 3277881d99332e773e94361eaec5f4d1
BLAKE2b-256 c51834534068e0291e837cdcd0584998814051d723051d683ad73f3d995ac790

See more details on using hashes here.

Provenance

The following attestation bundles were made for fastapi_msal-2.1.7-py3-none-any.whl:

Publisher: publish.yml on dudil/fastapi_msal

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

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