Send auth_token for authentication to ActionCable

后端 未结 10 1760
梦毁少年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 02:46

    It is also possible to pass the authentication token in the request headers and then validate the connection by accessing the request.headers hash. For example, if the authentication token were specified in a header called 'X-Auth-Token' and your User model have a field auth_token you could do:

    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.id
        end
    
        protected
    
        def find_verified_user
          if current_user = User.find_by(auth_token: request.headers['X-Auth-Token'])
            current_user
          else
            reject_unauthorized_connection
          end
        end
      end
    end
    

提交回复
热议问题