User Authentication

When you are developing a web application, you might need to authenticate users of the application using your own sign in system or by requesting authorization from user's accounts in popular social networks like Facebook and Twitter. It has become common for web applications to let users sign in using third party authorization (i.e. Facebook, Twitter, Google), as it has proven to increase sign ups since the user does not have to worry about remembering a new pair of username/password. If you want your Rails app to integrate with social networks (e.g.. make posts on a user's Facebook page), you need to get authorization from these social networks.

The screenshot below shows an authorization request made by OmniAuth using the Facebook strategy:

facebook

In Rails, you are of course free to develop your own sign in system (especially true if you are learning the language), but getting to the market fast is your priority, or you would use an available gem for user authentication, then I would highly recommend the OmniAuth library (https://github.com/intridea/omniauth) that provides standardized multi-provider authentication.

OmniAuth Facebook Strategy

First, create your app Facebook Developers. Copy and App ID and App Secret.

In config/intitializers/omniauth.rb, add this code:

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, 'your_app_id_here', 'your_app_secret_here',
  :scope => 'email,user_birthday,read_stream', :display => 'popup'
end

OmniAuth Tutorial from Rails Rumble

Rails Rumble has published an excellent step-by-step tutorial in implementing OmniAuth: http://blog.railsrumble.com/2010/10/08/intridea-omniauth/. If you decide to follow the Rumble tutorial, you might encounter some errors shown below (for which I provided some fixes):

Error Message in shell: You should not use the `match` method in your router without specifying an HTTP method.

Fix: In /config/routes.rb...

Change: match '/auth/:provider/callback', :to => 'sessions#create'

To: match '/auth/:provider/callback', :to => 'sessions#create', :via => [:get], :as => 'sessions_create'

Error (in browser): The callback page just prints "nil" after a successful authorization.

Fix: In sessions_controller.rb, change request.env['rack.auth'] to change request.env['omniauth.auth'].