Skip to content

Instantly share code, notes, and snippets.

@cyu
Last active November 18, 2016 23:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cyu/57d1253f18779af74899 to your computer and use it in GitHub Desktop.
Save cyu/57d1253f18779af74899 to your computer and use it in GitHub Desktop.
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) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment