Skip to content
mbleigh edited this page Aug 17, 2010 · 7 revisions

First, add oauth2 to your gems in config/environment.rb:

config.gem 'oauth2'

Next, let’s create a controller:

script/generate controller oauth

Now let’s make routes for it. In your config/routes.rb do:

map.oauth_authorize '/oauth/start', :controller => 'oauth', :action => 'start'
map.oauth_callback '/oauth/callback', :controller => 'oauth', :action => 'callback'

Now we need to set up our controller:

class OauthController < ApplicationController
  def start
    redirect_to client.web_server.authorize_url(
      :redirect_uri => oauth_callback_url
    )
  end

  def callback
    access_token = client.web_server.get_access_token(
      params[:code], :redirect_uri => oauth_callback_url
    )

    user_json = access_token.get('/me')
    # in reality you would at this point store the access_token.token value as well as 
    # any user info you wanted
    render :json => user_json
  end

  protected

  def client
    @client ||= OAuth2::Client.new(
      'app_id', 'app_secret', :site => 'https://graph.facebook.com'
    )
  end
end

Now to start the authentication process you just need to send the user to the oauth_authorize_path in your app.

Clone this wiki locally