Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails-api authentications for Facebook SDK iOS connect?

I'm planning to use rails-api for providing JSON API for iOS mobile application to consume. The process:

  1. User open the mobile app
  2. User taps on Facebook connect
  3. Mobile app get fb_access_token and post it to API server to identify the user
  4. API server get user profile on Facebook by using fb_access_token
  5. API server either create and look up the user, then response with a api_token for this particular user
  6. Mobile app use the api_token response for all communication afterward.

Which authentication should be the best option for this app? oAuth2 or BasicAuth? I tried rails-api with doorkeeper, but it doesn't work out of the box because doorkeeper need some assets.

like image 501
Samnang Avatar asked Jan 13 '14 08:01

Samnang


2 Answers

I am doing a basic authentication for this integrated with devise.

First i get the post parameters from the mobile application (the access_token and other stuff).

Then I use open-api to get the user details from facebook:

    url = "https://graph.facebook.com/me?access_token="
    begin
      content = open(URI.encode(url + params[:user][:access_token]))
    rescue OpenURI::HTTPError #with this I handle if the access token is not ok
      return render :json => {:error => "not_good_access_token" }
    end

Now Facebook returns the response

  status = content.status[0]
  content = ActiveSupport::JSON.decode(content)

  if status == "200"
    #get the email and check if the user is already in the database. If there is not email, check by the facebook id
    #If the user exists return the user. If the user does not exists create new

Hope this helps

Than you can user the same code also for google, just change the url to "https://www.googleapis.com/oauth2/v2/userinfo?access_token="

like image 107
Marko Jurinčič Avatar answered Oct 21 '22 20:10

Marko Jurinčič


I'd give omniauth-facebook at try, as it uses OAuth2 and is pretty easy to use. All omniauth strategies are rails middleware, so you just need to add gem 'omniauth-facebook' to your gemfile and add the following to config/initializers/omniauth.rb and you will be able to use /auth/facebook to log in via facebook and /auth/facebook/callback to create the user session (you might want to alter the :display key-value as pop-ups in mobile might not be aesthetically pleasing):

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET'],
           :scope => 'email,user_birthday,read_stream', :display => 'popup'
end

The facebook auth token will be in the request.env['omniauth.auth'][:credentials][:token] that gets returned to your callback endpoint, which you can integrate into your mobile authentication strategy. see the above link and the omniauth main page for more details.

like image 30
Marc Avatar answered Oct 21 '22 20:10

Marc