php - Google Admin SDK: You are not authorized to access this API -


since google login auth disabled since last week i'm trying oauth 2.0 working service account. want give users on our internal web application oppurtunity set there out of office.

i downloaded lastest google apis client library php. in google developer console, have created new project application , created service account credentials. have enabled api service: admin sdk in developer console.

enter image description here

i have granted account user id access correct scopes (i think): enter image description here

when use service-account.php example , change details, recieve json access token, when curl request (same before) e-mail settings user, error "you not authorized access api." occur.

my code:

<?php  include_once "templates/base.php"; require_once realpath(dirname(__file__) . '/../src/google/autoload.php'); $client_id = '124331845-deletedpart-hbh89pbgl20citf6ko.apps.googleusercontent.com'; //client id $service_account_name = '124331845-deletedpart-89pbgl20citf6ko@developer.gserviceaccount.com'; //email address $key_file_location = 'globaltext-4ce09b20cb73.p12'; //key.p12  $client = new google_client(); 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('https://apps-apis.google.com/a/feeds/emailsettings/2.0/'),     $key ); $client->setassertioncredentials($cred); if ($client->getauth()->isaccesstokenexpired()) {   $client->getauth()->refreshtokenwithassertion($cred); }  $aoutput = json_decode($client->getaccesstoken());  $stremailadressplit = explode('@', "firstname.lastname@domain.extension"); $strdomein = $stremailadressplit[1]; $stralias = $stremailadressplit[0];  $resconnectionjobs = curl_init(); $aheader = array(); $aheader[] = 'authorization: bearer '.$aoutput->access_token;  $aheader[] = 'content-type: application/atom+xml';   curl_setopt($resconnectionjobs, curlopt_url, "https://apps-apis.google.com/a/feeds/emailsettings/2.0/domain.extension/firstname.lastname/vacation");  curl_setopt($resconnectionjobs, curlopt_ssl_verifypeer, false); curl_setopt($resconnectionjobs, curlopt_httpheader, $aheader); curl_setopt($resconnectionjobs, curlopt_returntransfer, true); curl_setopt($resconnectionjobs, curlopt_header, false);  $ocurldata = curl_exec($resconnectionjobs);  curl_close($resconnectionjobs); echo $ocurldata;  ?> 

are credentials ok?

please try following procedure make sure have right credentials.

creating api keys

go developer's console , follow these steps:

  • select project
  • choose menu item "apis & auth"
  • choose menu item "registered app"
  • register app of type "web application"
  • choose 1 of following options, depending on kind of app you're creating. server side languages should use option :
    • key server apps (with ip locking)

getting access token & refresh token

create file contains following code :

<?php  if (isset($_get['code'])) {     // try access token     $code = $_get['code'];     $url = 'https://accounts.google.com/o/oauth2/token';     $params = array(         "code" => $code,         "client_id" => your_client_id,         "client_secret" => your_client_secret,         "redirect_uri" => 'http://' . $_server["http_host"] . $_server["php_self"],         "grant_type" => "authorization_code"     );      $ch = curl_init();     curl_setopt($ch, constant("curlopt_" . 'url'), $url);     curl_setopt($ch, constant("curlopt_" . 'post'), true);     curl_setopt($ch, constant("curlopt_" . 'postfields'), $params);     $output = curl_exec($ch);     $info = curl_getinfo($ch);     curl_close($ch);     if ($info['http_code'] === 200) {         header('content-type: ' . $info['content_type']);         return $output;     } else {         return 'an error happened';     } } else {      $url = "https://accounts.google.com/o/oauth2/auth";      $params = array(         "response_type" => "code",         "client_id" => your_client_id,         "redirect_uri" => 'http://' . $_server["http_host"] . $_server["php_self"],         "scope" => "https://www.googleapis.com/auth/plus.me"     );      $request_to = $url . '?' . http_build_query($params);      header("location: " . $request_to); } 

now, replace your_client_id , your_client_secret client id , client secret.

make sure scope correct. example, should https://www.googleapis.com/auth/analytics if want access analytics.

if run file, should oauth2 approval screen.

if press accept, should result looks this:

{   "access_token" : your_access_token,   "token_type" : "bearer",   "expires_in" : 3600,   "refresh_token" : your_refresh_token } 

the result may contain additional fields, depending on scope you're applying for.


connecting google's systems in background

once above work, application needs implement following workflow:

1) check if input contains parameter named "code". if "code" present, new access token , repeat step (refresh page) if "code" not present, go step 2.

2) check if have credentials stored service. if credentials present, check if access token has expired or expire soon. go step 3. if credentials not present, go auth path of service auth code , go step 1 (make sure google redirects current url).

3) if refresh needed, refresh page , go step 1. if refresh not needed, you're ready wanted in first place.


google's php library takes care if oauth2 flow you, however. if you're using library, each of steps in 3-step process taken care of library , should able whatever want google's services straight away. use strategy myself in my google adwords dashboard.

you can, however, write custom library , connect service directly. herebelow dev code project wrote few months ago. while doesn't work out of box (since it's controller that's part of larger application), should understand flow google's library takes care of under hood.

namespace application;  class controller_api_google_youtube extends controller_api {     public function read() {         $scope = "https://www.googleapis.com/auth/youtube";         $this->dooauth($scope);     }      function dooauth($scope) {          $oauth2credentials = json_file::load(__dir__ . directory_separator . 'config.json');          $paths = array(             'token' => 'https://accounts.google.com/o/oauth2/token',             'auth' => "https://accounts.google.com/o/oauth2/auth"         );         $refreshtime = 300;          if (isset($_get['code'])) {             // access code             $query = $_get;             unset($query['code']);             if (count($query) > 0) {                 $query = '?' . http_build_query($query);             } else {                 $query = '';             }              $client = \powertools\http_client::factory(                         array(                             'maps' => array(                                 'url' => $paths['token'],                                 'returntransfer' => 1,                                 'post' => true,                                 'postfields' => array(                                     'code' => $_get['code'],                                     "client_id" => $oauth2credentials['client_id'],                                     "client_secret" => $oauth2credentials['client_secret'],                                     "redirect_uri" => http_protocol . url_path . $query,                                     "grant_type" => "authorization_code"                                 )                             )                         )             )->execute();             $responses = $client->getresponses();             $response = array_pop($responses);             $info = $response['maps']->getinfo();             $content = $response['maps']->getcontent();             if ($info['http_code'] === 200) {                 $output = json::decode($content);                 $oauth2credentials[$scope] = array();                 $oauth2credentials[$scope]['expires'] = time() + $output['expires_in'];                 $oauth2credentials[$scope]['access_token'] = $output['access_token'];                 $oauth2credentials[$scope]['refresh_token'] = $output['refresh_token'];                 file_put_contents(__dir__ . directory_separator . 'config.json', json::encode($oauth2credentials));                 header("location: " . http_protocol . url_path . $query);             } else {                 echo "something went wrong";             }         } elseif (!isset($oauth2credentials[$scope])) {             // auth code              header("location: " . $paths['auth'] . '?' . http_build_query(                         array(                             "response_type" => "code",                             "client_id" => $oauth2credentials['client_id'],                             "redirect_uri" => http_protocol . domain_path,                             "scope" => $scope                         )             ));         } elseif ($oauth2credentials[$scope]['expires'] - $refreshtime < time()) {             // refresh access code              $client = \powertools\http_client::factory(                         array(                             'maps' => array(                                 'url' => $paths['token'],                                 'returntransfer' => 1,                                 'post' => true,                                 'postfields' => array(                                     "client_id" => $oauth2credentials['client_id'],                                     "client_secret" => $oauth2credentials['client_secret'],                                     "refresh_token" => $oauth2credentials[$scope]['refresh_token'],                                     "grant_type" => "refresh_token"                                 )                             )                         )             )->execute();             $responses = $client->getresponses();             $response = array_pop($responses);             $info = $response['maps']->getinfo();             $content = $response['maps']->getcontent();             if ($info['http_code'] === 200) {                 $output = json::decode($response['maps']->getcontent());                 $oauth2credentials[$scope]['expires'] = time() + $output['expires_in'];                 $oauth2credentials[$scope]['access_token'] = $output['access_token'];                 file_put_contents(__dir__ . directory_separator . 'config.json', json::encode($oauth2credentials));                 $this->read();             } else {                 $this->output = array("error" => "something went wrong");             }         } else {             $this->dosomethinguseful($oauth2credentials, $scope);         }         return $this;     }       function dosomethinguseful($oauth2credentials, $scope) {         // https://developers.google.com/youtube/v3/sample_requests?hl=nl         $client = \powertools\http_client::factory(                     array(                         'maps' => array(                             'useragent' => 'mozilla/5.0 (windows; u; windows nt 5.1; en-us; rv:1.8.1.13) gecko/20080311 firefox/2.0.0.13',                             'url' => 'https://www.googleapis.com/youtube/v3/channels?part=contentdetails&mine=true',                             'returntransfer' => true,                             'httpheader' => array(                                 'authorization: bearer ' . $oauth2credentials[$scope]['access_token'],                                 'accept-encoding: gzip, deflate'                             )                         )                     )         )->execute();         $responses = $client->getresponses();         $response = array_pop($responses);         $content = $response['maps']->getcontent();         $this->output = json::decode(gzdecode($content));     } } 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -