Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 125 additions & 0 deletions docs/addons/jwt.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,38 @@ If you don't want any logs, set it to `Auth::RECORD_LOGIN_ATTEMPT_NONE`.
If you want to log all login attempts, set it to `Auth::RECORD_LOGIN_ATTEMPT_ALL`.
It means you log all requests.

### Configure JWT Revocation

Shield stores JWT revocations in `auth_jwt_revocations`. To use a different
table name, set the `jwt_revocations` entry in `Config\Auth::$tables` in
**app/Config/Auth.php** before running the migration.

Run Shield's migrations from the new release before it starts verifying JWTs.

```console
php spark migrate --all
```

The store uses `Config\Auth::$DBGroup`. Every instance that verifies the same
JWTs must use the same revocation database. Route requests to the logout
endpoint once all servers that verify these JWTs have been upgraded.

Each protected request with a JWT that has a `jti` adds one database lookup
for revocation after the signature and revocation claims pass validation.

`JWTManager::issue()` and `JWTManager::generateToken()` automatically add a
random token ID (`jti`) when the caller omits it. Signed JWTs with a `jti`
require a non-empty string issuer (`iss`), a non-empty string `jti` of at most
255 bytes, and an integer expiration time (`exp`, in Unix seconds). If you
supply a `jti`, use a unique value for every token issued under the same
issuer. Set a stable issuer in `$defaultClaims` and let the manager set
`exp` from the configured lifetime, or pass an integer expiration claim
when issuing a token.

Legacy JWTs without a `jti` can still authenticate under the prior signature
and time checks. Clients using these JWTs must obtain a newly issued JWT to
use API logout.

## Issuing JWTs

To use JWT Authentication, you need a controller that issues JWTs.
Expand Down Expand Up @@ -286,6 +318,99 @@ that has the JWT. It then validates the token. If the token is valid, it can
determine the correct user, which will then be available through an `auth()->user()`
call.

## Revoking the Current API Token

Register the application-owned POST route in **app/Config/Routes.php**.

```php
$routes->post('api/logout', '\App\Controllers\Auth\JwtLogoutController::logout');
```

Apply the `jwt` filter to your protected API routes and keep this route outside
that filter. If you currently apply `jwt` to all `api/*` paths, move the filter
to the protected routes or a group that excludes this route. The logout
controller verifies the bearer token through `JWTManager::revokeToken()`, so
a repeat request with the same unexpired token can complete successfully.

Create **app/Controllers/Auth/JwtLogoutController.php**.

```php
<?php

declare(strict_types=1);

namespace App\Controllers\Auth;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Shield\Authentication\JWT\Exceptions\InvalidTokenException;
use CodeIgniter\Shield\Authentication\JWTManager;
use CodeIgniter\Shield\Exceptions\RuntimeException;

class JwtLogoutController extends BaseController
{
public function logout(): ResponseInterface
{
$header = $this->request->getHeaderLine(config('AuthJWT')->authenticatorHeader);
$bearer = '/\ABearer[ \t]+([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)\z/i';
if (preg_match($bearer, $header, $matches) !== 1) {
return $this->unauthorized();
}

/** @var JWTManager $manager */
$manager = service('jwtmanager');

try {
$manager->revokeToken($matches[1]);
} catch (InvalidTokenException) {
return $this->unauthorized();
} catch (RuntimeException) {
return $this->response->setStatusCode(ResponseInterface::HTTP_SERVICE_UNAVAILABLE);
}

return $this->response->setStatusCode(ResponseInterface::HTTP_NO_CONTENT)->setBody('');
}

private function unauthorized(): ResponseInterface
{
return $this->response
->setHeader('WWW-Authenticate', 'Bearer')
->setStatusCode(ResponseInterface::HTTP_UNAUTHORIZED);
}
}
```

For tokens issued with a custom key group, pass the trusted key group name as
the second argument to `revokeToken()`.

```bash
curl -i -X POST https://api.example.com/api/logout \
-H "Authorization: Bearer $JWT"
```

Success returns `204 No Content`, including repeat requests made before the
same token expires. Subsequent requests with that token fail verification in
the `jwt` filter or `JWTManager::parse()`. Missing, malformed, invalid, and
expired bearer tokens receive `401 Unauthorized`, as do signed JWTs without a
`jti`. If Shield cannot store the revocation, the controller returns
`503 Service Unavailable`.

