Package: fastapi_auth_middleware
FastAPI Auth MiddlewareWe atCode Specialistlove FastAPI for its simplicity and feature-richness. Though we were a bit staggered by the poor documentation and integration
of auth-concepts. That's why we wrote aFastAPI Auth Middleware. It integrates seamlessly into FastAPI applications and requires minimum configuration. It is built
uponStarletteand thereby requiresno dependenciesyou do not have included anyway.Caution: This is a middleware to plug in existing authentication. Even though we offer some sample code, this package assumes you already have a way to generate and verify
whatever you use, to authenticate your users. In most of the usual cases this will be an access token or bearer. For instance as inOAuth2orOpen ID Connect.Installpipinstallfastapi_auth_middlewareDocumentationMore detailed docs are available athttps://fastapi-auth-middleware.code-specialist.com.Why FastAPI Auth Middlware?Application or Route scoped automatic authorization and authentication with the perks of dependency injection (But without inflated signatures due toDepends())Lightweight without additional dependenciesEasy to configureEasy to extend and adjust to specific needsPlug-and-Play feelingUsageThe usage of this middleware requires you to provide a single function that validates a given authorization header. The middleware will extract the content of theAuthorizationHTTP header and inject it into your function that returns a list of scopes and a user object. The list of scopes may be empty if you do not use any scope based concepts. The user
object must be aBaseUseror any inheriting class such asFastAPIUser. Thereby, yourverify_authorization_headerfunction must implement a signature that contains a string as
an input and aTupleof aList of stringsand aBaseUseras output:fromtypingimportTuple,Listfromfastapi_auth_middlewareimportFastAPIUserfromstarlette.authenticationimportBaseUser...# Takes a string that will look like 'Bearer eyJhbGc...'defverify_authorization_header(auth_header:str)->Tuple[List[str],BaseUser]:# Returns a Tuple of a List of scopes (string) and a BaseUseruser=FastAPIUser(first_name="Code",last_name="Specialist",user_id=1)# Usually you would decode the JWT here and verify its signature to extract the 'sub'scopes=[]# You could for instance use the scopes provided in the JWT or request them by looking up the scopes with the 'sub' somewherereturnscopes,userThis function is then included as an keyword argument when adding the middleware to the app.fromfastapiimportFastAPIfromfastapi_auth_middlewareimportAuthMiddleware...app=FastAPI()app.add_middleware(AuthMiddleware,verify_authorization_header=verify_authorization_header)After adding this middleware, all requests will pass theverify_authorization_headerfunction and contain thescopesas well as theuser objectas injected dependencies.
All requests now pass theverify_authorization_headermethod. You may also verify that users posses scopes withrequires:fromstarlette.authenticationimportrequires...@app.get("/")@requires(["admin"])# Will result in an HTTP 401 if the scope is not matcheddefsome_endpoint():...You are also able to use theuserobject you injected on therequestobject:fromstarlette.requestsimportRequest...@app.get('/')defhome(request:Request):returnf"Hello{request.user.first_name}"# Assuming you use the FastAPIUser objectExamplesVarious examples on how to use this middleware are available
athttps://fastapi-auth-middleware.code-specialist.com/examples