Rails Action Cable:如何授权传入连接?

时间:2018-10-07 18:43:17

标签: ruby-on-rails ruby-on-rails-5 actioncable

我正在尝试对websocket连接(rails 5.2.1)实施授权

rubyonrails guideline之后,我创建了connection.rb,如下所示:

#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

    private
      def find_verified_user
        if verified_user = User.find_by(id: cookies.encrypted[:user_id])
          verified_user
        else
          reject_unauthorized_connection
        end
      end
  end
end

不幸的是,所有的websocket连接请求都被拒绝。 (我发现cookies.encrypted [:user_id]返回nil。)

Started GET "/cable" for ::1 at 2018-10-07 21:33:46 +0300
Started GET "/cable/" [WebSocket] for ::1 at 2018-10-07 21:33:46 +0300
Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
  User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."is_active" = $1 AND "users"."id" IS NULL LIMIT $2  [["is_active", true], ["LIMIT", 1]]
  ↳ app/channels/application_cable/connection.rb:12
An unauthorized connection attempt was rejected
Failed to upgrade to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
Finished "/cable/" [WebSocket] for ::1 at 2018-10-07 21:33:46 +0300
Finished "/cable/" [WebSocket] for ::1 at 2018-10-07 21:33:46 +0300

请您指导我如何访问app / channels / application_cable / connection.rb中的当前用户信息?

3 个答案:

答案 0 :(得分:2)

要从Devise获得current_user,您需要按以下方式更改connection.rb

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
      if verified_user = env['warden'].user
        verified_user
      else
        reject_unauthorized_connection
      end
    end
  end
end

答案 1 :(得分:0)

我遇到了确切的问题。我解决问题的方法是在用户登录时通过SessionsController < Devise::SessionsController添加一个cookie。 代码如下:

class Users::SessionsController < Devise::SessionsController
  # POST /resource/sign_in
  def create
    super
    cookies[:user_id] = current_user.id
  end
end

您可以通过运行以下代码从设计中获取SessionsController

rails generate devise:controllers [scope]

就我而言,范围是用户。

答案 2 :(得分:0)

路轨6:

cookies.encrypted[:user_id]

路轨5:

cookies.signed[:user_id]