PHPackages                             vaibhavpandeyvpz/jweety - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. vaibhavpandeyvpz/jweety

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

vaibhavpandeyvpz/jweety
=======================

Simple JWT (RFC 7519) encoding/decoding and validation library, for PHP &gt;= 8.2.

2.0.0(4mo ago)921.2k↓50%21MITPHPPHP ^8.2CI passing

Since Oct 9Pushed 4mo ago2 watchersCompare

[ Source](https://github.com/vaibhavpandeyvpz/jweety)[ Packagist](https://packagist.org/packages/vaibhavpandeyvpz/jweety)[ Docs](https://github.com/vaibhavpandeyvpz/jweety)[ RSS](/packages/vaibhavpandeyvpz-jweety/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (3)Versions (3)Used By (1)

jweety
======

[](#jweety)

[![Latest Version](https://camo.githubusercontent.com/2fc435dc9d97a99a1901e7f27e000effd94338f793244ed328ef174ccc745bba/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7661696268617670616e64657976707a2f6a77656574792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/vaibhavpandeyvpz/jweety)[![Downloads](https://camo.githubusercontent.com/5b16351ceeea798d89269c0f07bd9b5702ca1b96d8c07490ac1da7e03f3fcad4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7661696268617670616e64657976707a2f6a77656574792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/vaibhavpandeyvpz/jweety)[![PHP Version](https://camo.githubusercontent.com/375c10e4d04d52d38a1ab66df460c134290480b490fb876a84a3b521ff06b04e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f7661696268617670616e64657976707a2f6a77656574792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/vaibhavpandeyvpz/jweety)[![License](https://camo.githubusercontent.com/a43da7684804e82970cf4e3a333da3fcc7a219eacc695b0327f552cdb4ae96b4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f7661696268617670616e64657976707a2f6a77656574792e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![Build Status](https://camo.githubusercontent.com/dd5ad98250051bc4820c5962f9e70c3aa531c3a1d891ba7e76aeb1f8a6b649d0/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7661696268617670616e64657976707a2f6a77656574792f74657374732e796d6c3f6272616e63683d6d6173746572267374796c653d666c61742d737175617265)](https://github.com/vaibhavpandeyvpz/jweety/actions)

A simple, modern [JWT](https://jwt.io/) ([RFC 7519](https://tools.ietf.org/html/rfc7519)) encoding/decoding and validation library for PHP 8.2+.

Features
--------

[](#features)

- ✅ **RFC 7519 Compliant** - Full support for JSON Web Token standard
- ✅ **Modern PHP 8.2+** - Uses latest PHP features (enums, readonly properties, match expressions)
- ✅ **HMAC Algorithms** - Supports HS256, HS384, and HS512
- ✅ **Type Safe** - Comprehensive type hints and strict types
- ✅ **Claim Validation** - Automatic validation of `exp`, `iat`, and `nbf` claims
- ✅ **PSR-20 Clock Support** - Use any PSR-20 clock implementation for testable time-based validation
- ✅ **Exception Handling** - Specific exception types for different error scenarios
- ✅ **100% Test Coverage** - Fully tested with comprehensive test suite

Installation
------------

[](#installation)

Install via Composer:

```
composer require vaibhavpandeyvpz/jweety
```

Quick Start
-----------

[](#quick-start)

### Creating a Token

[](#creating-a-token)

```
use Jweety\Encoder;
use Jweety\Algorithm;

// Initialize encoder with secret key
$encoder = new Encoder('your-secret-key-here');

// Create claims
$claims = [
    'sub' => 'user123',
    'name' => 'John Doe',
    'iat' => time(),
    'exp' => time() + 3600, // Expires in 1 hour
];

// Generate token (defaults to HS256)
$token = $encoder->stringify($claims);
echo $token; // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
```

### Parsing and Validating a Token

[](#parsing-and-validating-a-token)

```
use Jweety\Encoder;
use Jweety\Exception\InvalidTokenException;
use Jweety\Exception\TokenExpiredException;
use Jweety\Exception\InvalidSignatureException;

$encoder = new Encoder('your-secret-key-here');

try {
    // Parse and validate token (validates signature and claims by default)
    $claims = $encoder->parse($token);

    echo $claims->sub;    // 'user123'
    echo $claims->name;    // 'John Doe'

} catch (TokenExpiredException $e) {
    // Token has expired
    echo "Token expired: " . $e->getMessage();

} catch (InvalidSignatureException $e) {
    // Signature verification failed
    echo "Invalid signature: " . $e->getMessage();

} catch (InvalidTokenException $e) {
    // Token is malformed or invalid
    echo "Invalid token: " . $e->getMessage();
}
```

### Parsing Without Claim Validation

[](#parsing-without-claim-validation)

```
// Parse token without validating claims (exp, iat, nbf)
$claims = $encoder->parse($token, false);
```

Usage Examples
--------------

[](#usage-examples)

### Using Different Algorithms

[](#using-different-algorithms)

```
use Jweety\Encoder;
use Jweety\Algorithm;

$encoder = new Encoder('your-secret-key');

// Using enum
$token = $encoder->stringify($claims, Algorithm::HS256);

// Using string
$token = $encoder->stringify($claims, 'HS384');

// Using HS512
$token = $encoder->stringify($claims, Algorithm::HS512);
```

### Restricting Allowed Algorithms

[](#restricting-allowed-algorithms)

```
use Jweety\Encoder;
use Jweety\Algorithm;

// Only allow HS256
$encoder = new Encoder('your-secret-key', Algorithm::HS256);

// Allow multiple algorithms
$encoder = new Encoder('your-secret-key', [Algorithm::HS256, Algorithm::HS384]);

// Using strings
$encoder = new Encoder('your-secret-key', ['HS256', 'HS512']);
```

### Using PSR-20 Clock for Testing

[](#using-psr-20-clock-for-testing)

The library supports PSR-20 Clock implementations for controllable time in tests:

```
use Jweety\Encoder;
use Samay\FrozenClock; // or any PSR-20 Clock implementation

// Create a frozen clock for testing
$clock = new FrozenClock(new \DateTimeImmutable('2024-01-01 12:00:00'));
$encoder = new Encoder('your-secret-key', [Algorithm::HS256], $clock);

// Now all time-based validations use the frozen time
$claims = [
    'sub' => 'user123',
    'exp' => $clock->now()->getTimestamp() + 3600, // 1 hour from frozen time
];

$token = $encoder->stringify($claims);
$parsed = $encoder->parse($token); // Uses frozen clock for validation
```

### Custom Token Type

[](#custom-token-type)

```
$token = $encoder->stringify($claims, Algorithm::HS256, 'CustomType');
```

### Manual Claim Validation

[](#manual-claim-validation)

```
use Jweety\Encoder;
use Jweety\Exception\TokenExpiredException;

$encoder = new Encoder('your-secret-key');

// Parse without validation
$claims = $encoder->parse($token, false);

// Manually validate claims
try {
    $encoder->assert($claims);
    echo "Token is valid";
} catch (TokenExpiredException $e) {
    echo "Token expired";
}
```

### Working with Standard JWT Claims

[](#working-with-standard-jwt-claims)

```
$claims = [
    // Subject - The user ID
    'sub' => 'user123',

    // Issued At - When the token was issued
    'iat' => time(),

    // Expiration Time - When the token expires
    'exp' => time() + 3600,

    // Not Before - Token cannot be used before this time
    'nbf' => time(),

    // Issuer - Who issued the token
    'iss' => 'https://example.com',

    // Audience - Who the token is intended for
    'aud' => 'https://api.example.com',

    // JWT ID - Unique identifier for the token
    'jti' => uniqid('', true),

    // Custom claims
    'role' => 'admin',
    'permissions' => ['read', 'write'],
];

$token = $encoder->stringify($claims);
```

API Reference
-------------

[](#api-reference)

### Encoder Class

[](#encoder-class)

#### Constructor

[](#constructor)

```
public function __construct(
    #[\SensitiveParameter]
    string $key,
    array|Algorithm|string $algorithms = [Algorithm::HS256, Algorithm::HS384, Algorithm::HS512],
    ?ClockInterface $clock = null
)
```

- `$key` - Secret key for HMAC signing (marked as sensitive)
- `$algorithms` - Allowed algorithms (defaults to all supported)
- `$clock` - Optional PSR-20 Clock implementation for time-based claim validation. If not provided, uses system time via `time()`. Useful for testing with controllable time.

#### Methods

[](#methods)

##### `stringify()`

[](#stringify)

Creates a JWT token from claims.

```
public function stringify(
    array|object $claims,
    Algorithm|string $alg = Algorithm::HS256,
    string $typ = 'JWT'
): string
```

**Parameters:**

- `$claims` - Claims to encode (array or object)
- `$alg` - Algorithm to use (enum or string)
- `$typ` - Token type (defaults to 'JWT')

**Returns:** JWT token string

**Throws:** `UnsupportedAlgorithmException` if algorithm is not allowed/supported

##### `parse()`

[](#parse)

Parses and validates a JWT token.

```
public function parse(string $token, bool $assert = true): object
```

**Parameters:**

- `$token` - JWT token string
- `$assert` - Whether to validate claims (defaults to true)

**Returns:** Decoded claims object

**Throws:**

- `InvalidTokenException` - Token is malformed or invalid
- `InvalidSignatureException` - Signature verification failed
- `TokenExpiredException` - Token has expired (if `$assert` is true)

##### `assert()`

[](#assert)

Validates JWT claims.

```
public function assert(object $claims): void
```

**Parameters:**

- `$claims` - Claims object to validate

**Throws:**

- `TokenExpiredException` - Token expired
- `InvalidTokenException` - Invalid claims (iat in future, nbf not met)

##### `encode()` / `decode()`

[](#encode--decode)

Static utility methods for base64url encoding/decoding.

```
public static function encode(string $payload): string
public static function decode(string $payload): string
```

### Algorithm Enum

[](#algorithm-enum)

```
enum Algorithm: string
{
    case HS256 = 'HS256';
    case HS384 = 'HS384';
    case HS512 = 'HS512';

    public function hashMethod(): string;
    public static function values(): array;
}
```

Exception Handling
------------------

[](#exception-handling)

The library provides specific exception types for different error scenarios:

- **`InvalidTokenException`** - Token is malformed, invalid encoding, or has invalid claims
- **`TokenExpiredException`** - Token has expired (exp claim)
- **`InvalidSignatureException`** - Signature verification failed
- **`UnsupportedAlgorithmException`** - Algorithm is not allowed or not supported

All exceptions extend standard PHP exceptions, so you can catch them specifically or use a general exception handler.

Security Considerations
-----------------------

[](#security-considerations)

1. **Secret Key Management**: Always use strong, randomly generated secret keys
2. **Key Storage**: Never commit secret keys to version control
3. **HTTPS**: Always transmit tokens over HTTPS
4. **Algorithm Restriction**: Restrict allowed algorithms to only what you need
5. **Token Expiration**: Always set appropriate expiration times
6. **Sensitive Data**: Don't store sensitive information in token payload (it's base64 encoded, not encrypted)

Requirements
------------

[](#requirements)

- PHP &gt;= 8.2
- Composer (for installation)

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

Support
-------

[](#support)

For issues, questions, or contributions, please visit the [GitHub repository](https://github.com/vaibhavpandeyvpz/jweety).

###  Health Score

54

—

FairBetter than 97% of packages

Maintenance75

Regular maintenance activity

Popularity33

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity77

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~3001 days

Total

2

Last Release

136d ago

Major Versions

1.0 → 2.0.02025-12-28

PHP version history (2 changes)1.0PHP ^5.3||^7.0

2.0.0PHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/4cf0d090043e41bf330d9ef1d0e7e799f1946145ddb3569ba38a003d47929378?d=identicon)[vaibhavpandeyvpz](/maintainers/vaibhavpandeyvpz)

---

Top Contributors

[![vaibhavpandeyvpz](https://avatars.githubusercontent.com/u/6647172?v=4)](https://github.com/vaibhavpandeyvpz "vaibhavpandeyvpz (3 commits)")

---

Tags

authenticationjsonwebtokenjwtphpsecurityjwtRFC7519AuthenticationJSON Web Tokenhmac

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/vaibhavpandeyvpz-jweety/health.svg)

```
[![Health](https://phpackages.com/badges/vaibhavpandeyvpz-jweety/health.svg)](https://phpackages.com/packages/vaibhavpandeyvpz-jweety)
```

###  Alternatives

[tymon/jwt-auth

JSON Web Token Authentication for Laravel and Lumen

11.5k49.1M350](/packages/tymon-jwt-auth)[php-open-source-saver/jwt-auth

JSON Web Token Authentication for Laravel and Lumen

8359.8M53](/packages/php-open-source-saver-jwt-auth)[auth0/auth0-php

PHP SDK for Auth0 Authentication and Management APIs.

40820.2M68](/packages/auth0-auth0-php)[auth0/login

Auth0 Laravel SDK. Straight-forward and tested methods for implementing authentication, and accessing Auth0's Management API endpoints.

2745.0M3](/packages/auth0-login)[auth0/symfony

Symfony SDK for Auth0 Authentication and Management APIs.

128738.1k](/packages/auth0-symfony)[auth0/wordpress

WordPress Plugin for Auth0

17419.5k](/packages/auth0-wordpress)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
