<?php
 declare(strict_types=1); namespace Jose\Component\Signature; use Exception; use Jose\Component\Checker\HeaderCheckerManager; use Jose\Component\Core\JWK; use Jose\Component\Core\JWKSet; use Jose\Component\Signature\Serializer\JWSSerializerManager; use Throwable; class JWSLoader { public function __construct( private readonly JWSSerializerManager $serializerManager, private readonly JWSVerifier $jwsVerifier, private readonly ?HeaderCheckerManager $headerCheckerManager ) { } public function getJwsVerifier(): JWSVerifier { return $this->jwsVerifier; } public function getHeaderCheckerManager(): ?HeaderCheckerManager { return $this->headerCheckerManager; } public function getSerializerManager(): JWSSerializerManager { return $this->serializerManager; } public function loadAndVerifyWithKey(string $token, JWK $key, ?int &$signature, ?string $payload = null): JWS { $keyset = new JWKSet([$key]); return $this->loadAndVerifyWithKeySet($token, $keyset, $signature, $payload); } public function loadAndVerifyWithKeySet( string $token, JWKSet $keyset, ?int &$signature, ?string $payload = null ): JWS { try { $jws = $this->serializerManager->unserialize($token); $nbSignatures = $jws->countSignatures(); for ($i = 0; $i < $nbSignatures; ++$i) { if ($this->processSignature($jws, $keyset, $i, $payload)) { $signature = $i; return $jws; } } } catch (Throwable) { } throw new Exception('Unable to load and verify the token.'); } private function processSignature(JWS $jws, JWKSet $keyset, int $signature, ?string $payload): bool { try { if ($this->headerCheckerManager !== null) { $this->headerCheckerManager->check($jws, $signature); } return $this->jwsVerifier->verifyWithKeySet($jws, $keyset, $signature, $payload); } catch (Throwable) { return false; } } } 