{"library":"sc-auth","title":"SocketCluster Authentication Module","description":"sc-auth is a foundational authentication module specifically designed for the SocketCluster real-time framework. It facilitates JSON Web Token (JWT) based authentication, which is the default mechanism in SocketCluster. This package, currently at version 6.0.0 (released approximately eight years ago), handles the core logic for signing and verifying JWTs within a SocketCluster environment. While newer SocketCluster documentation often guides developers towards using `agServer.auth.signToken` or `jsonwebtoken` directly, `sc-auth` provides a structured `AuthEngine` for this purpose. Its primary role is to enable persistent user sessions, cross-browser tab authentication, and secure access control by signing arbitrary data objects with a secret key. Due to its age, developers should be aware that active development is minimal, and practices may have evolved in the broader SocketCluster ecosystem. Its release cadence is effectively dormant, with its last major update occurring many years ago.","language":"javascript","status":"maintenance","last_verified":"Wed Apr 22","install":{"commands":["npm install sc-auth"],"cli":null},"imports":["const AuthEngine = require('sc-auth').AuthEngine;","const { createAuthEngine } = require('sc-auth');","const { signToken } = require('sc-auth');"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"const http = require('http');\nconst socketClusterServer = require('socketcluster-server');\nconst { AuthEngine } = require('sc-auth');\n\nconst AUTH_KEY = process.env.AUTH_SIGNATURE_KEY ?? 'my-secret-auth-key'; // NEVER hardcode in production!\nconst TOKEN_EXPIRY_IN_SECONDS = 3600; // 1 hour\n\nconst httpServer = http.createServer();\nconst authEngine = new AuthEngine(AUTH_KEY, {\n  algorithm: 'HS256', // Default algorithm\n  expiresIn: TOKEN_EXPIRY_IN_SECONDS\n});\n\nconst agServer = socketClusterServer.attach(httpServer, {\n  authKey: AUTH_KEY,\n  authEngine: authEngine // Inject sc-auth's engine\n});\n\n(async () => {\n  for await (let { socket } of agServer.listener('connection')) {\n    // Example of authenticating a socket after a login event\n    socket.on('login', async (credentials, respond) => {\n      if (credentials.username === 'user' && credentials.password === 'pass') {\n        const tokenData = { username: credentials.username, role: 'admin' };\n        try {\n          const token = await authEngine.signToken(tokenData);\n          socket.authenticate(token);\n          respond(); // Acknowledge successful login\n        } catch (error) {\n          respond(error); // Send error back to client\n        }\n      } else {\n        respond(new Error('Invalid credentials'));\n      }\n    });\n\n    // Example middleware to check authenticated status\n    agServer.setMiddleware(agServer.MIDDLEWARE_INBOUND, async (middlewareStream) => {\n      for await (let action of middlewareStream) {\n        if (action.type === action.PUBLISH_IN) {\n          if (!action.socket.authToken) {\n            action.block(new Error('Authentication required to publish.'));\n            continue;\n          }\n          // Further authorization checks based on action.socket.authToken.role\n          if (action.socket.authToken.role !== 'admin' && action.channel === 'adminChannel') {\n            action.block(new Error('Not authorized for this channel.'));\n            continue;\n          }\n        }\n        action.next();\n      }\n    });\n  }\n})();\n\nhttpServer.listen(8000, () => {\n  console.log(`SocketCluster server listening on port 8000`);\n});\n","lang":"javascript","description":"This quickstart demonstrates how to integrate `sc-auth` with a SocketCluster server to handle JWT-based authentication. It shows initializing the `AuthEngine`, using it to sign tokens upon a 'login' event, and implementing inbound middleware to verify token presence and perform basic role-based authorization for publishing to channels.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}