Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 36 ยท Middleware and Authentication

Authorization and Rate Limiting

Go beyond authentication. Enforce who may do what in Socket.IO with role and room checks, protect against floods with a token-bucket rate limiter, and cap connections per user or IP.

Authentication answers who are you? Authorization answers what may you do? A signed-in user may chat in their own team's room but not read another team's messages, and a moderator may delete messages that an ordinary user cannot. Closely related is rate limiting: even a legitimate user must not be able to flood the server with a thousand events per second. Together these two checks turn a demo into something you can expose to the internet.

Authorize every event

Because clients can emit any event with any data, authorization must happen in the server handler, on every event, not just at connection. A good habit is to answer three questions at the top of each handler:

  1. Who is this? socket.data.user (set by middleware; never from the payload).
  2. May they do this kind of thing? Role or permission check.
  3. May they do it to this thing? Ownership or membership check (the room, the document, the order).

The example below puts those questions into a tiny reusable guard function, and applies it to three events: reading history of a team room (members only), posting (members only), and deleting any message (moderators only).

Node.js Role and membership checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A frequent bug is hiding a button in the UI and assuming that protects the action. It does not: anyone can open the browser console and emit the event. The server check is the only real protection. Treat the UI as a convenience, never as security.

Where do permissions come from? Fetch them at authentication time and keep them in socket.data, or look them up in your database on each sensitive event if they change often. If a permission is revoked while the user is connected, remember to update or disconnect the live sockets (for example with io.in('user:42').disconnectSockets() as in Managing Sockets from the Server).

Why rate limiting matters

Each incoming event costs CPU, memory and possibly a database write. A buggy client in an infinite loop, or a malicious one on purpose, can emit thousands of events per second and starve everyone else. Sockets are not protected by the usual HTTP rate limiter, because after the handshake there are no more HTTP requests to count. You have to count events yourself.

The token bucket

A simple, popular algorithm is the token bucket. Imagine each client has a bucket holding up to capacity tokens. Every event removes one token. Tokens refill at a steady refillPerSecond. If the bucket is empty, the event is refused. This allows short bursts (a user pastes three quick messages) while capping the sustained rate.

Node.js A token bucket with a fake clock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first three events pass, the next two are rejected, the refill lets one event through at 1000 ms, the next at 1100 ms is rejected, and after the two-second pause only two events pass (the bucket refilled to just over two tokens).

Applying a limit to a socket

Create one bucket per socket when it connects, and consult it for each event, ideally in one place (with real Socket.IO that place is socket.use, which sees every packet). When the limit is hit, tell the client (so a good client can slow down) and optionally disconnect repeat offenders.

Node.js Limiting events per socket

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Three messages get through (the burst), the next three trigger warnings with rising strikes, and the third strike disconnects the client. The remaining events never reach a handler.

Other limits worth setting

  • Connections per user or IP. Count active sockets per userId or socket.handshake.address in middleware and refuse beyond, say, 10. Behind a proxy use the forwarded address carefully (X-Forwarded-For can be forged unless your proxy overwrites it).
  • Payload size. Keep maxHttpBufferSize small, and validate string lengths and array sizes in handlers.
  • Room joins. A user who can join unlimited rooms can exhaust memory; cap rooms per socket.
  • Expensive actions. Apply stricter, separate buckets to events that hit the database or call external services.

For limiting across several server processes, store counters in Redis (a library such as rate-limiter-flexible does this); in-memory buckets only count per process.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A 'delete message' button is hidden for normal users. Is the feature secure?

    UI restrictions are not security. Authorization must be enforced in the server handler.
  2. 2. In a token bucket with capacity 5 and refill 1 per second, what does a user who has been idle for a long time get?

    The bucket holds at most its capacity, so an idle user can burst up to that many events and then is limited by the refill rate.
  3. 3. Why is ordinary HTTP rate limiting not enough for Socket.IO events?

    A single long-lived connection can carry unlimited events with no further HTTP requests.
  4. 4. Where should the author of a chat message come from?

    Trust only the server-side identity established by authentication.

Summary

  • Authorization is checked in every handler: who, what kind of action, which resource.
  • Hiding UI elements is not security; the server must enforce roles and membership.
  • Rate-limit events per socket, for example with a token bucket that allows bursts but caps the sustained rate.
  • Warn, then disconnect, repeat offenders; also limit connections, payload sizes and room joins.
  • Use shared storage such as Redis when limits must hold across several processes.

Next: Error Handling and Input Validation