Well, in theory
- You have access to cookies in the
ActiveCable::Connection class. - You can set and receive
cookies.signed and cookies.encrypted - Both the application and the ActionCable use the same configuration, so they use the same "secret_key_base"
So, if you know the name of your session cookie (somehow obvious, let it be called " _session "), you can simply get the data in it:
cookies.encrypted['_session']
So you should be able to do something like:
user_id = cookies.encrypted['_session']['user_id']
It depends on whether you use the cookie store for the session and the exact authentication approach, but in any case the necessary data should be there.
I found this approach more convenient since the session is already managed by the authentication solution you are using, and you probably don't need to worry about things like cookie expiration and duplication of authentication logic.
Here is a more complete example:
module ApplicationCable class Connection < ActionCable::Connection::Base identified_by :current_user def connect session = cookies.encrypted['_session'] user_id = session['user_id'] if session.present? self.current_user = (user_id.present? && User.find_by(id: user_id)) reject_unauthorized_connection unless current_user end end end
Not entered
source share