Send auth_token for authentication to ActionCable

后端 未结 10 1544
梦毁少年i
梦毁少年i 2021-02-04 02:23
module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      #puts params[:auth_token]
      self         


        
10条回答
  •  死守一世寂寞
    2021-02-04 03:06

    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.

提交回复
热议问题