Authentication and Room Permissions

Identify users with connection middleware and check room permissions when joining and sending messages.

🎯 Introduction

The previous article isolated messages by room, but every client could choose room1 or room2. We will now add a rule: room1 allows User A and User B, while room2 allows only User A. The backend must identify who owns the connection before deciding what that user can do.


🧱 Identify the User, Then Check Permissions

Authentication answers “Who are you?” The client supplies credentials, and the server validates them to establish the user's identity. Authorization answers “What can you do?” For example, User B has a valid identity and can connect, but a request to enter room2 is rejected.

Continue with the previous project, adding only authentication and authorization code. Expected behavior:

Client credentialUser identified by serverCan connectroom1room2
demo-token-aUser AAllowedAllowedAllowed
demo-token-bUser BAllowedAllowedDenied
wrongUnrecognizedDeniedCannot requestCannot request

A token is a credential supplied by the client. Applications typically issue it after login; the client then submits it when connecting to Socket.IO. This lesson uses two fixed credentials to simulate an already completed login and focus on how Socket.IO receives and validates credentials.


🛠 Validate Credentials Before Accepting a Connection

In server.mjs, add this code after creating io and before registering the connection listener.

const sessions = new Map([
    ['demo-token-a', { userId: 'A' }],
    ['demo-token-b', { userId: 'B' }]
]);

io.use((socket, next) => {
    const token = socket.handshake.auth?.token;
    const session = sessions.get(token);

    if (!session) {
        next(new Error('UNAUTHENTICATED'));
        return;
    }

    socket.data.userId = session.userId;
    next();
});

sessions maps credentials to users. sessions.get(token) looks up a user by credential and returns undefined if none matches. This fixed table is only for practice; a production login system also needs expiration, logout, and disabled-user handling.

io.use registers connection middleware, a check that runs before a connection is accepted. Read the auth data submitted by the client from socket.handshake.auth. The ?. operator safely handles missing auth data.

The middleware reports its result to Socket.IO through next:

  • Call next() to continue establishing the connection. Once successful, the server's connection callback runs.
  • Call next(error) to reject the connection. The client receives connect_error, and the server does not run its connection callback for that client.

After successful authentication, store the user ID in socket.data.userId. Subsequent handlers can read this server-verified identity directly. Middleware

Submit the Token from the Client

In client.mjs, replace the original socket creation statement with this code. Keep the existing event listeners.

const socket = io('http://localhost:3000', {
    auth: {
        token: 'demo-token-a'
    }
});

Calling io still initiates the connection automatically, submitting auth with the connection request. The client does not need a separate “login event”.

Restart the server and run the client with a valid credential first, confirming that it can join the original room. Then change token to wrong, stop the client process, and restart it.

  • Valid credential: the client runs its connect callback and requests to join the room.
  • Invalid credential: the existing connect_error listener prints Connection failed UNAUTHENTICATED.
  • A client with invalid credentials never runs its connect callback, so it does not proceed to join or send messages.

Restore a valid token after testing.


🔐 Check Permissions When Joining and Sending

Define this function outside the server's connection callback. Both join and send operations will use it.

function canAccess(userId, room) {
    return room === 'room1' || (room === 'room2' && userId === 'A');
}

It returns a boolean: authenticated users may access room1, only the user with ID A may access room2, and other rooms return false.

Check Before Joining

In the room:join listener, insert this code after validating the room name and before checking the current room.

if (!canAccess(socket.data.userId, name)) {
    reply({ ok: false, error: 'You do not have permission to join this room' });
    return;
}

The subsequent join runs only if authorization succeeds. When User B requests room2, the connection stays open and its current room remains unchanged; only this join request is rejected.

Check Again Before Sending

In the chat:send listener, insert this code after the “Join a room first” check and before text validation.

if (!canAccess(socket.data.userId, socket.data.room)) {
    reply({ ok: false, error: 'You do not have permission to send messages in this room' });
    return;
}

Permissions remain fixed in this lesson. In real group chats, membership can be revoked while a user is connected, so check the permissions that apply when an operation runs. If receiving permission is revoked, the server should also remove the corresponding connection from the room to stop further pushes.

Identify the Sender with the Authenticated Identity

Replace the original broadcast statement with this code. senderId comes from the server's authentication result.

io.to(socket.data.room).emit('chat:message', {
    senderId: socket.data.userId,
    text: text.trim()
});

The previous client prints only the text. To display the identity too, replace the chat:message listener with:

socket.on('chat:message', (message) => {
    console.log(`[User ${message.senderId}] ${message.text}`);
});

When User A sends “Hello”, expect [User A] Hello. Even if the text says “I am User B”, the displayed sender remains User A: message content does not change the authentication result.


❓ Questions and Answers

Q1: Does io.use run for every message after connection authentication succeeds?

No. This middleware runs when establishing the connection; subsequent messages go to their event listeners. In production, login sessions can expire or be revoked. Recheck sessions before operations as needed, or proactively disconnect invalid sessions.

Q2: Can socket.id identify a user?

socket.id identifies a connection. Reconnecting usually produces a new value, and one user may have several connections simultaneously. This article uses userId from credential validation as the application user identity.


🧪 Exercise

Use the previous client's code, making sure the connect callback still sends only after joining successfully. Restore that callback if you previously tested leaving. Set text to “Hello”, then vary token and room. Stop the previous client before each restart.

  1. Set token to demo-token-a and room to room2.
    • Joining succeeds.
    • Receive [User A] Hello.
    • Sending succeeds.
  2. Set token to demo-token-b and room to room2.
    • The join result is { ok: false, error: 'You do not have permission to join this room' }.
    • No chat message or successful send output appears, because the callback returns after joining fails.
  3. Keep demo-token-b and change room to room1.
    • Joining and sending succeed.
    • Receive [User B] Hello.

Compare each result with the permissions table at the beginning to verify that authentication and room authorization each work as intended.


🎉 The server can now identify users and decide whether they may join rooms and send messages.