Open John-Doherty01 opened 3 years ago
you are welcome to come with a contribution
Hi! I've also was looking for a way to authenticate user with request auth header. Here is my implementation if it's help to someone
from channels.db import database_sync_to_async
from channels.middleware import BaseMiddleware
from channels.security.websocket import WebsocketDenier
from django.contrib.auth import authenticate
from django.http import HttpRequest
class OAuth2Middleware(BaseMiddleware):
@database_sync_to_async
def _authenticate(self, token: str) -> User | None:
http_request = HttpRequest()
http_request.META["Authorization"] = token
return authenticate(request=http_request)
async def authenticate_user(self, scope) -> None:
scope["user"] = None
token = None
for header_name, header_value in scope["headers"]:
if header_name == b"authorization":
token = header_value
break
if not token:
return
scope["user"] = await self._authenticate(token)
async def __call__(self, scope, receive, send):
await self.authenticate_user(scope)
if not scope["user"]:
denier = WebsocketDenier()
return await denier(scope, receive, send)
return await super().__call__(scope, receive, send)
Websockets are great to have within an API service toolkit for full duplex communication. Django's most popular implementation of this is https://channels.readthedocs.io/en/stable/
Handling authentication for this django channel library can be handled by providing a authentication middleware class which can then be referenced by django channels, example here using a custom authentication class called
TokenAuthMiddlewareStack
:I think it would be great if django-oauth-toolkit provided an out the box implementation of an authentication middleware which is compatible with django channels. I've made a quick working PoC below but hasn't been tested security wise:
I seen this has been mentioned in the past but thought it would be good to bring up again. I spent the time making this PoC but I'm not an active member of this repo, would be great to hear feedback of active contributors regarding this PoC.