Coder Social home page Coder Social logo

google-auth-library-php's Introduction

Google Auth Library for PHP

Homepage
http://www.github.com/google/google-auth-library-php
Reference Docs
https://googleapis.github.io/google-auth-library-php/main/
Authors
Tim Emiola
Stanley Cheung
Brent Shaffer
Copyright
Copyright © 2015 Google, Inc.
License
Apache 2.0

Description

This is Google's officially supported PHP client library for using OAuth 2.0 authorization and authentication with Google APIs.

Installing via Composer

The recommended way to install the google auth library is through Composer.

# Install Composer
curl -sS https://getcomposer.org/installer | php

Next, run the Composer command to install the latest stable version:

composer.phar require google/auth

Application Default Credentials

This library provides an implementation of Application Default Credentials (ADC) for PHP.

Application Default Credentials provides a simple way to get authorization credentials for use in calling Google APIs, and is the recommended approach to authorize calls to Cloud APIs.

Set up ADC

To use ADC, you must set it up by providing credentials. How you set up ADC depends on the environment where your code is running, and whether you are running code in a test or production environment.

For more information, see Set up Application Default Credentials.

Enable the API you want to use

Before making your API call, you must be sure the API you're calling has been enabled. Go to APIs & Auth > APIs in the Google Developers Console and enable the APIs you'd like to call. For the example below, you must enable the Drive API.

Call the APIs

As long as you update the environment variable below to point to your JSON credentials file, the following code should output a list of your Drive files.

use Google\Auth\ApplicationDefaultCredentials;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

// specify the path to your application credentials
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/credentials.json');

// define the scopes for your API call
$scopes = ['https://www.googleapis.com/auth/drive.readonly'];

// create middleware
$middleware = ApplicationDefaultCredentials::getMiddleware($scopes);
$stack = HandlerStack::create();
$stack->push($middleware);

// create the HTTP client
$client = new Client([
  'handler' => $stack,
  'base_uri' => 'https://www.googleapis.com',
  'auth' => 'google_auth'  // authorize all requests
]);

// make the request
$response = $client->get('drive/v2/files');

// show the result!
print_r((string) $response->getBody());
Guzzle 5 Compatibility

If you are using Guzzle 5, replace the create middleware and create the HTTP Client steps with the following:

// create the HTTP client
$client = new Client([
  'base_url' => 'https://www.googleapis.com',
  'auth' => 'google_auth'  // authorize all requests
]);

// create subscriber
$subscriber = ApplicationDefaultCredentials::getSubscriber($scopes);
$client->getEmitter()->attach($subscriber);

Call using an ID Token

If your application is running behind Cloud Run, or using Cloud Identity-Aware Proxy (IAP), you will need to fetch an ID token to access your application. For this, use the static method getIdTokenMiddleware on ApplicationDefaultCredentials.

use Google\Auth\ApplicationDefaultCredentials;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

// specify the path to your application credentials
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/credentials.json');

// Provide the ID token audience. This can be a Client ID associated with an IAP application,
// Or the URL associated with a CloudRun App
//    $targetAudience = 'IAP_CLIENT_ID.apps.googleusercontent.com';
//    $targetAudience = 'https://service-1234-uc.a.run.app';
$targetAudience = 'YOUR_ID_TOKEN_AUDIENCE';

// create middleware
$middleware = ApplicationDefaultCredentials::getIdTokenMiddleware($targetAudience);
$stack = HandlerStack::create();
$stack->push($middleware);

// create the HTTP client
$client = new Client([
  'handler' => $stack,
  'auth' => 'google_auth',
  // Cloud Run, IAP, or custom resource URL
  'base_uri' => 'https://YOUR_PROTECTED_RESOURCE',
]);

// make the request
$response = $client->get('/');

// show the result!
print_r((string) $response->getBody());

For invoking Cloud Run services, your service account will need the Cloud Run Invoker IAM permission.

For invoking Cloud Identity-Aware Proxy, you will need to pass the Client ID used when you set up your protected resource as the target audience. See how to secure your IAP app with signed headers.

Call using a specific JSON key

If you want to use a specific JSON key instead of using GOOGLE_APPLICATION_CREDENTIALS environment variable, you can do this:

use Google\Auth\CredentialsLoader;
use Google\Auth\Middleware\AuthTokenMiddleware;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

// Define the Google Application Credentials array
$jsonKey = ['key' => 'value'];

