Jwt Implementation

ยท

4 min read

Jwt Implementation

(CREATE + VERIFY)

Working with JWT (JSON Web Tokens) in a Node.js application involves several steps:

  1. generating a token

  2. sending it to the client

  3. receiving and verifying it on the server

  4. and extracting the payload information.

Below is an example of how you might implement this in a Node.js application using Express and the jsonwebtoken library.

First, install the necessary dependencies:

npm install express jsonwebtoken

Then, create a simple Node.js script. Here's an example:

const express = require("express");
const jwt = require("jsonwebtoken");

const app = express();
const port = 3000;

// Secret key for signing and verifying the JWT
const secretKey = "your_secret_key";

// Route to generate and send a JWT
app.get("/login", (req, res) => {
  const payload = { userId: "123456", username: "exampleUser", role: "user" };
  const options = { expiresIn: "1h" };
  const token = jwt.sign(payload, secretKey, options);
  res.json({ token });
});

// Middleware to check JWT on protected routes
const authenticateJWT = (req, res, next) => {
  const authHeader = req.headers.authorization;
  console.log(authHeader);

  if (!authHeader) {
    return res.sendStatus(401); // Unauthorized
  }

  const token = authHeader.split(" ")[1];
  jwt.verify(token, secretKey, (err, user) => {
    if (err) {
      return res.sendStatus(403); // Forbidden
    }

    req.user = user;
    next();
  });
};

// Protected route that requires a valid JWT
app.get("/protected-route", authenticateJWT, (req, res) => {
  res.json({ message: "Access granted to protected route", user: req.user });
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

In this example:

  1. We set up a simple Express server.

  2. The /login route seamlessly crafts a JWT with a predefined payload, dispatching it as a JSON response to establish a user session. This session informs the server of incoming requests from registered users until the token expires, prompting the need for reauthentication upon expiration.

  3. The /protected-route is a protected route that requires a valid JWT. It uses the authenticateJWT middleware to verify the token.

  4. To generate, secure secret key, you can use OpenSSL

    In bash/linux terminal:

     openssl rand -base64 32
    

To test this example:

  1. Start the server: node your-file-name.js

  2. Visit http://localhost:3000/generate-token in your browser to generate a token.

  3. Copy the token.

  4. Make a GET request to http://localhost:3000/protected-route with the token included in the Authorization header.

This is a basic example, and in a real-world application, you would likely use more secure methods for storing and managing your secret key, handle user authentication, and use HTTPS for secure communication.

(DELETE)

JWTs (JSON Web Tokens) are stateless and stored on the client side. They are typically deleted by removing them from the client, such as clearing them from cookies or local storage. The server doesn't store information about issued tokens, so deletion is handled on the client.

Here are common methods for "deleting" a JWT token:

  1. Clearing Cookies: If your JWT is stored in an HTTP-only cookie, you can clear the cookie to "delete" the token. This is a common practice for session-based authentication.

     res.clearCookie('jwtToken'); // Assuming 'jwtToken' is the cookie name
    
  2. Removing from Local Storage: If your JWT is stored in the browser's local storage, you can remove it like this:

     localStorage.removeItem('jwtToken'); // Assuming 'jwtToken' is the local storage key
    
  3. Expiring the Token: Set a short expiration time when creating the token. This way, the token will automatically become invalid after a certain period, requiring the user to re-authenticate.

     const options = { expiresIn: '15m' }; // Set a short expiration time, e.g., 15 minutes
     const token = jwt.sign(payload, secretKey, options);
    
  4. Handling Logout on the Server: While the server doesn't "delete" a token, you can implement a server-side action upon user logout. For example, you might blacklist or invalidate the token on the server, preventing it from being accepted for future requests.

Remember that when you "delete" a token on the client side, it's more about removing it from the client's storage or memory. The server doesn't actively delete or invalidate issued tokens but relies on their expiration and the trustworthiness of the client to stop using them after logout or other actions.

ย