Django Channels Custom Middleware Not Being Called

20 Views Asked by At

With Django 4 and Channels 4

I have a middleware as follows

from channels.middleware import BaseMiddleware

class TokenAuthMiddleware(BaseMiddleware):
    async def __call__(self, scope, receive, send):
        print('asdf')
        headers = dict(scope['headers'])
        if b'authorization' in headers:
            # Fetch the token here
            token = headers[b'authorization'].decode().split(' ')[-1]
            scope['token'] = token
        return await self.inner(scope, receive, send)

In my INSTALLED_APPS, I have channels and daphne near the top. I also have properly set ASGI_APPLICATION in my django settings.

And in my asgi.py I have:

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings')

application = ProtocolTypeRouter({
    'http': get_asgi_application(),
    'websocket': TokenAuthMiddleware(AuthMiddlewareStack(
        URLRouter([
            re_path(r'ws/agent/$', AgentConsumer.as_asgi()),
        ])
    )),
})

AgentConsumer is a channels consumer based on AsyncChannelConsumer

Yet when I connect to the websocket (in this case, a raw python script using the websockets module), I don't think the middleware is being run. If I put a print statement in the class definition, I see it. But if I put it in __call__(), I never see the print statement.

To add, I have AuthMiddlewareStack, but it seems like it's allowing even unauthenticated socket connections, meaning none of that middleware is being executed?

Is there a reason it seems like the middleware is not being executed?

0

There are 0 best solutions below