'How to allow a Channels consumer to access session generated by HTTP requests?
I have a project that used to run under WSGI, and I recently configured it to ASGI. It included code from back then, such as the following function that processes a login request:
def authenticate(req):
...
try:
query = models.User.objects.get(...)
req.session['user'] = query.id #Login successful
...
except:
#No record, reject request
...
What I want to do now is to create a WebsocketConsumer and access the session from within. I have enabled SessionMiddlewareStack. The problem is that the consumer does not even see the session because the session's ID is not attached to the WebSocket request as a header. Is there a way to allow it to access the data?
class SpaceConsumer(WebsocketConsumer):
def connect(self):
#Session object is empty, while HTTP requests see it as populated with the user's ID
if 'user' in self.scope['session']:
self.accept() #Only allow authenticated user
Information online is scarce, and most are written for older versions of Channels. I am using Channels v3.
Solution 1:[1]
Never mind; it was a stupid mistake.
In case other people come here in the future with the same confusion, here is a reference to a solution: Use session data on websocket handshake.
The domain with which you create a Websocket connection must match that of your page. In my case, I opened the application using 127.0.0.1 but connected to WS using localhost. As a result, the cookies were not exposed.
Channels provides access to session objects just fine.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | OddBirdStanley |
