Search code examples
phpauthenticationgoogle-appsgoogle-api-php-clientgoogle-directory-api

Google Directory API(PHP-client) - error 401 Login Required


I am trying to add user using Service Account and constantly get '401 Login Required' error. I already put p12-key on server and add permission Service Account/Scope in Admin Console. I had done implementation with usual authentication but got same problem.

<?php
        session_start();
        set_include_path($_SERVER['DOCUMENT_ROOT'].'/src/php/');
        require_once ('Google/Client.php');

        $scope = 'https://www.googleapis.com/auth/admin.directory.user'; 
        $client_id = 'xxxxx.apps.googleusercontent.com'; //Client ID
        $service_account_name = 'xxxxx@developer.gserviceaccount.com'; //Email Address 
        $key_file_location = 'key.p12'; //key.p12

        $client = new Google_Client();
        $client->setApplicationName("test product");

        if (isset($_SESSION['service_token'])) 
        {
          $client->setAccessToken($_SESSION['service_token']);
        }

        $key = file_get_contents($key_file_location);
        $cred = new Google_Auth_AssertionCredentials
        (
          $service_account_name,
          array($scope),
          $key
        );  
        $client->setAssertionCredentials($cred);

        if($client->getAuth()->isAccessTokenExpired()) 
        {
          $client->getAuth()->refreshTokenWithAssertion($cred);
        }
        $_SESSION['service_token'] = $client->getAccessToken();

        if($client->getAccessToken())
        {   
            $requestUrl = 'https://www.googleapis.com/admin/directory/v1/users';
            $requestMethod = 'POST';
            $requestHeader = array('Content-Type' => 'application/json', 'Content-Length' => 'CONTENT_LENGTH');
            $postBody ='{
                          "primaryEmail": "newuser@testpurpose.esy.es",
                          "name": {
                           "givenName": "user_name",
                           "familyName": "user_familyName"
                          },
                          "suspended": false,
                          "password": "passpass",
                          "ims": [
                           {
                            "type": "work",
                            "protocol": "gtalk",
                            "im": "user_im@talk.example.com",
                            "primary": true
                           }
                          ]
                        }';

            $request = new Google_Http_Request($requestUrl , $requestMethod,  $requestHeader, $postBody);
            $result = $client->execute($request); 

            print_r($result);     
        }
    ?>

Error

Uncaught exception 'Google_Service_Exception' with message 'Error calling POST https://www.googleapis.com/admin/directory/v1/users: (401) Login Required' in /home/u538421519/public_html/src/php/Google/Http/REST.php:79 Stack trace:
#0 /home/u538421519/public_html/src/php/Google/Http/REST.php(44): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request))
#1 /home/u538421519/public_html/src/php/Google/Client.php(556): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request)) 
#2 /home/u538421519/public_html/index.php(58): Google_Client->execute(Object(Google_Http_Request))
#3 {main} thrown in /home/u538421519/public_html/src/php/Google/Http/REST.php on line 79

Solution

  • Request is sent without token:

    $request = new Google_Http_Request($requestUrl , $requestMethod,  $requestHeader, $postBody);
    $result = $client->execute($request); 
    

    Request is sent with token:

    $request = new Google_Http_Request($requestUrl , $requestMethod,  $requestHeader, $postBody);
    $result = $client->getAuth()->authenticatedRequest($request);