向 ActionCable 发送 auth_token 进行身份验证 [英] Send auth_token for authentication to ActionCable

查看:37
本文介绍了向 ActionCable 发送 auth_token 进行身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      #puts params[:auth_token]
      self.current_user = find_verified_user
      logger.add_tags 'ActionCable', current_user.name
   end

  end
end

我不使用网络作为动作电缆的端点,所以我想使用 auth_token 进行身份验证.默认情况下,动作电缆使用会话用户 ID 进行身份验证.如何将参数传递给连接方法?

I don't use web as end point for action cable, so I want to use auth_token for authentication. By default action cable use session user id for authentication. How to pass params to connect method?

推荐答案

我设法将我的身份验证令牌作为查询参数发送.

I managed to send my authentication token as a query parameter.

在我的 javascript 应用程序中创建我的使用者时,我在有线服务器 URL 中传递令牌,如下所示:

When creating my consumer in my javascript app, I'm passing the token in the cable server URL like this:

wss://myapp.com/cable?token=1234

在我的电缆连接中,我可以通过访问 request.params 来获取这个 token:

In my cable connection, I can get this token by accessing the request.params:

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.name
    end

    protected:
    def find_verified_user
      if current_user = User.find_by(token: request.params[:token])
        current_user
      else
        reject_unauthorized_connection
      end
    end
  end
end

这显然不理想,但我认为您不能在创建 websocket 时发送自定义标头.

It's clearly not ideal, but I don't think you can send custom headers when creating the websocket.

这篇关于向 ActionCable 发送 auth_token 进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