验证ActionCable连接
我发现了一个美妙的ActionCable gem,这是SPA的一个很好的解决方案。验证ActionCable连接
我想只发送html
,css
和js
资产,所有其他连接将通过ActionCable
执行。交换字符串或整数并不困难,但我如何通过ActionCable登录?
# app/channels/application_cable/connection.rb
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
end
protected
def find_verified_user
if current_user = User.find(cookies.signed[:user_id])
current_user
else
reject_unauthorized_connection
end
end
end
end
所以看起来你可以在这里插入自己的find_verified_user
逻辑。 reject_unauthorized_connection
方法住在lib/action_cable/connection/authorization.rb
作为参考。
Heroku来自:
[验证]可以以多种方式来完成,如将的WebSockets 穿过标准HTTP标头通常用于身份验证。 这意味着你可以使用相同的身份验证机制 用于WebSocket连接的Web视图。
由于您无法通过JavaScript自定义WebSocket标头,因此012xx仅限于 浏览器发送的“隐式”授权(即Basic或cookie)。此外,处理 WebSockets的服务器与处理“普通”HTTP 请求的服务器完全分开是很常见的。这可能会导致共享授权头文件变得困难,或者无法使用 。
考虑到这一点,将可能是一个真正的痛苦不只是使用普通的Web登录流程设置您的身份验证cookie,则认证步骤后提供您的SPA,但希望这可以给你一些三分球。
仅供参考,如果你devise
已经安装在你的应用程序,那么你可以使用环境变量设置由warden
找到authenticated user
。对于每个经过身份验证的用户标识都将用户对象存储在环境var中。每个请求都通过warden
中间件进行验证。
注意:这个env是不同于ENV
。
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user_from_env
end
private
def find_verified_user_from_env
# extracting `user` from environment var
current_user = env['warden'].user
if current_user
current_user
else
reject_unauthorized_connection
end
end
end
end
如果你还没有使用devise
那么,这里是另一种解决方案。先决条件是,你将不得不在你的sessions_controller
或类似的东西中设置一个名为user_id
的签名cookie。 如
cookies.signed[:user_id] = current_user.id
和连接:
# app/channels/application_cable/connection.rb
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user_from_cookies
end
private
def find_verified_user_from_cookies
current_user = User.find_by_id(cookies.signed[:user_id])
if current_user
current_user
else
reject_unauthorized_connection
end
end
end
end
登录必须使用通常的Rails的方式来完成,你可以查看这里解释的用户是否经过验证:https://github.com/rails/ actioncable –
我知道我可以做到这一点,但我需要所有网站通过websockets工作。我可以执行此操作吗? – asiniy