Rails 5 中的用户会话身份验证 [英] User Session Authentication in Rails 5

查看:75
本文介绍了Rails 5 中的用户会话身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Rails 5 中的 action cable 实现通知.

I am trying to implement notification using the action cable in Rails 5.

阅读 Action cable 的教程后,该教程适用于会话 &基于 Cookie 的身份验证,用于接收当前登录用户的通知.

After reading the tutorial for the Action cable, which work on the session & Cookies based Authentication to receive the notification for the current logged in user.

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 中,我无法从会话中获取用户对象.

In the find_verified_user , I am not able to get the user object from the session.

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

Can anyone help me, to authenticate the user in action cable.

推荐答案

如果您的 session_store (config/initializers/session_store.rb) 使用 :cookie_store,然后您可以从加密的 cookie 中读取会话:

If your session_store (config/initializers/session_store.rb) uses :cookie_store, then you can read the session from encrypted cookies:

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

这篇关于Rails 5 中的用户会话身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