|
24 | 24 | namespace Google\Cloud\Samples\Iap; |
25 | 25 |
|
26 | 26 | # Imports OAuth Guzzle HTTP libraries. |
27 | | -use Jose\Factory\JWKFactory; |
28 | | -use Jose\Loader; |
| 27 | +use GuzzleHttp\Client; |
| 28 | +# Imports libraries for JWK validation |
| 29 | +use SimpleJWT\JWT; |
| 30 | +use SimpleJWT\Keys\KeySet; |
| 31 | +use SimpleJWT\InvalidTokenException; |
29 | 32 |
|
30 | 33 | /** |
31 | 34 | * Validate a JWT passed to your App Engine app by Identity-Aware Proxy. |
@@ -74,22 +77,26 @@ function validate_jwt_from_compute_engine($iap_jwt, $cloud_project_number, $back |
74 | 77 |
|
75 | 78 | function validate_jwt($iap_jwt, $expected_audience) |
76 | 79 | { |
| 80 | + // get the public key JWK Set object (RFC7517) |
| 81 | + $httpclient = new Client(); |
| 82 | + $response = $httpclient->request('GET', 'https://www.gstatic.com/iap/verify/public_key-jwk', []); |
| 83 | + |
77 | 84 | // Create a JWK Key Set from the gstatic URL |
78 | | - $jwk_set = JWKFactory::createFromJKU('https://www.gstatic.com/iap/verify/public_key-jwk'); |
| 85 | + $jwkset = new KeySet(); |
| 86 | + $jwkset->load((string) $response->getBody()); |
79 | 87 |
|
80 | | - // Validate the signature using the key set and ES256 algorithm. |
81 | | - $loader = new Loader(); |
82 | | - $jws = $loader->loadAndVerifySignatureUsingKeySet( |
83 | | - $iap_jwt, |
84 | | - $jwk_set, |
85 | | - ['ES256'] |
86 | | - ); |
87 | 88 |
|
| 89 | + // Validate the signature using the key set and ES256 algorithm. |
| 90 | + try { |
| 91 | + $jwt = JWT::decode($iap_jwt, $jwkset, 'ES256'); |
| 92 | + } catch (InvalidTokenException $e) { |
| 93 | + return print("Failed to validate JWT: " . $e->getMessage() . PHP_EOL); |
| 94 | + } |
88 | 95 | // Validate token by checking issuer and audience fields. |
89 | | - assert($jws->getClaim('iss') == 'https://cloud.google.com/iap'); |
90 | | - assert($jws->getClaim('aud') == $expected_audience); |
| 96 | + assert($jwt->getClaim('iss') == 'https://cloud.google.com/iap'); |
| 97 | + assert($jwt->getClaim('aud') == $expected_audience); |
91 | 98 |
|
92 | 99 | // Return the user identity (subject and user email) if JWT verification is successful. |
93 | | - return array('sub' => $jws->getClaim('sub'), 'email' => $jws->getClaim('email')); |
| 100 | + return array('sub' => $jwt->getClaim('sub'), 'email' => $jwt->getClaim('email')); |
94 | 101 | } |
95 | 102 | # [END iap_validate_jwt] |
0 commit comments