Last active
February 6, 2018 19:20
-
-
Save ryanmats/8579d3e07664cd7224b4626180c2e689 to your computer and use it in GitHub Desktop.
Shows how to authenticate to an Identity-Aware-Proxy protected application on GCP using a service account and PHP code.
This file contains 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
/** | |
* Make a request to an application protected by Identity-Aware Proxy. | |
* | |
* @param string $url The Identity-Aware Proxy-protected URL to fetch. | |
* @param string $clientId The client ID used by Identity-Aware Proxy. | |
* | |
* @return The response body. | |
*/ | |
function make_iap_request($url, $clientId, $pathToServiceAccount) | |
{ | |
$serviceAccountKey = json_decode(file_get_contents($pathToServiceAccount), true); | |
$oauth_token_uri = 'https://www.googleapis.com/oauth2/v4/token'; | |
$iam_scope = 'https://www.googleapis.com/auth/iam'; | |
# Create an OAuth object using the service account key | |
$oauth = new OAuth2([]); | |
$oauth->setGrantType(OAuth2::JWT_URN); | |
$oauth->setSigningKey($serviceAccountKey['private_key']); | |
$oauth->setSigningAlgorithm('RS256'); | |
$oauth->setAudience($oauth_token_uri); | |
$oauth->setAdditionalClaims([ | |
'target_audience' => $clientId, | |
]); | |
$oauth->setTokenCredentialUri($oauth_token_uri); | |
$oauth->setIssuer($serviceAccountKey['client_email']); | |
# Obtain an OpenID Connect token, which is a JWT signed by Google. | |
$guzzle = new Client(); | |
$httpHandler = \Google\Auth\HttpHandler\HttpHandlerFactory::build($guzzle); | |
$token = $oauth->fetchAuthToken($httpHandler); | |
$idToken = $oauth->getIdToken(); | |
# Construct a ScopedAccessTokenMiddleware with the ID token. | |
$middleware = new ScopedAccessTokenMiddleware( | |
function() use ($idToken) { | |
return $idToken; | |
}, | |
$iam_scope | |
); | |
$stack = HandlerStack::create(); | |
$stack->push($middleware); | |
# Create an HTTP Client using Guzzle and pass in the credentials. | |
$http_client = new Client([ | |
'handler' => $stack, | |
'base_uri' => $url, | |
'auth' => 'scoped', | |
'verify' => false | |
]); | |
# Make an authenticated HTTP Request | |
$response = $http_client->request('GET', '/', []); | |
return (string) $response->getBody(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment