Skip to content

Authenticate with actioncable

Justin Tomich edited this page Mar 9, 2017 · 1 revision

To verify users with Authenticate over Action Cable, we will implement a simple change in ActionCable::Connection.

Connection

For every WebSocket connection the Action Cable server accepts, a Connection object will be instantiated. The connection should deal with authentication and authorization.

Your user must already have an established Authenticate session before attempting to establish an Action Cable connection.

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
      session_token = cookies[Authenticate.configuration.cookie_name.to_sym]
      verified_user = Authenticate.configuration.user_model_class.where(session_token: session_token).first
      verified_user || reject_unauthorized_connection
    end
  end
end

To verify the user, we rely on the fact that the WebSocket connection is established with the cookies from the domain being sent along. This makes it easy to use signed cookies that were set when logging in via a web interface to authorize the WebSocket connection.