简体   繁体   English

将授权凭证发送到Django通道WebSocket(无需将令牌设置为cookie)

[英]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. 我有一个websocket,我想通过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). 我寻找了这个问题的答案,几乎所有建议都建议先使用javascript存储授权cookie,然后再连接到Web套接字(因此标头将从存储在网页中的cookie发送出去)。

But I prefer to not store the token in browser cookie and just send it in my websocket request scope. 但是我更喜欢不将令牌存储在浏览器cookie中,而只是将其发送到我的websocket请求范围中。

Here is a simple javascript code to connect to websocket. 这是连接到websocket的简单javascript代码。 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. 建立Web套接字连接后,立即将令牌发送到服务器。 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. 然后在Server(在我的情况下为django通道)的receive方法中,获取该令牌,如果令牌有效,则更新连接信息,如果令牌无效,则断开连接。

something like this: 像这样的东西:

js file: js文件:

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): 在服务器端(例如django):

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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