Chrome extension authentication with Twitter

chrome
javascript

#1

Hi,

I’ve tried to adapt the Google OAuth tutorial (https://developer.chrome.com/extensions/tut_oauth) to create an extension that can connect to Twitter.

Here is my code: (the other files are identical to the ones provided in the tutorial)

{
    "name": "OAuth Twitter",
    "version": "1.0.6",
	"icons": {  "48": "img/icon-48.png",
	            "128": "img/icon-128.png" },
    "description": "Uses OAuth to connect to Twitter.",
    "background": {
        "scripts": [
            "chrome_ex_oauthsimple.js",
            "chrome_ex_oauth.js",
	        "background.js"
        ]
    },
    "browser_action": {
    "default_title": "",
    "default_icon": "img/icon-19-off.png"
    },
    "permissions": [
        "tabs",
        "https://api.twitter.com/1.1/*",
        "https://api.twitter.com/oauth/request_token",
        "https://api.twitter.com/oauth/authorize",
        "https://api.twitter.com/oauth/access_token"
    ],
    "manifest_version": 2
}

manifest.json

<javascript>
var oauth = ChromeExOAuth.initBackgroundPage({
    'request_url' : 'https://api.twitter.com/oauth/request_token',
    'authorize_url' : 'https://api.twitter.com/oauth/authorize',
    'access_url' : 'https://api.twitter.com/oauth/access_token',
    'consumer_key' : 'MY_KEY',
    'consumer_secret' : 'MY_SECRET',
    'scope' : 'https://api.twitter.com/1.1/',
    'app_name' : 'MY_APP'
});
	
function onTest(text, xhr) {
    chrome.tabs.create({ 'url' : 'test.html'});
};
	
function doTest() {
    oauth.authorize(function() {
        console.log("on authorize");
        var url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
        var request = {
            'method': 'GET',
            'parameters' : {
                'screen_name': 'ndrezet',
                'count': '2'
            }
        };
        oauth.sendSignedRequest(url, onTest, request);
    });
};

function logout() {
    oauth.clearTokens();
    setIcon();
};

chrome.browserAction.onClicked.addListener(doTest);
</javascript>

background.js

<!DOCTYPE html>
<html>
  <head>
    <title>OAuth Redirect Page</title>
    <style type="text/css">
      body {
        font: 16px Arial;
        color: #333;
      }
    </style>
    <script type="text/javascript" src="chrome_ex_oauthsimple.js"></script>
    <script type="text/javascript" src="chrome_ex_oauth.js"></script>
    <script type="text/javascript" src="onload.js"></script>
  </head>
  <body>
    Redirecting...
  </body>
</html>

chrome_ex_oauth.html

<javascript>
window.onload = function() {
  ChromeExOAuth.initCallbackPage();
}
</javascript>

onload.js

So far, every time I click on the extension I get stuck on a webpage “Redirecting…”.

Do you have any idea of what I’m doing wrong? And what should be the value of the callback URL in the Twitter app settings?

I realized that when I use the twitteroauth PHP library https://github.com/abraham/twitteroauth on a local server and I set the callback URL to “http://127.0.0.1/twitteroauth/callback.php”, I am no longer stuck on the above webpage. Instead, I manage to get to the Twitter webpage when I’m asked to authorize the app to use my account. The problem is when I click on “Authorize app”, I only see a blank page.

I hope that all my explanations make sense. Thanks for your help.


#2

Hey, did you ever figure this out? I’m going through the exact same steps at the moment but OAuth inside a Google Chrome extension is a nightmare!


#3

As we state on the Twitter Libraries page

Reminder: It is strongly discouraged to use OAuth 1.0A with client-side Javascript.

We discourage it because it is extremely difficult to achieve! I’m afraid it is going to be difficult to do what you want within a Chrome extension.


#4

Hey Andy,

Thanks for your response – appreciated. I actually managed to get it working, by the power of a Bank Holiday weekend and lots of wine!

I know that OAuth 1.0A isn’t recommended in the front-end, but ultimately this will be a compiled plugin so it should be fine.

It turns out that Chrome extensions can actually play quite nicely with OAuth, but there’s not much documentation around so there’s a lot of debugging required.

Thx,

@PeteM


#5

Ah, good to know - thanks! :smile:


#6

Also, correcting myself :blush:

We actually have an example Chrome extension in our samples gallery! :gift:


#8

Hello ndrezet,

I know this is a old post but were you able to figure out what the error is. I’am also stuck at the same point. Any hep would be appreciated


#9

Did you take a look at the sample I posted a link to?


#10

Yeah,
I did Look into the example but I don’t believe it uses the chrome_oauth.js library. On a quick glance I got to know it uses a something called codebird. I don’t know if the codebird library internally uses the chrome’s oAuth implementation. I just wanted to know if the issue was resolved using the oAuth implementation. If not then I will have to look deeper into the sample you posted and either tailor it / reimplement the whole thing in the chrome extension with codebird.


#11

Hello @RajeevReddy & all future extension developers looking into this.

I have built a chrome extension using the Google Oauth 1.0 tutorial that the original author of this post mentions. It will take you a lot of tinkering to get working but it is NOT WORTH THE EFFORT. You will have seemingly random errors during the login process and no apparent way to fix or alert the user that signing in failed. I tested today and found about only 33% of the time I could sign in successfully (503 was the most common error)

I then found this page and the example @andypiper mentioned. It took a bit of effort to switch over to match the example but has been flawless since. Its unfortunate but I don’t think Twitter ever plans implementing OAuth2 for user sign in (at that point you can use chrome extension identity)

For anyone looking for the quickest way to switch over

  • Get codebird.js
  • Copy/Modify common.js to suit your needs
  • Setup your signin stuff to match what is in background.js

I hope this helps. I’ve spent way to much time at this problem, and the example created by the twitter devs is by far the BEST way I’ve come across/developed

Tags for googlers: google chrome extension twitter oauth user authentication oauth2 oauth1 signin api


#12

I was going through this thread, and had already started implementing this with the Codebird approach, when I realized something…

You can grab any Chrome extension, unpack it and see the code in it. Isn’t it hugely discouraged to distribute the consumer secret? And I’m guessing there are no exceptions to that rule, are they?

Thanks!


#13

I know this is an old thread, but I came across it when trying to implement Oauth for twitter. I didn’t go the codebird route, but managed to do it another way with content scripts.

I added a callback URL in the twitter apps. In the chrome extension, we then add a content script that is injected on that same domain. This content script will then parse the query string for the auth tokens, and send that as a message to your background script. The background script will listen for the message, get the auth tokens, and then make another request to Twitter (the final leg of the three legged oauth process) to get the final oauth token and oauth token secret, which can then be saved to localStorage or chrome.storage.

Hope that helps. I wrote a blog post that describes setting this up: