Google аутентификация с использованием JavaScript не удается - PullRequest
0 голосов
/ 12 октября 2018

Попытка использовать функцию gapi для реализации аутентификации Google (oauth2), но приведенный ниже код завершается ошибкой

<html>
  <head></head>
  <body>
    <script type="text/javascript">
      function handleClientLoad() {
        // Loads the client library and the auth2 library together for efficiency.
        // Loading the auth2 library is optional here since `gapi.client.init` function will load
        // it if not already loaded. Loading it upfront can save one network request.
        gapi.load('client:auth2', initClient);
      }

      function initClient() {
        // Initialize the client with API key and People API, and initialize OAuth with an
        // OAuth 2.0 client ID and scopes (space delimited string) to request access.
        gapi.client.init({
            apiKey: 'APP_ID',
            discoveryDocs: ["https://people.googleapis.com/$discovery/rest?version=v1"],
            clientId: 'CLEINT_ID.apps.googleusercontent.com',
            scope: 'profile'
        }).then(function () {
          // Listen for sign-in state changes.
          gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

          // Handle the initial sign-in state.
          updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
        });
      }

      function updateSigninStatus(isSignedIn) {
        // When signin status changes, this function is called.
        // If the signin status is changed to signedIn, we make an API call.
        if (isSignedIn) {
          makeApiCall();
        }
      }

      function handleSignInClick(event) {
        // Ideally the button should only show up after gapi.client.init finishes, so that this
        // handler won't be called before OAuth is initialized.
        gapi.auth2.getAuthInstance().signIn();
      }

      function handleSignOutClick(event) {
        gapi.auth2.getAuthInstance().signOut();
      }

      function makeApiCall() {
        // Make an API call to the People API, and print the user's given name.
        gapi.client.people.people.get({
          'resourceName': 'people/me',
          'requestMask.includeField': 'person.names'
        }).then(function(response) {
          console.log('Hello, ' + response.result.names[0].givenName);
        }, function(reason) {
          console.log('Error: ' + reason.result.error.message);
        });
      }
    </script>
    <script async defer src="https://apis.google.com/js/api.js"
      onload="this.onload=function(){};handleClientLoad()"
      onreadystatechange="if (this.readyState === 'complete') this.onload()">
    </script>
    <button id="signin-button" onclick="handleSignInClick()">Sign In</button>
    <button id="signout-button" onclick="handleSignOutClick()">Sign Out</button>
  </body>
</html>

и выдает ошибку

Не удалось выполнить 'postMessage'on 'DOMWindow': предоставленный целевой источник ('file: //') не соответствует источнику окна получателя ('null').

Куда я иду не так?

1 Ответ

0 голосов
/ 15 октября 2018

Исходя из этой ссылки , вы можете получить эту ошибку, если iFrame не загружен, и вы можете игнорировать ее, если все по-прежнему работает, так как он делает более одной попытки установить связь.Это может произойти, если целевой сайт забыл включить файл сценария окна контента.

Также из этой темы: Google API в Javascript

На основеошибка, которую вы получаете, я полагаю, что вы либо неправильно настроили свой Javascript Origin на консоли Google API , с которой вы получили свой идентификатор клиента, и / или вы пытаетесь запустить свой скрипт изфайловая система вместо веб-сервера, даже работающего на localhost.Клиент Google API, насколько я могу судить, не принимает запросы на авторизацию от файловой системы или любого домена, который не был настроен для запроса авторизации под предоставленным идентификатором клиента.

...