Skip to content

src/genro_asgi/middleware/authentication.py

Source from this local checkout, regenerated when the reader rebuilds. Line links use #L<number>; a GitHub line range opens its first line.

1 # Copyright 2025 Softwell S.r.l.2 #3 # Licensed under the Apache License, Version 2.0 (the "License");4 # you may not use this file except in compliance with the License.5 # You may obtain a copy of the License at6 #7 #     https://www.apache.org/licenses/LICENSE-2.08 #9 # Unless required by applicable law or agreed to in writing, software10 # distributed under the License is distributed on an "AS IS" BASIS,11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12 # See the License for the specific language governing permissions and13 # limitations under the License.14 15 """Authentication middleware — publishes the request identity on the scope.16 17 Delegates the whole verdict to ``server.authenticate(scope)`` (the §5.518 precedence living on ``AuthMixin``) and stores the result on ``scope["auth"]``19 for downstream handlers. A present-but-invalid credential raises20 ``HTTPUnauthorized`` from the auth core, caught outermost by ``ErrorMiddleware``21 (order 100) and turned into a 401. Armed by ``AuthMixin``; order 450 (INSIDE22 ``SessionMiddleware`` at 400, so ``scope["session"]`` is already attached and23 the §5.5 session fallback is live), default OFF. The chain only carries24 ``http`` scopes, so no scope filtering happens here.25 """26 27 from __future__ import annotations28 29 from typing import TYPE_CHECKING30 31 from .base import BaseMiddleware32 33 if TYPE_CHECKING:34     from ..types import Receive, Scope, Send35 36 __all__ = ["AuthMiddleware"]37 38 39 class AuthMiddleware(BaseMiddleware):40     """Sets ``scope["auth"]`` from the server's identity resolution."""41 42     middleware_order = 45043     middleware_default = False44 45     async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:46         """Resolve the identity via the server and publish it on the scope."""47         scope["auth"] = self.server.authenticate(scope)48         await self.app(scope, receive, send)