A complete NestJS backend service that supports:
- User authentication via JWT (signup/login)
- Service-to-Service access via API keys
- Flexible authentication middleware (accepts both JWT and API keys)
- Protected routes based on access type
POST /auth/signup- Register new userPOST /auth/login- Login userPOST /auth/logout- Logout user (requires JWT)
POST /keys/create- Generate API keys (requires JWT)GET /keys- List all API keys (requires JWT)DELETE /keys/:id- Revoke API key (requires JWT)
GET /protected/user-only- Accessible only with JWT Bearer tokenGET /protected/service-only- Accessible only with API keyGET /protected/flexible- Accessible with both JWT and API key
- JWT token generation with refresh tokens
- API key generation with expiration support
- API key revocation
- Last used tracking for API keys
- Flexible authentication middleware
- Swagger documentation
- Node.js 18+
- PostgreSQL database
- Install dependencies:
npm install- Configure environment variables in
.env:
PORT=3000
DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=postgres
DB_PASSWORD=password
DB_NAME=auth_api_key_db
JWT_SECRET=your-secret-key
JWT_EXPIRES_IN=1h
JWT_REFRESH_SECRET=your-refresh-secret
JWT_REFRESH_EXPIRES_IN=7d- Create PostgreSQL database:
CREATE DATABASE auth_api_key_db;- Start the application:
npm run start:devThe application will run on http://localhost:3000
Swagger documentation is available at: http://localhost:3000/api/docs
curl -X POST http://localhost:3000/auth/signup \
-H "Content-Type: application/json" \
-d '{
"email": "[email protected]",
"password": "Password123!",
"name": "John Doe"
}'Response:
{
"user": {
"id": "uuid",
"email": "[email protected]",
"name": "John Doe"
},
"accessToken": "eyJhbGc...",
"refreshToken": "eyJhbGc..."
}curl -X POST http://localhost:3000/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "[email protected]",
"password": "Password123!"
}'curl -X POST http://localhost:3000/keys/create \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-d '{
"name": "My Service API Key",
"expiresAt": "2025-12-31T23:59:59Z"
}'Response:
{
"id": "uuid",
"key": "sk_64characterhexstring...",
"name": "My Service API Key",
"expiresAt": "2025-12-31T23:59:59.000Z",
"createdAt": "2025-01-15T10:30:00.000Z"
}curl -X GET http://localhost:3000/protected/user-only \
-H "Authorization: Bearer YOUR_JWT_TOKEN"curl -X GET http://localhost:3000/protected/service-only \
-H "x-api-key: sk_your_api_key_here"# With JWT
curl -X GET http://localhost:3000/protected/flexible \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
# With API Key
curl -X GET http://localhost:3000/protected/flexible \
-H "x-api-key: sk_your_api_key_here"curl -X GET http://localhost:3000/keys \
-H "Authorization: Bearer YOUR_JWT_TOKEN"curl -X DELETE http://localhost:3000/keys/KEY_ID \
-H "Authorization: Bearer YOUR_JWT_TOKEN"Users Table:
- id (UUID, Primary Key)
- email (Unique)
- password (Hashed)
- name
- isActive
- refreshToken
- createdAt
- updatedAt
API Keys Table:
- id (UUID, Primary Key)
- key (Unique, Format: sk_64chars)
- name
- userId (Foreign Key)
- isActive
- expiresAt
- lastUsedAt
- createdAt
- updatedAt
User Authentication (JWT):
- User signs up or logs in
- Server generates JWT access token and refresh token
- Client stores tokens
- Client sends Bearer token in Authorization header
- Server validates JWT and grants access
Service Authentication (API Key):
- User creates API key via authenticated endpoint
- Server generates unique API key (sk_prefix + 64 hex chars)
- Service stores API key securely
- Service sends API key in x-api-key header
- Server validates API key and grants access
- JwtAuthGuard: Validates JWT Bearer tokens (user access)
- ApiKeyAuthGuard: Validates API keys (service access)
- FlexibleAuthGuard: Accepts both JWT and API keys
- Passwords hashed with bcrypt (10 rounds)
- JWT tokens with expiration
- API keys with optional expiration
- API key revocation support
- Last used tracking for API keys
- Inactive user/key blocking
- Secure API key generation (crypto.randomBytes)
src/
├── auth/
│ ├── dto/
│ ├── strategies/
│ ├── auth.controller.ts
│ ├── auth.service.ts
│ └── auth.module.ts
├── api-keys/
│ ├── dto/
│ ├── api-keys.controller.ts
│ ├── api-keys.service.ts
│ └── api-keys.module.ts
├── users/
│ ├── users.service.ts
│ └── users.module.ts
├── common/
│ ├── guards/
│ └── decorators/
├── database/
│ ├── entities/
│ └── data-source.ts
├── app.controller.ts
├── app.module.ts
└── main.ts
Use the Swagger UI at http://localhost:3000/api/docs to test all endpoints interactively.
- Change JWT secrets in production
- Set
synchronize: falsein TypeORM config - Use migrations for database schema changes
- Implement rate limiting
- Add request logging
- Use HTTPS
- Implement refresh token rotation
- Add API key usage analytics
- Implement API key rate limits per key
- Add webhook support for key events
MIT