All Projects → saravanabalagi → action-cable-react-jwt

saravanabalagi / action-cable-react-jwt

Licence: MIT license
Rails action-cable integration with JWT authentication

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to action-cable-react-jwt

React Stomp
React websocket component for STOMP protocol over SockJs
Stars: ✭ 110 (+189.47%)
Mutual labels:  websocket-client
Embedded Jetty Websocket Examples
Embedded Jetty WebSocket Examples
Stars: ✭ 159 (+318.42%)
Mutual labels:  websocket-client
Websocket Client
WebSocket client for Python
Stars: ✭ 2,810 (+7294.74%)
Mutual labels:  websocket-client
Xsound
Web Audio API Library for Synthesizer, Effects, Visualization, Multi-Track Recording, Audio Streaming, Visual Audio Sprite ...
Stars: ✭ 123 (+223.68%)
Mutual labels:  websocket-client
Osc Js
OSC library for Node.js, Electron, Chrome Apps, Webpages or any other JS application. It comes with a customizable Plugin API for WebSocket, UDP or bridge networking
Stars: ✭ 135 (+255.26%)
Mutual labels:  websocket-client
Flutter socket io
Socket IO supprt for flutter. Looking for contributors Swift and Java.
Stars: ✭ 170 (+347.37%)
Mutual labels:  websocket-client
Python Bittrex Websocket
Python websocket for Bittrex (non async).
Stars: ✭ 104 (+173.68%)
Mutual labels:  websocket-client
websocket-scala-client
WebSocket client based on Netty
Stars: ✭ 37 (-2.63%)
Mutual labels:  websocket-client
Poloniex Api Node
Poloniex API client for REST and WebSocket API
Stars: ✭ 138 (+263.16%)
Mutual labels:  websocket-client
Ixwebsocket
websocket and http client and server library, coming with ws, a command line swiss army knife utility
Stars: ✭ 204 (+436.84%)
Mutual labels:  websocket-client
Birdsong
🐦🎼 Swift WebSockets client for Phoenix Channels.
Stars: ✭ 124 (+226.32%)
Mutual labels:  websocket-client
Bolt Js
A framework to build Slack apps using JavaScript
Stars: ✭ 1,971 (+5086.84%)
Mutual labels:  websocket-client
Claws
Awesome WebSocket CLient - an interactive command line client for testing websocket servers
Stars: ✭ 187 (+392.11%)
Mutual labels:  websocket-client
Php Wss
Web-socket server/client with multi-process and parse templates support on server and send/receive options on client
Stars: ✭ 117 (+207.89%)
Mutual labels:  websocket-client
Websocat
Command-line client for WebSockets, like netcat (or curl) for ws:// with advanced socat-like functions
Stars: ✭ 3,477 (+9050%)
Mutual labels:  websocket-client
Coinbasepro Python
The unofficial Python client for the Coinbase Pro API
Stars: ✭ 1,386 (+3547.37%)
Mutual labels:  websocket-client
Libhv
🔥 比libevent、libuv更易用的国产网络库。A c/c++ network library for developing TCP/UDP/SSL/HTTP/WebSocket client/server.
Stars: ✭ 3,355 (+8728.95%)
Mutual labels:  websocket-client
meteorman
A DDP client with GUI (The Postman for Meteor)
Stars: ✭ 51 (+34.21%)
Mutual labels:  websocket-client
actioncable dart
actioncable client in dart, for pure dart or flutter project
Stars: ✭ 25 (-34.21%)
Mutual labels:  actioncable
Bolt Python
A framework to build Slack apps using Python
Stars: ✭ 190 (+400%)
Mutual labels:  websocket-client

action-cable-react-jwt

Same as action-cable-react, but allows authenticating websockets using JWTs

Installation

Yarn:

yarn add action-cable-react-jwt

npm:

npm install action-cable-react-jwt

Usage

Import action-cable-react-jwt

import ActionCable from 'action-cable-react-jwt.js';

// if you don't use ES6 then use
// const ActionCable = require('action-cable-react-jwt.js');

Creating an actioncable websocket

let App = {};
App.cable = ActionCable.createConsumer("ws://cable.example.com", jwt) // place your jwt here

// you shall also use this.cable = ActionCable.createConsumer(...)
// to create the connection as soon as the view loads, place this in componentDidMount

Subscribing to a Channel for Receiving data

this.subscription = App.cable.subscriptions.create({channel: "YourChannel"}, {
      connected: function() { console.log("cable: connected") },             // onConnect
      disconnected: function() { console.log("cable: disconnected") },       // onDisconnect
      received: (data) => { console.log("cable received: ", data); }         // OnReceive
}

Send data to a channel

this.subscription.send('hello world')

Call a method on channel with arguments

this.subscription.perform('method_name', arguments)

In your ApplicationCable::Connection class in Ruby add

# app/channels/application_cable/connection.rb
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
      begin
        header_array = request.headers[:HTTP_SEC_WEBSOCKET_PROTOCOL].split(',')
        token = header_array[header_array.length-1]
        decoded_token = JWT.decode token.strip, Rails.application.secrets.secret_key_base, true, { :algorithm => 'HS256' }
        if (current_user = User.find((decoded_token[0])['sub']))
          current_user
        else
          reject_unauthorized_connection
        end
      rescue
        reject_unauthorized_connection
      end
    end

  end
end

And in YourChannel.rb

# app/channels/you_channel.rb
class LocationChannel < ApplicationCable::Channel

  # calls connect in client
  def subscribed
    stream_from 'location_user_' + current_user.id.to_s
  end

  # calls disconnect in client
  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end
  
  # called when send is called in client
  def receive(params)
    print params[:data]
  end
  
  # called when perform is called in client
  def method_name(params)
    print params[:data]
  end
  
end

Remove a subscription from cable

App.cable.subscriptions.remove(this.subscription)

// Place this in componentWillUnmount to remove subscription on exiting app

Add a subscription to cable

App.cable.subscriptions.add(this.subscription)

Querying url and jwt from cable

console.log(App.cable.jwt);
console.log(App.cable.url);

Querying subscriptions and connection from cable

console.log(App.cable.subscriptions);
console.log(App.cable.connection);

License

MIT

Copyright (c) 2017 Zeke

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].