|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace SimpleSAML\Module\oidc\Services; |
| 6 | + |
| 7 | +use SimpleSAML\Module\oidc\ModuleConfig; |
| 8 | +use SimpleSAML\OpenID\Codebooks\ClaimsEnum; |
| 9 | +use SimpleSAML\OpenID\Jws; |
| 10 | + |
| 11 | +class NonceService |
| 12 | +{ |
| 13 | + public function __construct( |
| 14 | + protected readonly Jws $jws, |
| 15 | + protected readonly ModuleConfig $moduleConfig, |
| 16 | + protected readonly LoggerService $loggerService, |
| 17 | + ) { |
| 18 | + } |
| 19 | + |
| 20 | + /** |
| 21 | + * @throws \Exception |
| 22 | + */ |
| 23 | + public function generateNonce(): string |
| 24 | + { |
| 25 | + $signatureKeyPair = $this->moduleConfig->getVciSignatureKeyPairBag()->getFirstOrFail(); |
| 26 | + $currentTimestamp = $this->jws->helpers()->dateTime()->getUtc()->getTimestamp(); |
| 27 | + |
| 28 | + // Nonce is valid for 5 minutes (300 seconds) |
| 29 | + // TODO mivanci Consider making this configurable. |
| 30 | + $expiryTimestamp = $currentTimestamp + 300; |
| 31 | + |
| 32 | + $payload = [ |
| 33 | + ClaimsEnum::Iss->value => $this->moduleConfig->getIssuer(), |
| 34 | + ClaimsEnum::Iat->value => $currentTimestamp, |
| 35 | + ClaimsEnum::Exp->value => $expiryTimestamp, |
| 36 | + 'nonce_val' => bin2hex(random_bytes(16)), |
| 37 | + ]; |
| 38 | + |
| 39 | + $header = [ |
| 40 | + ClaimsEnum::Kid->value => $signatureKeyPair->getKeyPair()->getKeyId(), |
| 41 | + ]; |
| 42 | + |
| 43 | + return $this->jws->parsedJwsFactory()->fromData( |
| 44 | + $signatureKeyPair->getKeyPair()->getPrivateKey(), |
| 45 | + $signatureKeyPair->getSignatureAlgorithm(), |
| 46 | + $payload, |
| 47 | + $header, |
| 48 | + )->getToken(); |
| 49 | + } |
| 50 | + |
| 51 | + public function validateNonce(string $nonce): bool |
| 52 | + { |
| 53 | + try { |
| 54 | + $parsedJws = $this->jws->parsedJwsFactory()->fromToken($nonce); |
| 55 | + |
| 56 | + // Verify signature |
| 57 | + $signatureKeyPair = $this->moduleConfig->getVciSignatureKeyPairBag()->getFirstOrFail(); |
| 58 | + $parsedJws->verifyWithKey($signatureKeyPair->getKeyPair()->getPublicKey()->jwk()->all()); |
| 59 | + |
| 60 | + // Verify issuer |
| 61 | + if ($parsedJws->getIssuer() !== $this->moduleConfig->getIssuer()) { |
| 62 | + $this->loggerService->warning('Nonce validation failed: invalid issuer.'); |
| 63 | + return false; |
| 64 | + } |
| 65 | + |
| 66 | + // Verify expiration |
| 67 | + $currentTimestamp = $this->jws->helpers()->dateTime()->getUtc()->getTimestamp(); |
| 68 | + if ($parsedJws->getExpirationTime() < $currentTimestamp) { |
| 69 | + $this->loggerService->warning('Nonce validation failed: expired.'); |
| 70 | + return false; |
| 71 | + } |
| 72 | + |
| 73 | + return true; |
| 74 | + } catch (\Exception $e) { |
| 75 | + $this->loggerService->warning('Nonce validation failed: ' . $e->getMessage()); |
| 76 | + return false; |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments