Adding Azure Active Directory Authentication for FastAPI
Project description
Adding Azure Active Directory Authentication for FastAPI
Using it
The configuration is defined in src/fastapi_aad_auth/config.py, and includes options for configuring the AAD config, the login UI and the routes.
You can initialise it with:
from fastapi_aad_auth import AADAuth, AuthenticationState, Config auth_provider = AADAuth() # If you had a config that wasn't set in the environment, you could use # auth_provider = AADAuth(Config(<my config kwargs>)
You can use it for fastapi routes:
from fastapi import APIRouter, Depends # Use the auth_provider.api_auth_scheme for fastapi authentication router = APIRouter() @router.get('/hello') async def hello_world(auth_state: AuthenticationState =D epends(auth_provider.api_auth_scheme)): print(auth_state) return {'hello': 'world'}
For starlette routes (i.e. interactive/HTML pages), use the auth_provider.auth_required for authentication:
from starlette.responses import PlainTextResponse @auth_provider.auth_required() async def test(request): if request.user.is_authenticated: return PlainTextResponse('Hello, ' + request.user.display_name)
This middleware will set the request.user object and request.credentials object:
async def homepage(request): if request.user.is_authenticated: return PlainTextResponse('Hello, ' + request.user.display_name) return PlainTextResponse(f'Hello, you')
You can set the swagger_ui_init_oauth using auth_provider.api_auth_scheme.init_oauth:
from fastapi import FastAPI app = FastAPI(title='fastapi_aad_auth test app', description='Adding Azure Active Directory Authentication for FastAPI', version='0.1.0', openapi_url=f"/api/v0/openapi.json", docs_url='/api/docs', swagger_ui_init_oauth=auth_provider.api_auth_scheme.init_oauth, redoc_url='/api/redoc', routes=routes)
To add the required middleware to the fastapi app use:
auth_provider.configure_app(app)
(Built from package-template version 1.0.0)
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distributions
Built Distribution
File details
Details for the file fastapi_aad_auth-0.0.1-py3-none-any.whl
.
File metadata
- Download URL: fastapi_aad_auth-0.0.1-py3-none-any.whl
- Upload date:
- Size: 15.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.23.0 setuptools/40.8.0 requests-toolbelt/0.8.0 tqdm/4.50.2 CPython/3.7.4
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 4f96f5228dcdd2ed6d51055203463e1fee04543702728a3fa5111bcbf7411821 |
|
MD5 | 1b49ada4d93699e70626e28e9038210a |
|
BLAKE2b-256 | b42728a65707410e0ac5057a21e6a6dff0c06b5d8d2b235da91831d254a88ab2 |