Google-api-php-client: Service Accounts: Unauthorized client or scope in request.

Created on 19 Jul 2016  路  18Comments  路  Source: googleapis/google-api-php-client

I've tried every combination of things to try and gain some progress on this issue but I can't get anywhere. I'm trying to use a service account to access a calendar of a user on the domain. The service account is setup, appears to be working fine. As far as I can tell the Domain-wide Delegation is enabled according to https://developers.google.com/identity/protocols/OAuth2ServiceAccount?hl=en_US#delegatingauthority. In my code below, Everything works fine until I set the impersonation account and I get the error in the title.

$client = new Google_Client(); $client->setSubject('[email protected]'); $client->setAuthConfig($_SERVER['DOCUMENT_ROOT'] . '/private.json');

This will cause any type of api request to fail with the error:

Message: { "error": "unauthorized_client", "error_description": "Unauthorized client or scope in request." }

Most helpful comment

Doh! If anyone finds this and is wondering the same thing (I can't upgrade to API 2.0 yet because of dependencies on 1.1 still :-/) turns out the problem was mine. Follow these instructions:

https://developers.google.com/api-client-library/php/auth/service-accounts

My issue here was that my scopes array in PHP had one more scope in it than my service account had access to. Thus, not authorized! I didn't notice at first because the particular thing I was doing using Google APIs was authorized.

All 18 comments

I attempted to do this exact same thing in node.js and it works fine. My conclusion is that there's something wrong with the way the impersonation works. The node auth with impersonation works similar to the way v1.x worked.

$credentials = new Google_Auth_AssertionCredentials( $client_email, $scopes, $private_key, 'notasecret', 'http://oauth.net/grant_type/jwt/1.0/bearer', $user_to_impersonate, );

The new way of impersonating, setSubject, doesn't seem to work for me. I may be doing it wrong but I'd love some input from you others.

@thegregthomp can you include some node sample code so we can test this?

I am struggling similarly with Google_Service_Gmail - too many hours now.

Super curious to know as well, why @bshaffer 's block on pre-authenticating the service client here is fully undocumented here and here???

Probably because it's not at all official or supported 馃槃

I'm glad it was helpful though. I will see about getting it published.

thx for replying Brent. You may be speaking of the "beta" php client, but the flow is still fairly ident regardless of, no?
meantime, I've found no way to drop a message into my (own) gmail inbox from a web server - the literally simplest thing one would want to do :l

No, I'm talking about the flow itself. I suggest opening a Stack Overflow ticket with your code and posting the link here, and I'll try to help you figure it out. Sounds like you're struggling with the Auth and not the API, yes?

Indeed currently stuck on the Auth. Outlined here
Thanks.

I do have the same issue with a special twist: The code does work for a quite old service account. Trying to run it with a new developer account/service-account/json file the behaviour is exactly the same.

Without the

  $client->setSubject('[email protected]');

the code works fine - except that, of course, there is no useful data coming back.

Right, here are some more details about my code/setup. Forgive me if this is not the best place but I am getting a bit desperate here and it would be good to establish whether this is a code or config issue....

use Google_Client;
use Google_Service_Webmasters;

$client = new Google_Client();
$client->setApplicationName('s2s-test');
$client->setAuthConfig('auth.json');
$client->setScopes([Google_Service_Webmasters::WEBMASTERS_READONLY]);
$client->setSubject('[email protected]');

$service = new Google_Service_Webmasters($client);
$siteListResponse = $service->sites->listSites();

As for the auth.json I did:
a) Login as [email protected] at ttps://console.developers.google.com/iam-admin/serviceaccounts
b) Create/select project
c) Create new service account

  • download private key
  • select editor role
  • check DwD

d) Create key in JSON format

As mentioned above the code does work for an older account that already had an existing service account.

I've tried the new auth.json file with some sample python code from here: https://github.com/google/google-api-python-client and the service_account sample code works fine with it.
Either I have missed another step in configuring the service account or new accounts do behave slightly different.
OTOH, the python code doesn't do anything like setSubject('..')...

@DerManoMann: Yep, I can relate. In python we didn't need a method like setSubject('..') as well. Did you figure out a solution? :(

@negreanucalin Yes, I ended up following options 2 from here: https://github.com/google/google-api-php-client/issues/801#issuecomment-171417538

Not ideal, but it does work - I even wrote a little page with a form to deal with validate the new token, etc. so I do not have to start digging again!

@DerManoMann Unfortunately I would need to do my data processing in a cron job :( . thanks for the advice

@negreanucalin That is no problem - the token validation you have to do once only. After that you have a OAuth user/app with permission to access your account and you use the p12/json file just like before

I am also having difficulty with this code. Here's the thing -- at first the code worked fine, but now when I'm trying to refresh it breaks on the refresh:

        $credentials = new \Google_Auth_AssertionCredentials(
            \Config::get('services.google.service_account_credentials.client_email'),
            \Config::get('services.google.service_account_credentials.scopes', []),
            \Config::get('services.google.service_account_credentials.private_key'),
            'notasecret',
            'http://oauth.net/grant_type/jwt/1.0/bearer',
            $user
        );


        $googleClient = new \Google_Client();
        //$googleClient->setCache(new \Google_Cache_Apc($googleClient));
        $googleClient->setAssertionCredentials($credentials);

        if($googleClient->getAuth()->isAccessTokenExpired()) {
            $googleClient->getAuth()->refreshTokenWithAssertion();
        }

        return json_decode($googleClient->getAuth()->getAccessToken(), true);

This returns in error when calling refreshTokenWithAssertion():

{ "error" : "unauthorized_client", "error_description" : "Unauthorized client or scope in request." }

Doh! If anyone finds this and is wondering the same thing (I can't upgrade to API 2.0 yet because of dependencies on 1.1 still :-/) turns out the problem was mine. Follow these instructions:

https://developers.google.com/api-client-library/php/auth/service-accounts

My issue here was that my scopes array in PHP had one more scope in it than my service account had access to. Thus, not authorized! I didn't notice at first because the particular thing I was doing using Google APIs was authorized.

The original issue seems to be resolved. If there are still outstanding issues, please file a new bug.

@michaelbausor The original issue was resolved? Can you elaborate on that for me. I am having the exact same issue. I have code that was working for about a week and then all of a sudden started to get the Error retrieving token: unauthorized_client, Client is unauthorized to retrieve access tokens using this method. I'm worried as this prevents my app from performing its core functions. Please advise.

@teddyfran The previous post seems to give a resolution to the "Unauthorized client or scope in request." error described in the original post. Your error seems different, and better tracked by https://github.com/google/google-api-php-client/issues/1142 Is that correct?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kungufli picture kungufli  路  3Comments

unixkapl picture unixkapl  路  3Comments

camohub picture camohub  路  3Comments

artemiusgreat picture artemiusgreat  路  3Comments

mevsme picture mevsme  路  4Comments