简体   繁体   English

Flask SocketIO通过发送令牌在连接事件上进行身份验证

[英]Flask SocketIO authenticate on connect event by sending token

Currently after a user logs in, I return a token using JSON . 目前,在user登录后,我使用JSON返回token Subsequently they must make a request to the index page and pass the token in the HTTP Authorisation header . 随后,他们必须向index页发出请求,并在HTTP Authorisation header传递token

The index.html page contains the following: index.html页面包含以下内容:

var socket = io.connect('http://' + document.domain + ':' + location.port + namespace);

socket.on('connect', function() {          
          socket.emit('join', {room: 'venue_1'}); 
});  

If the user follows this process of events then connection to socket is only possible after they login . 如果user遵循此事件过程,则只有在他们login后才能连接到socket However, I am trying to prevent against the situation where someone may just create a html file containing the above code and not first go through the login step. 但是,我试图防止有人可能只是创建一个包含上述代码的html文件,而不先执行login步骤的情况。

Server Code 服务器代码

@socketio.on('connect', namespace='/test')
def test_connect():

    # Can anything be done here to verify a user?

    emit('my response', {'data': 'Connected'})

Is there a way I can pass a token to the above connect event so that I can verify the user there. 有没有一种方法可以将token传递给上述connect事件,以便在那里验证用户。 If the token ended up being invalid, I could maybe run a disconnect call. 如果token最终无效,则可以运行disconnect调用。

Or does this need to occur when I do the following call? 还是在我打以下电话时需要发生这种情况?

socket.emit('join', {room: 'venue_1', token:'token1234'}); 

Thanks for your help. 谢谢你的帮助。

The documentation for Flask-SocketIO includes a section on Authentication . Flask-SocketIO的文档包括Authentication一节。

The solution is based on the availability of the HTTP context (user session and cookies) inside your SocketIO handlers. 该解决方案基于SocketIO处理程序中HTTP上下文(用户会话和cookie)的可用性。 If you are using Flask-Login to manage the user session, then the current_user context variable is available in your socket handlers. 如果使用Flask-Login来管理用户会话,那么套接字处理程序中将提供current_user上下文变量。 For example: 例如:

@socketio.on('connect', namespace='/test')
def test_connect():
    if not current_user.is_authenticated()
        return  # do not respond or disconnect
    # user is authenticated
    emit('my response', {'data': 'Connected'})

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

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