Railsのアプリでもっとも重要な認証機能、その中のGoogleでのSNS認証を
導入します。
今回はomniauth-google-oauth2というgemの導入手順についての記事です。
目的
簡単にomniauth-google-oauth2を導入する
(前提、環境)
mac
macOS Mojave 10.14.5
ruby 2.5.1
rails 5.2.3
gem ‘devise’ 4.7.1
はじめに
omniauthについて
そもそものomniauthについてはこちらにまとめてあります。
Google以外でのSNS認証がしたい場合、参考にしてみてください!
RailsにSNS認証を分かりやすく導入する方法 Omniauthの導入
https://hirocorpblog.com/rails%e3%81%absns%e8%aa%8d%e8%a8%bc%e3%82%92%e5%88%86%e3%81%8b%e3%82%8a%e3%82%84%e3%81%99%e3%81%8f%e5%b0%8e%e5%85%a5%e3%81%99%e3%82%8b%e6%96%b9%e6%b3%95omniauth%e3%81%ae%e5%b0%8e%e5%85%a5/
公式
いつも通りまずは一次ソースのgithubを見に行きます。
omniauth-google-oauth2
https://github.com/zquestz/omniauth-google-oauth2
omniauth-google-oauth2とは
GoogleのAPIを利用して認証を行うgemです。
omniauthではGoogle認証は「omniauth-google-oauth」と「omniauth-google-oauth2」の二つが用意されているのですが、OAuth 2 APIを利用している最新の「omniauth-google-oauth2」の方がセキュリティー上強そうなのでこちらを利用します!
導入
Google APIの取得
まずはGoogle APIを取得しに行きます!
Google API Console
https://code.google.com/apis/console/
リファレンスも用意されているのでこちらも時間があれば読んでみましょう!
OAuth 2.0 を使ってGoogle APIsにアクセスする
https://developers.google.com/accounts/docs/OAuth2
①プロジェクトを作成
プロジェクトを作成をクリックしてプロジェクト名、組織、場所を選択しましょう!
②OAuthの同意をする
ナビゲーションメニューから「 APIとサービス」「OAuth 同意画面」を選択してクリックしてください。
内部か外部か選べます。
- 内部:会社やサークルの中だけ
- 外部:一般ユーザー全員
なのでポートフォリオとして、または通常のサービスとして使い方は外部を選択しましょう!
プロジェクト名を入力して保存しましょう!
③認証情報をセットする
ナビゲーションメニューから「 APIとサービス」「認証情報」を選択してクリックしてください。
認証情報を作成をクリックしましょう。
OAuthクライアントIDを選択してください。
次に以下を入力します。
・アプリケーションの種類 → 「ウェブアプリケーション」
・名前 → プロジェクト作成の時に入力したアプリ名。
・承認済みのリダイレクト URI → `http://localhost:3000/users/auth/google/callback`
アプリケーションは使いたいものに応じて選んでいただければと思いますが、今回はRailsに実装するので「ウェブアプリケーション」を選択します。
承認済みのリダイレクトURIに関してはローカルで動かしたいので一旦localhost:3000のパスを記述します。
クライアントIDとシークレットが生成されるので取っておきましょう。
④APIをセット
ナビゲーションメニューから「 ライブラリ」,「Google+」を選択して「有効化」を選択してください。
こちらでGoogleのAPIの設定は完了です!
Gemfile
Gemfileに記述
in Gemfile
gem 'omniauth-google-oauth2'
bundle install
bundle install
Railsにシークレットキーをセット
Railsに外部ツールのキーを設定する方法は様々ありますが、今回僕はRails5.2系を利用しているので推奨されているcredentials.ymlの設定方法で実装します。
※Rails5.1以下の場合はsecrets.ymlやdotenvのgemを使うと良いでしょう!
credentials.yml
まずはアプリのディレクトリに移動して下記のコマンドを打ちましょう。
EDITOR="vim" bin/rails credentials:edit
vimでcredentials.ymlが開くのでインサートモードにして、下記のように記述をしていきます。(先ほど取得したキーを参照にxを書き換えてください。)
google:
client_id: xxxxxxxxxx.apps.googleusercontent.com
client_secret: xxxxxxxxxxxxxxxxxxxxxxx
Railsのログイン機能に組み込む
僕はdeviseを利用しているので、deviseの組み込み方をこちらに記述します!
下の方にdeviseを使用していない場合を記述しておきます!
config/initializers/devise.rbに追記
# in config/initializers/devise.rb
Devise.setup do |config|
# 〜〜(省略)
config.omniauth :google_oauth2, Rails.application.credentials.google[:client_id], Rails.application.credentials.google[:client_secret], name: :google,
scope: %w(email)
end
config/routes.rbに追記
# in config/routes.rb
devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks' }
app/models/user.rbに追記
deviseで作成したUserモデルにomniauthが使えるように定義します!
後述のコントローラでfrom_authメソッドをUserモデルで使うので、ここで定義しておきましょう。
# in app/models/user.rb
devise :omniauthable, omniauth_providers: [:google_oauth2]
def self.from_omniauth(access_token)
data = access_token.info
user = User.where(email: data['email']).first
# Uncomment the section below if you want users to be created if they don't exist
# unless user
# user = User.create(name: data['name'],
# email: data['email'],
# password: Devise.friendly_token[0,20]
# )
# end
user
end
OmniauthCallbacksControllerに追記
コントローラーにgoogle_auth2メソッドを定義します!
# in app/controllers/user/OmniauthCallbacksController.rb
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def google_oauth2
# You need to implement the method below in your model (e.g. app/models/user.rb)
@user = User.from_omniauth(request.env['omniauth.auth'])
if @user.persisted?
flash[:notice] = I18n.t 'devise.omniauth_callbacks.success', kind: 'Google'
sign_in_and_redirect @user, event: :authentication
else
session['devise.google_data'] = request.env['omniauth.auth'].except(:extra) # Removing extra as it can overflow some session stores
redirect_to new_user_registration_url, alert: @user.errors.full_messages.join("\n")
end
end
end
viewファイルに記述
Google認証に飛ばしたいviewファイルに記述します。
<%= link_to "Sign in with Google", user_google_oauth2_omniauth_authorize_path %>
# Deviseのバージョンが4.1.0以下の場合
<%= link_to "Sign in with Google", user_omniauth_authorize_path(:google_oauth2) %>
【番外編】config/initializers/omniauth.rbに追記
deviseを使わずに認証機能を実装している方はこちらを
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, Rails.application.credentials.google[:client_id], Rails.application.credentials.google[:client_secret]
end
終わりに
GoogleのAPI取得からdeviseに実装するまでの流れは相当長くなってしまいました汗
でもGoogle先生APIありがとう!!