| 1 | <?php |
||
| 2 | |||
| 3 | namespace Parroauth2\Client\OpenID\IdToken; |
||
| 4 | |||
| 5 | use Base64Url\Base64Url; |
||
| 6 | use Parroauth2\Client\Jwt\JWA; |
||
| 7 | |||
| 8 | /** |
||
| 9 | * Utility class for compute and check the at_hash claim of the ID Token |
||
| 10 | * |
||
| 11 | * @see https://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken |
||
| 12 | */ |
||
| 13 | final class AccessTokenHash |
||
| 14 | { |
||
| 15 | /** |
||
| 16 | * @var JWA |
||
| 17 | */ |
||
| 18 | private $jwa; |
||
| 19 | |||
| 20 | /** |
||
| 21 | * AccessTokenHash constructor. |
||
| 22 | * |
||
| 23 | * @param JWA|null $jwa |
||
| 24 | */ |
||
| 25 | 29 | public function __construct(?JWA $jwa = null) |
|
| 26 | { |
||
| 27 | 29 | $this->jwa = $jwa ?: new JWA(); |
|
| 28 | 29 | } |
|
| 29 | |||
| 30 | /** |
||
| 31 | * Compute the at_hash claim value |
||
| 32 | * |
||
| 33 | * @param string $accessToken The access token string |
||
| 34 | * @param string $alg The "alg" header value of the ID Token's header |
||
| 35 | * |
||
| 36 | * @return string |
||
| 37 | */ |
||
| 38 | 16 | public function compute(string $accessToken, string $alg): string |
|
| 39 | { |
||
| 40 | 16 | $algo = $this->jwa->hashAlgorithm($alg); |
|
| 41 | |||
| 42 | 15 | $hash = hash($algo, $accessToken, true); |
|
| 43 | 15 | $hash = substr($hash, 0, intdiv(strlen($hash), 2)); |
|
| 44 | |||
| 45 | 15 | return Base64Url::encode($hash); |
|
| 46 | } |
||
| 47 | |||
| 48 | /** |
||
| 49 | * Check if the access token hash stored into the ID Token corresponds with the access token |
||
| 50 | * If the ID Token has no claim at_hash, this method will always return true |
||
| 51 | * |
||
| 52 | * @param IdToken $idToken The ID Token |
||
| 53 | * @param string $accessToken The access token string |
||
| 54 | * |
||
| 55 | * @return bool |
||
| 56 | */ |
||
| 57 | 4 | public function check(IdToken $idToken, string $accessToken): bool |
|
| 58 | { |
||
| 59 | 4 | if (!$idToken->accessTokenHash()) { |
|
| 60 | 2 | return true; |
|
| 61 | } |
||
| 62 | |||
| 63 | 3 | return hash_equals($this->compute($accessToken, $idToken->header('alg')), $idToken->accessTokenHash()); |
|
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 64 | } |
||
| 65 | } |
||
| 66 |