Search code examples
google-apigoogle-admin-sdk

How to access admin.directory.group via OAuth2 in a cron job?


I am trying (and failing) to use OAuth2 to make calls to the admin.directory.group scope via a command line script. I tried configuring a Service Account to do this, but get this error message:

Error calling GET https://www.googleapis.com/admin/directory/v1/groups/foo%40example.com: (403) Not Authorized to access this resource/api

I also tried using an "Installed" application type, taking the manual step of obtaining an authorization code and subsequently a refresh token, but got the same Not Authorized error.

I do have "Enable API access" checked, and also have "Admin SDK" enabled in my project (though oddly it doesn't list admin.directory.group as one of Admin SDK's scopes).

What am I doing wrong?


Solution

  • I finally got this to work using a service account. I did have to grant 3rd party access as Emily Lam suggested, but by a different means:

    1. Log in to admin console
    2. Security -> Advanced settings -> Authentication -> Mange third party OAuth Client access
    3. Authorize a new client by setting the Client Name to the Client ID of the service account, and the the API scope to whatever you need from the Admin SDK (e.g., https://www.googleapis.com/auth/admin.directory.group)

    The other thing I needed to do was make sure my request was being made on behalf on an administrative user. Using the PHP API, setting up the credentials object looks like this:

    $cred = new Google_Auth_AssertionCredentials(
        $clientEmail,
        'https://www.googleapis.com/auth/admin.directory.group',
        file_get_contents($keyFile));
    $cred->sub = '[email protected]';
    

    Now I am able to successfully make calls using the Google_Service_Directory class.