This repository contains a simple JWT-based authorization system built with Node.js and Express. The project demonstrates how to register and login users to generate a JWT token, and how to protect routes using that token.
- User Registration: Create a new user and receive a JWT.
- User Login: Authenticate an existing user and receive a JWT.
- Protected Route: Access routes that require a valid JWT.
Follow these steps to get the project up and running on your local machine:
-
Clone the repository:
git clone https://github.com/YourUsername/JWT-Exercise.git cd JWT-Exercise
-
Install dependencies:
npm install
-
Configure Environment Variables:
Create a
.env
file in the root directory and add your secret key. For example:SECRET_KEY=YOUR_SECRET_KEY_HERE
Note: The secret key is used to sign and verify JWTs. Make sure to keep it secure!
-
Start the Server:
If you installed
nodemon
as a dev dependency, you can add a start script in yourpackage.json
:"scripts": { "start": "nodemon app.js" }
Then run:
npm start
Alternatively, start the server with:
node app.js
-
Test Endpoints:
Use Postman or your preferred API testing tool to interact with the API.
-
Register:
-
Method: POST
-
URL:
http://localhost:3000/register
-
Body (JSON):
{ "email": "[email protected]", "password": "password123" }
-
-
Login:
-
Method: POST
-
URL:
http://localhost:3000/login
-
Body (JSON):
{ "email": "[email protected]", "password": "password123" }
-
-
Protected Route:
- Method: GET
- URL:
http://localhost:3000/protected
- Headers:
- Authorization: Paste your JWT token directly.
-
- Error Handling:
The application returns appropriate HTTP status codes and error messages when:- A user is not found.
- The token is missing, invalid, or expired.
Happy coding!