Skip to content

Doorkeeper and ActionCable

kp666 edited this page Nov 26, 2019 · 7 revisions

Doorkeeper + ActionCable integration (get current user from Doorkeeper OAuth2 Access Token in websocket / ActionCable).

You need to store access token somewhere on a frontend app (local storage or any else strategy) and then send it with WS requests:

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

    def connect
      self.current_user = authenticate!
    end

    protected

    def authenticate!
      user = User.find_by(id: doorkeeper_token.try(:resource_owner_id))

      user || reject_unauthorized_connection
    end
 # this will still allow expired tokens
 # you will need to check if token is valid with something like
 #  doorkeeper_token&.acceptable?(@_doorkeeper_scopes)
    def doorkeeper_token
      ::Doorkeeper.authenticate(request)
    end
  end
end

# ...

class SomeChannel < ApplicationCable::Channel
  def subscribed
     reject unless current_user
     stream_from 'some'
  end
end
Clone this wiki locally