#How can I exclude static files at / from my auth middleware?

1 messages · Page 1 of 1 (latest)

mystic badge
#

auth_middleware = DefineMiddleware(CustomAuthenticationMiddleware, exclude=["docs"])

Litestar(
  ...,
  create_static_files_router(
    path="/",
    directories=["html"],
    html_mode=True,
  ),
  middleware=[auth_middleware],
  ...,
)
#

I am using pretty much what's in the docs for custom auth middleware

tight echo
#

What's CustomAuthenticationMiddleware? Is it completely custom, or does it inherit a Litestar base middleware?

mystic badge
#
class CustomAuthenticationMiddleware(AbstractAuthenticationMiddleware):
    async def authenticate_request(self, connection: ASGIConnection) -> AuthenticationResult:
        """Authenticate request."""
        conn: Pool = connection.app.state["db_pool"]
        api_key = connection.headers.get("X-API-KEY")

        if str(connection.url) in {
            "http://localhost:8000/",
            "http://localhost:8000/favicon.ico", # TODO, there's gotta be a better way
        }:
            return AuthenticationResult(user="user", auth="token")

        if not api_key:
            raise NotAuthorizedException("Missing API key")

        query = """
            SELECT u.id, u.username, u.info, t.api_key
            FROM public.api_tokens t
            JOIN public.auth_users u ON t.user_id = u.id
            WHERE t.api_key = $1
        """

        row = await conn.fetchrow(query, api_key)

        if not row:
            raise NotAuthorizedException("Invalid API key")

        user = AuthUser(id=row["id"], username=row["username"], info=row["info"])
        token = AuthToken(api_key=row["api_key"])
        return AuthenticationResult(user=user, auth=token)
#

This is what I have now

tight echo
#

I would use the exclude_from_auth_key. It defaults to "exclude_from_auth", so if you pass that to your static files router, the middleware will skip it

#

create_static_files_router(..., opt={"exclude_from_auth": True})

mystic badge
#

awesome, I knew there was a better way