"""JWT authentication for browser WebSocket connections. Browsers cannot set an Authorization header on WebSocket constructors, so the client supplies its short-lived access token as a WebSocket subprotocol. The server negotiates only the non-secret ``jwt`` protocol, never echoing the token. """ from channels.db import database_sync_to_async from django.contrib.auth import get_user_model from django.contrib.auth.models import AnonymousUser from rest_framework_simplejwt.exceptions import InvalidToken, TokenError from rest_framework_simplejwt.tokens import AccessToken @database_sync_to_async def _user_from_access_token(raw_token): try: token = AccessToken(raw_token) user_id = token.get("user_id") if not user_id: return AnonymousUser() User = get_user_model() return User.objects.filter(pk=user_id, is_active=True).first() or AnonymousUser() except (InvalidToken, TokenError, TypeError, ValueError): return AnonymousUser() class JwtAuthMiddleware: """Populate ``scope['user']`` from a SimpleJWT access token.""" def __init__(self, app): self.app = app async def __call__(self, scope, receive, send): protocols = scope.get("subprotocols", []) token = protocols[1] if len(protocols) == 2 and protocols[0] == "jwt" else None user = await _user_from_access_token(token) if token else AnonymousUser() scope = dict(scope) scope["user"] = user return await self.app(scope, receive, send)