-
|
I see that JWT authentications and sessions are documented, how would a basic auth be implemented? I have an Authentication object with the username and a list of permissions. The idea I had was to connect to an ldap, validate those credentials, get the user permissions and then depending on the method validate one or the other. I have everything implemented except the rest api part. I had thought about implementing a custom authentication, but I don't see it documented in the openapi for example. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
Litestar doesn't ship a Basic Auth scheme out of the box, but the building blocks are there. Subclass Sketch: import base64
from litestar import Litestar
from litestar.connection import ASGIConnection
from litestar.exceptions import NotAuthorizedException
from litestar.middleware import AbstractAuthenticationMiddleware, AuthenticationResult
from litestar.openapi.config import OpenAPIConfig
from litestar.openapi.spec import Components, SecurityScheme
class BasicAuthMiddleware(AbstractAuthenticationMiddleware):
async def authenticate_request(self, connection: ASGIConnection) -> AuthenticationResult:
header = connection.headers.get("Authorization", "")
if not header.startswith("Basic "):
raise NotAuthorizedException("missing Basic auth")
try:
raw = base64.b64decode(header.removeprefix("Basic ")).decode("utf-8")
username, _, password = raw.partition(":")
except Exception as exc:
raise NotAuthorizedException("invalid Basic auth") from exc
user = await your_ldap_validate(username, password)
if user is None:
raise NotAuthorizedException("invalid credentials")
return AuthenticationResult(user=user, auth=None)Wire it up: app = Litestar(
route_handlers=[your_handlers],
middleware=[BasicAuthMiddleware],
openapi_config=OpenAPIConfig(
title="API",
version="1.0.0",
components=Components(
security_schemes={"basic_auth": SecurityScheme(type="http", scheme="basic")}
),
security=[{"basic_auth": []}],
),
)From running this kind of setup in prod, two things bit me.
LDAP roundtrips per request kill latency. Cache the validated user object (username plus a hash of the supplied password plus the permissions list) with a short TTL of 30 to 60 seconds. The session and JWT middleware sources in |
Beta Was this translation helpful? Give feedback.
Litestar doesn't ship a Basic Auth scheme out of the box, but the building blocks are there. Subclass
AbstractAuthenticationMiddlewareand add aSecuritySchemeentry in the OpenAPI config for the doc side.Sketch: