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

标签 php google-oauth gmail-api service-accounts google-workspace

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

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

如果没有,是否应该坚持使用服务帐户?是否必须以自己的方式对用户进行身份验证 - 老派风格?哈哈

谢谢。

关于服务帐户,我已启用全域delegation ,在我的 G Suite 管理控制台中启用了客户端 key + api 范围,并获得了书籍 api 工作的 php 示例。但是,每当我尝试除书籍之外的任何其他 api 时,我都会收到错误消息,

client is unauthorized to retrieve access tokens using this method



更新:我尝试使用@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);

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

编辑 :经过更多挖掘后,有一条注释:' 失败前提 ' - 知道这可能是哪个先决条件吗?我已在我的管理控制台中为客户端允许以下范围:

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/



并启用了 apis 并在“OAuth 同意屏幕”中启用了范围

DWD 也已启用:Service Account Overview Screenshot

编辑2 :好的,所以我发现缺少的先决条件是“setSubject”。

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

仅供引用:在创建服务帐户时,我给了它“项目 -> 所有者”角色。够了吗?是否必须添加更多?

编辑3 :我也刚刚检查了记录器,它说 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"     
   }

编辑4:终于开始工作了!

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

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

我必须授权我在第二个项目中没有做过的额外工作。

再次感谢。

编辑5:一个更简单的问题 - 这是在 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();
 }

最佳答案

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

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

  • OAuth2 原生
  • OAuth2 网页
  • 手机
  • 服务帐号

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

    "client is unauthorized to retrieve access tokens using this method".



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

    这是我的 serviceaccount.php样本。如果您的代码需要看起来像这样,并且您需要确保您在 google 开发者控制台上创建的客户端是服务帐户客户端。
    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();
        }
    }
    

    开发者控制台

    在客户端下检查您使用的客户端是否可以在服务帐户 key 下找到。如果不是,那么它是错误的客户端类型,将无法与您的代码一起使用。创建一个新的服务帐户客户端并使用该客户端 ID 设置域范围的委派。

    enter image description here

    关于php - 客户端未经授权使用此方法检索访问 token 服务帐户错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53441806/

    相关文章:

    php - 如何从 PHP 访问 ASP 经典 session 变量?

    authentication - Google oAuth 登录 - 如何仅允许白名单电子邮件登录我的应用程序

    javascript - 如何在Angular 5应用程序中从Gmail API获取authorization_code

    c# - Gmail API - 值 '= Get Labels google-api-dotnet-client/1.25.0.0 (gzip)' 的格式无效

    api - 如何从 Gmail 的主收件箱中获取未读邮件?

    php - 类(class)规模会太大吗?

    php - 一个适合我的基准测试的线图生成器?

    php - 如何将相关表中的值连接到 Laravel eloquent 集合?

    node.js - NodeMailer - 使用 Google 服务帐户发送邮件失败,因为 "Username and Password not accepted"

    python - 如何在不将 client_secret.json 检查到版本控制的情况下使用 Google API?