Design an authentication package

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2025-02-14

Problem Statement

Design and implement a reusable authentication package that can be integrated into different applications to provide secure login, session management, and token-based authentication.


The package should be modular, extensible, and support multiple authentication mechanisms.


Functional Requirements (FR)


User Authentication


•Register new users with username/email & password.
•Support login/logout.
•Validate credentials securely (hashed + salted passwords).


Session Management


•Maintain active user sessions.
•Support session timeouts and refresh mechanisms.
•Logout should invalidate the active session/token.


Token-Based Authentication


•Generate JWT (JSON Web Token) or equivalent tokens.
•Validate tokens for subsequent requests.
•Refresh expired tokens securely.


Role & Permission Management (Optional extension)


•Assign roles (Admin, User, Guest, etc.).
•Allow applications to check permissions via the package.


Extensibility


•Plug-in mechanism to support additional authentication strategies (OAuth, SSO, LDAP).


Non-Functional Requirements (NFR)


•Security → Passwords stored with hashing (e.g., bcrypt, Argon2). Tokens signed & verified with secret/keys.
•Scalability → Should handle thousands of authentication requests concurrently.
•Reusability → Exposed as a library/package with clear APIs.
•Configurable → Token expiry, hashing algorithm, and session timeout should be configurable.


Core Entities & Attributes


User


•userId, username/email, hashedPassword, roles, lastLogin


Session


•sessionId, userId, createdAt, expiresAt, status


Token


•tokenId, userId, issuedAt, expiresAt, signature


APIs / Operations


User APIs


•register(username, password)
•login(username, password)
•logout(userId/sessionId)


Token APIs


•generateToken(userId)
•validateToken(token)
•refreshToken(oldToken)


Session APIs


•createSession(userId)
•invalidateSession(sessionId)
•getActiveSessions(userId)


LLD Design Goals


•Class diagram connecting UserManager, AuthService, TokenManager, SessionManager.
•Design patterns:
•Singleton → For AuthService instance.
•Strategy → For supporting multiple authentication methods (password, OAuth, SSO).
•Factory → For token generation strategies (JWT, opaque tokens).
•Handle trade-offs: session storage in-memory vs. DB, stateless (JWT) vs. stateful sessions.


Solution

Comments