You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ActionCable中通过Doorkeeper实现安全验证(拦截过期令牌)

解决Doorkeeper过期访问令牌通过ActionCable验证的问题

你的代码仅验证了访问令牌是否存在,未检查令牌是否未过期且处于有效状态。Doorkeeper的AccessToken模型提供了valid?方法,可直接验证令牌的有效性(涵盖过期时间、是否被撤销等条件)。

修改后的完整代码如下:

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

    def connect
      self.current_user = find_verified_user
      self.room_id = @user.ac_channel_room
    end

    def disconnect
      # 客户端断开连接时执行的逻辑
    end

    private

    def find_verified_user 
      check_access_token
      @user = User.find_by_id(@resource_owner_id) if @resource_owner_id
      reject_unauthorized_connection unless @user
    end

    def check_access_token
      params = request.query_parameters
      @access_token = Doorkeeper::AccessToken.by_token(params[:access_token])
      
      # 验证令牌是否有效:未过期、未被撤销、关联应用合法
      unless @access_token&.valid?
        reject_unauthorized_connection
      end

      @resource_owner_id = @access_token.resource_owner_id
    end
  end
end

关键修改说明:

  • 在check_access_token方法中新增令牌有效性校验,一旦令牌无效(含过期),直接拒绝连接
  • 移除了冗余的||=赋值,确保每次连接都会重新验证令牌状态

如果仅需单独校验过期时间,可替换为以下逻辑:

unless @access_token && @access_token.expires_at > Time.current
  reject_unauthorized_connection
end

但更推荐使用valid?方法,它会同时验证令牌的所有合规性条件,保障验证的全面性。

内容的提问来源于stack exchange,提问作者chirag tomar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 20:01:14