ag-auth (SocketCluster Auth Module)

2.1.1 · active · verified Wed Apr 22

ag-auth is the official authentication module for SocketCluster (now Asyngular), providing a robust mechanism for securing real-time applications using JSON Web Tokens (JWT). It handles the signing, verification, and management of authentication tokens. Currently at version 2.1.1, the package is actively maintained, with the latest significant update published in November 2025. It serves as the underlying engine for SocketCluster's `agServer.auth` object, abstracting the complexities of JWT handling. While alternative methods for JWT exist (e.g., direct `jsonwebtoken` usage), ag-auth integrates seamlessly into the SocketCluster ecosystem, offering a standardized and convenient approach to user authentication across HTTP and WebSocket flows. Its primary differentiator is this tight integration, ensuring compatibility and streamlined development within SocketCluster projects.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how `ag-auth` (via `agServer.auth`) is used to sign and verify JWT tokens in a SocketCluster server, handling client authentication.

import { AGServer } from 'socketcluster-server';
import { AuthEngine } from 'ag-auth'; // Although usually accessed via agServer.auth

const SECRET_KEY = process.env.AUTH_SECRET_KEY ?? 'my-secret-key-123';

const agServer = new AGServer({
  authKey: SECRET_KEY,
  // If you were to override the default auth engine, you might do:
  // authEngine: new AuthEngine(SECRET_KEY)
});

(async () => {
  for await (const { socket } of agServer.listen()) {
    (async () => {
      // This is how ag-auth functionality is typically accessed
      // via the agServer instance.
      const tokenData = { username: 'testuser', roles: ['admin'] };

      try {
        // Sign a token using the configured authEngine (ag-auth)
        const token = await agServer.auth.signToken(tokenData, { expiresIn: '1h' });
        console.log(`Signed JWT: ${token}`);

        // Simulate client sending token and server verifying
        socket.on('login', async (data) => {
          try {
            const decodedToken = await agServer.auth.verifyToken(data.token);
            console.log(`Socket ${socket.id} authenticated:`, decodedToken);
            socket.emit('authSuccess', { message: 'Authenticated successfully', user: decodedToken.username });
          } catch (error) {
            console.error(`Socket ${socket.id} authentication failed:`, error.message);
            socket.emit('authFail', { message: 'Authentication failed', error: error.message });
          }
        });

        // Example: Client attempts to log in
        setTimeout(() => {
          console.log('Simulating client login attempt...');
          socket.emit('login', { token: token });
        }, 1000);

      } catch (error) {
        console.error('Error during auth setup:', error);
      }
    })();
  }
})();

console.log('SocketCluster server is listening for connections...');

view raw JSON →