Search code examples
ruby-on-rails-3openidomniauth

Intermittent OmniAuth errors authenticating against Google


When trying to authenticate using Omniauth, it works flawlessly in my development environment (Mac OSX Mavericks), but fails most of the time in production (on Heroku). The errors vary between "Invalid Credentials" and "Connection failed". In all cases, I'm already logged in to my Google account. I may get one or another of these errors anywhere between 4 and 8 times before the process succeeds.

Has anyone see this and can you shed some light on why this might be happening?

Gem: oa_openid (0.3.2)

config/routes.rb:

...
resource :admin_session, only: %w(show create destroy)
match '/auth/googleapps/callback' => 'admin_sessions#create'
...

config/omniauth.rb:

require 'openid/store/filesystem'

Rails.application.config.middleware.use OmniAuth::Strategies::GoogleApps, 
    OpenID::Store::Filesystem.new('./tmp'), 
    name: 'googleapps', domain: 'booktrakr.com'

admin_sessions_controller:

class AdminSessionsController < ApplicationController
  # GET /admin_sessions
  def show
    redirect_to "/auth/googleapps?origin=#{params[:origin] || request.fullpath}" and return unless is_admin?

    @session = authenticated_admin
  end

  # POST /admin_sessions
  def create
    authinfo = request.env['omniauth.auth']
    uid = authinfo['uid']

    unless uid =~ %r(^https?://(groundbreakingsoftware|booktrakr).com/openid)
      raise "Bad hacker, no cookie"
    end

    self.authenticated_admin = authinfo

    redirect_to request.env['omniauth.origin'], notice: 'Session was successfully created.'
  end

  # DELETE /admin_sessions
  def destroy
    self.authenticated_admin = nil

    redirect_to root_url
  end
end

Solution

  • It appears that switching to OAuth2 (https://github.com/zquestz/omniauth-google-oauth2) resolved the problem, at least at first blush. Thanks, @Ashitaka!