Пример #1
0
 /**
  * Configure HTTP Client
  *
  * @return ClientInterface
  */
 protected function initHttpClient()
 {
     // Middleware
     $obj_stack = HandlerStack::create();
     $obj_stack->push(ApplicationDefaultCredentials::getMiddleware(['https://www.googleapis.com/auth/datastore']));
     // Create the HTTP client
     return new Client(['handler' => $obj_stack, 'base_url' => self::BASE_URL, 'auth' => 'google_auth']);
 }
 public function __construct($bucket = null)
 {
     $this->bucket = $bucket ?: getenv('GOOGLE_CLOUD_STORAGE_BUCKET');
     if (!$this->bucket) {
         throw new ConfigurationException("GOOGLE_CLOUD_STORGE_BUCKET is not set");
     }
     // create middleware
     $middleware = ApplicationDefaultCredentials::getMiddleware(config('storage.scopes'));
     $stack = HandlerStack::create();
     $stack->push($middleware);
     // create the HTTP client
     $this->client = new Client(['handler' => $stack, 'auth' => 'google_auth']);
 }
 /**
  * @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();
 }
Пример #4
0
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'));
 }
 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::getSubscriber('a scope', $httpHandler));
 }
Пример #7
0
function updateAuthMetadataCallback($context)
{
    $authUri = $context->service_url;
    $methodName = $context->method_name;
    $auth_credentials = ApplicationDefaultCredentials::getCredentials();
    return $auth_credentials->updateMetadata($metadata = [], $authUri);
}
Пример #8
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');
}
 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::getFetcher('a scope', $client));
 }
Пример #10
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;
 }
Пример #11
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;
}
Пример #12
0
 /**
  * Adds auth listeners to the HTTP client based on the credentials
  * set in the Google API Client object
  *
  * @param GuzzleHttp\ClientInterface $http the http client object.
  * @param GuzzleHttp\ClientInterface $authHttp an http client for authentication.
  * @return void
  */
 public function authorize(ClientInterface $http, ClientInterface $authHttp = null)
 {
     $subscriber = null;
     $authIdentifier = null;
     // if we end up needing to make an HTTP request to retrieve credentials, we
     // can use our existing one, but we need to throw exceptions so the error
     // bubbles up.
     $authHttp = $authHttp ?: $this->createDefaultAuthHttpClient($http);
     // These conditionals represent the decision tree for authentication
     //   1.  Check for Application Default Credentials
     //   2.  Check for API Key
     //   3a. Check for an Access Token
     //   3b. If access token exists but is expired, try to refresh it
     if ($this->config->get('use_application_default_credentials')) {
         $scopes = $this->prepareScopes();
         if ($sub = $this->config->get('subject')) {
             // for service account domain-wide authority (impersonating a user)
             // @see https://developers.google.com/identity/protocols/OAuth2ServiceAccount
             if (!($creds = CredentialsLoader::fromEnv($scopes))) {
                 $creds = CredentialsLoader::fromWellKnownFile($scopes);
             }
             if (!$creds instanceof ServiceAccountCredentials) {
                 throw new DomainException('domain-wide authority requires service account credentials');
             }
             $creds->setSub($sub);
             $subscriber = new AuthTokenFetcher($creds, array(), $this->cache, $authHttp);
         } else {
             $subscriber = ApplicationDefaultCredentials::getFetcher($scopes, $authHttp, array(), $this->cache);
         }
         $authIdentifier = 'google_auth';
     } elseif ($key = $this->config->get('developer_key')) {
         // if a developer key is set, authorize using that
         $subscriber = new Simple(['key' => $key]);
         $authIdentifier = 'simple';
     } elseif ($token = $this->getAccessToken()) {
         $scopes = $this->prepareScopes();
         // add refresh subscriber to request a new token
         if ($this->isAccessTokenExpired() && isset($token['refresh_token'])) {
             $subscriber = $this->createUserRefreshCredentials($scopes, $token['refresh_token'], $authHttp);
             $authIdentifier = 'google_auth';
         } else {
             $subscriber = new ScopedAccessToken(function ($scopes) use($token) {
                 return $token['access_token'];
             }, (array) $scopes, []);
             $authIdentifier = 'scoped';
         }
     }
     if ($subscriber) {
         $http->setDefaultOption('auth', $authIdentifier);
         $http->getEmitter()->attach($subscriber);
         $this->getLogger()->log('info', sprintf('Added listener for auth type "%s"', $authIdentifier));
     }
     return $http;
 }
 /**
  * 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);
 }
Пример #14
0
<?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>';
}
Пример #15
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);
 }