2015-07-03 98 views
3

构建Gmail的Chrome扩展,尝试使用Chrome身份验证访问gmail API,其中包括this StackOverflow postthe Gmail API docs。我成功地接收令牌chrome.identity.getAuthToken({ 'interactive': true }, function(token) {}但是当我插上令牌到请求的URL,我得到以下401错误响应(代码如下)使用Chrome身份验证访问Chrome扩展中的Gmail api

错误响应

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

我的代码:
背景.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验证Gmail的API,但是我看过其他职位都使我相信这是一个切实可行的选项。

如果我的代码没有给出它,我是一个新手,所以任何帮助是最受欢迎的,我非常感谢你的时间。

+1

发表您的清单。 – Xan

+0

@Xan通过编辑添加。 –

回答

2

key是用于通用应用程序的秘密。对于用户特定的令牌,您需要使用access_token。并且标记不应该被包裹在{}中。如果mail%40gmail.com是您在URL中使用的实际值,则不起作用。它可能需要是已通过身份验证的用户的电子邮件地址或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 
+0

令人惊叹!神圣的抽烟@abraham,非常感谢你。当我的简单键vs access_token保存了一天的时候,我只是在把所有的东西都分开,尝试一种完全不同的方法。非常感谢你帮助我从我的新手程序员生活中减少了压力的时间:-) –

+0

@DanKlos很高兴听到你让它工作。 – abraham