DEV Community

Md. Asif Rahman
Md. Asif Rahman

Posted on

Build a JWT Generator in PHP from Scratch: A Step-by-Step Guide with Examples

In today's digital world, security is a major concern for web applications. With the rise of RESTful APIs, JSON Web Tokens (JWTs) have become a popular way to authenticate and authorize users in web applications. In this blog post, we will explore a PHP class that can generate, validate, and decode JWTs.

The JwtGenerator Class:



<?php
namespace RestApi;
class JwtGenerator
{
    private $key;

    public function __construct(string $key)
    {
        $this->key = $key;
    }

    public function generateToken(array $payload, int $exp = 3600): string
    {
        $header = base64_encode(json_encode(['alg' => 'HS256', 'typ' => 'JWT']));
        $issuedAt = time();
        $expiresAt = $issuedAt + $exp;

        $payload = base64_encode(json_encode($payload));

        $signature = hash_hmac('sha256', "$header.$payload", $this->key, true);
        $signature = base64_encode($signature);

        return "$header.$payload.$signature";
    }

    public function validateToken(string $token): bool
    {
        $token_parts = explode('.', $token);
        if (count($token_parts) !== 3) {
            return false;
        }

        $header = base64_decode($token_parts[0]);
        $payload = base64_decode($token_parts[1]);
        $signature = base64_decode($token_parts[2]);

        $header_data = json_decode($header);
        if (!isset($header_data->alg) || $header_data->alg !== 'HS256') {
            return false;
        }

        $valid_signature = hash_hmac('sha256', "$header.$payload", $this->key, true);
        $valid_signature = base64_encode($valid_signature);

        return ($signature === $valid_signature);
    }

    public function decodeToken(string $token): object
    {
        $payload = base64_decode(explode('.', $token)[1]);
        return json_decode($payload);
    }
}


Enter fullscreen mode Exit fullscreen mode

The JwtGenerator class is a PHP class that can be used to generate, validate, and decode JWTs. The class takes in a private key that is used to sign the token. Here's a breakdown of the class and its methods:

Constructor:

The constructor method takes in a private key that is used to sign the token.

Image description

generateToken():

The generateToken method takes in an array of data that you want to include in the token's payload and an optional expiration time (in seconds). The method then creates a header and a payload and signs the token with the private key. Finally, the method returns the signed token.

Image description

validateToken():

The validateToken method takes in a token and verifies its signature using the private key. The method returns true if the signature is valid and false otherwise.

Image description

decodeToken():

The decodeToken method takes in a token and decodes its payload. The method returns the decoded payload as an object.

Image description

Here's an example of how to use the JwtGenerator class to generate a JWT token, validate it, and decode it:

Image description

In this example, we first include the JwtGenerator class and initialize it with a secret key. Then we set the payload data and generate a token using the generateToken method, with an expiration time of 1 hour (3600 seconds). We print the generated token to the console.

Next, we validate the token using the validateToken method and print a message indicating whether the token is valid or not.

Finally, we decode the token payload using the decodeToken method and print the decoded payload to the console.

Conclusion:

JWTs are a popular way to authenticate and authorize users in web applications. The JwtGenerator class is a PHP class that can be used to generate, validate, and decode JWTs. It provides a simple and secure way to implement authentication and authorization in your web application. I hope this blog post has been informative and has provided you with a better understanding of JWTs and how to implement them in PHP.

Top comments (0)