Skip to main content

FastAPI Authentication Middelware

Starlette has an authentication middleware built into the library that you can use to authenticate requests coming into your FastAPI app.

starlette.middleware.authentication.AuthenticationMiddleware

What this does is send the request Scope to a user defined subclass of the AuthenticationBackend class which does the business logic for authenticating a request. From there it will attach 2 items to the request Scope and send it on its way.

Here is the abstract class of the backend.

class AuthenticationBackend:
async def authenticate(self, conn: HTTPConnection) -> tuple[AuthCredentials, BaseUser] | None:
raise NotImplementedError() # pragma: no cover

Here is an implementation of this class.

class MyAuthBackend(AuthenticationBackend):
async def authenticate(self, conn: HTTPConnection) -> tuple[AuthCredentials, SimpleUser] | None:
auth_creds = AuthCredentials(scopes=["admin"])
simple_user = SimpleUser(username="bill")
return auth_creds, simple_user

The AuthenticationMiddleware calls authenticate which runs my code and returns the details.

  • AuthCredentials could be extended to package up more context about any tokens or cookies passed.

I can't say I see too much value in using AuthCredentials personally, but being able to subclass the BaseUser to represent a user