Fix ActionCable::Connection::Authorization::UnauthorizedError: An unauthorized connection attempt was rejected in Rails
This error occurs when ActionCable rejects a WebSocket connection because the connect method in your connection class calls reject_unauthorized_connection. This typically means the user is not authenticated or the session cookie is not being sent with the WebSocket handshake. Verify your authentication logic in ApplicationCable::Connection.
Reading the Stack Trace
Here's what each line means:
- app/channels/application_cable/connection.rb:8:in `connect': Your connection.rb connect method calls reject_unauthorized_connection because the user lookup failed.
- actioncable (7.1.3) lib/action_cable/connection/authorization.rb:14:in `reject_unauthorized_connection': ActionCable rejects the WebSocket upgrade request and closes the connection.
- actioncable (7.1.3) lib/action_cable/connection/base.rb:65:in `process': The connection processing pipeline where authentication is checked during the WebSocket handshake.
Common Causes
1. Session not available in WebSocket
The session cookie is not sent during the WebSocket handshake due to cross-origin or missing credentials.
# 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
def find_verified_user
user = User.find_by(id: cookies.encrypted[:user_id])
user || reject_unauthorized_connection
end
end
end
2. CORS blocking WebSocket
The WebSocket connection is from a different origin and ActionCable's allowed origins does not include it.
# config/environments/production.rb
config.action_cable.allowed_request_origins = ['https://myapp.com']
# But frontend is on https://app.myapp.com
3. Missing cable.yml configuration
The cable.yml config does not specify the correct adapter for the environment.
# config/cable.yml
production:
adapter: async # Should be redis for multi-server setups
The Fix
Add a fallback authentication method using a token parameter for cases where cookies are not available. This handles cross-origin WebSocket connections where session cookies may not be sent.
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
end
def find_verified_user
user = User.find_by(id: cookies.encrypted[:user_id])
user || reject_unauthorized_connection
end
end
end
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
end
def find_verified_user
if (user = User.find_by(id: cookies.encrypted[:user_id]))
user
elsif (user = authenticate_with_token)
user
else
reject_unauthorized_connection
end
end
def authenticate_with_token
token = request.params[:token]
User.find_by(auth_token: token) if token.present?
end
end
end
Testing the Fix
require 'rails_helper'
RSpec.describe ApplicationCable::Connection, type: :channel do
let(:user) { create(:user) }
it 'connects with valid cookie' do
cookies.encrypted[:user_id] = user.id
connect '/cable'
expect(connection.current_user).to eq(user)
end
it 'connects with valid token' do
user.update!(auth_token: 'valid_token')
connect '/cable?token=valid_token'
expect(connection.current_user).to eq(user)
end
it 'rejects unauthorized connections' do
expect { connect '/cable' }.to have_rejected_connection
end
end
Run your tests:
bundle exec rspec spec/channels/connection_spec.rb
Pushing Through CI/CD
git checkout -b fix/rails-action-cable-auth,git add app/channels/application_cable/connection.rb,git commit -m "fix: add token-based fallback auth for ActionCable connections",git push origin fix/rails-action-cable-auth
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_PASSWORD: postgres
ports: ['5432:5432']
redis:
image: redis:7
ports: ['6379:6379']
steps:
- uses: actions/checkout@v4
- uses: ruby/setup-ruby@v1
with:
ruby-version: '3.3'
bundler-cache: true
- run: bin/rails db:setup
- run: bundle exec rspec
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
gem install bugstack
Step 2: Initialize
require 'bugstack'
Bugstack.init(api_key: ENV['BUGSTACK_API_KEY'])
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Update the connection authentication logic.
- Add channel specs for all authentication paths.
- Configure allowed_request_origins for your domains.
- Open a pull request.
- Merge and verify WebSocket connections work in staging.
Frequently Asked Questions
BugStack runs the fix through your existing test suite, generates additional edge-case tests, and validates that no other components are affected before marking it safe to deploy.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.
If your frontend and backend are on different subdomains, the browser may not send cookies during the WebSocket handshake due to SameSite cookie policies.
Use Redis in production for multi-server deployments. The async adapter only works within a single process and will not broadcast across servers.