public function testSuccedsIfNoDefaultFilesButIsOnGCE()
 {
     $wantedTokens = ['access_token' => '1/abdef1234567890', 'expires_in' => '57', 'token_type' => 'Bearer'];
     $jsonTokens = json_encode($wantedTokens);
     // simulate the response from GCE.
     $httpHandler = getHandler([buildResponse(200, [GCECredentials::FLAVOR_HEADER => 'Google']), buildResponse(200, [], Psr7\stream_for($jsonTokens))]);
     $this->assertNotNull(ApplicationDefaultCredentials::getCredentials('a scope', $httpHandler));
 }
 public function testSuccedsIfNoDefaultFilesButIsOnGCE()
 {
     $client = new Client();
     // simulate the response from GCE.
     $wantedTokens = ['access_token' => '1/abdef1234567890', 'expires_in' => '57', 'token_type' => 'Bearer'];
     $jsonTokens = json_encode($wantedTokens);
     $plugin = new Mock([new Response(200, [GCECredentials::FLAVOR_HEADER => 'Google']), new Response(200, [], Stream::factory($jsonTokens))]);
     $client->getEmitter()->attach($plugin);
     $this->assertNotNull(ApplicationDefaultCredentials::getCredentials('a scope', $client));
 }
 /**
  * @return array
  */
 protected static function getToken()
 {
     if (isset(static::$token)) {
         return static::$token;
     }
     // specify the path to your application credentials
     if (!getenv('GOOGLE_APPLICATION_CREDENTIALS')) {
         putenv('GOOGLE_APPLICATION_CREDENTIALS=Bloomon-62a712b0d88d.json');
     }
     // define the scopes for your API call
     $scopes = ['https://spreadsheets.google.com/feeds'];
     $credentials = ApplicationDefaultCredentials::getCredentials($scopes);
     return static::$token = $credentials->fetchAuthToken();
 }
function getToken()
{
    // specify the path to your application credentials
    if (!getenv('GOOGLE_APPLICATION_CREDENTIALS')) {
        putenv('GOOGLE_APPLICATION_CREDENTIALS=Bloomon-62a712b0d88d.json');
    }
    // define the scopes for your API call
    $scopes = ['https://spreadsheets.google.com/feeds'];
    // create the HTTP client
    $client = new Client(['base_url' => 'https://www.googleapis.com', 'defaults' => ['auth' => 'google_auth']]);
    $credentials = ApplicationDefaultCredentials::getCredentials($scopes);
    $token = $credentials->fetchAuthToken();
    return $token;
}
 public function testSucceedIfFileIsPresent()
 {
     putenv('HOME=' . __DIR__ . '/fixtures');
     $this->assertNotNull(ApplicationDefaultCredentials::getCredentials('a scope'));
 }
示例#6
0
function updateAuthMetadataCallback($context)
{
    $authUri = $context->service_url;
    $methodName = $context->method_name;
    $auth_credentials = ApplicationDefaultCredentials::getCredentials();
    return $auth_credentials->updateMetadata($metadata = [], $authUri);
}
示例#7
0
/**
 * Run the per_rpc_creds auth test.
 * @param $stub Stub object that has service methods
 * @param $args array command line args
 */
function perRpcCreds($stub, $args)
{
    $jsonKey = json_decode(file_get_contents(getenv(CredentialsLoader::ENV_VAR)), true);
    $auth_credentials = ApplicationDefaultCredentials::getCredentials($args['oauth_scope']);
    $token = $auth_credentials->fetchAuthToken();
    $metadata = array(CredentialsLoader::AUTH_METADATA_KEY => array(sprintf("%s %s", $token['token_type'], $token['access_token'])));
    $result = performLargeUnary($stub, $fillUsername = true, $fillOauthScope = true, $metadata);
    hardAssert($result->getUsername() == $jsonKey['client_email'], 'invalid email returned');
}
示例#8
0
 private function createApplicationDefaultCredentials()
 {
     $scopes = $this->prepareScopes();
     $sub = $this->config['subject'];
     $signingKey = $this->config['signing_key'];
     // create credentials using values supplied in setAuthConfig
     if ($signingKey) {
         $serviceAccountCredentials = array('client_id' => $this->config['client_id'], 'client_email' => $this->config['client_email'], 'private_key' => $signingKey, 'type' => 'service_account');
         $keyStream = Psr7\stream_for(json_encode($serviceAccountCredentials));
         $credentials = CredentialsLoader::makeCredentials($scopes, $keyStream);
     } else {
         $credentials = ApplicationDefaultCredentials::getCredentials($scopes);
     }
     // for service account domain-wide authority (impersonating a user)
     // @see https://developers.google.com/identity/protocols/OAuth2ServiceAccount
     if ($sub) {
         if (!$credentials instanceof ServiceAccountCredentials) {
             throw new DomainException('domain-wide authority requires service account credentials');
         }
         $credentials->setSub($sub);
     }
     return $credentials;
 }
示例#9
0
function _makeStub($args)
{
    if (!array_key_exists('server_host', $args)) {
        throw new Exception('Missing argument: --server_host is required');
    }
    if (!array_key_exists('server_port', $args)) {
        throw new Exception('Missing argument: --server_port is required');
    }
    if (!array_key_exists('test_case', $args)) {
        throw new Exception('Missing argument: --test_case is required');
    }
    if ($args['server_port'] == 443) {
        $server_address = $args['server_host'];
    } else {
        $server_address = $args['server_host'] . ':' . $args['server_port'];
    }
    $test_case = $args['test_case'];
    $host_override = 'foo.test.google.fr';
    if (array_key_exists('server_host_override', $args)) {
        $host_override = $args['server_host_override'];
    }
    $use_tls = false;
    if (array_key_exists('use_tls', $args) && $args['use_tls'] != 'false') {
        $use_tls = true;
    }
    $use_test_ca = false;
    if (array_key_exists('use_test_ca', $args) && $args['use_test_ca'] != 'false') {
        $use_test_ca = true;
    }
    $opts = [];
    if ($use_tls) {
        if ($use_test_ca) {
            $ssl_credentials = Grpc\ChannelCredentials::createSsl(file_get_contents(dirname(__FILE__) . '/../data/ca.pem'));
        } else {
            $ssl_credentials = Grpc\ChannelCredentials::createSsl();
        }
        $opts['credentials'] = $ssl_credentials;
        $opts['grpc.ssl_target_name_override'] = $host_override;
    } else {
        $opts['credentials'] = Grpc\ChannelCredentials::createInsecure();
    }
    if (in_array($test_case, ['service_account_creds', 'compute_engine_creds', 'jwt_token_creds'])) {
        if ($test_case == 'jwt_token_creds') {
            $auth_credentials = ApplicationDefaultCredentials::getCredentials();
        } else {
            $auth_credentials = ApplicationDefaultCredentials::getCredentials($args['oauth_scope']);
        }
        $opts['update_metadata'] = $auth_credentials->getUpdateMetadataFunc();
    }
    if ($test_case == 'oauth2_auth_token') {
        $auth_credentials = ApplicationDefaultCredentials::getCredentials($args['oauth_scope']);
        $token = $auth_credentials->fetchAuthToken();
        $update_metadata = function ($metadata, $authUri = null, ClientInterface $client = null) use($token) {
            $metadata_copy = $metadata;
            $metadata_copy[CredentialsLoader::AUTH_METADATA_KEY] = [sprintf('%s %s', $token['token_type'], $token['access_token'])];
            return $metadata_copy;
        };
        $opts['update_metadata'] = $update_metadata;
    }
    if ($test_case == 'unimplemented_method') {
        $stub = new grpc\testing\UnimplementedServiceClient($server_address, $opts);
    } else {
        $stub = new grpc\testing\TestServiceClient($server_address, $opts);
    }
    return $stub;
}
 public function testAppEngineFlexible()
 {
     $_SERVER['SERVER_SOFTWARE'] = 'Google App Engine';
     $_SERVER['GAE_VM'] = 'true';
     $httpHandler = getHandler([buildResponse(200, [GCECredentials::FLAVOR_HEADER => 'Google'])]);
     $this->assertInstanceOf('Google\\Auth\\Credentials\\GCECredentials', ApplicationDefaultCredentials::getCredentials(null, $httpHandler));
 }
 /**
  * Gets the credentials fetcher and sets up caching. Precedence begins with
  * user supplied credentials fetcher instance, followed by a reference to a
  * key file stream, and finally the application default credentials.
  *
  * @return FetchAuthTokenInterface
  */
 public function getCredentialsFetcher()
 {
     $fetcher = null;
     if ($this->credentialsFetcher) {
         $fetcher = $this->credentialsFetcher;
     } elseif ($this->keyFile) {
         $fetcher = CredentialsLoader::makeCredentials($this->scopes, $this->keyFile);
     } else {
         $fetcher = ApplicationDefaultCredentials::getCredentials($this->scopes, $this->authHttpHandler);
     }
     return new FetchAuthTokenCache($fetcher, $this->authCacheOptions, $this->authCache);
 }
<?php

require_once __DIR__ . '/../vendor/autoload.php';
use Google\Auth\ApplicationDefaultCredentials;
$auth_credentials = ApplicationDefaultCredentials::getCredentials(['https://www.googleapis.com/auth/pubsub']);
$channel_credentials = Grpc\ChannelCredentials::createSsl(file_get_contents(__DIR__ . '/../vendor/grpc/grpc/etc/roots.pem'));
$opts = ['credentials' => $channel_credentials, 'grpc.ssl_target_name_override' => 'pubsub.googleapis.com'];
$client = new google\pubsub\v1\PublisherClient('pubsub.googleapis.com', $opts);
$deadline = Grpc\Timeval::InfFuture();
$req = new google\pubsub\v1\ListTopicsRequest();
$proj = getenv('GAE_LONG_APP_ID');
$req->setProject('projects/' . $proj);
$call = $client->ListTopics($req, [], ['call_credentials_callback' => function ($context) use($auth_credentials) {
    return $auth_credentials->updateMetadata([], $context->service_url);
}]);
list($response, $status) = $call->wait();
if ($status->code != 0) {
    echo 'gRPC to PubSub failed, printing RPC status:<br>';
    print_r($status);
    exit(1);
}
foreach ($response->getTopics() as $topic) {
    echo $topic->getName() . '<br>';
}
示例#13
0
 /**
  * Gets the credentials fetcher. Precedence begins with user supplied
  * credentials fetcher instance, followed by a reference to a key file
  * stream, and finally the application default credentials.
  *
  * @return FetchAuthTokenInterface
  */
 public function getCredentialsFetcher()
 {
     if ($this->credentialsFetcher) {
         return $this->credentialsFetcher;
     }
     if ($this->keyFile) {
         return CredentialsLoader::makeCredentials($this->scopes, $this->keyFile);
     }
     return ApplicationDefaultCredentials::getCredentials($this->scopes, $this->authHttpHandler);
 }