如何在ActionCable rails-5-api应用程序中获取current_user?

Sar*_*ran 13 authentication ruby-on-rails actioncable

为什么我无法current_user在我的频道内检索或我应该如何检索current_user

我该用什么?

  • Rails 5.0.1 --api (我没有任何意见NOR使用咖啡)
  • 我使用react-native app来测试这个(没有授权就可以正常工作)
  • 我不使用devise for auth (我使用JWT而不是使用Knock,所以没有cookie)

尝试current_user进入我的ActionCable频道,如rubydoc.info中所述

代码看起来像

class MessageChannel < ApplicationCable::Channel
  identified_by :current_user

  def subscribed
    stream_from 'message_' + find_current_user_privileges
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end

  protected

  def find_current_user_privileges
    if current_user.has_role? :admin
      'admin'
    else
      'user_' + current_user.id
    end
  end

end
Run Code Online (Sandbox Code Playgroud)

运行它,我得到这个错误:

[NoMethodError - undefined method `identified_by' for MessageChannel:Class]
Run Code Online (Sandbox Code Playgroud)

如果我删除identified_by :current_user,我得到

[NameError - undefined local variable or method `current_user' for #<MessageChannel:0x7ace398>]
Run Code Online (Sandbox Code Playgroud)

Saj*_*jan 6

如果看到提供的文档,您将知道这identified_by不是Channel实例的方法。这是一种方法Actioncable::Connection。从Rails的《 Actioncable Overview》指南中,Connection类的外观如下:

#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 current_user = User.find_by(id: cookies.signed[:user_id])
          current_user
        else
          reject_unauthorized_connection
        end
      end
  end
end
Run Code Online (Sandbox Code Playgroud)

如您所见,current_user此处不可用。相反,您必须current_user在连接中创建一个here。

websocket服务器没有会话,但可以读取与主应用程序相同的cookie。因此,我想您需要在身份验证后保存cookie。


小智 6

如果您在导轨中使用devise宝石,请替换此功能:

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
Run Code Online (Sandbox Code Playgroud)

希望对您有帮助。