arthurakay
arthurakay

Reputation: 5651

Connecting Chrome Extension to StackExchange oAuth API

TL;DR -- I am trying to build a Chrome extension that displays the number of current notifications for a user from StackOverflow.

I am following the Chrome Extension tutorial on creating an extension that utilizes oAuth. Swapping out the Google oAuth bits for (what I think are) the StackExchange API bits, I end up with the following in my background.js file:

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...');
});

When I run the extension locally, it attempts to open a new browser tab to complete the oAuth handshake -- which is great, except that I end up at the following URL: https://stackexchange.com/oauth/login_success?oauth_token=undefined

The browser tab gets stuck here.enter image description here

I'm not really sure what the problem is - I don't know if I have the wrong URLs listed in my initBackgroundPage() call, or if my StackApp has the wrong oAuth domain (since it's a Chrome extension... this question didn't really answer things for me).

Any ideas would be most appreciated!

Upvotes: 2

Views: 270

Answers (1)

arthurakay
arthurakay

Reputation: 5651

From what I can tell, the oAuth tutorial I mentioned in my OP is outdated -- you no longer need any of that, you can use chrome.identity instead.

To be clear, there are a few things I had to do:

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);
});

Note the redirect_uri -- this ends up being a subdomain of chromiumapp.org, so you need to list that in StackApps as the domain for your app (allowing oAuth to continue).

Upvotes: 5

Related Questions