Building Custom JWT Debugger Tool using PHP

0
28

In the world of modern web development, JSON Web Tokens (JWTs) have become a cornerstone for secure authentication and data exchange. Whether you’re building a single-page application, a mobile app, or a microservices architecture, JWTs play a crucial role in ensuring secure communication between clients and servers. However, working with JWTs can sometimes be challenging, especially when debugging or testing tokens. This is where a JWT Debugger tool comes in handy.

In this article, we’ll walk you through the steps to build a simple yet powerful JWT Debugger tool. This tool will allow you to encode and decode JWTs effortlessly, making it easier to test and debug your tokens during development. By the end of this guide, you’ll have a fully functional web-based tool that you can use to streamline your JWT-related workflows.

Follow this video for complete guidance:

What is a JWT Debugger?

A JWT Debugger is a tool that helps developers encode and decode JSON Web Tokens. Encoding a JWT involves converting a JSON payload into a secure token, while decoding involves breaking down the token to reveal its header, payload, and signature. This process is essential for debugging, testing, and understanding how JWTs work under the hood.

Our JWT Debugger tool will provide two main functionalities:

  1. Encoding: Convert a JSON payload into a JWT using a secret key.
  2. Decoding: Break down a JWT into its components (header, payload, and signature) for inspection.

Step 1: Setting Up the Backend

The backend of our JWT Debugger is powered by PHP, a widely-used server-side scripting language. The backend handles the encoding and decoding of JWTs using the firebase/php-jwt library, which is a popular PHP library for working with JWTs.

Use Firebase JWT for encoding/decoding. Install it via Composer:

composer require firebase/php-jwt

Then use following code for jwt.php

<?php
require 'vendor/autoload.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

header("Content-Type: application/json");

$action = $_POST['action'] ?? null;
$secret = $_POST['secret'] ?? 'default_secret';

$response = [];

if ($action === 'encode') {
    $payload = json_decode($_POST['payload'], true);
    if (!$payload) {
        echo json_encode(["error" => "Invalid JSON payload"]);
        exit;
    }
    $jwt = JWT::encode($payload, $secret, 'HS256');
    $response = ["jwt" => $jwt];

} elseif ($action === 'decode') {
    $token = $_POST['jwt'] ?? '';
    try {
        $decoded = JWT::decode($token, new Key($secret, 'HS256'));
        $response = [
            "header" => json_decode(base64_decode(explode('.', $token)[0]), true),
            "payload" => (array)$decoded,
            "signature" => explode('.', $token)[2] ?? ''
        ];
    } catch (Exception $e) {
        $response = ["error" => "Invalid JWT"];
    }
}

echo json_encode($response);
?>

Finally code for index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JWT Debugger</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="min-h-screen bg-gradient-to-br from-blue-900 to-green-900 flex items-center justify-center p-4">
    <div class="w-full max-w-4xl rounded-2xl shadow-2xl overflow-hidden">
        <div class="bg-blue-700 text-white p-6">
            <h2 class="text-3xl font-bold">JWT Debugger</h2>
            <p class="text-white/80">Encode and Decode JSON Web Tokens</p>
        </div>
        
        <div class="p-6 grid md:grid-cols-2 gap-6">
            <div class="p-4 rounded-xl border border-white/10">
                <h3 class="text-xl font-semibold text-blue-400 mb-4">Encode JWT</h3>
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm text-white/80 mb-2">Secret Key</label>
                        <input 
                            type="text" 
                            id="secret" 
                            class="w-full px-3 py-2 bg-white/10 text-white rounded-lg border border-white/20 focus:outline-none focus:ring-2 focus:ring-blue-500"
                            value="default_secret"
                        >
                    </div>
                    <div>
                        <label class="block text-sm text-white/80 mb-2">JWT Payload (JSON)</label>
                        <textarea 
                            id="payload" 
                            rows="4" 
                            class="w-full px-3 py-2 bg-white/10 text-white rounded-lg border border-white/20 font-mono focus:outline-none focus:ring-2 focus:ring-blue-500"
                        >{ 
  "user": "JohnDoe", 
  "role": "admin" 
}</textarea>
                    </div>
                    <button 
                        onclick="encodeJWT()" 
                        class="w-full bg-blue-600 text-white py-2 rounded-lg hover:bg-blue-500 transition"
                    >
                        Generate Token
                    </button>
                </div>
            </div>

            <div class="p-4 rounded-xl border border-white/10">
                <h3 class="text-xl font-semibold text-green-400 mb-4">Decode JWT</h3>
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm text-white/80 mb-2">JWT Token</label>
                        <textarea 
                            id="jwt" 
                            rows="4" 
                            placeholder="Paste JWT here..." 
                            class="w-full px-3 py-2 bg-white/10 text-white rounded-lg border border-white/20 font-mono focus:outline-none focus:ring-2 focus:ring-green-500"
                        ></textarea>
                    </div>
                    <button 
                        onclick="decodeJWT()" 
                        class="w-full bg-green-600 text-white py-2 rounded-lg hover:bg-green-500 transition"
                    >
                        Decode Token
                    </button>
                </div>
            </div>
        </div>

        <div class="p-6">
            <h3 class="text-xl text-white/80 font-semibold mb-4">Output</h3>
            <pre 
                id="output" 
                class="bg-white/10 text-white font-mono text-sm p-4 rounded-lg max-h-48 overflow-y-auto"
            ></pre>
        </div>
    </div>

    <script>
        async function encodeJWT() {
            const payload = document.getElementById("payload").value.trim();
            const secret = document.getElementById("secret").value.trim();
            const response = await fetch("jwt.php", {
                method: "POST",
                headers: { "Content-Type": "application/x-www-form-urlencoded" },
                body: `action=encode&payload=${encodeURIComponent(payload)}&secret=${encodeURIComponent(secret)}`
            });
            const data = await response.json();
            document.getElementById("output").innerText = data.jwt || data.error;
        }

        async function decodeJWT() {
            const jwt = document.getElementById("jwt").value.trim();
            const secret = document.getElementById("secret").value.trim();
            const response = await fetch("jwt.php", {
                method: "POST",
                headers: { "Content-Type": "application/x-www-form-urlencoded" },
                body: `action=decode&jwt=${encodeURIComponent(jwt)}&secret=${encodeURIComponent(secret)}`
            });
            const data = await response.json();
            document.getElementById("output").innerText = JSON.stringify(data, null, 4);
        }
    </script>
