简体   繁体   English

强制Django Channels Websocket身份验证

[英]Force Django Channels Websocket Authentication

The website I am working on requires login for every page by using a login required middleware. 我正在工作的网站要求使用登录所需的中间件来登录每个页面。

I am trying to add websockets with Channels for two way communication to the client web browser for notifications. 我正在尝试使用带有通道的websocket添加用于双向通信到客户端Web浏览器的通知。

Daphne is running as the interface server and manage.py runworker is running the workers. Daphne作为界面服务器运行,manage.py runworker正在运行工作程序。

I have a have a working function in the consumers.py file that runs when the connection has been opened. 在打开连接后运行的consumers.py文件中有一个工作功能。

The problem is that this connection can be opened, and the function runs by any web browser, without being logged in. 问题在于可以打开此连接,并且该功能可以通过任何Web浏览器运行,而无需登录。

How can I force login before the connection can be opened? 如何在打开连接之前强制登录?

If you want the user to be logged in for the page you can use the decorator login_required for your views. 如果希望用户登录该页面,则可以使用装饰器login_required作为视图。 You first need to import it 您首先需要导入

from django.contrib.auth.decorators import login_required

and for the views you can then use it as any other normal decorator for example:- 对于视图,您可以将其用作其他任何普通装饰器,例如:

@login_required
def my_view(request):
    ...

What this will do is it will ensure that the user is logged in before he is able to view the page. 这样做是为了确保用户登录后才能查看页面。

This will take him to the login page if you have implemented your authentication back end and after he is logged in then redirect to the page in your view. 如果您已经实现了身份验证后端,那么这会将他带到登录页面,并且在他登录后,然后重定向到您视图中的页面。 If he is already logged in then he is allowed to access the page directly. 如果他已经登录,则可以直接访问该页面。

看到“ channels_api”库,他们做得很好。

You can use @channel_session_user_from_http for "websocket.connect" , @channel_session_user for "websocket.receive" . 您可以将@channel_session_user_from_http用作"websocket.connect" ,将@channel_session_user用作"websocket.receive"

You can got message.user from http session. 您可以从http会话获取message.user


http://channels.readthedocs.io/en/stable/getting-started.html#authentication http://channels.readthedocs.io/zh-CN/stable/getting-started.html#authentication

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

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