User Session Authentication in Rails 5

余生长醉 提交于 2019-12-24 09:29:45

问题


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

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

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.


回答1:


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



回答2:


Because you have not access to session, you must use cookie:

1) Go to your_app/config/initializers/session_store.rb and paste this code:

Rails.application.config.session_store :cookie_store, key: 'your_super_secret_code'

2) After anywhere you can get user id:

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

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

Example for session: How can I find a devise user by it's session id?



来源:https://stackoverflow.com/questions/39806405/user-session-authentication-in-rails-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!