env ['warden']不使用Rails 5

时间:2017-04-06 14:43:49

标签: ruby-on-rails

我按照本指南使用Websockets创建聊天功能。 https://www.sitepoint.com/rails-and-actioncable-adding-advanced-features/

我遇到了一个问题env['warden'].user即使用标准的Devise表单登录到应用程序也没有重新调整任何内容。

如果我使用其他方法(现在已注释) - 它会返回错误的用户

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)

3 个答案:

答案 0 :(得分:7)

我在这篇文章中找到了解决方案 https://rubytutorial.io/actioncable-devise-authentication/

我不确定它是如何工作的,但它确实达成了协议。如何对有类似问题的人有所帮助。

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文件

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

答案 1 :(得分:6)

我遇到了同样的问题,但事实证明我的问题是因为我有两个Devise模型:UserCustomer,因为User用于管理人员,所以Customer设置为Warden的{{ 1}}。因此,要访问default_scope范围,我必须执行以下操作

user

末尾的符号定义了使用范围。

在这里,我找到了有关Warden范围内用户的信息:https://github.com/wardencommunity/warden/wiki/Scopes#scoped-user-access

答案 2 :(得分:0)

使用Devise进行身份验证,我遇到了同样的问题,被接受的答案并没有帮助我。我的错误是在routes.rb文件中。 我放置了:mount ActionCable.server, at: '/cable'authenticate :user do块中。将其移至Rails.application.routes.draw do块对我来说解决了这个问题。