Ruby Rails 5中的用户会话身份验证

Ruby Rails 5中的用户会话身份验证,ruby,websocket,notifications,ruby-on-rails-5,actioncable,Ruby,Websocket,Notifications,Ruby On Rails 5,Actioncable,我正在尝试使用Rails 5中的操作电缆实现通知 阅读了Action cable的教程后,Action cable使用基于会话和Cookie的身份验证来接收当前登录用户的通知 module ApplicationCable class Connection < ActionCable::Connection::Base identified_by :current_user def connect self.current_user = find_verified_

我正在尝试使用Rails 5中的操作电缆实现通知

阅读了Action cable的教程后,Action cable使用基于会话和Cookie的身份验证来接收当前登录用户的通知

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.username
  end

  protected

  def find_verified_user
    if verified_user = env['warden'].session(:user)
      verified_user
    else
      reject_unauthorized_connection
    end
  end
end
模块应用程序表
类连接
在find_verified_用户中,我无法从会话中获取用户对象


任何人都可以帮助我验证行动电缆中的用户。

如果您的
会话存储
config/initializers/session\u store.rb
)使用
:cookie\u存储
,则您可以从加密cookie读取会话:

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      if user = User.find_by(id: session[:user_id])
        self.current_user = user
      else
        reject_unauthorized_connection
      end
    end

    private

      def session
        key = Rails.application.config.session_options.fetch(:key)
        cookies.encrypted[key]&.symbolize_keys || {}
      end
  end
end
模块应用程序表
类连接
因为您没有访问会话的权限,所以必须使用cookie:

1) 转到您的_app/config/initializers/session_store.rb并粘贴以下代码:

Rails.application.config.session_store :cookie_store, key: 'your_super_secret_code'
2) 在任何可以获取用户id的位置之后:

 key = Rails.application.config.session_options.fetch(:key)
 cookies.encrypted[key]&.symbolize_keys || {}

 User.find(cookies["warden.user.user.key"][0][0])

会话示例:

不要将会话用于ActionCable,请参阅以下答案: