JWT Authentication
JWT Authentication
Harshit KatheriaDemonstrating a simple authentication system using Node.js, Express.js, and MongoDB. It includes APIs for user registration, login, fetching user details, and updating user details, all protected by JWT-based authentication.
What is JWT?
JWT stands for JSON Web Token. It is an open standard that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.
Why JWT?
The main reason for using JWT is that it allows the server to verify the integrity of the information contained in the token without storing any information about the user on the server. This makes JWTs a great choice for authentication.
- Secure: JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA. This means that the server can verify the integrity of the information contained in the token.
- Cybersecurity: JWTs are digitally signed, which means that they are tamper-proof. This prevents attacks such as Man-in-the-Middle (MITM) attacks.
Installation
Clone the repository.
1 | $ git clone https:://github.com/UxHarshit/SecureLoginSystem.git |
Install the dependencies.
1 | $ cd SecureLoginSystem |
Copy example.env to .env and update the values.
1 | $ cp example.env .env |
Run the server.
1 | $ npm run dev |
Api Endpoints
User Registration
- URL: /api/auth/register
- Method: POST
- Request Body:
1
2
3
4
5
6
7{
"name": "firstname",
"lastname": "lastname",
"username": "username",
"email": "abc@email.com",
"password": "password"
} - Response:
1
2
3{
"msg": "User registered"
} - Error Response:
1
2
3{
"msg": "User already exists"
}
User Login
- URL: /api/auth/login
- Method: POST
- Request Body:
1
2
3
4{
"email": "abc@email.com",
"password": "password"
} - Response:
1
2
3{
"msg": "JWT token",
} - Error Response:
1
2
3{
"msg": "Invalid credentials"
}
Get User Details
- URL: /api/auth/user
- Method: GET
- Request Header:
1
2
3{
"Authorization": "Bearer <JWT token>"
} - Response:
1
2
3
4
5
6{
"name": "name",
"lastname": "lastname",
"username": "username",
"email": "email"
} - Error Response:
1
2
3{
"msg": "Authorization denied"
}
Update User Details
- URL: /api/auth/user
- Method: PUT
- Request Header:
1
2
3{
"Authorization": "Bearer <JWT token>"
} - Request Body:
1
2
3
4
5
6{
"name": "firstname",
"lastname": "lastname",
"username": "username",
"email": "email"
} - Response:
1
2
3{
"msg": "User updated"
} - Error Response:
1
2
3{
"msg": "Authorization denied"
}