使用OAuth 2.0和客户端ID从Google Chrome扩展程序获取辅助ID的验证令牌

Sto*_*ker 7 javascript oauth google-chrome-extension

我很擅长开发chrome扩展,更具体地说是chrome扩展中的用户身份验证部分.我正在关注Google Developer docs中的User Identity示例.

这个例子非常好用.我能够为chrome应用生成客户端ID,在我的案例Gmail API中添加API的范围.最后通过添加identity权限获取Auth Token,manifest.json如下所示

"oauth2": {
    "client_id": "MY CLIENT ID",
    "scopes": [
      "https://www.googleapis.com/auth/gmail.readonly",
      "https://www.googleapis.com/auth/gmail.modify"
    ]
  }
Run Code Online (Sandbox Code Playgroud)

我的app.js是一个content_script,它有以下代码.

chrome.identity.getAuthToken({ 'interactive': true }, function(token) {
    /* With which I can use xhr requests to get data from Gmail API */
      console.log('Access Token : '+token);
});
Run Code Online (Sandbox Code Playgroud)

现在,我获得的这个令牌为我提供了我已登录chrome的用户的结果.含义假设我有一个UserA,电子邮件地址为user_a@gmail.com,我已将此日志用于Chrome浏览器.

如何获取关联帐户或辅助帐户?例如,假设用户通过Chrome浏览器登录Gmail.是否可以访问当前登录的特定用户的Gmail API?

我在这里尝试过几件事.

gapi.auth.authorize({
            'client_id': CLIENT_ID,
            'scope': SCOPES.join(' '),
            'immediate': true
          }, 
          function(authResult){//do something});
Run Code Online (Sandbox Code Playgroud)

在上面的场景中,客户端ID和范围是从manifest.json使用中获取的chrome.runtime.getManifest();.

  • 此方法使用来自google api的client.js并使用gapi变量.
  • 在这种情况下,我为我生成客户端ID的用户获取访问令牌,甚至不是chrome应用程序用户.
  • 此外,当我打开隐身模式并访问此插件时,仍然可以获得相同用户的访问令牌.

附加说明

gapi.auth.authorize()使用Web OAuth 2客户端ID 尝试了相同的操作.它工作得很好.我的意思是无论何时执行此授权,它都会获取当前登录用户的数据,或者它要求用户登录并进行身份验证的登录.如何在chrome扩展中实现相同的功能?如果我在这里错过了什么,请告诉我.

小智 0

http://developer.streak.com/2014/10/how-to-use-gmail-api-in-chrome-extension.html

是我最近在后台页面上实现的与 Gmail API 配合使用的完整解决方案。

内容脚本调用弹出窗口来授权使用生成的 URL 和简单的服务器端点来存储刷新令牌。

$.oauthpopup = function (options) {
options.windowName = options.windowName || 'ConnectWithOAuth'; // should not include space for IE

var left = (screen.width / 2) - (800 / 2);
var top = (screen.height / 2) - (500 / 1.4);

options.windowOptions = options.windowOptions || 'location=0,status=0,width=800,height=500,left=' + left + ',top=' + top;
options.callback = options.callback || function () {
    window.location.reload();
};
var that = this;

debug('oauthpopup open separate _oauthWindow');
that._oauthWindow = window.open(options.path, options.windowName, options.windowOptions);
};

$.oauthpopup({
            path: 'https://accounts.google.com/o/oauth2/auth?' +
            'access_type=offline' +
            '&approval_prompt=force' +
            '&client_id=' + clientID +
            '&redirect_uri=' + callBackUrl +
            '&response_type=code' +
            '&scope=https://mail.google.com/ email profile' +
            '&state=' + login.timyoUUID +
            '&user_id=' + login.user_email,
            callback: function () {
                // do callback stuff
            },
        });
Run Code Online (Sandbox Code Playgroud)

callBackUrl 用于在服务器上存储刷新令牌。

这是我如何为每个请求设置访问令牌的示例

export function setTokenForGAPI(accessToken) {
return getGAPIClient()
    .then(() => {
        const isSameToken = (currentAccessToken === accessToken);
        const noToken = ((accessToken === undefined) || (accessToken === ''));
        if (isSameToken || noToken) return;

        gapi.auth.setToken({
            access_token: accessToken,
        });

        currentAccessToken = accessToken;
    })
    .catch(function (e) {
        console.log('error in setTokenForGAPI', e);
    });
}
export function getEmailsByThreadIds(accessToken, ids) {
    return setTokenForGAPI(accessToken)
        .then(groupedThreadDetailsRequests(ids))
        .then(processEmailDetailsResponse);
}
Run Code Online (Sandbox Code Playgroud)