Send auth_token for authentication to ActionCable
Pierre's answer works. However, it's a good idea to be explicit about expecting these parameters in your application.
For instance, in one of your config files (e.g. application.rb
, development.rb
, etc...) you can do this:
config.action_cable.mount_path = '/cable/:token'
And then simply access it from your Connection
class with:
request.params[:token]
I managed to send my authentication token as a query parameter.
When creating my consumer in my javascript app, I'm passing the token in the cable server URL like this:
wss://myapp.com/cable?token=1234
In my cable connection, I can get this token
by accessing the request.params
:
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
logger.add_tags 'ActionCable', current_user.name
end
protected:
def find_verified_user
if current_user = User.find_by(token: request.params[:token])
current_user
else
reject_unauthorized_connection
end
end
end
end
It's clearly not ideal, but I don't think you can send custom headers when creating the websocket.