Omniauth and Google OAuth in Rails 3

12 Sep 2011

If you want to build an app on the Google Apps platform, or offer an app in the Google Apps marketplace, you’ll probably need to authenticate users on the Google platform. The omniauth library has support for Google OAuth, but the documentation to configure this is scattered.

The first step is to get your OAuth consumer key and secret key. To get this, log into your Google Apps account (i.e google.com/a/yourdomain.com), and select Advanced Tools then Manage OAuth domain key. They keys should be listed here. A nifty little utility to generate OAuth keys is Google’s xoauth.py.

When you have your consumer and secret keys, you’ll need to set up omniauth. The first step is adding omniauth to your Gemfile:

gem 'omniauth'

Your initializers/omniauth.rb should look like:

OmniAuth.config.full_host = "http://localhost:3000"

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :google, 'domain.com', 'oauth_secret', :scope => 'https://mail.google.com/mail/feed/atom/' 
end

OmniAuth.config.full_host is important. If this isn’t configured, you’ll receive strange OAuth::Unauthorized errors. The scope specifies what kind of data your application will access.

You can read more about Auth scopes here.

Next you’ll need to configure by adding a sessions controller.

rails g controller sessions

Then, add a couple actions to this controller for You can see how to do there here.

class SessionsController < ApplicationController
  def create
    auth = request.env["omniauth.auth"]
    user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth)
    session[:user_id] = user.id
    redirect_to root_url, :notice => "Signed in!"
  end

  def destroy
    session[:user_id] = nil
    redirect_to root_url, :notice => "Signed out!"
  end
end

Finally, you have to add a couple lines to routes.rb:

match "/auth/:provider/callback" => "sessions#create"
match "/signout" => "sessions#destroy", :as => :signout

After this, if you visit http://localhost:3000/auth/google, you should be redirected to a Google auth screen. When you authorize, you’re redirected back to the create action. From here you can store the various bits of data in request.env“omniauth.auth”.