【问题标题】:User Session Authentication in Rails 5Rails 5 中的用户会话身份验证
【发布时间】:2016-10-01 12:03:51
【问题描述】:

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

在阅读了 Action 电缆的教程后,该电缆使用基于会话和 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_user 中,我无法从会话中获取用户对象。

任何人都可以帮助我,在行动电缆中对用户进行身份验证。

【问题讨论】:

标签: ruby websocket notifications ruby-on-rails-5 actioncable


【解决方案1】:

如果您的 session_store (config/initializers/session_store.rb) 使用 :cookie_store,那么您可以从加密的 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

【讨论】:

    【解决方案2】:

    因为你无权访问session,所以必须使用cookie:

    1) 转到 your_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])
    

    会话示例:How can I find a devise user by it's session id?

    【讨论】:

      猜你喜欢
      • 2016-03-05
      • 2020-10-06
      • 2012-04-29
      • 2016-04-12
      • 1970-01-01
      • 2016-07-07
      • 2019-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多