phithi92/json-web-token

Handles the generation of JSON Web Tokens (JWT), including both JWS (JSON Web Signature) and JWE (JSON Web Encryption). Provides methods for creating and validating tokens.

0.2.1 2024-11-06 09:48 UTC

This package is auto-updated.

Last update: 2024-11-07 01:00:56 UTC


README

⚠️ Attention: This project is still in active development. Unexpected changes and errors may occur. ⚠️

JsonWebToken PHP Library

PHP Version Latest Version Software License Issues Build Total Downloads

The JsonWebToken class is a PHP library that facilitates the creation, signing, and validation of JSON Web Tokens (JWT), supporting both JSON Web Signature (JWS) and JSON Web Encryption (JWE). It provides a secure framework for generating tokens using various cryptographic algorithms to ensure data integrity and confidentiality.

Prerequisites

Before using this library, ensure your environment meets the following requirements:

  • PHP Version: 8.1 or higher
  • PHP Extensions: openssl
  • Composer: For managing dependencies

How the Library Works

This library operates according to key standards such as RFC 7519 (JWT), RFC 7515 (JWS), and RFC 7516 (JWE). During token signing (JWS), the library uses the HMAC algorithm (e.g., HS256) to create a signature by combining the token's header and payload with a secret key. This signature ensures the token's integrity, following the specifications in RFC 7515.

For token encryption (JWE), the payload is encrypted using algorithms like AES, as defined in RFC 7516, ensuring that only authorized recipients can decrypt and access the token's data. The entire process relies on Base64URL encoding (RFC 4648) to safely transmit the token over the web.

You can find more information about the JWT RFC here.

Installation

To integrate this library into your project, clone the repository or download the necessary files. It is recommended to use Composer for managing dependencies.

Step 1: Clone the Repository

Clone the project to your local environment:

git clone https://github.com/phithi92/json-web-token.git

or

You can install the library directly through Composer by running:

composer require phithi92/json-web-token

Step 2: Install Dependencies

Ensure Composer is installed, and run the following command to install the required dependencies:

composer install

The project uses the following dependencies (defined in composer.json):

  • PHPUnit: Used for unit testing to ensure robustness.

Usage Guide

Generating a JSON Web Token (JWT)

To generate a JWT, instantiate the JsonWebToken class and call the create() method. This method can generate either a signed (JWS) or encrypted (JWE) token.

use Phithi92\JsonWebToken\JsonWebToken;
use Phithi92\JsonWebToken\PayloadBuilder;
use Phithi92\JsonWebToken\Security\Openssl;

For RSA Algorithm

$algorithm = (new JwtAlgorithmManager())
    ->setPrivateKey('your-private-key')
    ->setPublicKey('your-public-key');

$payload = (new JwtPayload())
            ->setExpiration('+15 minutes');

$token = JwtTokenFactory::createToken($algorithm, $payload);

For Hmac Algorithm

$algorithm = (new JwtAlgorithmManager())
    ->setPassphrase('passphrase');

$payload = (new PayloadBuilder())
    ->setExpiration('+15min');

$token = JwtTokenFactory::createToken($algorithm, $payload);

Error Handling

When using the library, several exceptions may be thrown in cases of invalid input, such as:

  • InvalidTokenException: Thrown when the token provided is malformed or invalid, as per the JWT specifications in RFC 7519.
  • InvalidArgumentException: Raised when an invalid argument is passed to one of the methods, such as an unsupported algorithm or an empty payload.
  • HashErrorException: Triggered when an issue occurs during the HMAC signing process, ensuring that hashing operations conform to RFC 7515.
  • UnexpectedErrorException: A general exception that is raised when an unexpected error occurs during encoding, decoding, or encryption processes.
  • CipherErrorException: Raised when a problem occurs during token encryption or decryption, ensuring compliance with the JWE standard in RFC 7516.

You can catch these exceptions and handle them accordingly in your application:

try {
    $isValid = $jwt->validateToken($token, $key);
} catch (TokenException $e) {
    // Handle invalid token
} catch (PayloadException $e) {
    // Handle payload exeption
}catch (JsonException $e) {
    // Handle token json error
} catch () {
}

Supported Algorithms

The JsonWebToken class supports a variety of cryptographic algorithms for both JSON Web Signature (JWS) and JSON Web Encryption (JWE). Below are the lists of supported algorithms:

JSON Web Signature (JWS) Algorithms
JSON Web Encryption (JWE) Algorithms

This allows for proper error handling and ensures your application can respond appropriately to invalid or unsupported tokens.

Running Tests

Unit tests are included in the project to ensure the reliability of the library. These tests cover token creation, validation, and error handling. To run the tests, execute the following command:

vendor/bin/phpunit

All test cases are located in the tests/ directory and ensure that the class functions correctly under various scenarios.

Donation

Donations are a great way to support creators and their work. Every contribution helps sustain projects and shows appreciation for their efforts, making a real difference.