客户端未经授权使用此方法检索访问令牌服务帐户错误

ndo*_*m91 5 php google-oauth service-accounts gmail-api google-workspace

让我的服务帐户在同一个 web 应用程序上进行身份验证是一件非常令人头疼的事情,我也让用户通过 oauth2 登录。

所以我想知道,这可能吗?

如果不是,是否应该坚持使用服务帐户?是否必须自行对用户进行身份验证(老派风格)?哈哈

谢谢。

关于服务帐户,我已经启用了域范围委托,在我的 G Suite 管理控制台中启用了客户端密钥 + api 范围,并且已经获得了 php 示例,并且书籍 api 正常工作。然而,每当我尝试除书籍之外的任何其他 api 时,我都会收到错误,

客户端无权使用此方法检索访问令牌

更新:我尝试使用@dalmto的示例,并添加了几行来测试gmail api,例如:

putenv('GOOGLE_APPLICATION_CREDENTIALS=credentials.json');

$user = 'email@domain.de';

function getGoogleClient() {
    return getServiceAccountClient();
}

function getServiceAccountClient() {
    try {
        // Create and configure a new client object.
        $client2 = new Google_Client();
        $client2->useApplicationDefaultCredentials();
        $client2->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/admin.directory.user.readonly','https://www.googleapis.com/auth/userinfo.profile','https://www.googleapis.com/auth/gmail.readonly','https://www.googleapis.com/auth/calendar'));
        $client2->setAccessType('offline');
        $client2->setSubject($user);
        return $client2;
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

$newGoogleClient = getGoogleClient();

$service3 = new Google_Service_Gmail($newGoogleClient);
$results3 = $service3->users_labels->listUsersLabels($user);
Run Code Online (Sandbox Code Playgroud)

但我现在刚刚收到“400:错误请求”错误

编辑:经过更多挖掘后,有一条注释:“ failedPrecondition ”-知道可能是哪个先决条件吗?我在管理控制台中允许客户端使用以下范围:

hxxps://www.googleapis.com/auth/gmail.metadata,hxxps://www.googleapis.com/auth/userinfo.email,hxxps://www.googleapis.com/auth/userinfo.profile,hxxps: //www.googleapis.com/auth/gmail.modify,hxxps://www.googleapis.com/auth/gmail.readonly,hxxps://www.googleapis.com/auth/gmail.labels,hxxps://

​mail.google.com/

并启用 api 并启用“OAuth 同意屏幕”中的范围

DWD 也已启用:服务帐户概述屏幕截图

EDIT2:好吧,我发现缺少的前提条件是“setSubject”。

一旦我补充说它更进一步,但仍然再次失败'"error": "unauthorized_client",\n "error_description": "Client is unauthorized to retrieve access tokens using this method.'

仅供参考:创建服务帐户时,我赋予它“项目 -> 所有者”角色。这样就足够了吗?还需要添加更多吗?

EDIT3:我也刚刚检查了记录器,它说 DWD 已启用..我在这里结束了哈哈

   client: {
    adminState: {
     updateTime:  "2018-11-23T00:29:44.810Z"      
    }
    assertionMatchExistingGrant:  "MATCH_GRANT_DISABLED"     
    authType:  "PUBLIC_KEY"     
    brandId:  "aaaaaaaaaaaaaa"     
    clientId:  "aaaaaaaaaaaaaaaaaa"     
    consistencyToken:  "2018-11-23T00:29:44.953175Z"     
    creationTime:  "2018-11-23T00:29:44.810Z"     
    displayName:  "Client for servicemaint1"     
    domainWideDelegation:  "DELEGATION_ENABLED"     
    projectNumber:  "aaaaaaaaaaaaaaaa"     
    threeLeggedOauth:  "DISABLED"     
    updateTime:  "2018-11-23T00:29:44.953175Z"     
   }
Run Code Online (Sandbox Code Playgroud)

编辑4:终于可以工作了!

所以我一直在一个我为测试整个早上/昨晚创建的新项目中尝试这个。但是我的 oauth2 用户身份验证是通过另一个项目运行的(我也无法让服务帐户在昨天早上/下午工作)。

所以无论如何,我注意到: https: //myaccount.google.com/permissions “有权访问您帐户的应用程序” - 只有我的旧项目/应用程序获得了授权。因此,我切换回我的第一个项目,创建了一个新的服务帐户客户端 ID .json 文件,它最终成功对两者进行了身份验证!:)

我必须在额外的地方获得授权,而我在第二个项目中没有这样做。

再次感谢。

EDIT5:还有一个简单的问题 - 这是在 stackoverflow 上执行此操作的正确方法吗?不断回去编辑?

另外,对于后来偶然发现这一点的其他人,这是我的总身份验证块(抱歉有点长):

putenv('GOOGLE_APPLICATION_CREDENTIALS=maintenanceapp.json');

$user = 'xyz@abc.com';

function getGoogleClient() {
    return getServiceAccountClient();
}

function getServiceAccountClient() {
  $user = 'xyz@abc.com';
    try {
        // Create and configure a new client object.
        $client2 = new Google_Client();
        $client2->useApplicationDefaultCredentials();
        $client2->setScopes(['https://www.googleapis.com/auth/gmail.metadata','https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile','https://www.googleapis.com/auth/gmail.modify','https://www.googleapis.com/auth/gmail.readonly','https://www.googleapis.com/auth/gmail.labels']);
        //$client2->setAccessType('offline');
        $client2->setSubject($user);
        return $client2;
    } catch (Exception $e) {
        echo "An error occurred: " . $e->getMessage();
    }
}

$newGoogleClient = getGoogleClient();

$service3 = new Google_Service_Gmail($newGoogleClient);
$results3 = $service3->users_labels->listUsersLabels($user);


 /*************************************************
  * Ensure you've downloaded your oauth credentials
  ************************************************/
 if (!$oauth_credentials = getOAuthCredentialsFile()) {
   echo missingOAuth2CredentialsWarning();
   return;
 }
 /************************************************
  * NOTICE:
  * The redirect URI is to the current page, e.g:
  * http://localhost:8080/idtoken.php
  ************************************************/
 $redirect_uri = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
 $client = new Google_Client();
 // USER AUTH
 $client->setAuthConfig($oauth_credentials);
 $client->setRedirectUri($redirect_uri);
 $client->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile','https://www.googleapis.com/auth/gmail.readonly','https://www.googleapis.com/auth/calendar'));
 $client->setApprovalPrompt('auto');
 $client->setAccessType('offline');
 $plus = new Google_Service_Plus($client);

 /************************************************
  * If we're logging out we just need to clear our
  * local access token in this case
  ************************************************/
 if (isset($_REQUEST['logout'])) {
   unset($_SESSION['id_token_token']);
 }

 /************************************************
  * If we have a code back from the OAuth 2.0 flow,
  * we need to exchange that with the
  * Google_Client::fetchAccessTokenWithAuthCode()
  * function. We store the resultant access token
  * bundle in the session, and redirect to ourself.
  ************************************************/
 if (isset($_GET['code'])) {
   $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
   // store in the session also
   $_SESSION['id_token_token'] = $token;
   // redirect back to the example
   header('Location: https://abc.de/index.php');
   // return;
 }
 /************************************************
   If we have an access token, we can make
   requests, else we generate an authentication URL.
  ************************************************/
 if (
   !empty($_SESSION['id_token_token'])
   && isset($_SESSION['id_token_token']['id_token'])
 ) {
   $client->setAccessToken($_SESSION['id_token_token']);
 } else {
   $authUrl = $client->createAuthUrl();
   //header('Location: ' . $authUrl);
 }
 /************************************************
   If we're signed in we can go ahead and retrieve
   the ID token, which is part of the bundle of
   data that is exchange in the authenticate step
   - we only need to do a network call if we have
   to retrieve the Google certificate to verify it,
   and that can be cached.
  ************************************************/
 if ($client->getAccessToken()) {
   $token_data = $client->verifyIdToken();
 }
Run Code Online (Sandbox Code Playgroud)

DaI*_*mTo 0

在谷歌开发者控制台中,当您创建项目和凭据时,您必须选择要为哪种类型的应用程序创建哪种类型的客户端。

有几种不同的方法可以向谷歌进行身份验证。

  • OAuth2 原生
  • OAuth2 网络
  • 移动的
  • 服务帐号

使用这些客户端的代码也不同。您无法创建 Web OAuth2 客户端并将其用于调用服务帐户的代码。

“客户端无权使用此方法检索访问令牌”。

正是这个意思。您在 Google 开发者控制台上设置的客户端要么不是服务帐户客户端,要么您使用的代码不适用于服务帐户客户端。

这是我的serviceaccount.php示例。如果您的代码需要看起来像这样,并且您需要确保您在谷歌开发者控制台上创建的客户端是服务帐户客户端。

require_once __DIR__ . '/vendor/autoload.php';
// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() {
    return getServiceAccountClient();
}
/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
 * Scopes will need to be changed depending upon the API's being accessed. 
 * array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
 * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
 * @return A google client object.
 */
function getServiceAccountClient() {
    try {   
        // Create and configure a new client object.        
        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope([YOUR SCOPES HERE]);
        return $client;
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}
Run Code Online (Sandbox Code Playgroud)

开发者控制台

在“客户端”下,检查您使用的客户端是否可以在服务帐户密钥下找到。如果不是,那么它是错误的客户端类型,并且不适用于您的代码。创建一个新的服务帐户客户端并使用该客户端 ID 设置域范围委派。

在此输入图像描述