masrlinu
masrlinu

Reputation: 103

Django Channels session is not persistent. disconnect -> logged out

I have a websocket-router:

application = ProtocolTypeRouter({
    'websocket': 
    AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter(
                [
                    url("ws/", Consumer)
                ]
            )
        )
    )
})

I am logging in a user by sending a command to the websocket. The user gets logged in like this:

if cmd == 'login':
    user = await database_sync_to_async(authenticate)(consumer.scope, email=request['eMail'], password=request['pass'])
    if user is not None:
        # login the user to this session.
        await login(consumer.scope, user, backend='allauth.account.auth_backends.AuthenticationBackend')
        # save the session
        consumer.scope['session'].modified = True
        await database_sync_to_async(consumer.scope['session'].save)()

Every time, the websocket-connection gets disconnected, the user is not logged in anymore. I thought, the session gets saved by

consumer.scope['session'].save()

but it doesn´t work. The session is not persistent.

How can I solve this problem?

Upvotes: 0

Views: 878

Answers (1)

Matthaus Woolard
Matthaus Woolard

Reputation: 2408

which session backend are you using in Django.

Due to how web sockets work once the connection is created you can't set any cookies so if your using a session backend that depends on cookie storage the save will have no effect since the web-browser can't be updated.

Currently channels does not even support setting cookies durring the accept method. https://github.com/django/channels/issues/1096#issuecomment-619590028

However if you ensure that you users already has a session cookie then you can upgrade that session to a logged in user.

Upvotes: 3

Related Questions