PHPackages                             sherinbloemendaal/yii2-jwt - 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. sherinbloemendaal/yii2-jwt

ActiveYii2-extension[Authentication &amp; Authorization](/categories/authentication)

sherinbloemendaal/yii2-jwt
==========================

JWT Authentication for Yii2

1.0.1(1y ago)0427MITPHPPHP ^8.1CI passing

Since Jun 12Pushed 1y agoCompare

[ Source](https://github.com/SherinBloemendaal/yii2-jwt)[ Packagist](https://packagist.org/packages/sherinbloemendaal/yii2-jwt)[ RSS](/packages/sherinbloemendaal-yii2-jwt/feed)WikiDiscussions main Synced 3w ago

READMEChangelog (2)Dependencies (5)Versions (3)Used By (0)

Yii2 JWT
========

[](#yii2-jwt)

[![Packagist Version](https://camo.githubusercontent.com/ae0eca865c1ba1b7dae29e61069f548e71d65f5105b308a9add607c93b69b028/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f73686572696e626c6f656d656e6461616c2f796969322d6a77743f7374796c653d666f722d7468652d6261646765266c6f676f3d7061636b6167697374)](https://camo.githubusercontent.com/ae0eca865c1ba1b7dae29e61069f548e71d65f5105b308a9add607c93b69b028/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f73686572696e626c6f656d656e6461616c2f796969322d6a77743f7374796c653d666f722d7468652d6261646765266c6f676f3d7061636b6167697374)[![CI Status](https://camo.githubusercontent.com/4e67013ca07e77b726efcfe928e8f971d5760350c5255901178dcc5c40505758/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f73686572696e626c6f656d656e6461616c2f796969322d6a77742f63692e796d6c3f6272616e63683d6d61696e267374796c653d666f722d7468652d6261646765266c6f676f3d676974687562)](https://camo.githubusercontent.com/4e67013ca07e77b726efcfe928e8f971d5760350c5255901178dcc5c40505758/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f73686572696e626c6f656d656e6461616c2f796969322d6a77742f63692e796d6c3f6272616e63683d6d61696e267374796c653d666f722d7468652d6261646765266c6f676f3d676974687562)[![License](https://camo.githubusercontent.com/52eda7bfc1b182e4e29e1a1058bc859717aacbffb095b635670df2d9c87424d0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f73686572696e626c6f656d656e6461616c2f796969322d6a77743f7374796c653d666f722d7468652d6261646765)](https://camo.githubusercontent.com/52eda7bfc1b182e4e29e1a1058bc859717aacbffb095b635670df2d9c87424d0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f73686572696e626c6f656d656e6461616c2f796969322d6a77743f7374796c653d666f722d7468652d6261646765)[![PHP Version](https://camo.githubusercontent.com/9e53ce95644177a867a21e9bcf2fa69e607ea5a26fe9583a3f29c096bb61fbaf/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f73686572696e626c6f656d656e6461616c2f796969322d6a77743f7374796c653d666f722d7468652d6261646765266c6f676f3d706870)](https://camo.githubusercontent.com/9e53ce95644177a867a21e9bcf2fa69e607ea5a26fe9583a3f29c096bb61fbaf/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f73686572696e626c6f656d656e6461616c2f796969322d6a77743f7374796c653d666f722d7468652d6261646765266c6f676f3d706870)

**🔐 Modern, type-safe JWT for Yii2**

*Seamless [lcobucci/jwt](https://github.com/lcobucci/jwt) 5.x integration for Yii 2.0 with PHP 8.1+ support*

[Installation](#-installation) • [Quick Start](#-quick-start) • [Examples](#-examples) • [API Reference](#-api-reference) • [Contributing](#-contributing)

---

📋 Table of Contents
-------------------

[](#-table-of-contents)

- [✨ Features](#-features)
- [📋 Requirements](#-requirements)
- [📦 Installation](#-installation)
- [🚀 Quick Start](#-quick-start)
- [🔧 Configuration](#-configuration)
- [💡 Examples](#-examples)
- [🔑 Supported Algorithms](#-supported-algorithms)
- [📚 API Reference](#-api-reference)
- [🛠 Troubleshooting](#-troubleshooting)
- [🤝 Contributing](#-contributing)
- [📄 License](#-license)

---

✨ Features
----------

[](#-features)

- 🔒 **Secure JWT Operations** - Create, parse, and validate JWT tokens with industry-standard security
- 🧩 **Modern PHP** - Native PHP 8.1+ types, enums, and attributes
- 🛡️ **Multiple Algorithms** - HMAC, RSA, ECDSA support with easy configuration
- ⚡ **Yii2 Integration** - Seamless component integration with dependency injection
- 🧑‍💻 **Developer Friendly** - Clean, IDE-friendly API with full type hints
- 🔄 **Flexible Configuration** - Support for various key formats and validation constraints
- 🌐 **REST Ready** - Built-in HTTP Bearer authentication filter

---

📋 Requirements
--------------

[](#-requirements)

- [![PHP](https://camo.githubusercontent.com/ea03c620f2b2b21efdfa9504904ca1103c89a17f7720f265d0f1147337e6d409/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e312b2d3737374242343f7374796c653d666c6174266c6f676f3d706870)](https://camo.githubusercontent.com/ea03c620f2b2b21efdfa9504904ca1103c89a17f7720f265d0f1147337e6d409/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e312b2d3737374242343f7374796c653d666c6174266c6f676f3d706870) PHP 8.1 or higher
- [![Yii2](https://camo.githubusercontent.com/b9040539f7addb227a93812162b6f32c1727599c73229efef7d6e74a391c9cee/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f596969322d322e302e35322b2d3030373345363f7374796c653d666c6174)](https://camo.githubusercontent.com/b9040539f7addb227a93812162b6f32c1727599c73229efef7d6e74a391c9cee/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f596969322d322e302e35322b2d3030373345363f7374796c653d666c6174) Yii2 ^2.0.52
- [![JWT](https://camo.githubusercontent.com/effef54ef5fd59d0e4f6edaf233fda7d72c376aa03c5b9834739a872744f0731/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c636f62756363692f6a77742d352e302b2d3030303030303f7374796c653d666c6174)](https://camo.githubusercontent.com/effef54ef5fd59d0e4f6edaf233fda7d72c376aa03c5b9834739a872744f0731/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c636f62756363692f6a77742d352e302b2d3030303030303f7374796c653d666c6174) lcobucci/jwt ^5.0

### Optional Dependencies

[](#optional-dependencies)

For time-based validation constraints, you may want to install a PSR-20 clock implementation:

```
composer require lcobucci/clock
```

---

📦 Installation
--------------

[](#-installation)

Install via Composer:

```
composer require sherinbloemendaal/yii2-jwt
```

---

🚀 Quick Start
-------------

[](#-quick-start)

### 1. Configure the Component

[](#1-configure-the-component)

Add to your Yii2 application configuration:

```
'components' => [
    'jwt' => [
        'class' => \sherinbloemendaal\jwt\Jwt::class,
        'signer' => \sherinbloemendaal\jwt\JwtSigner::HS256,
        'signerKey' => \sherinbloemendaal\jwt\JwtKey::PLAIN_TEXT,
        'signerKeyContents' => getenv('JWT_SECRET') ?: 'your-secret-key',
        'constraints' => [
            static fn() => new \Lcobucci\JWT\Validation\Constraint\IssuedBy('https://your-app.com'),
        ],
    ],
],
```

### 2. Create Your First Token

[](#2-create-your-first-token)

```
/** @var \sherinbloemendaal\jwt\Jwt $jwt */
$jwt = Yii::$app->jwt;
$now = new DateTimeImmutable();

$token = $jwt->getBuilder()
    ->issuedBy('https://your-app.com')           // iss claim
    ->permittedFor('https://api.your-app.com')   // aud claim
    ->identifiedBy('unique-token-id')            // jti claim
    ->issuedAt($now)                            // iat claim
    ->expiresAt($now->modify('+1 hour'))        // exp claim
    ->withClaim('uid', 42)                      // custom claim
    ->withClaim('role', 'admin')                // another custom claim
    ->getToken($jwt->getSigner(), $jwt->getSignerKey());

echo $token->toString();
```

### 3. Parse and Validate Token

[](#3-parse-and-validate-token)

```
$tokenString = '...'; // JWT token from request

try {
    $token = $jwt->loadToken($tokenString, validate: true);

    // Access claims
    $userId = $token->claims()->get('uid');
    $userRole = $token->claims()->get('role');

    echo "Welcome user #{$userId} with role: {$userRole}";
} catch (\Exception $e) {
    echo "Invalid token: " . $e->getMessage();
}
```

---

🔧 Configuration
---------------

[](#-configuration)

### Basic Configuration Options

[](#basic-configuration-options)

```
'jwt' => [
    'class' => \sherinbloemendaal\jwt\Jwt::class,

    // Signing algorithm
    'signer' => \sherinbloemendaal\jwt\JwtSigner::HS256,

    // Key configuration
    'signerKey' => \sherinbloemendaal\jwt\JwtKey::PLAIN_TEXT,
    'signerKeyContents' => 'your-secret-key',
    'signerKeyPassphrase' => '', // for encrypted keys

    // Validation constraints
    'constraints' => [
        static fn() => new \Lcobucci\JWT\Validation\Constraint\IssuedBy('https://your-app.com'),
    ],
],
```

### Clock Implementations (Optional)

[](#clock-implementations-optional)

For time-based JWT validation (checking expiration, not-before, issued-at claims), you need a PSR-20 compatible clock:

**Option 1: Using lcobucci/clock (Recommended for time validation)**

```
composer require lcobucci/clock
```

```
// Time-based validation with SystemClock
static fn() => new \Lcobucci\JWT\Validation\Constraint\LooseValidAt(
    \Lcobucci\Clock\SystemClock::fromUTC()
),

// With leeway for clock skew
static fn() => new \Lcobucci\JWT\Validation\Constraint\LooseValidAt(
    \Lcobucci\Clock\SystemClock::fromUTC(),
    new \DateInterval('PT30S') // 30 second leeway
),
```

**Option 2: Built-in PSR-20 Implementation (no dependencies)**

```
static function() {
    return new \Lcobucci\JWT\Validation\Constraint\LooseValidAt(
        new class implements \Psr\Clock\ClockInterface {
            public function now(): \DateTimeImmutable
            {
                return new \DateTimeImmutable('now', new \DateTimeZone('UTC'));
            }
        }
    );
},
```

### Advanced Configuration

[](#advanced-configuration)

```
'jwt' => [
    'class' => \sherinbloemendaal\jwt\Jwt::class,

    // Custom encoder/decoder
    'encoder' => ['class' => \Lcobucci\JWT\Encoding\JoseEncoder::class],
    'decoder' => ['class' => \Lcobucci\JWT\Encoding\JoseEncoder::class],

    // Custom claims formatter
    'claimsFormatter' => [
        'class' => \sherinbloemendaal\jwt\Encoding\ChainedFormatter::class,
        'formatters' => [
            \Lcobucci\JWT\Encoding\UnifyAudience::class,
            \Lcobucci\JWT\Encoding\MicrosecondBasedDateConversion::class,
        ],
    ],
],
```

---

💡 Examples
----------

[](#-examples)

### REST API Authentication

[](#rest-api-authentication)

Create a secure REST controller with JWT authentication:

```
