Gmail API: проблема с применением аутентификационного токена без участия пользователя - PullRequest
0 голосов
/ 30 апреля 2020

ОС: Windows 10, Браузер: Chrome v.81, Сервер: PHP 5.6, JQuery: Версия 2.1.1

Приложение: Быстрый запуск браузера

Клиент хочет, чтобы это приложение браузера автоматически обновляло токен пользователя, не вынуждая пользователя каждый раз вручную повторной авторизации.

Согласно странице быстрого запуска: «После первоначальной авторизации пользователя вызовы gapi.auth.authorize, использующие немедленный режим: true, получают токен авторизации без взаимодействия с пользователем».

I'm близко к тому, чтобы заставить это работать. Я могу авторизовать и собрать новый токен аутентификации, но не могу найти правильный синтаксис для применения этого токена для обновленной последовательности входа в систему. Вот что у меня пока есть.


    // Initializes the API client library and sets up sign-in state listeners.

    function initClient() {
        gapi.client.init({
          apiKey: API_KEY,
          clientId: CLIENT_ID,
          discoveryDocs: DISCOVERY_DOCS,
          scope: SCOPES
        }).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());
          authorizeButton.onclick = handleAuthClick;
          signoutButton.onclick = handleSignoutClick;
        }, function(error) {
          appendPre(JSON.stringify(error, null, 2));
        });
      }

    //Checks user's login state

    function updateSigninStatus(isSignedIn) {
        if (isSignedIn) {
          authorizeButton.style.display = 'none';
          signoutButton.style.display = 'block';

          //This is the API interaction I want to run.
          displayInbox();

        } else {

//I think this is where the automatic token refresh would happen (when the user
//is no longer logged in), which is why I've added in the "autoRefresh" function.

          autoRefresh();

          authorizeButton.style.display = 'block';
          signoutButton.style.display = 'none';
        }
      }

//My Auto Refresh Function, to get the new token without client interaction

    function autoRefresh() {
        gapi.auth.authorize({
          'client_id':CLIENT_ID,
          'immediate':'true',
          'scope':SCOPES
        }).then(function(response) {
            console.log(response);
            var access_token = response.access_token;
            console.log(access_token);

// This is where I'm stuck. I have the token, but idea how to feed it back to the 
// API, to actually renew the client's authentication.
// The only server-side example is in Python, which I can't use (client's locked into PHP).
// Before you ask, the Client's PHP server is unable to run the GMAIL API from PHP. 
// All my hopes rest on vanilla javascript... So,
// How do I authorize the client with the new access_token from here?

        });
      }

      /**
       *  These are the button functions. I've added them in just to be thorough. I'm trying 
       *  to replace the "handleAuthClick(event)" with my "autoRefresh()" function.
       */

      function handleAuthClick(event) {
        gapi.auth2.getAuthInstance().signIn();
      }

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

Как видите, я близок к повторной авторизации клиента, я просто не знаю последний шаг для отправки токена обратно на сервер API для повторной авторизации.

Код кнопки «аутентифицировать» в руководстве (gapi.auth2.getAuthInstance (). SignIn ();), по-видимому, требует, чтобы пользователь выполнил вход вручную, и я не могу найти эквивалентный код для аутентификации на auth2 без необходимости входа пользователя.

Я надеюсь, что это не слишком долго, и я хотел бы заранее поблагодарить вас за ваше время и помощь.

Любая помощь, ссылки или советы будут с благодарностью.

Хорошего дня!

...