我正在尝试使用我的Chrome扩展程序中的多个用户的google apis。
主要问题是:
1)如果我没有登录浏览器,我无法使用谷歌授权
2)如果我在浏览器中登录然后尝试登录该应用程序,那么无论我在菜单中选择哪个帐户,都可以在该帐户和Chrome中自动停用。
从背景调用的函数toggleGetIdTokenListener
。
export const toggleGetIdTokenListener = () => {
chrome.runtime.onMessage.addListener((request) => {
if (request.type === 'get_idToken') {
getTokenId();
}
});
};
const createRequestURL = () => {
const manifest = chrome.runtime.getManifest();
const clientId = encodeURIComponent(manifest.oauth2.client_id);
const scopes = encodeURIComponent(manifest.oauth2.scopes.join(' '));
const redirectUri = encodeURIComponent('urn:ietf:wg:oauth:2.0:oob:auto');
const url = 'https://accounts.google.com/o/oauth2/auth' +
'?client_id=' + clientId +
'&response_type=id_token' +
'&access_type=offline' +
'&redirect_uri=' + redirectUri +
'&scope=' + scopes;
return url;
};
const getTokenId = () => {
chrome.tabs.create({
url: createRequestURL(),
active: false
}, getResponseFromGoogle);
};
const getResponseFromGoogle = (authenticationTab) => {
const RESULT_PREFIX = ['Success', 'Denied', 'Error'];
// After the tab has been created, open a window to inject the tab
chrome.tabs.onUpdated.addListener(function googleAuthorizationHook(tabId, changeInfo) {
const titleParts = changeInfo.title.split(' ', 2);
const result = titleParts[0];
if (titleParts.length === 2 && RESULT_PREFIX.indexOf(result) >= 0) {
chrome.tabs.onUpdated.removeListener(googleAuthorizationHook);
chrome.tabs.remove(tabId);
const response = titleParts[1];
chrome.identity.getAuthToken({'interactive': true}, function (token) {
if (chrome.runtime.lastError) {
console.log('ERROR', chrome.runtime.lastError.message);
return;
}
const x = new XMLHttpRequest();
x.open('GET', 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=' + token);
x.onload = function () {
populateUserData(JSON.parse(x.response), response);
};
x.send();
});
}
});
createPopupWindow(authenticationTab)
};
const createPopupWindow = (authenticationTab) => {
chrome.windows.create({
tabId: authenticationTab.id,
type: 'popup',
focused: true
// incognito, top, left, ...
}, function () {
chrome.tabs.update(authenticationTab.id, {'url': createRequestURL()});
});
};
const populateUserData = (userInfo, id_token) => {
const userData = [{
name: userInfo.name,
email: userInfo.email,
id_token: id_token.substring(id_token.indexOf('=') + 1, id_token.indexOf('&')),
clientId: '711602808537-cv3p6pe7hc2lvmo88ri0oti0rcqcme7a.apps.googleusercontent.com',
picture: userInfo.picture
}];
connector.init();
getUserFromServer(userData);
};
有什么想法吗?不管怎样,谢谢!