env['warden'] 不适用于 Rails 5 [英] env['warden'] not working with Rails 5
问题描述
我按照本指南使用 Websockets 创建聊天功能.https://www.sitepoint.com/rails-and-actioncable-添加高级功能/
Im following this guide to create Chatting feature with a use of Websockets. https://www.sitepoint.com/rails-and-actioncable-adding-advanced-features/
我遇到了一个问题,即使我使用标准设计表单登录到应用程序,env['warden'].user
也没有重新调整任何内容.
Im stuck with a problem that env['warden'].user
is retuning nothing even when Im loggined to the app with standard Devise form.
如果我使用另一种方法(现在已评论) - 它返回错误的用户
And if I use another method (which is commented now) - it return wrong 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.email
end
protected
def find_verified_user # this checks whether a user is authenticated with devise
verified_user = env['warden'].user
if verified_user
verified_user
else
reject_unauthorized_connection
end
end
# def find_verified_user
# user_id = request.headers['HTTP_AUTHORIZATION']
# if verified_user = User.find_by(user_id)
# verified_user
# else
# reject_unauthorized_connection
# end
# end
end
end
日志说
Started GET "/cable/" [WebSocket] for 127.0.0.1 at 2017-04-06 17:40:17 +0300
Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
An unauthorized connection attempt was rejected
Failed to upgrade to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
推荐答案
我在这篇文章中找到了解决方案https://rubytutorial.io/actioncable-devise-authentication/
I found solution on this article https://rubytutorial.io/actioncable-devise-authentication/
我不确定它是如何工作的,但它确实有效.它将如何帮助有类似问题的人.
Im not sure how it works, but it does the deal. How it would help for people with similar problem.
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.email
end
protected
def find_verified_user
verified_user = User.find_by(id: cookies.signed['user.id'])
if verified_user && cookies.signed['user.expires_at'] > Time.now
verified_user
else
reject_unauthorized_connection
end
end
end
end
我还创建了/config/initializers/warden_hooks.rb 文件
And I also created /config/initializers/warden_hooks.rb file
Warden::Manager.after_set_user do |user,auth,opts|
scope = opts[:scope]
auth.cookies.signed["#{scope}.id"] = user.id
auth.cookies.signed["#{scope}.expires_at"] = 60.minutes.from_now
end
Warden::Manager.before_logout do |user, auth, opts|
scope = opts[:scope]
auth.cookies.signed["#{scope}.id"] = nil
auth.cookies.signed["#{scope}.expires_at"] = nil
end
这篇关于env['warden'] 不适用于 Rails 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!