A lightweight authentication and API key management service built with NestJS, PostgreSQL, and JWT.
Designed for projects that need both user authentication and service-to-service API key access.
-
User Authentication (JWT)
- Register / Login
- Secure password hashing
- JWT-based session handling
-
API Key System
- Users can generate API keys
- Keys are hashed using HMAC-SHA256 and stored securely
- Optional TTL (auto-expiry)
- Revocation system
- One-time return of the plain API key
-
Dual Auth Support
Bearer <token>→ User accessApiKey <key>orx-api-key→ Service access
-
Guards
UserGuard()— only logged-in usersServiceGuard()— API key clientsAnyAuthGuard()— either user or service
- NestJS (Core framework)
- TypeORM (ORM)
- PostgreSQL (Database)
- JWT (User authentication)
- Crypto (API key hashing)
POST /auth/registerPOST /auth/login
POST /keys/create— create a new API keyGET /keys/list— list user-owned keysPOST /keys/revoke/:id— revoke a key
src/
├── auth/ # JWT login/register logic
├── keys/ # API key entity, service, controller
├── users/ # User entity + user logic
├── common/
│ ├── auth.middleware.ts
│ ├── auth.guard.ts
│ └── guards.ts
├── app.module.ts
└── main.ts
Create a .env file:
DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=postgres
DB_PASSWORD=postgres
DB_DATABASE=authdb
JWT_SECRET=your_jwt_secret_here
API_KEY_SALT=your_api_key_salt_here
npm install
npm run start:devEnsure PostgreSQL is running and the environment variables are set.
- API keys cannot be recovered once created — only the hashed version is stored.
- Make sure to keep
JWT_SECRETandAPI_KEY_SALTprivate. - Suitable for personal projects, microservices, or learning real-world auth systems.