Day 7 of 100daysofcode : A Deep Dive into Authentication

Today’s focus was on a crucial aspect of user authentication. I built an authentication flow using the MERN stack (MongoDB, Express, React, Node.js). Here’s a breakdown of what I accomplished:

1-Backend (Node.js/Express):
-User Registration: Created API endpoints for user registration, receiving user data (username, password).
-Password Hashing (bcrypt): Instead of storing passwords directly in the database (which is a major security risk), I used bcrypt to hash passwords. Hashing transforms the password into a one-way string of characters, making it virtually impossible to reverse engineer the original password even if the database is compromised.
-JWT (JSON Web Tokens): After successful login, the server generates a JWT. This token is a compact, self-contained way to securely transmit information between parties as a JSON object. It contains information about the user (e.g., user ID) and is digitally signed, ensuring its integrity.
-Protected Routes: Implemented middleware to protect specific API routes. Only requests with a valid JWT in their header are allowed to access these routes.

2-Frontend (React):
-User Interface: Created forms for user registration and login.
-API Calls: Used axios to make API requests to the backend for registration and login.
-Token Storage: After successful login, the JWT is stored in the browser (local storage).
-Authorization: Included the JWT in the Authorization header of subsequent API requests to access protected resources.

3-Database (MongoDB):
-User Model: Created a schema to store user information, including the hashed password.

Why is this important?

Authentication is essential for securing web applications. It verifies the identity of users, preventing unauthorized access to sensitive data and functionalities. Using bcrypt for hashing and JWT for authorization are industry best practices for building secure authentication systems.

4-Example (Simplified flow):

  1. User submits login credentials on the React frontend.
  2. The frontend sends a request to the backend.
  3. The backend verifies the credentials and generates a JWT.
  4. The backend sends the JWT back to the frontend.
  5. The frontend stores the JWT.
  6. For subsequent requests to protected routes, the frontend includes the JWT in the Authorization header.
  7. The backend verifies the JWT before granting access.

100daysofcode lebanon-mug