Skip to content

Latest commit

 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

backend-refresh-token-auth-api

Secure authentication API using short-lived access tokens, rotating refresh tokens, MongoDB, and HttpOnly cookies.

Features

  • User registration, login, current-user, refresh, and logout endpoints
  • 15-minute access tokens
  • Seven-day refresh tokens with bcrypt-hashed storage
  • Refresh token rotation and reuse invalidation
  • Secure configurable HttpOnly cookies
  • Password hashing and input validation
  • Helmet security headers and authentication rate limiting
  • Configurable CORS with credentials
  • Safe errors, request limits, standardized API responses, and request logs

Requirements

  • Node.js 18 or newer
  • MongoDB running locally or a hosted MongoDB connection

Setup

npm install
copy .env.example .env

Set two different random JWT secrets with at least 32 characters each.

Run

npm run dev

The default port is 1198.

Environment variables

Variable Required Description
PORT No Server port, defaults to 1198
MONGO_URI Yes MongoDB connection string
JWT_ACCESS_SECRET Yes Access token secret, minimum 32 characters
JWT_REFRESH_SECRET Yes Refresh token secret, minimum 32 characters
NODE_ENV No Use production to enable Secure cookies
CLIENT_ORIGINS No Comma-separated trusted frontend origins
COOKIE_SAME_SITE No Cookie policy, defaults to lax

API endpoints

Method Endpoint Access Purpose
GET / Public API status
GET /health Public Health response
POST /api/auth/register Public Register and authenticate
POST /api/auth/login Public Login and rotate tokens
POST /api/auth/refresh-token Refresh cookie Rotate access and refresh tokens
GET /api/auth/me Access cookie Get current user
POST /api/auth/logout Public Revoke refresh token and clear cookies

All JSON responses include apiUrl as the first field. Browser clients must use credentials: "include" for cookie-based requests.

License

MIT. See LICENSE.

Author

Ashish Ranjan

Full-Stack Web Developer

Links

Support

About

Secure backend authentication API implementing access token and refresh token flow with HttpOnly cookies using Node.js, Express, and MongoDB.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages