PHP code example of methorz / jwt-auth-middleware

1. Go to this page and download the library: Download methorz/jwt-auth-middleware library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

methorz / jwt-auth-middleware example snippets


// config/pipeline.php
$app->pipe(\MethorZ\JwtAuthMiddleware\Middleware\JwtAuthenticationMiddleware::class);

$app->add(\MethorZ\JwtAuthMiddleware\Middleware\JwtAuthenticationMiddleware::class);

$app->get('/api/protected', ProtectedHandler::class, 'protected-route')
    ->setOptions(['auth' => ['

public function handle(ServerRequestInterface $request): ResponseInterface
{
    // Get JWT claims from request
    $claims = $request->getAttribute('jwt_claims');
    $userId = $claims->get('sub'); // User ID from token

    // Optional: Get loaded user (if user loader configured)
    $user = $request->getAttribute('user');

    return new JsonResponse(['user_id' => $userId]);
}

// config/autoload/jwt-auth.php
return [
    'jwt_auth' => [
        'algorithm' => 'HS256',
        'secret' => $_ENV['JWT_SECRET'],

        // Validation constraints
        'issuer' => 'your-app',
        'audience' => 'your-api',

        // Token extraction
        'header_name' => 'Authorization',
        'header_prefix' => 'Bearer',

        // Optional: Custom header
        // 'header_name' => 'X-Auth-Token',
        // 'header_prefix' => '',

        // Optional: User loader service
        // 'user_loader' => UserLoaderInterface::class,
    ],
];

// Only et('/public', PublicHandler::class); // No auth

$app->get('/protected', ProtectedHandler::class)
    ->setOptions(['auth' => ['

// Require specific scopes
$app->post('/admin/users', AdminHandler::class)
    ->setOptions([
        'auth' => [
            '

use MethorZ\JwtAuthMiddleware\Contract\UserLoaderInterface;
use Lcobucci\JWT\Token\Plain;

class DatabaseUserLoader implements UserLoaderInterface
{
    public function __construct(private UserRepository $repository) {}

    public function loadUser(Plain $token): ?object
    {
        $userId = $token->claims()->get('sub');
        return $this->repository->findById($userId);
    }
}

// ConfigProvider.php
use MethorZ\JwtAuthMiddleware\Contract\UserLoaderInterface;

return [
    'dependencies' => [
        'factories' => [
            UserLoaderInterface::class => DatabaseUserLoaderFactory::class,
        ],
    ],
];

use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;

$config = Configuration::forSymmetricSigner(
    new Sha256(),
    InMemory::plainText($_ENV['JWT_SECRET'])
);

$now = new DateTimeImmutable();
$token = $config->builder()
    ->issuedBy('your-app')
    ->permittedFor('your-api')
    ->identifiedBy('unique-token-id')
    ->issuedAt($now)
    ->expiresAt($now->modify('+1 hour'))
    ->withClaim('sub', 'user123')
    ->withClaim('scope', 'users:read users:write')
    ->getToken($config->signer(), $config->signingKey());

echo $token->toString(); // Send to client