Authentication with omniauth-github in Rails

Authenticating with 3rd party services is widely used on many websites. You can log with Facebook, Google Account or other depending on website. For some of my Rails projects I need authentication with GitHub.

First, we start with adding omniauth (Rack framework for authentication) and omniauth-github (OmniAuth strategy for GitHub) to Gemfile.

gem 'omniauth', '~> 1.2.2'
gem 'omniauth-github', '~> 1.1.2'

Second, we create config/initializers/omniauth.rb

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :github, ENV.fetch('GITHUB_CLIENT_ID'), ENV.fetch('GITHUB_CLIENT_SECRET')
end

As you can see I pass environment variables GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET to GitHub provider. Feel free to do it in your preferred way.

Here comes third step, it’s necessary to provide mentioned environment variables. On https://github.com/settings/applications/new we register a new OAuth application.

For development purposes we can set:

Sequence of requests between application and GitHub is following:

authentication

To routes.rb we add to two lines:

  get '/login' => redirect('/auth/github')
  get '/auth/:provider/callback', to: 'sessions#create'

Then we create app/controllers/sessions_controller.rb and we add following code:

class SessionsController < ApplicationController
  def create
    user = User.find_or_create_by(user_attributes)

    session[:user_id] = user.id
    redirect_to(root_path)
  end

  private

  def user_attributes
    {
      provider: auth['provider'],
      username: auth['info']['nickname']
    }
  end

  def auth
    request.env['omniauth.auth']
  end
end

This is basic template I use for my projects. Sometimes I extract more information from request.env['omniauth.auth'] and store in database.

More info in documentation:

Posted on 28/11/2014, in Rails. Bookmark the permalink. Dodaj komentarz.

Skomentuj

Wprowadź swoje dane lub kliknij jedną z tych ikon, aby się zalogować:

Logo WordPress.com

Komentujesz korzystając z konta WordPress.com. Log Out / Zmień )

Zdjęcie z Twittera

Komentujesz korzystając z konta Twitter. Log Out / Zmień )

Facebook photo

Komentujesz korzystając z konta Facebook. Log Out / Zmień )

Google+ photo

Komentujesz korzystając z konta Google+. Log Out / Zmień )

Connecting to %s

%d bloggers like this: