|
24 | 24 | namespace Google\Cloud\Samples\Iap; |
25 | 25 |
|
26 | 26 | # Imports Auth libraries and Guzzle HTTP libraries. |
27 | | -use Google\Auth\OAuth2; |
28 | | -use Google\Auth\Middleware\ScopedAccessTokenMiddleware; |
| 27 | +use Google\Auth\ApplicationDefaultCredentials; |
29 | 28 | use GuzzleHttp\Client; |
30 | 29 | use GuzzleHttp\HandlerStack; |
31 | 30 |
|
|
37 | 36 | * |
38 | 37 | * @return The response body. |
39 | 38 | */ |
40 | | -function make_iap_request($url, $clientId, $pathToServiceAccount) |
| 39 | +function make_iap_request($url, $clientId) |
41 | 40 | { |
42 | | - $serviceAccountKey = json_decode(file_get_contents($pathToServiceAccount), true); |
43 | | - $oauth_token_uri = 'https://www.googleapis.com/oauth2/v4/token'; |
44 | | - $iam_scope = 'https://www.googleapis.com/auth/iam'; |
45 | | - |
46 | | - # Create an OAuth object using the service account key |
47 | | - $oauth = new OAuth2([ |
48 | | - 'audience' => $oauth_token_uri, |
49 | | - 'issuer' => $serviceAccountKey['client_email'], |
50 | | - 'signingAlgorithm' => 'RS256', |
51 | | - 'signingKey' => $serviceAccountKey['private_key'], |
52 | | - 'tokenCredentialUri' => $oauth_token_uri, |
53 | | - ]); |
54 | | - $oauth->setGrantType(OAuth2::JWT_URN); |
55 | | - $oauth->setAdditionalClaims(['target_audience' => $clientId]); |
56 | | - |
57 | | - # Obtain an OpenID Connect token, which is a JWT signed by Google. |
58 | | - $token = $oauth->fetchAuthToken(); |
59 | | - $idToken = $oauth->getIdToken(); |
60 | | - |
61 | | - # Construct a ScopedAccessTokenMiddleware with the ID token. |
62 | | - $middleware = new ScopedAccessTokenMiddleware( |
63 | | - function () use ($idToken) { |
64 | | - return $idToken; |
65 | | - }, |
66 | | - $iam_scope |
67 | | - ); |
68 | | - |
| 41 | + // create middleware, using the client ID as the target audience for IAP |
| 42 | + $middleware = ApplicationDefaultCredentials::getIdTokenMiddleware($clientId); |
69 | 43 | $stack = HandlerStack::create(); |
70 | 44 | $stack->push($middleware); |
71 | 45 |
|
72 | | - # Create an HTTP Client using Guzzle and pass in the credentials. |
73 | | - $http_client = new Client([ |
74 | | - 'handler' => $stack, |
75 | | - 'base_uri' => $url, |
76 | | - 'auth' => 'scoped' |
| 46 | + // create the HTTP client |
| 47 | + $client = new Client([ |
| 48 | + 'handler' => $stack, |
| 49 | + 'auth' => 'google_auth' |
77 | 50 | ]); |
78 | 51 |
|
79 | | - # Make an authenticated HTTP Request |
80 | | - $response = $http_client->request('GET', '/', []); |
81 | | - return $response; |
| 52 | + // make the request |
| 53 | + return $client->get($url); |
82 | 54 | } |
83 | 55 | # [END iap_make_request] |
0 commit comments