// define the scopes for your API call
$scopes = ['https://www.googleapis.com/auth/drive.readonly'];

// Load credentials
$creds = CredentialsLoader::makeCredentials($scopes, $jsonKey);

// optional caching
// $creds = new FetchAuthTokenCache($creds, $cacheConfig, $cache);

// create middleware
$middleware = new AuthTokenMiddleware($creds);
$stack = HandlerStack::create();
$stack->push($middleware);

// create the HTTP client
$client = new Client([
  'handler' => $stack,
  'base_uri' => 'https://www.googleapis.com',
  'auth' => 'google_auth'  // authorize all requests
]);

// make the request
$response = $client->get('drive/v2/files');

// show the result!
print_r((string) $response->getBody());

Call using Proxy-Authorization Header

If your application is behind a proxy such as Google Cloud IAP, and your application occupies the Authorization request header, you can include the ID token in a Proxy-Authorization: Bearer header instead. If a valid ID token is found in a Proxy-Authorization header, IAP authorizes the request with it. After authorizing the request, IAP passes the Authorization header to your application without processing the content. For this, use the static method getProxyIdTokenMiddleware on ApplicationDefaultCredentials.

use Google\Auth\ApplicationDefaultCredentials;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

// specify the path to your application credentials
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/credentials.json');

// Provide the ID token audience. This can be a Client ID associated with an IAP application
//    $targetAudience = 'IAP_CLIENT_ID.apps.googleusercontent.com';
$targetAudience = 'YOUR_ID_TOKEN_AUDIENCE';

// create middleware
$middleware = ApplicationDefaultCredentials::getProxyIdTokenMiddleware($targetAudience);
$stack = HandlerStack::create();
$stack->push($middleware);

// create the HTTP client
$client = new Client([
  'handler' => $stack,
  'auth' => ['username', 'pass'], // auth option handled by your application
  'proxy_auth' => 'google_auth',
]);

// make the request
$response = $client->get('/');

// show the result!
print_r((string) $response->getBody());

External credentials (Workload identity federation)

Using workload identity federation, your application can access Google Cloud resources from Amazon Web Services (AWS), Microsoft Azure or any identity provider that supports OpenID Connect (OIDC).

Traditionally, applications running outside Google Cloud have used service account keys to access Google Cloud resources. Using identity federation, you can allow your workload to impersonate a service account. This lets you access Google Cloud resources directly, eliminating the maintenance and security burden associated with service account keys.

Follow the detailed instructions on how to Configure Workload Identity Federation.

Verifying JWTs

If you are using Google ID tokens to authenticate users, use the Google\Auth\AccessToken class to verify the ID token:

use Google\Auth\AccessToken;

$auth = new AccessToken();
$auth->verify($idToken);

If your app is running behind Google Identity-Aware Proxy (IAP), you can verify the ID token coming from the IAP server by pointing to the appropriate certificate URL for IAP. This is because IAP signs the ID tokens with a different key than the Google Identity service:

use Google\Auth\AccessToken;

$auth = new AccessToken();
$auth->verify($idToken, [
  'certsLocation' => AccessToken::IAP_CERT_URL
]);

License

This library is licensed under Apache 2.0. Full license text is available in COPYING.

Contributing

See CONTRIBUTING.

Support

Please report bugs at the project on Github. Don't hesitate to ask questions about the client or APIs on StackOverflow.

google-auth-library-php's People

Contributors

ait-sd avatar bshaffer avatar carusogabriel avatar cedricziel avatar dwsupplee avatar gabihodoroaga avatar google-cloud-policy-bot[bot] avatar jdpedrie avatar jeromegamez avatar justinbeckwith avatar kasperfranz avatar michaelbausor avatar murgatroid99 avatar nyholm avatar paolaruby avatar piaxc avatar release-please[bot] avatar renovate-bot avatar samanthaadrichem avatar saranshdhingra avatar silvolu avatar stanley-cheung avatar stephenmcd avatar tbetbetbe avatar theacodes avatar vishwarajanand avatar vojtasvoboda avatar yash30201 avatar yfuruyama avatar zhouyihaiding avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

google-auth-library-php's Issues

Usage with Guzzle5

If you create a project with the following composer.json. How can I get it to work? The readme suggest using HandlerStack but that is only available in Guzzle6. Am I missing something?

"require": {
        "google/auth": "^0.7.0",
        "guzzlehttp/guzzle": "^5.0"
    }

Pass Expire on Set instead of Get in CacheInterface

Modern Key-Value stores such as Redis and Memcached set the expire-time of a key during the Set operation by setting a TTL for a key.

The CacheInterface instead passes the expire option in the Get function, which makes things difficult because now we have to store a timestamp during Set function and check it in the Get function. Additionally, the key can no longer be automatically garbage collected by the Key-Value store..

Expire param should be switched to the Set operation.

OpenSSL unable to sign data

Trying to use account service authorization and get error message like in Subject.
Also test readme code, still such error appears. =\

PS: This error is rised at firebase/JWT class, but i can not understand what's wrong. Manually trying different algos, still have this error.

Any help?

DefaultCredentials can be consolidated into CredentialsLoader

  1. The autoloader will not be able to locate DefaultCredentials because it is in the file of a different class name
  2. the call to CredentialsLoader::fromWellKnownFile will throw a fatal error because makeCredentials does not exist in this class

I recommend we move function makeCredentials into the CredentialsLoader class and remove the DefaultCredentials class all together.

Promote OAuth2 service account to Jwt Access credentials

Application Default Credentials can return Oauth2 service account credentials. gRPC can use more efficient JwtAccess credentials in place of this if no scopes have been specified. This tracks logic to detect this case and "promote" the credentials to JwtAccess form with the same identity properties if the OAuth2 form is passed in for use by gRPC.

Logic should be similar to this (in Java):

if (credentials instanceof ServiceAccountOAuth2Credentials) {
ServiceAccountOAuth2Credentials serviceAccount =
(ServiceAccountOAuth2Credentials)credentials;
if (serviceAccount.getScopes().length() == 0) {
credentials = new ServiceAccountJwtAccessCredentials(
serviceAccount.getAccountEmail(),
serviceAccount.getPrivateKey(),
serviceAccount.getPrivateKeyId());
}
}

ADC Support for User Refresh Tokens

The initial implementation of Application Default Credentials is missing one of the 3 credential types: User Refresh Tokens. This is basically the end result of a 3LO flow, and is an important part of the tool integration, as the Cloud SDK writes out this form of credential in the well-known-file location.

The file format to support is this:

{

"type": "authorized_user",

"client_id": "kflc91.apps.googleusercontent.com",

"client_secret": "1/olgReg3YaBQqxm6T",
"refresh_token": "2/fFAGRNJru1FTz70BzhT3Zg"

}
The "type" value is to differentiate it from a service account. The other 3 values are needed to get refresh tokens back. This is a common OAuth2 scenario, so there is likely to be an existing object that already supports getting access tokens from these values. This file could be in either the well-known file location or the environment variable location.

For reference, the Java implementation of these features is here:
https://github.com/google/google-auth-library-java/blob/master/oauth2_http/java/com/google/auth/oauth2/GoogleCredentials.java
https://github.com/google/google-auth-library-java/blob/master/oauth2_http/java/com/google/auth/oauth2/UserCredentials.java

Add getter on subscribers for auth identifiers

  • AuthTokenFetcher requires ['auth' => 'google_auth']
  • ScopedAccessToken requires ['auth' => 'scoped']
  • Simple requires ['auth' => 'simple']

It would be helpful to have a getAuthIdentifier method on these classes so we can obtain the values they expect programmatically.

Although, I am not sure why these are required in the first place, so maybe I'm missing something. I assume the reasoning for requiring the auth property to be set in Guzzle is best practices, and so it's ok to programmatically apply it.

No sample code provided

As far as I can tell, this library doesn't provide any sample code showing how to use it. I would expect to see a brief overview in the README, with a complete working sample application that uses it.

Jwt Access Credentials should cache JWTs

The JWT Access Credentials should temporarily cache JWTs. Suggested algorithm:

  • Hash JWTs using Audience as key.
  • Also store the timestamp of last use with each JWT.
  • On access clear any JWT unused for more than 1 hour.

Confusion between naming of "Fetcher", "Credentials" and "Loader"

Some things I found confusing:

  • The class AuthTokenFetcher does not implement FetchAuthTokenInterface, but implements SubscriberInterface
  • The class CredentialsLoader implements FetchAuthTokenInterface
  • All instances passed in as the $fetcher variable are suffixed with Credentials
  • the IAMCredentials do not extend CredentialsLoader but other Credentials classes do

We can use namespacing to make these more obvious. Something like this might work:

