Skip to main content

Hybrid Authentication System

Design Philosophy: Support multiple authentication methods with a unified interface for route handlers.

Authentication Methods

  1. Clerk JWT Authentication (for web applications)
    Authorization: Bearer <clerk_jwt_token>
    
  2. API Key Authentication (for machine-to-machine)
    X-CLOUDGENI-API-KEY: cgk_xxxxxxxx_xxxxxxxxxxxxxxxx
    

Authentication Flow Architecture

// Authentication middleware chain
RequestauthStrategyDetectorconditionalAuthrouteHandler
                ↓                      ↓
        [sets authStrategy]    [applies appropriate auth]

                              [Clerk Path or API Key Path]

Middleware Application Pattern

Public Routes (no authentication):
const publicRouter = express.Router();
publicRouter.use('/', createGlobalRoutes()); 
apiRoutes.use('/v1', publicRouter);
Auth-Only Routes (Clerk authentication required):
const authRouter = express.Router();
authRouter.use('/auth', clerkAuthOnly, loginAuditLogger, createAuthRoutes());
apiRoutes.use('/v1', authRouter);
Protected Routes (hybrid authentication):
const protectedRouter = express.Router();
protectedRouter.use('/users', createUsersRoutes());
protectedRouter.use('/organizations', createOrganizationsRoutes());
apiRoutes.use('/v1', hybridAuth, protectedRouter);

Request Context Pattern

After authentication, ALL route handlers receive:
interface AuthenticatedRequest extends Request {
  user: CloudgeniUser;           // Always real user (creator for API keys)
  organization: CloudgeniOrganization; // Current organization context
  authStrategy: 'clerk' | 'api_key';   // How user was authenticated
}
Route Handler Pattern:
router.get('/', async (req: Request, res: Response) => {
  if (!req.user?.id) {
    return res.status(401).json({
      success: false,
      error: 'AUTHENTICATION_REQUIRED',
      message: 'Authentication required'
    });
  }

  const userId = req.user.id;           // Always real user ID
  const orgId = req.organization.id;    // Current organization
  
  // Business logic here - no auth method awareness needed
});

API Key Design

API Key Format: cgk_<8_hex_chars>_<16_hex_chars>
  • cgk_: Cloudgeni Key prefix
  • First part: Key identifier for database lookup
  • Second part: Secret for validation
Key Principles:
  • API keys inherit permissions from their creator
  • Actions are attributed to the real creator user
  • Organization scope is enforced at the API key level
  • Usage is logged for analytics and security