Setting up simple OmniAuth authentication with Facebook
If you have watched Ryan Bates’ tutorial Simple OmniAuth you probably already know OmniAuth is awesome. Ryan doesn’t go into details about setting up OmniAuth with Facebook so this post has a couple of pointers to help out in that regard. It’s meant as a continuation to the screencast, so if you haven’t seen it start there.
In particular I had trouble getting the correct Facebook Application settings for development and ran into a silly little issue that took ages to figure out. So here’s more about that.
Create a Facebook App
Log in to your Facebook account and go to http://www.facebook.com/developers
Click the Set Up New App button at the top of the right column.
In the “Website” tab set the Site URL (formerly known as Connect URL) to http://localhost:3000/ and the Domain to localhost.
In the end your application settings should look something like this.
Add the Facebook App ID and API Key to config/initializers/omniauth.rb . If you want to specify different keys per environment and per developer you can use the following.
if Rails.env == "production"
# no production app yet
if ENV['USER'] == 'monica'
Rails.application.config.middleware.use OmniAuth::Builder do
provider :twitter, 'CONSUMER_KEY', 'CONSUMER_SECRET'
provider :facebook, 'APP_ID', 'APP_SECRET' # Find these values on the Facebook App page
Try it out!
Now all you have to do is create a link somewhere in your view
<%= link_to "Log in with Facebook", "/auth/facebook" %>
No need to create a route – it is handled by OmniAuth.
In your application click the “Log in with Facebook” link. You should see the Request for Permission box below.
Click agree and assuming you followed Ryan Bates’ tutorial you should see whatever your SessionsController#create action produces.
If you get an error related to the redirect_uri keep on reading.
Invalid redirect_uri: Given URL is not allowed by the Application configuration
"message": "Invalid redirect_uri: Given URL is not allowed by the Application configuration."
What this error is saying is that the Site URL that we set up with Facebook does not match where OmniAuth is telling Facebook to take the user after they logged in. So Facebook refuses to perform the redirect.
But how can that be? We set the Site URL to localhost:3000. Where is OmniAuth redirecting the request?
A quick look at the URL reveals the problem: OmniAuth is setting the redirect_uri to 127.0.0.1:3000 instead of localhost:3000. If this happens to you make sure you’re accessing your app on your dev machine through http://localhost:3000 instead of http://127.0.0.1:3000 . OmniAuth will pick up the url you enter in your browser as the application url and use it for the callback.