How do I get current_user in ActionCable rails-5-api app?

后端 未结 5 1654
故里飘歌
故里飘歌 2020-12-15 20:57

Why am I not able to retrieve current_user inside my channel or how should I retrieve current_user?

What do I use?

  • Rails 5.0.
5条回答
  •  爱一瞬间的悲伤
    2020-12-15 21:32

    If you see the doc you provided, you will know that identified_by is not a method for a Channel instance. It is a method for Actioncable::Connection. From Rails guide for Actioncable Overview, this is how a Connection class looks like:

    #app/channels/application_cable/connection.rb
    module ApplicationCable
      class Connection < ActionCable::Connection::Base
        identified_by :current_user
    
        def connect
          self.current_user = find_verified_user
        end
    
        private
          def find_verified_user
            if current_user = User.find_by(id: cookies.signed[:user_id])
              current_user
            else
              reject_unauthorized_connection
            end
          end
      end
    end
    

    As you can see, current_user is not available here. Instead, you have to create a current_user here in connection.

    The websocket server doesn't have a session, but it can read the same cookies as the main app. So I guess, you need to save cookie after authentication.

提交回复
热议问题