Skip to content

BaseAuthMiddleware class

This is the reference for the main object BaseAuthMiddleware that contains all the parameters, attributes and functions.

esmerald.middleware.authentication.BaseAuthMiddleware

BaseAuthMiddleware(app)

Bases: ABC, MiddlewareProtocol

BaseAuthMiddleware is the object that you can implement if you want to implement any authentication middleware with Esmerald.

It is not mandatory to use it and you are free to implement your.

Esmerald being based on Lilya, also offers a simple but powerful interface for handling authentication and permissions.

Once you have installed the AuthenticationMiddleware and implemented the authenticate, the request.user will be available in any of your endpoints.

Read more about how Esmerald implements the BaseAuthMiddleware.

When implementing the authenticate, you must assign the result into the AuthResult object in order for the middleware to assign the request.user properly.

The AuthResult is of type esmerald.middleware.authentication.AuthResult.

PARAMETER DESCRIPTION
app

An ASGI type callable.

TYPE: ASGIApp

Source code in esmerald/middleware/authentication.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def __init__(
    self,
    app: Annotated[
        ASGIApp,
        Doc(
            """
            An ASGI type callable.
            """
        ),
    ],
):
    super().__init__(app)
    self.app = app
    self.scopes: Set[str] = {ScopeType.HTTP, ScopeType.WEBSOCKET}

app instance-attribute

app = app

scopes instance-attribute

scopes = {HTTP, WEBSOCKET}

authenticate abstractmethod async

authenticate(request)

The abstract method that needs to be implemented for any authentication middleware.

PARAMETER DESCRIPTION
request

TYPE: Connection

Source code in esmerald/middleware/authentication.py
77
78
79
80
81
82
@abstractmethod
async def authenticate(self, request: Connection) -> AuthResult:
    """
    The abstract method that needs to be implemented for any authentication middleware.
    """
    raise NotImplementedError("authenticate must be implemented.")

esmerald.middleware.authentication.AuthResult

Bases: ArbitraryBaseModel

user instance-attribute

user

Arbitrary user coming from the authenticate of the BaseAuthMiddleware and can be assigned to the request.user.