</body>
</html>

 

ALSO READ  Develop a Custom Search Engine Using PHP and MySQL

The backend script receives requests from the frontend, processes the JWT operations, and returns the results in JSON format. It supports two actions:

  • Encode: Takes a JSON payload and a secret key, and generates a JWT.
  • Decode: Takes a JWT and a secret key, and returns the decoded header, payload, and signature.

The backend ensures that the operations are secure and efficient, providing a reliable foundation for the frontend interface.

Step 2: Designing the Frontend

The frontend of our JWT Debugger is built using HTML, Tailwind CSS, and JavaScript. It provides a clean and intuitive user interface for interacting with the backend. The design is modern and responsive, ensuring that the tool works seamlessly on both desktop and mobile devices.

The frontend consists of two main sections:

  1. Encode JWT: This section allows users to input a JSON payload and a secret key to generate a JWT. The payload is pre-filled with an example to help users understand the required format.
  2. Decode JWT: This section allows users to paste a JWT and decode it to view its header, payload, and signature.

The output of both operations is displayed in a dedicated output area, making it easy for users to view and copy the results.

Step 3: Connecting the Frontend and Backend

The frontend and backend are connected using JavaScript’s Fetch API. When a user clicks the “Generate Token” or “Decode Token” button, the frontend sends a POST request to the backend with the necessary data (payload, JWT, and secret key). The backend processes the request and returns the result, which is then displayed on the frontend.

ALSO READ  Create your own Time Machine for Websites

This seamless integration ensures that the tool is fast, responsive, and easy to use. Users can encode and decode JWTs in real-time without needing to refresh the page.

Step 4: Testing and Debugging

Once the tool is built, it’s important to test it thoroughly to ensure that it works as expected. You can test the tool by encoding and decoding various JWTs, using different payloads and secret keys. Pay attention to edge cases, such as invalid JSON payloads or incorrect secret keys, to ensure that the tool handles errors gracefully.

The output section of the tool provides detailed information about the JWT, including its header, payload, and signature. This makes it easy to debug issues and verify the integrity of your tokens.

Step 5: Deploying the Tool

After testing, the final step is to deploy the JWT Debugger tool so that it can be accessed online. You can deploy the tool on any web server that supports PHP, such as Apache or Nginx. Alternatively, you can use a cloud hosting service like AWS, Google Cloud, or Heroku for deployment.

Once deployed, the tool can be used by developers worldwide to encode and decode JWTs, making it a valuable resource for the developer community.

Why Use a JWT Debugger?

A JWT Debugger tool is an essential addition to any developer’s toolkit. Here are some reasons why you should consider using one:

  1. Simplify Debugging: Quickly inspect the contents of a JWT to identify issues.
  2. Test Payloads: Experiment with different payloads to see how they affect the generated token.
  3. Learn JWTs: Gain a deeper understanding of how JWTs work by encoding and decoding tokens.
  4. Save Time: Avoid manual decoding and encoding, which can be time-consuming and error-prone.
ALSO READ  How to get MAC Address of all Devices in my Network using PHP ?

Building a JWT Debugger tool is a rewarding project that can help you and other developers work more efficiently with JWTs. By following the steps outlined in this article, you can create a powerful and user-friendly tool that simplifies the process of encoding and decoding JWTs. Whether you’re a seasoned developer or just starting out, this project is a great way to enhance your skills and contribute to the developer community.

So, what are you waiting for? Start building your JWT Debugger today and take your JWT game to the next level!

TagsjwtPHP

Comments are closed.