From: Michael Tremer Date: Sun, 29 Jun 2025 17:20:41 +0000 (+0000) Subject: api: Make authentication work with WebSockets, too X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=60215302e4a5d423a2efb5aca126899ee49370c8;p=pbs.git api: Make authentication work with WebSockets, too Signed-off-by: Michael Tremer --- diff --git a/src/api/auth.py b/src/api/auth.py index 1170a5d6..bb7c4651 100644 --- a/src/api/auth.py +++ b/src/api/auth.py @@ -25,6 +25,7 @@ import kerberos import os import pydantic import socket +import starlette import typing from . import apiv1 @@ -51,8 +52,18 @@ router = fastapi.APIRouter( tags=["Authentication"], ) +class HTTPBearer(fastapi.security.HTTPBearer): + """ + This is a custom implementation of HTTPBearer which also supports WebSockets + """ + # This works because fastapi.Request and fastapi.WebSocket both inherit from + # starlette's HTTPConnection. + async def __call__(self, request: starlette.requests.HTTPConnection) \ + -> typing.Optional[fastapi.security.HTTPAuthorizationCredentials]: + return await super().__call__(request) + # Class to extract the Bearer token from the request headers -security = fastapi.security.HTTPBearer() +security = HTTPBearer() async def get_current_principal( credentials: fastapi.security.HTTPAuthorizationCredentials = fastapi.Depends(security)