Skip to content

Instantly share code, notes, and snippets.

@joeldsa
Created October 8, 2012 16:19
Show Gist options
  • Save joeldsa/3853374 to your computer and use it in GitHub Desktop.
Save joeldsa/3853374 to your computer and use it in GitHub Desktop.
Oauth2 for ruby web apps
require 'uaa'
# the URL of the UAA
UAA_TARGET = "https://uaa.cf102.dev.las01.vcsops.com"
# UAA Client Application Registration info
CLIENT_ID = "app" # the name registered with the UAA for this app
CLIENT_SECRET = "appclientsecret" # the app registration code
SCOPE = "dashboard.user openid" # this app will ask users to delegate authorization for these scopes
REDIR_URI = nil # as registered with the UAA. Specify a value here to override the default of http://host:port/CALLBACK_PATH
CALLBACK_PATH = "/loggedin" # path of the endpoint of this app to recieve the authcode
enable :sessions
token_issuer = CF::UAA::TokenIssuer.new(UAA_TARGET, CLIENT_ID, CLIENT_SECRET)
logger = Logger.new(STDOUT)
logger.level = Logger::TRACE
token_issuer.logger = logger
UAA_TARGET = UAA_TARGET.sub(/(\/)+$/,'')
get '/login' do
redir_uri = REDIR_URI ? REDIR_URI : "http://#{request.host}:#{request.port}#{CALLBACK_PATH}"
redir_uri = token_issuer.authcode_uri(redir_uri, SCOPE)
session["redir_uri"] = redir_uri
redirect redir_uri
end
get CALLBACK_PATH do
token = token_issuer.authcode_grant(session["redir_uri"], request.query_string)
puts "TOKEN #{token.inspect}"
contents = CF::UAA::Misc.whoami(UAA_TARGET, token.auth_header)
session[:user_id] = contents[:user_id]
session[:email] = contents[:user_name]
redirect '/'
end
before do
if !["#{CALLBACK_PATH}",
'/login',
'/logout'].include?(request.path_info)
redirect '/login' unless session[:user_id]
end
end
get '/logout' do
session.clear
redirect "#{UAA_TARGET}/logout.do?redirect=http://#{request.host}:#{request.port}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment