使用Chrome身份验证访问Chrome扩展程序内的gmail api

时间:2015-07-03 20:54:26

标签: google-chrome google-chrome-extension gmail gmail-api gapi

为Gmail构建Chrome扩展程序,尝试使用Chrome Auth获取{j {3}}和this StackOverflow post等gmail api的访问权限。我成功收到了chrome.identity.getAuthToken({ 'interactive': true }, function(token) {}的令牌,但是当我将令牌插入请求网址时,我收到以下401错误响应(代码如下)

错误回复

{
  "error": {
    "errors": [
      {
        "domain": "global",
        "reason": "required",
        "message": "Login Required",
        "locationType": "header",
        "location": "Authorization"
      }
    ],
    "code": 401,
    "message": "Login Required"
  }
}

我的代码:
background.js

chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
  if (changeInfo.status == 'complete') {
    chrome.identity.getAuthToken({ 'interactive': true }, function(token) {
      thisToken = token
      chrome.runtime.onMessage.addListener(
        function(request,sender,sendResponse){
          var gapiRequestUrlAndToken = "https://www.googleapis.com/gmail/v1/users/mail%40gmail.com/threads?key={" + thisToken + "}"

          var makeGetRequest = function (gapiRequestURL)
            {
                var xmlHttp = new XMLHttpRequest();
                xmlHttp.open( "GET", gapiRequestURL, false );
                xmlHttp.send( null );
                return xmlHttp.responseText;
            }

          makeGetRequest(gapiRequestUrlAndToken);
        }
      );
    });
  }
})

的manifest.json

{
  "manifest_version": 2,
  "key": "<key>",
  "name": "exampleName",
  "description": "Description",
  "version": "0.0.1.7",
  "default locale": "en",
  "icons": { "128": "imgs/pledge_pin.png"},
  "content_scripts" : [
    {
      "matches": ["*://mail.google.com/mail/*"],
      "js": ["js/jquery.js", "js/compose.js", "bower_components/jqnotifybar/jquery.notifyBar.js"],
      "css": ["css/stylesheet.css", "bower_components/jqnotifybar/css/jquery.notifyBar.css"]
    }
  ],
  "background": {
    "scripts": ["scripts/background.js"]
  },
  "permissions": [
    "identity"
  ],
  "oauth2": {
    "client_id": "<client id>",
    "scopes": ["https://www.googleapis.com/auth/gmail.modify"]
  }
}

我怀疑这与我尝试使用Chrome Auth for Gmail api这一事实有关,但我读过的其他帖子让我相信这是一个可行的选择。

如果我的代码没有放弃,我是新手,所以非常欢迎任何帮助,我非常感谢你的时间。

1 个答案:

答案 0 :(得分:2)

key用于通用应用程序机密。对于特定于用户的令牌,您需要使用access_token。并且令牌不应包含在{}中。如果mail%40gmail.com是您在网址中使用的实际值,则无法正常工作。它必须是经过身份验证的用户的电子邮件地址或me

所以改变:

"https://www.googleapis.com/gmail/v1/users/mail%40gmail.com/threads?key={" + thisToken + "}"

对此:

"https://www.googleapis.com/gmail/v1/users/me/threads?access_token=" + thisToken