Send auth_token for authentication to ActionCable

alxibra picture alxibra · Feb 19, 2016 · Viewed 9.4k times · Source
module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      #puts params[:auth_token]
      self.current_user = find_verified_user
      logger.add_tags 'ActionCable', current_user.name
   end

  end
end

I don't use web as end point for action cable, so I want to use auth_token for authentication. By default action cable use session user id for authentication. How to pass params to connect method?

Answer

Pierre Fraisse picture Pierre Fraisse · Apr 10, 2016

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.