"Unlocking the Magic: How Node.js Keeps Your Website Safe with Secret Passcodes"

"Unlocking the Magic: How Node.js Keeps Your Website Safe with Secret Passcodes"

"Decoding the Mystery: Node.js and JWT - Your Key to Secure Online Hangouts"

In this blog, we're gonna talk about a fancy-sounding thing called "Node.js Authentication with JWT".

Practical example :

Imagine you're building a secret club on the internet, and you want to make sure only the right people get in. That's where authentication comes in, making sure folks are who they say they are.

So, we're using Node.js, which is like a superhero for building web stuff, and this thing called JSON Web Tokens (JWT), which is like a secret passcode to enter the club. We've got this special code written in Node.js that does all the heavy lifting.

First, we set up our club by bringing in some tools (modules) and creating a make-believe list of club members with their usernames and passwords. Then, we have a smart function that checks if someone is on our member list.

Now, when someone wants to join the club, they hit a special door (a route) called "/signIn". Our code checks if they're on the member list. If they are, we give them a super-secret token (like a stamp on their hand) using JWT. If not, we tell them they're not on the list.

But wait, we don't want just anyone to stroll into our secret rooms! So, we create another door ("/users") that only opens if they show us their special token. Inside, we check the token, and if it's valid, we let them in and say, "Hey, you're our friend, [username]!"

In the end, our Node.js superhero is always on the lookout, making sure only the cool folks with the right tokens get access to the secret club. And that's how we keep our internet hangout safe and sound! 🚀

Let`s code now...

Authentication is a crucial aspect of web development, ensuring that users are who they claim to be. In this blog post, we'll break down a simple Node.js code snippet that demonstrates user authentication using JSON Web Tokens (JWT). The code utilizes the Express.js framework, a popular choice for building web applications with Node.js

Setting Up the Environment

// Importing necessary modules
const express = require("express");
const app = express();
const port = 3000;

// Using the json middleware to parse incoming requests
app.use(express.json());

// Importing the JSON Web Token library and setting a secret password
const jwt = require("jsonwebtoken");
const jwtPassword = "1234";

// Mock database of users
const All_USERS = [
  {
    username: "bharat@example.com",
    password: "12345",
    name: "bharat",
  },
  {
    username: "vinay@example.com",
    password: "12345",
    name: "vinay",
  },
  {
    username: "ram@example.com",
    password: "12345",
    name: "ram",
  },
];

Here, we have set up an Express.js application, imported the necessary modules, and initialized a simple in-memory database (All_USERS) with user credentials.

User Authentication Logic

// Function to check if a user with the given credentials exists
const userExists = (username, password) => {
  let userExists = false;
  for (let i = 0; i < All_USERS.length; i++) {
    if (All_USERS[i].username == username && All_USERS[i].password == password) {
      userExists = true;
    }
  }
  return userExists;
};

// Route for user sign-in
app.post("/signIn", (req, res) => {
  const username = req.body.username;
  const password = req.body.password;

  if (!userExists(username, password)) {
    return res.json({ message: "User does not exist in our memory database" });
  }

  // Generating a JWT token and sending it in the response
  var token = jwt.sign({ username: username }, jwtPassword);
  return res.json({ token });
});

This part of the code defines a function userExists to check if a user with the provided credentials exists in the mock database. The /signIn route handles the user sign-in process. If the user exists, a JWT token is generated and sent as a response.

Protected Route

// Route to retrieve user information using the token
app.get("/users", (req, res) => {
  const token = req.headers.authorization;

  try {
    // Verifying the token and extracting the username
    const decoded = jwt.verify(token, jwtPassword);
    const username = decoded.username;
    res.json({ username });
  } catch (error) {
    // Handling token verification errors
    return res.status(400).json({
      message: "Your Token Is Not Valid, Please Put Correct token",
    });
  }
});

// Listening on the specified port
app.listen(port);

Finally, the /users route is a protected route that requires a valid JWT token in the Authorization header. The server verifies the token and responds with the associated username or an error message if the token is invalid.

Understanding this simple Node.js authentication code can provide a foundation for building more secure and robust authentication systems in your web applications.

"Small steps today pave the way for big victories tomorrow."

#Keep coding #keepLearinig