In a Rails Action Cable connection class, how do identified_by, connect and reject_unauthorized_connection authenticate each WebSocket?
answer
- one Connection object per socket
- identified_by adds an attr_accessor
- connect runs once, after the upgrade
- cookies from the upgrade request
- UnauthorizedError, reconnect: false
basics
~20 sApplicationCable::Connection declares identified_by :current_user; its connect method runs once when the socket opens and sets current_user from a signed cookie, or calls reject_unauthorized_connection, which raises UnauthorizedError so Rails closes the socket with reason unauthorized and no reconnect.
solid answer
~30 sAction Cable builds one `ApplicationCable::Connection` per WebSocket. `identified_by :current_user` defines an `attr_accessor` and registers the name as an identifier; every channel on that socket gets a delegating `current_user` method. `connect` runs once, after the upgrade has been accepted, and can read `cookies` (including `cookies.signed` and `cookies.encrypted`) and `request` from the upgrade request. If it finds no user it calls `reject_unauthorized_connection`, which logs and raises `ActionCable::Connection::Authorization::UnauthorizedError`; Rails rescues it, sends a `disconnect` message with reason `unauthorized` and `reconnect: false`, and closes the socket, so the JavaScript consumer stops retrying. The identifiers also name the connection for `ActionCable.server.remote_connections.where(current_user: user).disconnect`.
code
ruby · 15 linesmodule ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
logger.add_tags "ActionCable", current_user.id
end
private
def find_verified_user
User.find_by(id: cookies.signed[:user_id]) || reject_unauthorized_connection
end
end
endgo deeper
Recall the three names: identified_by declares who the socket belongs to, connect finds that user, and reject_unauthorized_connection refuses the socket.
Explain that connect runs once after the upgrade, reads signed cookies, and that rejection raises UnauthorizedError and sends a no-reconnect disconnect.
Show you handle stale identity: remote_connections.where(...).disconnect across servers, re-checks inside channel actions, and per-command callbacks where needed.
Decide where identity lives for real-time features: cookie-based sockets shared with the web app versus separate credentials for other clients, and how revocation reaches long-lived sockets.
## One connection object per socket Action Cable has two server-side layers. A **connection** is created for every WebSocket the server accepts; a **channel** is created for every subscription made over that socket. The connection's job is authentication: deciding who is on the other end. Channels then do authorisation for each thing that user subscribes to. In a support desk where agents and customers chat on tickets, the connection answers "which user is this?", and the ticket chat channel answers "may this user see ticket 42?". The application's connection class is `ApplicationCable::Connection < ActionCable::Connection::Base`, in `app/channels/application_cable/connection.rb`. The version `bin/rails generate channel` writes is empty: with no `connect` method, Rails accepts every socket without identifying anyone. ## identified_by `identified_by(*identifiers)` does three things: - defines an `attr_accessor` for each name, so `self.current_user = user` works inside the connection; - adds the names to the `identifiers` class attribute, so each channel instance gets a method of the same name that delegates to the connection (`current_user` inside `TicketChatChannel`); - builds `connection_identifier` from the values: each object's GlobalID (`to_gid_param`) or `to_s`, sorted and joined with `:`. You can declare several identifiers, for example `identified_by :current_user, :desk`. ## connect and the upgrade request `connect` is called once per socket, from `handle_open`, after the HTTP upgrade has already been answered with 101. It runs on the Action Cable worker pool and has access to: - `cookies`, the request's cookie jar, with `signed` and `encrypted` readers, because the browser sends the domain's cookies with the upgrade; - `request`, the `ActionDispatch::Request` for the upgrade, with its headers and query string; - `logger`, a tagged logger (`logger.add_tags` adds per-connection tags). A typical body looks the user up and either assigns it or rejects: ```ruby def connect self.current_user = User.find_by(id: cookies.signed[:user_id]) || reject_unauthorized_connection end ``` The authentication generator writes its own version of this file that reads its session cookie; that file is covered with the generator. ## What rejection does, step by step 1. `reject_unauthorized_connection` logs "An unauthorized connection attempt was rejected" and raises `ActionCable::Connection::Authorization::UnauthorizedError`. 2. `handle_open` rescues it and calls `close(reason: "unauthorized", reconnect: false)`. 3. `close` transmits `{type: "disconnect", reason: "unauthorized", reconnect: false}` and closes the socket. 4. The JavaScript connection logs the reason and closes with `allowReconnect: false`, so its connection monitor does not keep retrying. Because rejection happens after the 101 response, the browser sees the socket open briefly and then a disconnect message, not an HTTP 401. The origin check is the part that runs before the upgrade. ## Connection-level vs channel-level refusal | Call | Where | Effect | |---|---|---| | `reject_unauthorized_connection` | `ApplicationCable::Connection#connect` | closes the whole socket, no reconnect | | `reject` | a channel's `subscribed` | refuses one subscription; the socket stays open | ## Identifiers after connect - `connect` does not run again for each message. A user whose account is disabled stays connected until the socket closes. - `ActionCable.server.remote_connections.where(current_user: user).disconnect` broadcasts a disconnect on the connection's internal channel, so it reaches the socket on whichever server holds it. It sends `reconnect: true` unless you pass `reconnect: false`; with the default, the browser reconnects and `connect` runs again. - `where` must name every declared identifier, or it raises `InvalidIdentifiersError`. - `before_command`, `after_command` and `around_command` callbacks run around each incoming command if you need per-message context. ## Mistakes to avoid - **Setting an instance variable without `identified_by`.** `@current_user = user` inside the connection is invisible to channels, which only get delegating methods for declared identifiers. - **Trusting the query string alone.** `request.params` is readable in `connect`, but anything there is chosen by the client; tie identity to a signed or encrypted cookie the server set at sign-in, or to another credential you verify. - **Slow work in `connect`.** It runs on Action Cable's worker pool, the same threads that run channel actions, so a slow lookup delays other sockets too. Keep it to one indexed query. - **Assuming rejection is visible as HTTP.** Monitoring that counts 401s will never see it; look for the "An unauthorized connection attempt was rejected" log line instead. ## Why it is built this way Channels are long-lived and may run many actions, so doing authentication once per socket keeps each action cheap, while identifiers give every channel the same `current_user` without passing it around. The cost is that anything decided in `connect` is a snapshot: freshness is the application's job, through `remote_connections` or checks inside channel actions.
- How do you drop a support agent's open sockets when their account is disabled?Call `ActionCable.server.remote_connections.where(current_user: agent).disconnect`. It broadcasts a disconnect on the connection's internal channel through the pub/sub adapter, so it reaches the agent's sockets on any server. The default `reconnect: true` lets the browser reconnect, which reruns `connect` and should now reject; `reconnect: false` tells the client not to try.
- What happens if ApplicationCable::Connection has no connect method?Rails calls `connect` only `if respond_to?(:connect)`, so every socket is accepted with no identifiers set. The empty class from `bin/rails generate channel` behaves exactly like this; channels then have no `current_user` to authorise against unless you add `identified_by` and `connect`.
- Does connect run again before each channel action?No. It runs once per socket, from `handle_open`. For logic around every incoming command, use `before_command`, `after_command` or `around_command` on the connection; for per-subscription checks, use the channel's `subscribed` and its actions.
- identified_by makes current_user available only inside the connection, not in channels.
- connect runs before every channel action, like a controller before_action.
- reject_unauthorized_connection returns false and the socket stays open without a user.
- A rejected connection answers the upgrade request with HTTP 401 before any socket opens.
- The browser keeps reconnecting forever after an unauthorized rejection.