我有一个部署到扭矩盒的 ruby on rails 应用程序。我需要一些方法来保护我的应用程序中的 websocket。我正在使用 stomp websockets ,有没有办法在用户建立 websocket 连接时对其进行身份验证?我可以使用用户名和密码参数,但它们目前被忽略。还有其他方法可以验证此连接吗?谢谢!
最佳答案
您可以使用 session 和存储的 token 向 Stomplet 验证消息。为此,您必须设置 Rails 以使用 Torquebox session 存储。这可以通过初始化程序来完成,例如 config/initializers/torquebox_init.rb
:
AppName::Application.config.session_store :torquebox_store
现在 Stomplet 将可以访问 session 。这是一个使用 session 参数
:authentication_token
的示例 Stomplet匹配数据库中用户的 authentication_token。检查 auth token 的订阅、发送消息和取消订阅: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]
设置。大多数情况下,这将在 Controller 中设置: # user has successfully authenticates
session[:authentication_token] = @user.authentication_token
关于authentication - 验证 stomp Web 套接字客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16718884/