LoginSignup
7
8

More than 5 years have passed since last update.

OAuth2 gemでGoogle Api よりaccess tokenを取得する

Last updated at Posted at 2017-11-15

OAuth2 gemでrailsのWEBアプリケーションとGoogle Api のOAuth連携を試す。

前提

  • Google Cloud Platform にログインし、コンソール>APIとサービス>認証情報より、新規プロジェクト、OAuth クライアントIDを作成。
  • railsアプリケーションにOAuth2 gemをインストール済み。

実装

お試しなのでcontroller に直接実装したが、moduleにでも出す。

oauth_controller.rb
require 'oauth2'

# google の認可サーバにリクエスト
def authorization
  client = OAuth2::Client.new(
    CLIENT_ID,
    CLIENT_SECRET,
    {
      site: 'https://accounts.google.com/',
      authorize_url: 'o/oauth2/auth',
    }
  )
  redirect_to client.auth_code.authorize_url(
    redirect_uri: 'http://localhost:8080/oauth/callback',
    scope: SCOPE_CODE,
    # see about scopes: https://developers.google.com/identity/protocols/googlescopes
  )
end

# パラメータで認可コード(code)を取得し、access_tokenをリクエスト・取得する。
def callback
  client = OAuth2::Client.new(
    CLIENT_ID,
    CLIENT_SECRET,
    {
      site: 'https://accounts.google.com/',
      token_url: 'o/oauth2/token',
    }
  )
  # 認可コードよりaccess_tokenをリクエスト・取得。
  token = client.auth_code.get_token(
    params[:code],
    redirect_uri: 'http://localhost:8080/oauth/callback',
  )
  # 適当なAPIを叩く
  response = token.get(
    'https://www.googleapis.com/plus/v1/people/me/activities/public'
  )
end

備考

  • このとり方ではrefresh_tokenはとれなかったので、別途対処が必要。
  • 例外処理は考えていない。
  • アプリケーションでアカウント認証が必要な場合はその処理も必要。
    今回、アカウントは作らないので、authoraization でsessionを作成し、callbackでsession取得・削除することとした。

参考

7
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8