Search code examples
ruby-on-railsrubyruby-on-rails-5actioncable

How to get request.session inside ActionCable Channel?


Is there a way to get (or pass from Connection) request data(actually, I need session[:_csrf_token], don't ask why) in the Channel? For example:

class MeetingChannel < ApplicationCable::Channel
  def subscribed
    session[:_csrf_token]
  end
end

For now, I could only get csrf_token in Connection:

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    def connect
      puts "**********************************************************"
      puts "CSRF token: #{request.session[:_csrf_token]}"
      puts "**********************************************************"
    end
  end
end

It outputs (when connecting):

**********************************************************
CSRF token: u33bsVI7HnF2bqWRfkriQUlLzIUpCcDVovgRTAkoGKM=
**********************************************************

Solution

  • In the connection, we create this method (because of @request being private):

    def session
      @request.session
    end
    

    Then, in the channel you can access the session like so:

    session = connection.session