问题
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