我有一个 ruby on rails 应用程序部署到扭矩箱。我需要一些方法来保护我的应用程序中的 websocket。我正在使用 stomp websockets ,有没有办法在用户建立 websocket 连接时对其进行身份验证?我可以使用用户名和密码参数,但它们目前被忽略。还有其他方法可以验证此连接吗?谢谢!
问问题
1634 次
2 回答
1
您可以使用会话和存储的令牌对 Stomplet 的消息进行身份验证。为此,您必须设置 Rails 以使用 Torquebox 会话存储。这可以通过初始化器来完成,例如config/initializers/torquebox_init.rb
:
AppName::Application.config.session_store :torquebox_store
现在 Stomplet 将可以访问会话。这是一个使用会话参数:authentication_token
匹配数据库中用户的 authentication_token 的示例 Stomplet。检查身份验证令牌的订阅、发送消息和取消订阅:
require 'torquebox-stomp'
class StompletDemo
def initialize()
super
@subscribers = []
end
def configure(stomplet_config)
end
def on_message(stomp_message, session)
token = session[:authentication_token]
if is_authenticated?( token )
@subscribers.each do |subscriber|
subscriber.send( stomp_message )
end
end
end
def on_subscribe(subscriber)
session = subscriber.session
if is_authenticated?(session[:authentication_token])
@subscribers << subscriber
end
end
def on_unsubscribe(subscriber)
session = subscriber.session
if is_authenticated?(session[:authentication_token])
@subscribers.delete( subscriber )
end
end
def is_authenticated?(token)
User.where( authentication_token: token ).exists?
end
end
现在您所要做的就是确保当用户进行身份验证时,session[:authentication_token]
设置了。大多数情况下,这将在控制器中设置:
# user has successfully authenticates
session[:authentication_token] = @user.authentication_token
于 2013-06-19T02:10:19.620 回答
1
对于其他遇到此问题的人,这就是我解决它的方法。
https://gist.github.com/j-mcnally/6207839
基本上,令牌系统对我来说没有扩展性,特别是因为我使用了 devise。如果您想在 chrome 扩展中托管您的 websocket,只需将用户名/密码直接传递给 stomp 并让它在 stomplet 中管理自己的虚拟订阅者会话就更容易了。这也允许你做一些有趣的事情,只要你推给谁。
于 2013-08-12T02:22:22.853 回答