I have a ruby on rails application deployed to torquebox. I need some way to secure the websockets in my application. I am using the stomp websockets , is there a way to authenticate users while they make a websocket connection? I could use the username and password parameters but they are currently ignored. Is there any other way to authenticate this connection? Thanks!
2 Answers
You can authenticate a message to a Stomplet by using the session and a stored token. For this to work, you have to setup Rails to use the Torquebox session store. This can be done with an initializer, such as config/initializers/torquebox_init.rb
:
AppName::Application.config.session_store :torquebox_store
Now the Stomplet will have access to the session. Here is an example Stomplet that uses the session param :authentication_token
to match the User's authentication_token in the database. The auth token is checked for subscribing, sending a message, and unsubscribing:
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
Now all you have to do is make sure that when the user authenticates, the session[:authentication_token]
is set. Mostly like this will be set in a controller:
# user has successfully authenticates
session[:authentication_token] = @user.authentication_token

- 8,946
- 2
- 39
- 61
For other people having this issue, this is how I solved it.
https://gist.github.com/j-mcnally/6207839
Basically the token system didnt scale for me, especially since I use devise. If you want to host your websocket in say a chrome extension its easier to just pass username/password directly to stomp and have it manage its own virtual subscriber sessions in the stomplet. This also allow you to do some fun things as far as who you are pushing to.

- 6,928
- 2
- 31
- 46