'How to use Postman to connect to Ruby on Rails 5 Actioncable (Websocket)?
I am running a Rails 5.2.7 engine which has actioncable (websockets) set up. The websocket connection is successfully established when the application is run via the browser, using a React UI with actioncable-js-jwt, a version of actioncable's js package that supports jwt. However I am unable to establish the connection via postman's beta websockets option.
My connection.rb file is very simple:
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
# Public: Invoked as part of the websocket connection establishment
def connect
self.current_user = {
...(hardcoded values)
}
end
end
end
Engine.rb looks like this:
require 'action_cable/engine'
module RoundaboutEngine
class << self
def cable
@cable ||= ActionCable::Server::Configuration.new
end
end
class Engine < ::Rails::Engine
isolate_namespace RoundaboutEngine
class << self
def server
@server ||= ActionCable::Server::Base.new(config: RoundaboutEngine.cable)
end
end
config.roundaboutengine_cable = RoundaboutEngine.cable
config.roundaboutengine_cable.mount_path = '/cable'
config.roundaboutengine_cable.connection_class = -> { RoundaboutEngine::Connection }
config.roundaboutengine_cable.disable_request_forgery_protection = true
initializer 'roundaboutengine_cable.cable.config' do
RoundaboutEngine.cable.cable = { adapter: 'async' }
end
initializer 'roundaboutengine_cable.cable.logger' do
RoundaboutEngine.cable.logger ||= ::Rails.logger
end
end
end
The browser request network tab shows the following:
Request URL: ws://localhost:9292/cable
Request Method: GET
Status Code: 101 Switching Protocols
Connection: Upgrade
Sec-WebSocket-Accept: [string]
Sec-WebSocket-Protocol: actioncable-v1-json
Upgrade: websocket
In postman, I also use ws://localhost:9292/cable as a raw connection. However, it seems to turn that into an http url, as shown in the request information:
Request URL: http://localhost:9292/cable
Request Method: GET
Status Code: 404 Not Found
Request Headers
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: [string]
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Host: localhost:9292
I am not sure why postman is turning the request into an http request, or how to make this work.
I also tried adding Sec-WebSocket-Protocol: actioncable-v1-json to the postman request headers, with no luck.
Solution 1:[1]
Resolved: I had to replace a line in engine.rb
I removed:
config.roundaboutengine_cable.disable_request_forgery_protection = true
I added:
config.action_cable.allowed_request_origins = [/http:\/\/*/, /https:\/\/*/, nil]
In particular, the nil was important for postman and is what was causing the problem.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user1779418 |
