Authenticate connections¶
This page shows how to decide who a WebSocket connection belongs to and which web pages can open one. You configure an authenticator, a function that maps the upgrade request to an identity, and a list of allowed origins. For the full list of settings, see Authentication in the reference.
Authenticate with the session¶
If your app signs users in with a cookie session, the authenticator can read that session. The browser sends the session cookie with a same-origin WebSocket connection.
To authenticate connections with the session, complete the following steps:
-
Add a session secret to your settings. rack-session needs at least 64 bytes:
-
Enable sessions in
config/app.rb. Hanami doesn't enable them by default: -
In
config/providers/sockets.rb, set an authenticator that reads the user ID from the session:
Mankai calls the authenticator once per connection, when the browser client sends its hello
frame. It passes the Rack::Request of the upgrade request and the token subject, or nil if
there's no token. If a user signs in through your existing actions, the authenticator sees their
session.
The authenticator returns one of the following values:
- A
Mankai::Sockets::Identity, which accepts the connection. nil, which closes the connection with code 4401. The browser client doesn't reconnect.
If the authenticator raises an exception, Mankai closes the connection in the same way and
publishes the exception as a mankai.sockets.error event.
An identity has a key and a value. The key identifies the person behind the connection. Mankai
uses it to count connections against max_connections_per_identity and to find connections for
disconnect, so make it stable, such as "user:42". The value is yours. Mankai never sends it to
the browser, and channels read it as subscription.identity.value.
Authenticate with tokens¶
Use tokens when the WebSocket connection can't carry the session cookie, for example when it goes to another host, or to a separate process that serves only the endpoint and skips the session middleware. A token is a signed, short-lived subject, such as a user ID.
To authenticate connections with tokens, complete the following steps:
-
Add a token secret of at least 32 bytes to your settings:
-
Set the
SOCKETS_TOKEN_SECRETenvironment variable. -
Pass the secret to the provider, and read the token subject in the authenticator:
# config/providers/sockets.rb configure do |config| config.token_secret = Hanami.app.settings.sockets_token_secret config.authenticator = lambda do |request, token_subject| user_id = token_subject || request.session[:user_id] user_id && Mankai::Sockets::Identity.new(key: "user:#{user_id}", value: user_id) end # ... endThe subject is always a
String, whatever type you issued it with. Settingtoken_secretregisters thesockets.tokenscomponent. -
Add a route for the token action, next to the endpoint:
-
Add an action that issues a token to the signed-in user:
# app/actions/sockets/token.rb module Bookshelf module Actions module Sockets class Token < Bookshelf::Action include Deps["sockets.tokens"] def handle(request, response) user_id = request.session[:user_id] halt 401 unless user_id response.headers["Cache-Control"] = "no-store" response.format = :txt response.body = tokens.issue(user_id, expires_in: 60) end end end end endissueaccepts any subject that isn'tnilor empty, such as an integer ID, and converts it to aString. Mankai checks the token only when the connection opens, so keepexpires_inshort. -
In the browser, pass a
tokenfunction tocreateConsumer. The client calls it before every connection attempt, so each attempt gets a fresh token:
An invalid or expired token closes the connection with code 4401. So does any token if
token_secret isn't set.
Accept anonymous clients¶
To accept clients without identifying them, set allow_anonymous:
Mankai then accepts every client for which the authenticator returns nil, or every client if
there's no authenticator. Each anonymous connection gets its own identity. Use anonymous clients in
development or for public, read-only feeds. Don't use them for private data.
Restrict allowed origins¶
The allowed_origins setting is required. It lists the pages that can open a connection. Set it
to one of the following values:
# config/providers/sockets.rb
config.allowed_origins = :same_origin
config.allowed_origins = ["https://example.com"]
config.allowed_origins = ["https://example.com", "https://*.example.com"]
:same_origin accepts only the app's own origin. An exact origin must match scheme, host, and
port. A wildcard such as https://*.example.com matches subdomains only, so list the bare domain
too if pages there connect. Mankai has no "allow all" value, and it refuses requests without an
Origin header.
A refused origin gets an HTTP 403 response before the upgrade. Mankai parses the patterns when the provider starts, so an invalid pattern fails at boot.
Close a user's connections¶
When a user signs out or loses access, close their open connections with disconnect and the
identity key:
Each process that receives the request closes that identity's connections with code 4401, and the
browser client doesn't reconnect. With the memory backend, only the current process receives the
request. With the SQL backend, every process receives it, even if you call disconnect from a
job.