Created
April 5, 2016 09:23
-
-
Save mosson/5ef6f6145725aad2246c82d03546f832 to your computer and use it in GitHub Desktop.
example oauth2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding: utf-8 | |
require 'rubygems' | |
require 'bundler/setup' | |
require 'oauth2' | |
require 'sinatra' | |
require 'faraday' | |
OAuth2::Response.register_parser(:text, 'text/plain') do |body| | |
key, value = body.split('=') | |
{key => value} | |
end | |
class ExampleApp < Sinatra::Base | |
SITE = 'https://graph.facebook.com' | |
TOKEN_URI = '/oauth/access_token' | |
KEY = ENV['FACEBOOK_KEY'] | |
SECRET = ENV['FACEBOOK_SECRET'] | |
set :port, 3000 | |
configure do | |
use Rack::Session::Cookie | |
end | |
get '/' do | |
callback_url='http://example.com:3000/oauth/callback' | |
client = OAuth2::Client.new(KEY, SECRET, site: SITE, token_url: TOKEN_URI) | |
url = client.auth_code.authorize_url(redirect_uri: callback_url) | |
redirect url | |
end | |
get '/oauth/callback' do | |
client = OAuth2::Client.new(KEY, SECRET, site: SITE, token_url: TOKEN_URI) | |
access_token = client.auth_code.get_token(params[:code], {redirect_uri: request.url}) | |
session[:access_token] = access_token.token | |
redirect '/me' | |
end | |
get '/me' do | |
conn = Faraday::Connection.new(:url => 'https://graph.facebook.com') do |builder| | |
builder.use Faraday::Request::UrlEncoded # リクエストパラメータを URL エンコードする | |
builder.use Faraday::Response::Logger # リクエストを標準出力に出力する | |
builder.use Faraday::Adapter::NetHttp # Net/HTTP をアダプターに使う | |
end | |
response = conn.get "/me?access_token=#{session[:access_token]}" | |
response.body | |
end | |
end | |
ExampleApp.run! if __FILE__ == $0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment