简体   繁体   English

Django Channels - 拒绝未经授权的 websocket 请求的正确方法?

[英]Django Channels - correct way to reject an unauthorized websocket request?

I have a AsyncWebSocketConsumer which first authorizes a user's credential cookies before accepting their connection, as so:我有一个AsyncWebSocketConsumer ,它在接受用户的连接之前首先授权用户的凭证 cookie,如下所示:

// consumer.py

class AuthWebSocketConsumer(AsyncWebSocketConsumer):

    async def connect(self):
        
        if not(await self.authorized(self.scope)):
            await self.close(code=4004)
        else:
            await self.accept()

However, on the client side, I am seeing this as an onerror event followed by an onclose event with a Websocket code of 1006 , not 4004 as I sent back.但是,在客户端,我将其视为一个onerror事件,然后是一个onclose事件,Websocket 代码为1006 ,而不是我发回的4004

// socket.js

this.log_socket = new WebSocket(url.href);

this.log_socket.onerror = (event) => {
  // Happens on Websocket REJECTs
  console.log("Socket error", event);
};

this.log_socket.onclose = (event) => {
  console.log("Socket closed: ", event);
};

The logged close event being as so记录的关闭事件如此

CloseEvent {isTrusted: true, wasClean: false, code: 1006, reason: "", type: "close", …}
bubbles: false
cancelBubble: false
cancelable: false
code: 1006

在此处输入图片说明

It seems either Django channels is not forwarding the websocket close code, or the browser is masking the error code as the connection was never accepted.似乎 Django 频道没有转发 websocket 关闭代码,或者浏览器正在屏蔽错误代码,因为连接从未被接受。 In which case, what is the proper way to relay to the client that they are not authenticated for Websocket connects (or some other rejection reason)?在这种情况下,向客户端中继他们未针对 Websocket 连接(或其他一些拒绝原因)进行身份验证的正确方法是什么? It seems at the moment, I need to accept the connection before immediately closing it - which seems a little bit like a security flaw?目前看来,我需要在立即关闭连接之前接受连接 - 这似乎有点像一个安全漏洞?

I had the same problem once and solved it like follows:我曾经遇到过同样的问题,并按如下方式解决了它:

// consumer.py

class AuthWebSocketConsumer(AsyncWebSocketConsumer):

    async def connect(self):
        await self.accept()
        if not(await self.authorized(self.scope)):
            await self.close(code=4004)

I saw someone's comment on stackoverflow.我看到有人对 stackoverflow 的评论。 It said that you need to accept the connection first to send the close code.它说您需要先接受连接才能发送关闭代码。 Unfortunately I wasn't able to find the original comment.不幸的是,我无法找到原始评论。

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

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