Skip to content

n1kFord/jwt-auth

Repository files navigation

πŸ” JWT Authentication API

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

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

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

✨ 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

  • Node.js 20+
  • Docker & Docker Compose

Installation

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

# Install dependencies
npm install

# Copy environment variables
cp .env.example .env

# Start MongoDB and Redis
docker-compose up -d

# Run development server
npm run dev

Environment Variables

PORT=8080
MONGO_URI=mongodb://localhost:27017/authDB
REDIS_CLIENT_URI=redis://localhost:6379
JWT_SECRET=your-jwt-secret
JWT_REFRESH_SECRET=your-refresh-secret

πŸ“ 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

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

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors