Skip to content

Instantly share code, notes, and snippets.

@hopsoft
Last active April 19, 2019 09:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hopsoft/02dfdf4456b3ac52f4eaf242289bdd36 to your computer and use it in GitHub Desktop.
Save hopsoft/02dfdf4456b3ac52f4eaf242289bdd36 to your computer and use it in GitHub Desktop.
Eliminate unauthorized ActionCable connection attempts

Problem

Unauthorized ActionCable connection attempts that produce the following

Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
Finished "/cable/" [WebSocket] for 127.0.0.1 at 2018-11-16 08:32:24 -0700
An unauthorized connection attempt was rejected

Solution

Simply opt-in to ActionCable with the data-cable attribute on the body element.

Use current_user or whatever conditional logic makes sense for your app.

<!-- app/views/layouts/application.html.erb -->
<!DOCTYPE html>
<html>
<head></head>
<body <%= "data-cable" if current_user.present? %>>
</body>
</html>
// app/assets/javascripts/cable.js
//= require action_cable
//= require_self
//= require_tree ./channels
(function() {
function connect() {
if (document.querySelector('body[data-cable]')) {
this.App || (this.App = {});
App.cable || (App.cable = ActionCable.createConsumer());
}
}
document.addEventListener('DOMContentLoaded', connect);
}.call(this));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment