Package: fastapi-msal
FastAPI/MSAL - MSAL (Microsoft Authentication Library) plugin for FastAPIFastAPI -https://github.com/tiangolo/fastapiFastAPI 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-pythonThe Microsoft Authentication Library for Python enables applications to integrate with theMicrosoft identity platform.It allows you to sign in users or apps with Microsoft identities
and obtain tokens to call Microsoft APIs such asMicrosoft Graphor your own APIs registered with the Microsoft identity platform.
It is built using industry standard OAuth2 and OpenID Connect protocolsThefastapi_msalpackage 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.FeaturesIncludes Async implementation of MSAL confidential client class utilizaing Starlette threadpool model.Use pydantic models to translate the MSAL objects to data objects which are code and easy to work with.Have a built-in router which includes the required paths for the authentication flow.Include a dependency class to authenticate and secure your application APIsIncludes a pydantic setting class for easy and secure configuration from your ENV (or .env or secrets directory)Full support with FastAPI swagger documentations and authentication simulationInstallationpipinstall"fastapi_msal"Or if you wish to have all the required packages straight forwardpipenvinstall"fastapi_msal[full]"PrerequisetsPython 3.7 and aboveAs part of your fastapi application the following packages should be included:(if you use the[full]method it is not required.)python-multipart,From FastAPI documentation:
This is required since OAuth2 (Which MSAL is based upon) uses "form data" to send the credentials.itsdangerousUsed by Starlettesession middlewareUsageFollow the applicationregistration process
with the Microsoft Identity Platform. Finishing the processes will allow you toregister your app callback path with the platform, as well as to retrieve your applicationclient_id,tenant_idandclient_credential(client secrets) - see images below:Create a new main.py file and add the following lines.
Make sure to update the lines with the information retrieved in the previous stepimportuvicornfromfastapiimportFastAPI,Dependsfromstarlette.middleware.sessionsimportSessionMiddlewarefromfastapi_msalimportMSALAuthorization,UserInfo,MSALClientConfigclient_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)asyncdefread_users_me(current_user:UserInfo=Depends(msal_auth.scheme))->UserInfo:returncurrent_userif__name__=="__main__":uvicorn.run("main:app",host="localhost",port=5000,reload=True)Run your app(pipenvshell)$pythonmain.py
INFO:Uvicornrunningonhttp://localhost:5000(PressCTRL+Ctoquit)INFO:Startedreloaderprocess[12785]usingstatreload
INFO:Startedserverprocess[12787]INFO:Waitingforapplicationstartup.
INFO:Applicationstartupcomplete.Browse tohttp://localhost:5000/docs- this is the API docs generated by FastAPI (totaly cool!)Using the "built-in" authenticaiton button (the little lock) you will be able to set the full authentication process(Igonre the cline_id and client_secret - they are not relevant for the process as you already set them)After you complete the process you will get a confirmation popupTrying out theMEapi endpointWorking Example/TemplateIf 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-webappNB!Make sure you are using thefastapi_msalbranch!!!TODO ListAdd support for local/redis session cacheAdd TestsProper Documentation