Skip to content

JWT

As part of the support, Esmerald developed an authentication middleware using pyjwt allowing JWT integration with the current supported models.

JWTAuthMiddleware

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

from esmerald.contrib.auth.saffier.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 esmerald import EsmeraldAPISettings
from esmerald.config.jwt import JWTConfig
from esmerald.contrib.auth.saffier.middleware import JWTAuthMiddleware
from lilya._internal._module_loading import import_string
from lilya.middleware import DefineMiddleware as LilyaMiddleware

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 [
            LilyaMiddleware(
                JWTAuthMiddleware,
                config=self.jwt_config,
                user_model=import_string("myapp.models.User"),
            )
        ]

Via application instantiation

from esmerald import Esmerald
from esmerald.conf import settings
from esmerald.config.jwt import JWTConfig
from esmerald.contrib.auth.saffier.middleware import JWTAuthMiddleware
from lilya._internal._module_loading import import_string
from lilya.middleware import DefineMiddleware as LilyaMiddleware

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

jwt_auth_middleware = LilyaMiddleware(
    JWTAuthMiddleware,
    config=jwt_config,
    user=import_string("myapp.models.User"),
)

app = Esmerald(middleware=[jwt_auth_middleware])

Via overriding the JWTAuthMiddleware

from esmerald import Esmerald
from esmerald.conf import settings
from esmerald.config.jwt import JWTConfig
from esmerald.contrib.auth.saffier.middleware import JWTAuthMiddleware
from lilya._internal._module_loading import import_string
from lilya.types import ASGIApp


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 esmerald import EsmeraldAPISettings
from esmerald.conf import settings
from esmerald.config.jwt import JWTConfig
from esmerald.contrib.auth.saffier.middleware import JWTAuthMiddleware
from lilya._internal._module_loading import import_string
from lilya.types import ASGIApp

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 LilyaMiddleware 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 lilya.middleware.DefineMiddleware 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.