facebookのOAuth2を使って、RubyのCGIウェブアプリケーションを認可するサンプルです。
Preparation
- Ruby CGI environment
- For example, Apache 2.2 and ruby 1.8.7
- facebook application ID and secret ID
Sequence
Code
login.rb
#!/usr/local/bin/ruby
require "cgi"
client_id = "xxxxxxxx" # set your facebook application client_id
redirect_uri = CGI.escape("http://myapp.com/top.rb") # set your application url
#
# 2. Redirect
#
url = "https://graph.facebook.com/oauth/authorize?" +
"response_type=code&" +
"client_id=#{client_id}&" +
"redirect_uri=#{redirect_uri}"
cgi = CGI.new
print cgi.header({ 'status' => 'REDIRECT', 'Location' => url })
top.rb
#!/usr/local/bin/ruby
require 'rubygems'
require 'json'
require 'cgi'
client_id = "xxxxxx" # set your facebook application client_id
client_secret = "xxxxxx" # set your facebook application client_secret
redirect_uri = CGI.escape("http://myapp.com/top.rb") # set your application url
#
# 5. Access Token Request
#
code = CGI.new()["code"]
url = "/oauth/access_token?" +
"client_id=#{client_id}&" +
"client_secret=#{client_secret}&" +
"redirect_uri=#{redirect_uri}&"+
"code=#{code}"
# start ssl
require 'net/https'
https = Net::HTTP.new('graph.facebook.com',443)
https.use_ssl = true
https.verify_mode = OpenSSL::SSL::VERIFY_NONE
access_token=""
https.start {
response = https.get(url)
# perse string such as "access_token=AAAsZCLvBgZDZD&expires=4992995"
response.body.split("&").each do |param|
access_token = param.split("=")[1] if param.split("=")[0] == "access_token"
end
}
#
# 7. Request User Information Using Access Token
#
json=""
url = "/me?access_token=#{access_token}"
https.start {
json = https.get(url).body
}
#
# 9. User Infomation Page
#
name = JSON.parse(json)["name"]
print "Content-Type: text/html\n\nHello #{name}\n<hr>\n#{json}\n"