简体   繁体   中英

Send Authorization Credentials to Django-channels WebSocket (without setting token as cookie)

I have a websocket that i want to be authenticated with Token Authorization on handshake on opennig. I looked for answers for this problem and almost all of them suggested to store Authorization cookie first with javascript then connect to web socket (so the header will be sent from cookie stored in web page).

But I prefer to not store the token in browser cookie and just send it in my websocket request scope.

Here is a simple javascript code to connect to websocket. I really appreciate it if any one help me on this context:

<script>
const socket = new WebSocket('ws://localhost:8001/announcement');

socket.onopen = function open() {
  console.log('WebSockets connection created.');
};

// Listen for messages
socket.addEventListener('announcement', function (event) {
    console.log('Message from server ', event.data);
});
</script>

I found a solution. Correct me if I'm wrong.

Right after web socket connection established, send the token to server. And in Server (in my case django channels) in receive method, I fetch that token and if token is valid, I update the connection information, And if the token is not valid disconnect the connection.

something like this:

js file:

const socket = new WebSocket('ws://localhost:8001/announcement');

socket.onopen = function open() {
  console.log('WebSockets connection created.');

  let authData = {'token': '<valid-token-here>'}
  socket.send(JSON.stringify(authData));

};

and on server side (django for example):

def receive(self, text_data=None, bytes_data=None):
    if self.scope['user'].id:
        pass
    else:
        try:
            # It means user is not authenticated yet.
            data = json.loads(text_data)
            if 'token' in data.keys():
                token = data['token']
                user = fetch_user_from_token(token)
                self.scope['user'] = user
        except Exception as e:
            # Data is not valid, so close it.
            print(e)
            pass

    if not self.scope['user'].id:
        self.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM