【问题标题】:Rails Action Cable: Authorize the incoming connection from mobile devicesRails Action Cable:授权来自移动设备的传入连接
【发布时间】:2020-06-29 10:21:31
【问题描述】:

我想授权对通过移动设备进行的 websocket 连接的连接请求。 我在Connection < ActionCable::Connection::Base 中的代码如下:

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[:user_id])
          verified_user
        else
          reject_unauthorized_connection
        end
      end
  end
end

这非常适合 WebBrowser 客户端,因为一旦用户使用 Devise 登录系统,我就设置了 cookies .

Devise 的 SessionsController 中的代码如下所示:

class Users::SessionsController < Devise::SessionsController

  # POST /resource/sign_in
  def create
    super
    cookies[:user_id] = current_user.id
  end

这工作正常。

但是当我尝试通过手机连接到 websocket 连接时,我收到 reject_unauthorized_connection 错误。

当用户从移动设备登录时,我还尝试在 api/signin api 中设置 cookie。 api 代码 如下所示:

class Api::SessionsController < Api::ApiController

  def create
    user = User.find_by_email params[:email]

    if user && user.valid_password?(params[:password])

      # Set the user cookie
      cookies[:user_id] = user.id

      render json: { token: token_sign_in(user), user: user, department: user.department, organization: user.organization }
    else
      render json: { error: "invalid credentials" }, status: :unauthorized
    end
  end

发生错误是因为您无法在移动应用程序上设置 cookie 吗?如果不是,那么在不使用 cookie 的情况下,对来自移动设备的传入 websocket 连接请求进行身份验证的下一个最佳方法是什么。

【问题讨论】:

    标签: ruby-on-rails websocket actioncable


    【解决方案1】:

    当尝试验证来自移动设备的连接请求时,请使用移动应用程序在记录时发送到服务器的 令牌唯一标识符(在我的情况下为电子邮件 ID)在,与标题。

    所以,这些是我在 connection.rb 文件中所做的更改。

    token = request.headers[:email]
      if token
        @verified_user = User.find_by(email: token)
      else
        reject_unauthorized_connection
      end
    

    您也可以使用 JWT 令牌 代替电子邮件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-11
      • 1970-01-01
      • 2021-05-29
      • 2018-06-02
      • 2018-03-10
      • 2018-03-28
      • 2017-08-23
      • 1970-01-01
      相关资源
      最近更新 更多