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/ */
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]);
}
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);
}
}