src/
    Subscriber/
        AuthTokenFetcher
        Simple
        ScopedAccessToken
    Fetcher/
        AbstractCredentials (renamed from CredentialsLoader)
        AppIdentityCredentials
        ServiceAccountCredentials
        ServiceAccountJwtAccessCredentials
        GCECredentials
        UserRefreshCredentials

... as for IAMCredentials, I assume this needs to implement FetchAuthTokenInterface, but this hasn't been done yet.

Missing Client Credentials when fetching Auth Token

the call to generateCredentialsRequest, called from fetchAuthToken, does not include the client credentials. This results in a 400 Bad Request

{
    "error": "invalid_request",
    "error_description": "Missing parameter: client_id"
}

It seems to me the HTTP Basic authorization header should be added to the HTTP client before the request is sent. This is a pretty glaring absence, am I missing something here?

Returns short information

If I use a simple json wrapper when attempting to update a location wiht a bad address using Google My Business API I get the following error.

{
  "error": {
    "code": 400,
    "message": "Request contains an invalid argument.",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.mybusiness.v2.ValidationError",
        "errorDetails": [
          {
            "code": 1100,
            "field": "location.address.country",
            "message": "We cannot locate the specified address. Please verify it is correct and/or drag the marker pin on the provided map to the correct location."
          }
        ]
      }
    ]
  }
}

using google php client RC, with this library.

I get

{
  "error": {
    "code": 400,
    "message": "Request contains an invalid argument.",
    "errors": [
      {
        "message": "Request contains an invalid argument.",
        "domain": "global",
        "reason": "badRequest"
      }
    ],
    "status": "INVALID_ARGUMENT"
  }
}

Is there any way to get more information from the guzzle6 error?

Add a new credentials type: IAMCredential

It is constructed with and holds two fields

  • iam-token
  • iam-authority-selector

IAMCredential applies these values to requests as a pair HTTP headers (or an equivalents) keys

  • "x-goog-iam-authorization-token"
  • "x-goog-iam-authority-selector"
    respectively

N.B, there is no requirement that an IAMCredential be returned by Application Default Credentials.

Apache2 / php on a Mac -- Documentation suggestions...

For a Mac, you can enable Apache2 using these instructions.

Once that is done, you should can set either the HOME or the GOOGLE_APPLICATION_CREDENTIALS in either .htaccess or /etc/apache2/users/userName.conf

SetEnv GOOGLE_APPLICATION_CREDENTIALS /Users/lesv/Downloads/Abelana-5ca655910529.json
# SetEnv HOME /Users/lesv/

dead link in docs

To use Application Default Credentials, You first need to download a set of JSON credentials for your project. Go to APIs & Auth > Credentials in the Google Developers Console and select Service account from the Add credentials dropdown.

the Google Developers Console link is 404.

Implement Caching on a Credentials level

Caching could be implemented on a Credentials level instead of a Middleware/Subscriber level.