This operation revokes the presented JWT. Use the application's existing flows
to end browser sessions or revoke refresh tokens.

### Clean Up Expired Revocations

The database stores a digest of the issuer and token ID with the expiration
timestamp. JWTs with a `jti` use the signed `exp` as a strict cutoff without
expiration leeway. Keep the clocks of verifying servers synchronized, and run
the following from a scheduled application task to remove expired records.

```php
$removed = service('jwtmanager')->purgeExpiredRevocations();
```

The method returns the number of records removed.

## Method References

### Generating Signed JWTs
Expand Down
1 change: 1 addition & 0 deletions docs/customization/table_names.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ public array $tables = [
'identities' => 'auth_identities',
'logins' => 'auth_logins',
'token_logins' => 'auth_token_logins',
'jwt_revocations' => 'auth_jwt_revocations',
'remember_tokens' => 'auth_remember_tokens',
'groups_users' => 'auth_groups_users',
'permissions_users' => 'auth_permissions_users',
Expand Down
2 changes: 2 additions & 0 deletions rector.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@
])
->withBootstrapFiles([
realpath(getcwd()) . '/vendor/codeigniter4/framework/system/Test/bootstrap.php',
// Load Config\Migrations before PHPStan's reflection can intercept its autoload.
realpath(getcwd()) . '/vendor/codeigniter4/framework/app/Config/Migrations.php',
])
->withPHPStanConfigs([
__DIR__ . '/phpstan.dist.neon',
Expand Down
105 changes: 103 additions & 2 deletions src/Authentication/JWTManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,13 @@
namespace CodeIgniter\Shield\Authentication;

use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\JWT\Exceptions\InvalidTokenException;
use CodeIgniter\Shield\Authentication\JWT\JWSDecoder;
use CodeIgniter\Shield\Authentication\JWT\JWSEncoder;
use CodeIgniter\Shield\Entities\User;
use CodeIgniter\Shield\Exceptions\RuntimeException;
use CodeIgniter\Shield\Models\JWTRevocationModel;
use RuntimeException as NativeRuntimeException;
use stdClass;

/**
Expand All @@ -32,6 +36,7 @@ public function __construct(
?Time $clock = null,
?JWSEncoder $jwsEncoder = null,
?JWSDecoder $jwsDecoder = null,
private readonly ?JWTRevocationModel $revocationModel = null,
) {
$this->clock = $clock ?? new Time();
$this->jwsEncoder = $jwsEncoder ?? new JWSEncoder(null, $this->clock);
Expand Down Expand Up @@ -79,16 +84,112 @@ public function issue(
$keyset = 'default',
?array $headers = null,
): string {
if (! array_key_exists('jti', $claims)) {
$claims['jti'] = bin2hex(random_bytes(16));
}

return $this->jwsEncoder->encode($claims, $ttl, $keyset, $headers);
}

/**
* Returns payload of the JWT
* Verifies the JWT and returns its payload unless it has been revoked.
*
* @param string $keyset The key group. The array key of Config\AuthJWT::$keys.
*/
public function parse(string $encodedToken, $keyset = 'default'): stdClass
{
return $this->jwsDecoder->decode($encodedToken, $keyset);
$payload = $this->jwsDecoder->decode($encodedToken, $keyset);

// Keep signed JWTs issued before token IDs were added usable.
if (! property_exists($payload, 'jti')) {
return $payload;
}

[$identifier, $expiresAt] = $this->revocationIdentity($payload);

try {
$revoked = $this->revocations()->isRevoked($identifier);
} catch (NativeRuntimeException) {
log_message('error', '[Shield] JWT revocation lookup failed.');
$revoked = true;
}

if ($revoked) {
throw new InvalidTokenException(lang('Auth.invalidJWT'), InvalidTokenException::INVALID_TOKEN);
}

// An expired revocation record could have been removed during the lookup.
$this->enforceExpiry($expiresAt);

return $payload;
}

/**
* Revokes a verified, unexpired JWT with a token ID.
*
* @throws InvalidTokenException If the JWT is invalid or cannot be revoked.
* @throws RuntimeException If storage fails.
*/
public function revokeToken(string $encodedToken, string $keyset = 'default'): void
{
// Verify again without checking the revocation store so retries are safe.
$payload = $this->jwsDecoder->decode($encodedToken, $keyset);
[$identifier, $expiresAt] = $this->revocationIdentity($payload);

try {
$this->revocations()->revoke($identifier, $expiresAt);
} catch (NativeRuntimeException) {
throw new RuntimeException('JWT revocation could not be stored.');
}
}

/**
* Removes revocation records whose signed JWTs have expired.
*
* @return int The number of removed records.
*
* @throws RuntimeException If the revocation records cannot be removed.
*/
public function purgeExpiredRevocations(): int
{
try {
return $this->revocations()->purgeExpired($this->clock::now()->getTimestamp());
} catch (NativeRuntimeException) {
throw new RuntimeException('Expired JWT revocations could not be purged.');
}
}

/**
* @return array{string, int} The issuer-scoped digest and expiry.
*/
private function revocationIdentity(stdClass $payload): array
{
$issuer = $payload->iss ?? null;
$jti = $payload->jti ?? null;
$expiresAt = $payload->exp ?? null;

if (! is_string($issuer) || $issuer === ''
|| ! is_string($jti) || $jti === '' || strlen($jti) > 255
|| ! is_int($expiresAt)
) {
throw new InvalidTokenException(lang('Auth.invalidJWT'), InvalidTokenException::INVALID_TOKEN);
}

$this->enforceExpiry($expiresAt);

return [hash('sha256', strlen($issuer) . ':' . $issuer . $jti), $expiresAt];
}

private function enforceExpiry(int $expiresAt): void
{
// The revocation store can remove this record at exp, so ignore decoder leeway here.
if ($expiresAt <= $this->clock::now()->getTimestamp()) {
throw new InvalidTokenException(lang('Auth.expiredJWT'), InvalidTokenException::EXPIRED_TOKEN);
}
}

private function revocations(): JWTRevocationModel
{
return $this->revocationModel ?? model(JWTRevocationModel::class);
}
}
2 changes: 2 additions & 0 deletions src/Config/Auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,7 @@ class Auth extends BaseConfig
* - auth_identities Auth Identities Table, Used for storage of passwords, access tokens, social login identities, etc.
* - auth_logins Auth Login Attempts, Table records login attempts.
* - auth_token_logins Auth Token Login Attempts Table, Records Bearer Token type login attempts.
* - auth_jwt_revocations Revoked JWTs Table.
* - auth_remember_tokens Auth Remember Tokens (remember-me) Table.
* - auth_groups_users Groups Users Table.
* - auth_permissions_users Users Permissions Table.
Expand All @@ -426,6 +427,7 @@ class Auth extends BaseConfig
'identities' => 'auth_identities',
'logins' => 'auth_logins',
'token_logins' => 'auth_token_logins',
'jwt_revocations' => 'auth_jwt_revocations',
'remember_tokens' => 'auth_remember_tokens',
'groups_users' => 'auth_groups_users',
'permissions_users' => 'auth_permissions_users',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

declare(strict_types=1);

/**
* This file is part of CodeIgniter Shield.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace CodeIgniter\Shield\Database\Migrations;

use CodeIgniter\Database\Forge;
use CodeIgniter\Database\Migration;
use CodeIgniter\Shield\Config\Auth;

class CreateJWTRevocations extends Migration
{
private readonly string $table;

public function __construct(?Forge $forge = null)
{
/** @var Auth $authConfig */
$authConfig = config('Auth');

if ($authConfig->DBGroup !== null) {
$this->DBGroup = $authConfig->DBGroup;
}

parent::__construct($forge);

// Older application configs may override the table map without this entry.
$this->table = $authConfig->tables['jwt_revocations'] ?? 'auth_jwt_revocations';
}

public function up(): void
{
$this->forge->addField([
'identifier' => ['type' => 'varchar', 'constraint' => 64],
'expires_at' => ['type' => 'bigint'],
]);
$this->forge->addPrimaryKey('identifier');
$this->forge->addKey('expires_at');

$attributes = $this->db->getPlatform() === 'MySQLi' ? ['ENGINE' => 'InnoDB'] : [];
$this->forge->createTable($this->table, false, $attributes);
}

public function down(): void
{
$this->forge->dropTable($this->table, true);
}
}
Loading