Create a gist now

Instantly share code, notes, and snippets.

@moonmilk /README.md
Last active Feb 19, 2017

manually authorize a twitter app to a twitter account

So you're writting a twitterbot and you need to authorize your application to post to the account. You need an access token and secret for the account you're posting to. If the posting account is the same account that owns the application, no problem, you just push the button on your application's settings page to make the keys. But if you want to post to a different twitter account, there's no UI on apps.twitter.com to authorize it. So I made this bare-minimum node server to run through the authorization process. There's probably a much better way to do this, so please let me know what that way is!

ignore this and go down to the comments for better solutions

  • You'll need a server with node.js!
  • Make sure your application has a callback URL specified in its settings page, even if it's just a placeholder. If there's nothing in the callback URL slot, this method of authorization won't work.
  • In authorize.js, fill in your application's consumer key and secret, and the domain on which you'll be running this mini-server (I think it'll work with 'localhost' if you're running it on your laptop, but I haven't tested it that way).
  • Install the application (npm install)
  • Run the server (node authorize.js)
  • In a browser, make sure you're logged in to the account that you want to authorize, and then visit this server in the browser (e.g. http://localhost:3456)
  • Click "authenticate" and you should be sent to the Twitter app authorization page
  • When you authorize the app, you should see a page displaying your new access token and secret. Keep those safe!

If it doesn't work for you, I probably can't help you, but someone who understands this system better than I do will probably make a version of this process that works better.

var express = require('express');
var app = express();
var twitterAPI = require('node-twitter-api');
var twitter = new twitterAPI({
// application keys for your application
consumerKey: '...',
consumerSecret: '...',
callback: 'http://your domain or localhost:3456/auth'
});
var requestToken, requestTokenSecret;
// following instructions from https://www.npmjs.org/package/node-twitter-api
app.get('/', function(req, res){
twitter.getRequestToken(function(error, _requestToken, _requestTokenSecret, results){
if (error) {
res.send(error);
} else {
//store token and tokenSecret somewhere, you'll need them later; redirect user
requestToken = _requestToken;
requestTokenSecret = _requestTokenSecret;
res.send('<a href="' + twitter.getAuthUrl(requestToken) + '">authenticate</a>');
}
});
});
app.get('/auth', function(req, res) {
twitter.getAccessToken(requestToken, requestTokenSecret, req.query.oauth_verifier, function(error, accessToken, accessTokenSecret, results) {
if (error) {
res.send(error);
} else {
//store accessToken and accessTokenSecret somewhere (associated to the user)
res.send('accessToken: <b>' + accessToken + '</b><br/>accessTokenSecret: <b>' + accessTokenSecret + '</b>');
}
});
});
app.listen(3456);
{
"name": "twitter authorizing thingy",
"version": "1.0.0",
"description": "",
"main": "authorize.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.10.1",
"node-twitter-api": "^1.5.0"
}
}
@beaugunderson

I usually use the PIN authorization method since you don't have to set up a server or specify a callback URL; if I understand what you're doing I think it will work for your case as well. Here's an example in Python (but I'm interested in implementing this same functionality in my bot-utilities library):

#!/usr/bin/env python

import tweepy

# From your app settings page
CONSUMER_KEY = ""
CONSUMER_SECRET = ""

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.secure = True
auth_url = auth.get_authorization_url()

print 'Please authorize: ' + auth_url

verifier = raw_input('PIN: ').strip()

auth.get_access_token(verifier)

print "ACCESS_KEY = '%s'" % auth.access_token.key
print "ACCESS_SECRET = '%s'" % auth.access_token.secret

It works by giving you a URL to authorize with, you paste that into a browser that's logged in as the given user. You'll get a PIN back, which the app is now waiting for--from there you get your access key and secret.

@moonmilk
Owner
moonmilk commented Nov 9, 2014

Ahhh, that's much better. I'm totally using that next time I have to do this.

@moonmilk
Owner

Used it to authorize @hafaslegomenon just now, and it was so much easier than my version!

@vagelim
vagelim commented Jan 28, 2015

I know this is an old thread, just thought I'd show how I usually authorize my bots.

#!/usr/bin/env python
#To get twitter oauth tokens
#1. Get your consumer key and consumer secret from the app page on apps.twitter.com
#2. Use the birdy python library

from birdy.twitter import UserClient

key = raw_input("Consumer key: ")
secret = raw_input("Consumer secret: ")
client = UserClient(key, secret)
token = client.get_signin_token()
access_key = token.oauth_token
access_secret = token.oauth_token_secret
print token.auth_url
pin = raw_input("PIN: ")
client = UserClient(key, secret, access_key, access_secret)
client.get_access_token(pin)
print token
@aparrish

aaaaand the Twython version

import twython

app_key = raw_input("Your app key: ")
app_secret = raw_input("Your app secret: ")

twitter = twython.Twython(app_key, app_secret)

auth = twitter.get_authentication_tokens()

print "Log into Twitter as the user you want to authorize and visit this URL:"
print "\t" + auth['auth_url']

pin = raw_input("Enter your PIN: ")

twitter = twython.Twython(app_key, app_secret, auth['oauth_token'],
        auth['oauth_token_secret'])
tokens = twitter.get_authorized_tokens(pin)

print "Your token: " + tokens['oauth_token']
print "Your token secret: " + tokens['oauth_token_secret']
@aparrish

hey, I made a command-line-only version for node.js (using the node-twitter-api library) in case you nodesters don't want to have to use python for this one tiny task.

@frandevel

@aparrish Thanks for the node version. Works perfect.

@hugovk
hugovk commented Sep 25, 2015

Here's my updated version of @beaugunderson's PIN method because auth.access_token.key and auth.access_token.secret are now auth.access_token andauth.access_token_secret`. It also prints all four out ready for saving in a YAML file.

#!/usr/bin/env python
"""
Authorise a Twitter bot account against a Twitter bot application.

It works by giving you a URL to authorise with, you paste that into a browser
that's logged in as the given (bot) user. You'll get a PIN back, which the app
is now waiting for -- from there you get your access key and secret.

Based on beaugunderson's:
https://gist.github.com/moonmilk/035917e668872013c1bd#gistcomment-1333900
"""
from __future__ import print_function, unicode_literals
import argparse
import tweepy


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Authorise a Twitter account against an app.",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument(
        'consumer_key',
        help="From your app settings page")
    parser.add_argument(
        'consumer_secret',
        help="From your app settings page")
    args = parser.parse_args()

    auth = tweepy.OAuthHandler(args.consumer_key, args.consumer_secret)
    auth.secure = True
    auth_url = auth.get_authorization_url()

    print()
    print("Please open this URL in a browsr that's logged in as your bot,\n"
          "authorise the application, and then type in the PIN back here.")
    print()
    print(auth_url)

    verifier = raw_input('PIN: ').strip()

    auth.get_access_token(verifier)

    print()
    print("consumer_key: " + args.consumer_key)
    print("consumer_secret: " + args.consumer_secret)
    print("access_token: " + auth.access_token)
    print("access_token_secret: " + auth.access_token_secret)

# End of file

Also here: https://github.com/hugovk/twitter-tools/blob/master/bot_authorise.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment