|
24 | 24 | namespace Google\Cloud\Samples\Iap;
|
25 | 25 |
|
26 | 26 | # Imports OAuth Guzzle HTTP libraries.
|
27 |
| -use GuzzleHttp\Client; |
28 |
| -use Lcobucci\JWT\Parser; |
29 |
| -use Lcobucci\JWT\ValidationData; |
30 |
| -use Lcobucci\JWT\Signer\Ecdsa\Sha256; |
| 27 | +use Jose\Factory\JWKFactory; |
| 28 | +use Jose\Loader; |
31 | 29 |
|
32 | 30 | /**
|
33 | 31 | * Validate a JWT passed to your App Engine app by Identity-Aware Proxy.
|
@@ -76,27 +74,22 @@ function validate_jwt_from_compute_engine($iap_jwt, $cloud_project_number, $back
|
76 | 74 |
|
77 | 75 | function validate_jwt($iap_jwt, $expected_audience)
|
78 | 76 | {
|
79 |
| - // Validate the algorithm and kid headers. Also fetch the public key using the kid. |
80 |
| - $token = (new Parser())->parse((string) $iap_jwt); // Parses from a string |
81 |
| - $algorithm = $token->getHeader('alg'); |
82 |
| - assert($algorithm =='ES256'); |
83 |
| - $kid = $token->getHeader('kid'); |
84 |
| - $client = new Client(['base_uri' => 'https://www.gstatic.com/']); |
85 |
| - $response = $client->request('GET', 'iap/verify/public_key'); |
86 |
| - $body_content = json_decode((string) $response->getBody()); |
87 |
| - $public_key = $body_content->$kid; |
| 77 | + // Create a JWK Key Set from the gstatic URL |
| 78 | + $jwk_set = JWKFactory::createFromJKU('https://www.gstatic.com/iap/verify/public_key-jwk'); |
88 | 79 |
|
89 |
| - // Validate token by checking issuer and audience fields. The JWT library automatically checks the time constraints. |
90 |
| - $data = new ValidationData(); |
91 |
| - $data->setIssuer('https://cloud.google.com/iap'); |
92 |
| - $data->setAudience($expected_audience); |
93 |
| - assert($token->validate($data)); |
| 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 | + ); |
94 | 87 |
|
95 |
| - // Verify the signature using the JWT library. |
96 |
| - $signer = new Sha256(); |
97 |
| - assert($token->verify($signer, $public_key)); |
| 88 | + // 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); |
98 | 91 |
|
99 | 92 | // Return the user identity (subject and user email) if JWT verification is successful.
|
100 |
| - return array('sub' => $token->getClaim('sub'), 'email' => $token->getClaim('email')); |
| 93 | + return array('sub' => $jws->getClaim('sub'), 'email' => $jws->getClaim('email')); |
101 | 94 | }
|
102 | 95 | # [END validate_jwt]
|
0 commit comments