Skip to content

Repository files navigation

πŸ” JWT Authentication API

Node.js Version Express.js Version MongoDB Redis License Tests Code Style PRs Welcome

πŸš€ JWT authentication API with refresh tokens, CSRF protection, and Redis storage.

πŸ“š Educational project for learning modern authentication patterns with Node.js.

πŸ”„ Looking for a session-based alternative? Check out: https://github.com/n1kFord/session-auth

✨ Features

  • πŸ”‘ JWT Access & Refresh Tokens with automatic rotation
  • πŸ›‘οΈ CSRF Protection (Double Submit Cookie pattern)
  • πŸ“¦ Redis for persistent refresh token storage
  • 🚦 Rate limiting to prevent brute force attacks
  • πŸͺ΅ Winston + Morgan logging with chalk styling
  • πŸ§ͺ Comprehensive test suite with Jest & Supertest
  • ✨ ESLint + Prettier for code quality
  • 🐳 Docker Compose for easy development

πŸ› οΈ Tech Stack

  • Runtime: Node.js 20+
  • Framework: Express.js 5.x
  • Database: MongoDB + Mongoose
  • Cache: Redis (refresh tokens)
  • Security: bcrypt, JWT, CSRF, rate limiting
  • Logging: Winston, Morgan, Chalk
  • Testing: Jest + Supertest
  • Code Quality: ESLint + Prettier

πŸš€ Quick Start

Prerequisites

  • Docker & Docker Compose (recommended)
  • Node.js >= 20 (for local development)

With Docker (Recommended)

# Clone repository
git clone https://github.com/n1kFord/jwt-auth.git
cd jwt-auth

# Start all services (MongoDB, Redis, and API)
docker compose up -d

# Check logs
docker compose logs -f

# Stop services
docker compose down

# Stop and remove volumes (clears database)
docker compose down -v

Local Development

# Install dependencies
npm install

# Setup environment
cp .env.example .env
# Edit .env with your configuration

# Start MongoDB and Redis (using Docker)
docker compose up -d mongo redis

# Start development server
npm run dev

# Production mode
npm start

Environment Variables

# Server
PORT=8080
NODE_ENV=development

# MongoDB
MONGO_URI=mongodb://localhost:27017/authDB

# Redis
REDIS_CLIENT_URI=redis://localhost:6379

# JWT Secrets (generate strong secrets β€” at least 32 chars!)
JWT_SECRET=your_super_secret_jwt_key_min_32_chars
JWT_REFRESH_SECRET=your_super_secret_refresh_key_min_32_chars

πŸ“ Project Structure

jwt-auth/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ config/          # Configuration (DB, Redis, constants)
β”‚   β”œβ”€β”€ middlewares/     # Auth, CSRF, validation, logging
β”‚   β”œβ”€β”€ models/          # User model
β”‚   β”œβ”€β”€ routers/         # /auth and /me endpoints
β”‚   β”œβ”€β”€ store/           # Redis token storage
β”‚   β”œβ”€β”€ utils/           # Helpers (tokens, logger, hash, cookies)
β”‚   β”œβ”€β”€ __tests__/       # Jest tests
β”‚   └── index.js         # Entry point
β”œβ”€β”€ logs/                # Winston log files
β”œβ”€β”€ docker-compose.yml
β”œβ”€β”€ Dockerfile
└── package.json

πŸ“ Logging

  • Winston β€” file + console logging with levels (error, warn, info, debug)
  • Morgan β€” HTTP request logging integrated with Winston
  • Chalk β€” colored console output

🎨 Code Style

npm run lint        # Check code style
npm run format      # Auto-format with Prettier

πŸ”Œ API Endpoints

Auth (/auth)

Method Endpoint Description CSRF
POST /register Register user ❌
POST /login Login user ❌
POST /refresh Refresh tokens βœ…
POST /logout Logout ❌

User (/me)

Method Endpoint Description CSRF
GET / Get profile ❌
POST /change-email Change email βœ…
POST /change-password Change password βœ…
POST /change-username Change username βœ…
POST /change-bio Change bio βœ…
DELETE / Delete account βœ…

πŸ“ Examples

Register

curl -X POST http://localhost:8080/auth/register \
  -H "Content-Type: application/json" \
  -d '{"email":"user@example.com","password":"secret123","confirmPassword":"secret123"}'

Login

curl -X POST http://localhost:8080/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"user@example.com","password":"secret123"}'

Get Profile (with CSRF)

curl -X GET http://localhost:8080/me/ \
  -H "x-csrf-token: your-csrf-token" \
  -H "Cookie: token=access-token; XSRF-TOKEN=csrf-token"

πŸ§ͺ Testing

npm test

🐳 Docker

# Start all services
docker-compose up -d

# Stop all services
docker-compose down

πŸ”§ Environment Variables

Variable Description
PORT Server port (default: 8080)
MONGO_URI MongoDB connection string
REDIS_CLIENT_URI Redis connection string
JWT_SECRET Secret for access tokens
JWT_REFRESH_SECRET Secret for refresh tokens

πŸ›‘οΈ Security

  • JWT with short-lived access tokens (15min) and long-lived refresh tokens (7d)
  • Token rotation β€” new refresh token on each refresh
  • CSRF protection β€” Double Submit Cookie pattern
  • Rate limiting β€” 100 req/15min global, 10 login attempts
  • HTTP-only cookies β€” prevents XSS attacks
  • Bcrypt for password hashing

🀝 Contributing

Contributions are welcome! Feel free to open issues and pull requests.

πŸ“„ License

This project is licensed under the MIT License.
Feel free to use, modify, and distribute with attribution.

πŸ’‘ Created with care by @n1kFord


⭐ Star this repo if you found it helpful!

About

πŸ” JWT authentication API with refresh tokens, CSRF protection, and Redis

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages