cyu
5/6/2014 - 2:59 PM

How to get a Twitter application-only bearer token#

How to get a Twitter application-only bearer token#

# https://dev.twitter.com/docs/auth/application-only-auth

require 'open-uri'
require "base64"
require 'net/http'
require 'json'

CONSUMER_KEY    = 'MY_CONSUMER_KEY'
CONSUMER_SECRET = 'MY_CONSUMER_SECRET'

key_encoded    = URI::encode(CONSUMER_KEY)
secret_encoded = URI::encode(CONSUMER_SECRET)

key_secret_combined = [key_encoded, secret_encoded].join(':')
key_secret_encoded  = Base64.encode64(key_secret_combined).gsub("\n", '')

uri = URI('https://api.twitter.com/oauth2/token')

req = Net::HTTP::Post.new(uri)
req['Content-Type' ] = 'application/x-www-form-urlencoded;charset=UTF-8'
req['Authorization'] = "Basic #{key_secret_encoded}"
req.form_data = {
  :grant_type => 'client_credentials'
}

response = Net::HTTP.start(uri.hostname, uri.port,
                           :use_ssl => uri.scheme == 'https') do |http|
  http.request(req)
end

bearer_token = nil
if parsed_response = JSON.parse(response.body)
  if parsed_response['token_type'] == 'bearer'
    bearer_token = parsed_response['access_token']
  end
end

puts bearer_token

# example of how to use the token
uri = URI('https://api.twitter.com/1.1/statuses/user_timeline.json?count=4&screen_name=scoutmob')
req = Net::HTTP::Get.new(uri)
req['Authorization'] = "Bearer #{bearer_token}"

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
response = http.start { |http| http.request(req) }