Skip to content
Edit this page View source of this page

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:

  1. Add a session secret to your settings. rack-session needs at least 64 bytes:

    # config/settings.rb
    module Bookshelf
      class Settings < Hanami::Settings
        setting :session_secret, constructor: Types::String.constrained(min_size: 64)
      end
    end
    
  2. Enable sessions in config/app.rb. Hanami doesn't enable them by default:

    # config/app.rb
    module Bookshelf
      class App < Hanami::App
        config.actions.sessions = :cookie, {secret: settings.session_secret}
      end
    end
    
  3. In config/providers/sockets.rb, set an authenticator that reads the user ID from the session:

    # config/providers/sockets.rb
    config.authenticator = lambda do |request, _token_subject|
      user_id = request.session[:user_id]
      user_id && Mankai::Sockets::Identity.new(key: "user:#{user_id}", value: user_id)
    end
    

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:

  1. Add a token secret of at least 32 bytes to your settings:

    # config/settings.rb
    setting :sockets_token_secret, constructor: Types::String.constrained(min_size: 32)
    
  2. Set the SOCKETS_TOKEN_SECRET environment variable.

  3. 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
      # ...
    end
    

    The subject is always a String, whatever type you issued it with. Setting token_secret registers the sockets.tokens component.

  4. Add a route for the token action, next to the endpoint:

    # config/routes.rb
    get "/sockets/token", to: "sockets.token"
    mount Hanami.app["sockets.endpoint"], at: "/sockets"
    
  5. 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
    end
    

    issue accepts any subject that isn't nil or empty, such as an integer ID, and converts it to a String. Mankai checks the token only when the connection opens, so keep expires_in short.

  6. In the browser, pass a token function to createConsumer. The client calls it before every connection attempt, so each attempt gets a fresh token:

    const consumer = createConsumer("/sockets", {
      token: async () => {
        const response = await fetch("/sockets/token", {credentials: "same-origin"});
        if (!response.ok) throw new Error(`token request failed (${response.status})`);
        return response.text();
      },
    });
    

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:

# config/providers/sockets.rb
config.allow_anonymous = true

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:

Hanami.app["sockets.server"].disconnect("user:42")

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.

What's next