PROS:

  • Caching happens closer to the actual token fetching, which will allow more libraries to take advantage of caching hands-free (see googleapis/gax-php#26)
  • Straightforward refactoring

CONS:

  • Breaking BC (again)

ScopedAccessToken subscriber/middleware has caching. We could leave the caching logic in there.

Guzzle6/PSR-7 support

The lack of support for Guzzle6 in this library is causing problems for our users (see googleapis/google-api-php-client#720). We have a few options:

  1. Implement handlers, and use the handler for the appropriate guzzle version.
    • Pros: There is a precedent for it
    • Cons: Additional classes, and it may not work for more fancy things such as subscribers
  2. Check which version is being used in the OAuth2 and GCECredentials, as these are the only places where the Guzzle Client is called directly! This still requires adding Middleware support, but this could be added in a single class (similar to AuthTokenFetcher) specifically for Guzzle6/PSR7.
    • Pros: Minimal change required - two files + 1 new file. Should then work for all PSR-7-compatible HTTP Clients, and may be able to play nicely with the third option (see below)
    • Cons: May be trickier to implement with Middleware than expected
  3. Use an HTTP abstraction library (see #81)
    • Pros: Users can add Google Authentication onto whatever HTTP client they are using, we do not force them to use Guzzle
    • Cons: Adds another dependency. Adds yet another abstraction layer. It's hard to say if these libraries will actually be supported (similar to ORM problem). The library mentioned might not be stable enough.

Some additional thoughts:

  • The most important thing is for this library to work with at least one HTTP Client
  • The Google Client library can be opinionated with Guzzle (because of its complexity)
  • If this library can work with any PSR-7-compatible HTTP library, that would be a huge community win.

composer.phar -- can't find this.

$ php ~/bin/composer.phar require google/auth

[InvalidArgumentException]
Could not find package google/auth at any version for your minimum-stability (stable). Check the package spelling or your minimum-stability

require [--dev] [--prefer-source] [--prefer-dist] [--no-progress] [--no-update] [--update-no-dev] [--update-with-dependencies] [--ignore-platform-reqs] [--sort-packages] [packages1] ... [packagesN]

Retrieve `expires_in` when new access token is fetched automatically from refresh token

The callback option #110 added is great, but it only provides the access token. But I'd also like to know when the access token is going to expire. Why not pass the entire access token response to the callback? I am updating my persistent store with the new access token, but need to know when it expires so that the refresh token (already stored) can be used if necessary. And assuming an hour expiration isn't safe.

I suggest changing AuthTokenMiddleware.php#L163 to:

call_user_func($this->tokenCallback, $this->getFullCacheKey(), $auth_tokens);

That way in the callback you can access $auth_tokens['access_token'] and $auth_tokens['expires_in'].

If we need to make this change backwards compatible, we could always do this for now:

call_user_func($this->tokenCallback, $this->getFullCacheKey(), $auth_tokens['access_token'], $auth_tokens);

Please and thank you! :)

Make CredentialsLoader abstract and remove fetchAuthToken and getCacheKey

CredentialsLoader contains references to this->auth, which are defined in some subclasses but not all of them. This will create PHP fatal errors in some cases. We should

  1. Remove fetchAuthToken and getCacheKey from CredentialsLoader
    • Paste this code in the subclasses which use them
  2. Make CredentialsLoader abstract
    • The static calls to fromWellKnownFile and fromEnv will still function as expected

Autoload in php not working

Included auto-load

<?php require_once('controller/google-auth-library-php-master/autoload.php'); ?>
throw me error on any class that i call

PSR

Considering Google is quite an influencial body, you guys really should be following coding standards.

Please see this guide...
http://www.php-fig.org/

OAuth2 class seems to have some bugs with service account JWT flow.

(1) The DEFAULT_EXPIRY_MINUTES is actually used as seconds, so it should be renamed to _SECONDS and updated to 3600:
https://github.com/google/google-auth-library-php/blob/master/src/OAuth2.php#L38

(2) According to this doc:
https://developers.google.com/identity/protocols/OAuth2ServiceAccount
"prn" is no longer used and "scope" is required. So some of the logic here:
https://github.com/google/google-auth-library-php/blob/master/src/OAuth2.php#L366

needs to be updated.

Can you confirm this is the case. I can submit a pull request for this. Thanks.

Change example requests from taskqueue to something more universal

The sample code that calls the TaskQueue API makes it really easy to accidentally receive the error message "you are not allowed to make this api call"

This is because it requires the user to:

  1. replace "myproject" in the URL with their current Project ID
  2. replace "myqueue" in the URL with their Queue ID
  3. Set up a task queue

It would be great to have an easier path to make the first Google API call, one that doesn't require subbing out these parameters. The Google+ API is a good example of this - it's very simple, and doesn't require any steps to activate other than attaching the authentication

Help: How to call my own API hosted on https://xxx.appspot.com/myapp

I need to post some data that is generated periodically to my GAE app using a PHP script. I don't really understand how to make this library work for that. I generated a service key which my script points to like this putenv('GOOGLE_APPLICATION_CREDENTIALS=/Users/me/myfile.json');
However the docs at https://github.com/google/google-auth-library-php talks about scopes like Drive etc, and I am not using Drive, just my own API at that URL.
I used to have this script automatically uploading data last year until that way of authenticating was deprecated.
What is the "scope" of a GAE app? How would the sample code below "Call the APIs" be changed to allow POSTs to an GAE app?

New docset required

  • Add a separate doc set for PHP authentication, distinct from the api
  • The link in composer.json should be updated to the docset link

PHP Default Credentials check for and user GAE App Identity Credentials

The current implementation of ApplicationDefaultCredentials in PHP does not yet support the GAE App Identty. The first class GAE lanauges should check for this environment and use this identity after checking for the environment variable and well-known-file, but before checking for GCE.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.