Last active
September 29, 2017 18:32
-
-
Save bshaffer/35fc2fb65df200c5e3a201c70c466c8b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Make an IAP request using "google/auth" | |
*/ | |
use Google\Auth\CredentialsLoader; | |
use Google\Auth\Middleware\ScopedAccessTokenMiddleware; | |
use Google\Auth\OAuth2; | |
use GuzzleHttp\Client; | |
use GuzzleHttp\HandlerStack; | |
// $credentialsFile = '/path/to/credentials.json'; | |
// $projectId = 'YOUR_PROJECT_ID'; | |
// $clientId = 'YOUR_CLIENT_ID'; | |
$serviceAccountCredentials = json_decode(file_get_contents($credentialsFile), true); | |
$oauth = new OAuth2(); | |
$oauth->setGrantType(OAuth2::JWT_URN); | |
$oauth->setSigningKey($serviceAccountCredentials['private_key']); | |
$oauth->setSigningAlgorithm('RS256'); | |
$oauth->setAudience(CredentialsLoader::TOKEN_CREDENTIAL_URI); | |
$oauth->setIssuer($projectId); | |
$oauth->setAdditionalClaims([ | |
'target_audience' => $clientID, | |
]); | |
// this should have "id_token" | |
$token = $oauth->fetchAuthToken(); | |
var_dump($token); | |
// get the Open ID Connect token | |
$idToken = $oauth->getIdToken(); | |
/** NOW WE CAN MAKE AN HTTP REQUEST!! **/ | |
$scope = 'https://www.googleapis.com/auth/iam'; | |
$middleware = new ScopedAccessTokenMiddleware( | |
function() use ($idToken) { | |
return $idToken; | |
}, | |
$scope | |
); | |
$stack = HandlerStack::create(); | |
$stack->push($middleware); | |
$client = new Client([ | |
'handler' => $stack, | |
'auth' => 'google_auth' // authorize all requests | |
]); | |
$res = $client->get('https://someproject.appspot.com/testurl'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment