Send auth_token for authentication to ActionCable

后端 未结 10 1764
梦毁少年i
梦毁少年i 2021-02-04 02:23
module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      #puts params[:auth_token]
      self         


        
10条回答
  •  醉酒成梦
    2021-02-04 02:57

    I was asked about it recently and want to share the solution that I currently use in production systems.

    class MyChannel < ApplicationCable::Channel
      attr_accessor :current_user
    
      def subscribed
        authenticate_user!
      end
    
      private
    
      # this works, because it is actually sends via the ws(s) and not via the url <3
      def authenticate_user!
        @current_user ||= JWTHelper.new.decode_user params[:token]
    
        reject unless @current_user
      end
    end
    

    Then re-use warden strategies to work with that JWT (and let it handle all possible edge cases and pitfalls).

    class JWTHelper
      def decode_user(token)
        Warden::JWTAuth::UserDecoder.new.call token, :user, nil if token
      rescue JWT::DecodeError
        nil
      end
    
      def encode_user(user)
        Warden::JWTAuth::UserEncoder.new.call(user, :user, nil).first
      end
    end
    

    Though I didn't use ActionCable for the frontend it should roughly work like this:

    this.cable.subscriptions.create({
      channel: "MyChannel",
      token: "YOUR TOKEN HERE",
    }, //...
    

提交回复
热议问题