API Google Identity Toolkit для PHP возвращает INVALID_CLIENT

Я пытаюсь заставить API Google Identity Toolkit работать с приложением на основе PHP.

Я следил за кратким руководством от Google, доступным здесь: https://developers.google.com/identity/toolkit/web/quickstart/php

Я точно выполнил все шаги (и проверил, и дважды проверил).

Кнопка входа появится на странице index.php. При нажатии на нее выполняется перенаправление на страницу widget.php. Я могу выбрать, с какой учетной записью я хочу войти, а затем, когда вернусь на страницу успешного входа (снова index.php), я получаю следующее сообщение об ошибке:

Неустранимая ошибка: Неперехваченное исключение "Google_Auth_Exception" с сообщением "Ошибка обновления токена OAuth2, сообщение:" {"error": "invalid_client", "error_description": "Клиент OAuth недействителен". } '

Я пробовал воссоздать клиент OAuth в консоли разработчика Google. Некоторые результаты поиска, упомянутые для проверки полей электронной почты и имени проекта, были заполнены на экране согласия OAuth, и все это я сделал.

Любая помощь и совет будут приняты с благодарностью. Примечание. Я использую только «Google» из числа доступных в настройках API Identity Toolkit.

Моя страница index.php:

<!DOCTYPE html>
<html>
<head>

<!-- 1: Load the Google Identity Toolkit helpers -->
<?php
  set_include_path(get_include_path() . PATH_SEPARATOR . __DIR__ .'/vendor/google/apiclient/src');
  require_once __DIR__ . '/vendor/autoload.php';

  $gitkitClient = Gitkit_Client::createFromFile(dirname(__FILE__) . '/gitkit-server-config.json');
  $gitkitUser = $gitkitClient->getUserInRequest();
?>
<!-- End modification 1 -->

<script type="text/javascript" src="//www.gstatic.com/authtoolkit/js/gitkit.js"></script>
<link type=text/css rel=stylesheet href="//www.gstatic.com/authtoolkit/css/gitkit.css" />

<script type=text/javascript>
  window.google.identitytoolkit.signInButton(
    '#navbar',
    {
      widgetUrl: "/gitkit",
      signOutUrl: "/index"
    }
  );
</script>
</head>
<body>
<div id="navbar"></div>

<!-- 2: Print the user information if a signed in user is present -->
<p>
  <?php if ($gitkitUser) { ?>
    Welcome back!<br><br>
    Email: <?= $gitkitUser->getEmail() ?><br>
    Id: <?= $gitkitUser->getUserId() ?><br>
    Name: <?= $gitkitUser->getDisplayName() ?><br>
    Identity provider: <?= $gitkitUser->getProviderId() ?><br>
  <?php } else { ?>
    You are not logged in yet.
  <?php } ?>
</p>
<!-- End modification 2 -->

</body>
</html>

Моя страница gitkit.php:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<!-- Copy and paste here the client configuration from Developer Console into the config variable -->
<script type="text/javascript" src="//www.gstatic.com/authtoolkit/js/gitkit.js"></script>
<link type="text/css" rel="stylesheet" href="//www.gstatic.com/authtoolkit/css/gitkit.css" />
<script type="text/javascript">
  var config =
    {
  "widgetUrl": "http://local.myfakedomain.com/gitkit",
  "signInSuccessUrl": "/",
  "signOutUrl": "/",
  "oobActionUrl": "/",
  "apiKey": "<my-api-key-here>",
  "siteName": "this site",
  "signInOptions": ["password","google"]
}
  ;
  // The HTTP POST body should be escaped by the server to prevent XSS
  window.google.identitytoolkit.start(
      '#gitkitWidgetDiv', // accepts any CSS selector
      config,
      JSON.parse('<?php echo json_encode(file_get_contents("php://input")); ?>')
  );
</script>
<!-- End modification -->

</head>
<body>

<!-- Include the sign in page widget with the matching 'gitkitWidgetDiv' id -->
<div id="gitkitWidgetDiv"></div>
<!-- End identity toolkit widget -->

</body>
</html>

мой файл gitkit-server-config.json:

{
  "clientId": "<my-client-id-here>",
  "projectId": "<my-project-id-here>",
  "serviceAccountEmail": "<my-serviceAccountEmail-here>",
  "serviceAccountPrivateKeyFile": "<my-p12-KeyFile-location-here>",
  "widgetUrl": "http://local.myfakedomain.com/gitkit",
  "cookieName": "gtoken"
}

person J Lamb    schedule 23.03.2016    source источник


Ответы (3)


У меня была такая же проблема, которую я решил, вставив "правильный" адрес электронной почты учетной записи службы в код конфигурации сервера:

{
  "clientId": "<my-client-id-here>",
  "projectId": "<my-project-id-here>",
  "serviceAccountEmail": "<Correct-serviceAccountEmail-here>",
  "serviceAccountPrivateKeyFile": "<my-p12-KeyFile-location-here>",
  "widgetUrl": "http://local.myfakedomain.com/gitkit",
  "cookieName": "gtoken"
}

Хитрость в том, что serviceAccountEmail не является вашим адресом электронной почты Google, чтобы найти правильный адрес электронной почты, перейдите в Учетные данные, затем в разделе Ключи служебного аккаунта нажмите Управление Учетные записи служб, перейдите по ссылке справа, перейдите к используемой службе и обратите внимание на поле адреса электронной почты. Электронное письмо длинное, его формат будет примерно таким: имя-службы@имя-проекта.xxx.xxxxxxxxx.xxx.

person DeepBlue    schedule 30.03.2016
comment
Это решило мою проблему. К вашему сведению: правильный адрес электронной почты сервисного аккаунта можно найти здесь: console.developers.google.com/permissions/serviceaccounts Найдите столбец идентификатора сервисного аккаунта. - person hirikarate; 13.04.2016

В вашем файле gitkit-server-config.json serviceAccountEmail не должен быть пустым. Вы можете скопировать адрес электронной почты сервисного аккаунта со страницы настроек проекта в Google Developers Console.

person Jin Liu    schedule 23.03.2016

Помимо адреса электронной почты учетной записи службы (что-то вроде "[email protected]", у меня возникли проблемы с идентификатором проекта.

Решение, которое я нашел, заключалось в том, что если Google сказал, что ваш идентификатор проекта - «example.com:appname», измените его на «appname».

person Daniel    schedule 28.03.2016