将Chrome扩展程序连接到StackExchange oAuth API

时间:2015-07-01 16:01:19

标签: javascript google-chrome google-chrome-extension oauth

TL; DR - 我正在尝试构建一个Chrome扩展程序,用于显示StackOverflow中用户的当前通知数。

我正在关注Chrome Extension tutorial创建一个使用oAuth的扩展程序。换掉Google oAuth位(我认为是)StackExchange API位,我最终在我的background.js文件中输入以下内容:

var oauth = ChromeExOAuth.initBackgroundPage({
    //ES6 template strings!
    'request_url'   : `https://stackexchange.com/oauth?client_id=${STACK_APP.id}&scope=read_inbox,no_expiry`, 

    'authorize_url' : 'https://stackexchange.com/oauth/login_success',
    'access_url'    : 'https://stackexchange.com/oauth/access_token',

    'consumer_key'    : STACK_APP.key,
    'consumer_secret' : STACK_APP.secret,

    //'scope'    : '', //not sure I need this...

    'app_name' : 'StackOverflow Notifications (Chrome Extension)'
});

oauth.authorize(function () {
    console.log('authorize...');
});

当我在本地运行扩展时,它会尝试打开一个新的浏览器选项卡来完成oAuth握手 - 这很棒,除了我最终在以下URL:     https://stackexchange.com/oauth/login_success?oauth_token=undefined

浏览器标签卡在此处。enter image description here

我不确定问题是什么 - 我不知道我的initBackgroundPage()电话中是否列出了错误的网址,或者我的StackApp是否有错误的oAuth域名(从那时起)它是Chrome扩展程序...... this question并没有真正为我解答问题。

任何想法都会非常感激!

1 个答案:

答案 0 :(得分:3)

据我所知,我在OP中提到的oAuth教程已经过时 - 您不再需要这些教程,您可以使用chrome.identity代替。

要说清楚,我必须做一些事情:

STACK_APP = {
    id           : 1234,
    scope        : 'read_inbox,no_expiry',

    request_uri  : 'https://stackexchange.com/oauth/dialog',
    redirect_uri : chrome.identity.getRedirectURL("oauth2")
};

//ES6 template string!
var requestUrl = `${STACK_APP.request_uri}?client_id=${STACK_APP.id}&scope=${STACK_APP.scope}&redirect_uri=${STACK_APP.redirect_uri}`;


//https://developer.chrome.com/extensions/identity
//https://developer.chrome.com/extensions/app_identity#update_manifest
chrome.identity.launchWebAuthFlow({
    url         : requestUrl,
    interactive : true
}, function (url) {
    console.log('redirected to: ' + url);
});

请注意redirect_uri - 这最终成为chromiumapp.org的子域名,因此您需要在StackApps中将其列为您应用的域名(允许oAuth继续)。