This project implements JWT authentication with best practices to ensure security and efficient user management. Below are the key practices and setup instructions.
- Ensure that ACCESS_TOKEN_SECRET and REFRESH_TOKEN_SECRET are long, random, and kept secure. These values should be stored in environment variables, not hardcoded.
- Example:
ACCESS_TOKEN_SECRET=your_strong_access_token_secret REFRESH_TOKEN_SECRET=your_strong_refresh_token_secret
- Access tokens should have short expiration times, typically 15 minutes. This minimizes the damage if a token is compromised.
- Refresh tokens should be used to issue new access tokens when they expire. These should be securely stored, typically in HTTP-only cookies.
- Implement token revocation strategies such as using a blacklist or rotating refresh tokens to invalidate old ones.
- Always use HTTPS to encrypt sensitive data during transmission, including JWT tokens.
- Never store JWT tokens in
localStorageorsessionStorageas they are vulnerable to cross-site scripting (XSS) attacks. Prefer storing them in HTTP-only cookies.
- Node.js and npm must be installed.
git clone https://github.com/KapalaBintang/JWT-Authentication.git
cd backend
npm installCreate a .env file in the root of your project and fill in the following variables:
PORT=YOUR_PORT
ACCESS_TOKEN_SECRET=your_strong_access_token_secret
REFRESH_TOKEN_SECRET=your_strong_refresh_token_secretTo run the application in development mode:
npm run start:devTo run the application in production mode:
npm run start:prodYou can use tools like Postman or Insomnia to test the API endpoints:
- POST
/auth/login- Login endpoint - GET
/users- Get users (admin only) - POST
/users- Create a new user (admin only)
Feel free to fork and contribute to this project. Make sure to follow best practices for security and coding style.
Itu adalah kode lengkap untuk JWT authentication di NestJS dan file README.md untuk proyek ini.