客户端未授权使用此方法服务帐户错误检索访问令牌
client is unauthorized to retrieve access tokens using this method service account error
让我的服务帐户在用户也通过 oauth2 登录的同一个 Web 应用程序上进行身份验证真是太让人头疼了。
所以我想知道,这可能吗?
如果不是,是否应该坚持使用服务帐户?然后是否必须自己对用户进行身份验证 - 老派风格?哈哈
谢谢。
关于服务帐户,我在我的 G 套件管理控制台中启用了域范围 delegation,启用了客户端密钥 + api 范围,并获得了 php 样本与书籍 api 一起工作。但是,无论何时我尝试任何其他 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:错误请求”错误
编辑:经过更多挖掘后,有一个注释:'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/
并启用 apis 并启用 'OAuth Consent Screen'
中的范围
DWD 也已启用:Service Account Overview Screenshot
EDIT2:好的,所以我发现缺少的先决条件是 "setSubject"。
有一次我补充说更进了一步,但还是在'"error": "unauthorized_client",\n "error_description": "Client is unauthorized to retrieve access tokens using this method.'
处再次失败
仅供参考:在创建服务帐户时,我给了它 "project -> owner" 角色。够了吗?还要加一个吗?
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"
}
编辑 4: 终于成功了!
所以我整个早上/昨晚都在为测试而创建的新项目中尝试这个。但是我的 oauth2 用户身份验证是 运行 通过另一个项目(昨天上午/下午我也无法让服务帐户正常工作)。
所以无论如何,我注意到:https://myaccount.google.com/permissions "Apps with Access to your account" - 只有我的旧项目/应用程序获得授权。所以我切换回我的第一个项目,创建了一个新的服务帐户客户端 ID .json 文件,它最终成功地验证了两者! :)
我必须在第二个项目中没有完成的地方获得授权。
再次感谢。
EDIT5: 另一个快速问题 - 这是在 Whosebug 上执行此操作的正确方法吗?不断回去编辑?
另外,对于后来遇到此问题的其他人,这是我的全部身份验证块(抱歉有点长):
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();
}
在 google 开发人员控制台中,当您创建项目和凭据时,您必须选择要为哪种类型的应用程序创建哪种类型的客户端。
google 有几种不同的身份验证方法。
- 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();
}
}
开发者控制台
在客户端下检查您正在使用的客户端是否可以在服务帐户密钥下找到。如果不是,那么它是错误的客户端类型,将无法使用您的代码。创建一个新的服务帐户客户端并使用该客户端 ID 设置域范围的委派。
response_type=code
client_id=348268306866-9dl0kdgn2f9bjhoge7pris1jo8u9si47.apps.googleusercontent.com
redirect_uri=https://degoo.com/me/googleoauth2callback
access_type=offline
scope=https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/contacts.readonly
state={"RedirectUrl":"/me/chooseaccount","RegisterIfNotExists":true}
这就是我们所知道的。
让我的服务帐户在用户也通过 oauth2 登录的同一个 Web 应用程序上进行身份验证真是太让人头疼了。
所以我想知道,这可能吗?
如果不是,是否应该坚持使用服务帐户?然后是否必须自己对用户进行身份验证 - 老派风格?哈哈
谢谢。
关于服务帐户,我在我的 G 套件管理控制台中启用了域范围 delegation,启用了客户端密钥 + api 范围,并获得了 php 样本与书籍 api 一起工作。但是,无论何时我尝试任何其他 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:错误请求”错误
编辑:经过更多挖掘后,有一个注释:'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/
并启用 apis 并启用 'OAuth Consent Screen'
中的范围DWD 也已启用:Service Account Overview Screenshot
EDIT2:好的,所以我发现缺少的先决条件是 "setSubject"。
有一次我补充说更进了一步,但还是在'"error": "unauthorized_client",\n "error_description": "Client is unauthorized to retrieve access tokens using this method.'
仅供参考:在创建服务帐户时,我给了它 "project -> owner" 角色。够了吗?还要加一个吗?
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"
}
编辑 4: 终于成功了!
所以我整个早上/昨晚都在为测试而创建的新项目中尝试这个。但是我的 oauth2 用户身份验证是 运行 通过另一个项目(昨天上午/下午我也无法让服务帐户正常工作)。
所以无论如何,我注意到:https://myaccount.google.com/permissions "Apps with Access to your account" - 只有我的旧项目/应用程序获得授权。所以我切换回我的第一个项目,创建了一个新的服务帐户客户端 ID .json 文件,它最终成功地验证了两者! :)
我必须在第二个项目中没有完成的地方获得授权。
再次感谢。
EDIT5: 另一个快速问题 - 这是在 Whosebug 上执行此操作的正确方法吗?不断回去编辑?
另外,对于后来遇到此问题的其他人,这是我的全部身份验证块(抱歉有点长):
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();
}
在 google 开发人员控制台中,当您创建项目和凭据时,您必须选择要为哪种类型的应用程序创建哪种类型的客户端。
google 有几种不同的身份验证方法。
- 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();
}
}
开发者控制台
在客户端下检查您正在使用的客户端是否可以在服务帐户密钥下找到。如果不是,那么它是错误的客户端类型,将无法使用您的代码。创建一个新的服务帐户客户端并使用该客户端 ID 设置域范围的委派。
response_type=code
client_id=348268306866-9dl0kdgn2f9bjhoge7pris1jo8u9si47.apps.googleusercontent.com
redirect_uri=https://degoo.com/me/googleoauth2callback
access_type=offline
scope=https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/contacts.readonly
state={"RedirectUrl":"/me/chooseaccount","RegisterIfNotExists":true}
这就是我们所知道的。