Stephen Stephen - 7 months ago 38
Ruby Question

What is Facebook callback_url and how to use it in rails?

I am using the

Facebook Graph API
in my rails projects, no matter I use
oauth2
gem or
koala
, It need
callback_url


Oauth2

token = client.auth_code.get_token('code_value', :redirect_uri => 'http://localhost:8080/oauth/callback')


Koala

@oauth = Koala::Facebook::OAuth.new(app_id, app_secret, callback_url)


I try to use
http://localhost:3000/callback
in my project, but it's not working.

Should I develop a routes for that?

like:
get 'callback' => 'oauth#callback'
?

What should I write in the
callback
method in
OauthController
, what does it use for? Thanks

Answer

Yes, you should. Basically, OAuth uses callback data to provide tokens for authenticating users.

For example

  • user clicks on "sign in" (or whatever) link and your app redirects they to the OAuth provider (or open it in the iframe).
  • user permits to your app to use they profile details
  • OAuth provider send callback to your app with unique code
  • app uses that code to get secure access token for API communications

That's just a basic example.

In your case you need to implement controller that will parse callback data.

Here is the code example

@oauth = Koala::Facebook::OAuth.new(api_key, app_secret, callback_url)
=> #<Koala::Facebook::OAuth:0x007fc919d014e0 @app_id=1234567890, @app_secret="FaKeAppSecretKey", @oauth_callback_url="http://localhost:3000/callback">

@oauth.url_for_oauth_code
=> "https://www.facebook.com/dialog/oauth?client_id=893637180663238&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fcallback"

And when you go to https://www.facebook.com/dialog/oauth?client_id=893637180663238&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fcallback FB will redirect you to

http://localhost:3000/callback?code=CODE_FROM_CALLBACK

Then you should use implement controller that uses code to get access token

access_token = @oauth.get_access_token(params[:code])
=> "ACCESS_TOKEN"

@graph = Koala::Facebook::API.new(access_token)
 => #<Koala::Facebook::API:0x007fc91a903ae0  @access_token="ACCESS_TOKEN", @app_secret=nil>

profile = @graph.get_object("me")
=> {"id"=>"4492344324865", "email"=>"my_fake_email_address@gmail.com", "first_name"=>"Roman", "gender"=>"male", "last_name"=>"Sotnikov", "link"=>"https://www.facebook.com/app_scoped_user_id/4492344324865/", "locale"=>"en_US", "name"=>"Roman Sotnikov", "timezone"=>6, "updated_time"=>"2015-05-18T05:19:54+0000", "verified"=>true}

Please check https://github.com/arsduo/koala/wiki/OAuth for additional info.

Comments