Musings of an 8-bit Vet

A Student Coders Tech Diary

Capture OMNIAUTH Failures in Development Mode

As part of a recent Rails project, I was implementing authentication using GitHub credentials via OmniAuth.

I came across an annoying problem with the way OmniAuth handles a failure to authenticate while in development mode. In normal deployment a failure to authenticate will redirect back to the requesting website.

However, while in development mode in Rails, the failure endpoint causes the controller to throw an error and brings the site to a halt. This is not particularly graceful.

After some Googling I found a solution:

Take a look at the omniauth.rb file under the initializers directory of your Rails app:

1
2
3
4
5
6
7
8
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET'],
            scope: "user:email"
end

OmniAuth.config.on_failure = Proc.new { |env|
  OmniAuth::FailureEndpoint.new(env).redirect_to_failure
}

The first line configures the Rails middleware to use OmniAuth and to pass various values to the provider, in this case GitHub.

The code on line 6-8 solves the development failure endpoint by allowing you to redirect to the page of your choice via routes.rb:

1
2
get '/auth/:provider/callback' => 'sessions#create'
get '/auth/failure', to: redirect('/')

Further actions would be handled by the sessions or other authentication controller.

This allows you to better test authentication, and to get an idea of how your application will behave without having to deploy it first. The code can remain in production, it does not need to be removed.

I’ll cover more on OmniAuth authentication in a later post.

Resources:

Intridea OmniAuth FAQ