Не удается запустить Google войти всплывающее окно при нажатии - PullRequest
0 голосов
/ 01 апреля 2020

Попытка получить Google OAuth, запустив всплывающее окно Google с помощью chrome .identity.LaunchWebAuthFlow (), но поток, похоже, идет не так, как ожидалось, при нажатии на chrome .identity.LaunchWebAuthFlow () ... непосредственно переходит к этапу извлечения токена напрямую, фактически не прося меня выполнить вход. Я предположил, что это может быть вызвано тем, что вы уже вошли в систему с аккаунта Google. не запрашивает другого и напрямую выбирает AuthToken ... но это тоже не дало мне решения ... это код, за которым я следовал ... хотелось бы получить некоторую помощь по нему. Спасибо.

...

/* exported getAccessToken */

const REDIRECT_URL = chrome.identity.getRedirectURL();
const CLIENT_ID = [YOUR_CLIENT_ID];
const SCOPES = ["openid", "email", "profile"];
const AUTH_URL =
`https://accounts.google.com/o/oauth2/auth\
?client_id=${CLIENT_ID}\
&response_type=token\
&redirect_uri=${encodeURIComponent(REDIRECT_URL)}\
&scope=${encodeURIComponent(SCOPES.join(' '))}`;
const VALIDATION_BASE_URL="https://www.googleapis.com/oauth2/v3/tokeninfo";

function extractAccessToken(Redirect_URL) {
  let m = Redirect_URL.match(/[#?](.*)/);
  if (!m || m.length < 1)
    return null;
  let params = new URLSearchParams(m[1].split("#")[0]);
  return params.get("access_token");
}

/**
Validate the token contained in redirectURL.
This follows essentially the process here:
https://developers.google.com/identity/protocols/OAuth2UserAgent#tokeninfo-validation
- make a GET request to the validation URL, including the access token
- if the response is 200, and contains an "aud" property, and that property
matches the clientID, then the response is valid
- otherwise it is not valid
Note that the Google page talks about an "audience" property, but in fact
it seems to be "aud".
*/
function validate(Redirect_URL) {
  const accessToken = extractAccessToken(Redirect_URL);
  if (!accessToken) {
    throw "Authorization failure";
  }
  const validationURL = `${VALIDATION_BASE_URL}?access_token=${accessToken}`;
  const validationRequest = new Request(validationURL, {
    method: "GET"
  });

  function checkResponse(response) {
    return new Promise((resolve, reject) => {
      if (response.status != 200) {
        reject("Token validation error");
      }
      response.json().then((json) => {
        if (json.aud && (json.aud === CLIENT_ID)) {
          resolve(accessToken);
        } else {
          reject("Token validation error");
        }
      });
    });
  }

  return fetch(validationRequest).then(checkResponse);
}

/**
Authenticate and authorize using browser.identity.launchWebAuthFlow().
If successful, this resolves with a redirectURL string that contains
an access token.
*/
function authorize() {
  return chrome.identity.launchWebAuthFlow({
    interactive: true,
    url: AUTH_URL
  },
  function(redirectURL) {
    console.log(redirectURL);
    var q = redirectURL.substr(redirectURL.indexOf('#')+1);
    var parts = q.split('&');
    for (var i = 0; i < parts.length; i++) {
      var kv = parts[i].split('=');
      if (kv[0] == "access_token") {
        token = kv[1];
        console.log('token is', token);
      }
    }
    // return REDIRECT_URL;
  });
}

function getAccessToken() {
  // return authorize().then(validate);
  var object1 =  authorize();
  return validate(object1);
}

...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...