Skip to content

Middleware

As part of the support, Esmerald developed an authentication middleware using python-jose allowing JWT integration with the current supported documents.

JWTAuthMiddleware

This simple but effective middleware extends the BaseAuthMiddleware and enables the authentication via JWT.

from esmerald.contrib.auth.mongoz.middleware import JWTAuthMiddleware

Parameters

  • app - Any ASGI app instance. E.g.: Esmerald instance.
  • config - An instance of JWTConfig object.
  • user - The user class (not instance!) being used by the application.

How to use it

There are different ways of calling this middleware in any Esmerald application.

Via settings

from typing import TYPE_CHECKING, List

from starlette.middleware import Middleware as StarletteMiddleware

from esmerald import EsmeraldAPISettings
from esmerald.config.jwt import JWTConfig
from esmerald.contrib.auth.mongoz.middleware import JWTAuthMiddleware
from esmerald.utils.module_loading import import_string

if TYPE_CHECKING:
    from esmerald.types import Middleware


class CustomSettings(EsmeraldAPISettings):
    @property
    def jwt_config(self) -> JWTConfig:
        """
        A JWT object configuration to be passed to the application middleware
        """
        return JWTConfig(signing_key=self.secret_key, auth_header_types=["Bearer", "Token"])

    @property
    def middleware(self) -> List["Middleware"]:
        """
        Initial middlewares to be loaded on startup of the application.
        """
        return [
            StarletteMiddleware(
                JWTAuthMiddleware,
                config=self.jwt_config,
                user_model=import_string("myapp.models.User"),
            )
        ]

Via application instantiation

from starlette.middleware import Middleware as StarletteMiddleware

from esmerald import Esmerald
from esmerald.conf import settings
from esmerald.config.jwt import JWTConfig
from esmerald.contrib.auth.mongoz.middleware import JWTAuthMiddleware
from esmerald.utils.module_loading import import_string

jwt_config = JWTConfig(signing_key=settings.secret_key, auth_header_types=["Bearer", "Token"])

jwt_auth_middleware = StarletteMiddleware(
    JWTAuthMiddleware,
    config=jwt_config,
    user_model=import_string("myapp.models.User"),
)

app = Esmerald(middleware=[jwt_auth_middleware])

Via overriding the JWTAuthMiddleware

from starlette.types import ASGIApp

from esmerald import Esmerald
from esmerald.conf import settings
from esmerald.config.jwt import JWTConfig
from esmerald.contrib.auth.mongoz.middleware import JWTAuthMiddleware
from esmerald.utils.module_loading import import_string


class AppAuthMiddleware(JWTAuthMiddleware):
    """
    Overriding the JWTAuthMiddleware
    """

    jwt_config = JWTConfig(signing_key=settings.secret_key, auth_header_types=["Bearer", "Token"])

    def __init__(self, app: "ASGIApp"):
        super().__init__(
            app, config=self.jwt_config, user_model=import_string("myapp.models.User")
        )


app = Esmerald(middleware=[AppAuthMiddleware])
from typing import TYPE_CHECKING, List

from starlette.types import ASGIApp

from esmerald import EsmeraldAPISettings
from esmerald.conf import settings
from esmerald.config.jwt import JWTConfig
from esmerald.contrib.auth.mongoz.middleware import JWTAuthMiddleware
from esmerald.utils.module_loading import import_string

if TYPE_CHECKING:
    from esmerald.types import Middleware


class AppAuthMiddleware(JWTAuthMiddleware):
    """
    Overriding the JWTAuthMiddleware
    """

    jwt_config = JWTConfig(signing_key=settings.secret_key, auth_header_types=["Bearer", "Token"])

    def __init__(self, app: "ASGIApp"):
        super().__init__(
            app, config=self.jwt_config, user_model=import_string("myapp.models.User")
        )


class AppSettings(EsmeraldAPISettings):
    @property
    def middleware(self) -> List["Middleware"]:
        """
        Initial middlewares to be loaded on startup of the application.
        """
        return [AppAuthMiddleware]

Important note

In the examples you could see sometimes the StarletteMiddleware being used and in other you didn't. The reason behind is very simple and also explained in the middleware section.

If you need to specify parameters in your middleware then you will need to wrap it in a starlette.middleware.Middleware object to do it so.

If no parameters are needed, then you can simply pass the middleware class directly and Esmerald will take care of the rest.