Help us understand the problem. What is going on with this article?

OmniAuth

More than 5 years have passed since last update.

OmniAuth

様々なプロバイダーのログイン認証を手軽に実現するプラグイン。

公式リポジトリ

https://github.com/intridea/omniauth

公式ドキュメント

https://github.com/intridea/omniauth/wiki

The Ruby Toolbox

https://www.ruby-toolbox.com/projects/omniauth

参考ドキュメント

簡単なOmniAuth - ASCIIcasts
Rails3.2.3 + omniauth-twitter New App - I can't change the world.

インストール

For GitHub

Gemfileに、omniauth、omniauth-githubを記述する。

Gemfile
gem 'omniauth'
gem 'omniauth-github'

インストールする。

$ bundle install

初期設定

For GitHub

設定ファイルを新規作成する。
CLIENT_IDSECRETには、GitHubで登録したアプリケーションのClient ID、Secretを設定する。

config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :github, "CLIENT_ID", "SECRET"
end

セッションコントローラを新規作成する。

rails g controller sessions
      create  app/controllers/sessions_controller.rb
      invoke  erb
      create    app/views/sessions
      invoke  helper
      create    app/helpers/sessions_helper.rb
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/sessions.js.coffee
      invoke    scss
      create      app/assets/stylesheets/sessions.css.scss
app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
  def callback
    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_path
  end

  def destroy
    reset_session
    redirect_to root_path
  end
end

ルーティングを追加する。

config/routes.rb
match "/auth/:provider/callback" => "sessions#callback"
match "/signout" => "sessions#destroy"

Userモデルを新規作成する。

$ rails generate model user
      invoke  active_record
      create    db/migrate/20120418060936_create_users.rb
      create    app/models/user.rb
db/migrate/20120418060936_create_users.rb
class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :provider, :null => false
      t.string :uid, :null => false
      t.string :name, :null => false
      t.string :nickname
      t.string :image
      t.string :token

      t.timestamps
    end
  end
end
app/models/user.rb
class User < ActiveRecord::Base
  def self.create_with_omniauth(auth)
    create! do |user|
      user.provider = auth["provider"]
      user.uid = auth["uid"]
      user.name = auth["info"]["name"]
      user.nickname = auth["info"]["nickname"]
      user.image = auth["extra"]["raw_info"]["avatar_url"]
      user.token = auth["credentials"]["token"]
    end
  end
end
$ rake db:migrate
==  CreateUsers: migrating ====================================================
-- create_table(:users)
   -> 0.0021s
==  CreateUsers: migrated (0.0022s) ===========================================

ヘルパーメソッドを追加する。

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery

  helper_method :current_user

  private

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end
end

ビューにログイン、ログアウトのリンクを追加する。

<% if current_user %>
  <%= link_to "Sign out", signout_path 
<% else %>
  <%= link_to "Sign in with GitHub", "/>
<% end %>

OmniAuthで取得可能な情報

For GitHub

OmniAuthで取得出来る情報は以下の通り。

{"provider"=>"github",
 "uid"=>572020,
 "info"=>
  {"nickname"=>"FakeStarBaby",
   "email"=>nil,
   "name"=>"Yoshinori Hirasawa",
   "urls"=>
    {"GitHub"=>"https://github.com/FakeStarBaby",
     "Blog"=>"http://twitter.com/#!/fakestarbaby"}},
 "credentials"=>
  {"token"=>"1234567890123456789012345678901234567890", "expires"=>false},
 "extra"=>
  {"raw_info"=>
    {"public_gists"=>10,
     "type"=>"User",
     "blog"=>"http://twitter.com/#!/fakestarbaby",
     "location"=>"Tokyo",
     "html_url"=>"https://github.com/FakeStarBaby",
     "created_at"=>"2011-01-19T05:08:56Z",
     "email"=>nil,
     "public_repos"=>51,
     "followers"=>16,
     "company"=>"Japan",
     "hireable"=>false,
     "bio"=>nil,
     "url"=>"https://api.github.com/users/FakeStarBaby",
     "following"=>69,
     "login"=>"FakeStarBaby",
     "name"=>"Yoshinori Hirasawa",
     "gravatar_id"=>"0e3e4d3a8e69ccae1e9b9dcc219f3f1f",
     "avatar_url"=>
      "https://secure.gravatar.com/avatar/0e3e4d3a8e69ccae1e9b9dcc219f3f1f?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-140.png",
     "id"=>572020}}}
fakestarbaby
嫁と娘(7歳)と息子(4歳)を愛するパパエンジニア Unity, C#, CoronaSDK, Lua, Ruby, Rails
http://blog.fakestarbaby.com/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした