A simple Node.js project demonstrating authentication and authorization using bcrypt for password hashing and JSON Web Tokens (JWT) for secure user sessions. This project includes user registration, login, and role-based access control for user and admin endpoints.
- User Registration: Securely register users with hashed passwords.
- Login: Authenticate users and generate JWT tokens.
- Role-Based Access Control: Separate endpoints for users and admins.
- Secure Passwords: Passwords are hashed using bcrypt.
- Token-Based Authentication: JWT tokens are used to protect endpoints.
Ensure you have the following installed:
-
Clone the repository:
git clone https://github.com/ravivr-dev/nodejs-auth-demo.git cd nodejs-auth-demo
-
Install dependencies:
npm install
-
Create a
.env
file in the project root and add the following:PORT=3000 MONGO_URI=mongodb://localhost:27017/nodejs-auth-demo JWT_SECRET=your_secret_key
-
Start the application:
npm start
The server will run on http://localhost:3000
by default.
POST /api/register
Request Body:
{
"name": "John Doe",
"email": "john.doe@example.com",
"password": "password123"
}
POST /api/login
Request Body:
{
"email": "john.doe@example.com",
"password": "password123"
}
Response:
{
"token": "your_jwt_token"
}
GET /api/user
Headers:
{
"Authorization": "Bearer your_jwt_token"
}
GET /api/admin
Headers:
{
"Authorization": "Bearer your_jwt_token"
}
nodejs-auth-demo/
├── controllers/
│ ├── authController.js
│ └── userController.js
├── middleware/
│ └── authMiddleware.js
├── models/
│ └── userModel.js
├── routes/
│ ├── authRoutes.js
│ └── userRoutes.js
├── .env
├── server.js
└── package.json
- Node.js: JavaScript runtime environment
- Express.js: Web framework for Node.js
- MongoDB: NoSQL database for storing user data
- bcrypt: Library for hashing passwords
- jsonwebtoken: Library for creating and verifying JWT tokens
This project is licensed under the MIT License.
Contributions are welcome! Feel free to submit a pull request or open an issue if you have suggestions or improvements.
For any inquiries or issues, please reach out:
- GitHub: ravivr-dev