Stories From The Field / Tech

Using the Google Authenticator App with Rails

Posted on June 29 2011 by Richard Taylor (@moomerman)

Following on from last weeks post on Two-factor Authentication with Rails this post adds support for the Google Authenticator app for Android, iPhone and Blackberry. The full source code is available on github and there is now a live demo available on heroku.

Integration

The integration is very straight-forward thanks to the ROTP library. Add it to your Gemfile.

gem 'rotp'

The authentication mechanism works by having a per-user shared key between your web application and the app on the phone so we're going to add one to our User model:

add_column :users, :auth_secret, :string

And assign a random base32 string when you create a new User.

class User < ActiveRecord::Base
  ...
  before_validation :assign_auth_secret, :on => :create
  ...
  def assign_auth_secret
    self.auth_secret = ROTP::Base32.random_base32
  end
end

Now we can present that auth_secret to the user when they sign up and they can add it to Google Authenticator. The app can also scan a QR Code to save the user having to enter the secret manually. This helper uses Google Charts to generate the QR Code:

module SessionsHelper
  def google_authenticator_qrcode(user)
    data = "otpauth://totp/two_factor_demo?secret=#{user.auth_secret}"
    data = Rack::Utils.escape(data)
    url = "https://chart.googleapis.​com/chart?chs=200x200&chld=M|0&cht=qr&chl=#{data}"
    return image_tag(url, :alt => 'Google Authenticator QRCode')
  end
end

All that is left to do is validate the code in our Session model when the user enters it.


def validates?
  return true if self.validation_code == ROTP::TOTP.new(self.user.auth_secret).now.to_s
end

That's it. You can try it out on the demo site.

Comments