LoginSignup
7

More than 5 years have passed since last update.

Ruby on Rails + OmniAuthでGoogleCalendarにアクセスしたい

Last updated at Posted at 2017-12-03

Ruby on Rails + OmniAuthでGoogleCalendarにアクセスしたい。どうするの?

configする

scope:prompt:access_type: がミソ。

config/initializers/omniauth.rb
  provider :google_oauth2,
           ENV['GOOGLE_CLIENT_ID'],
           ENV['GOOGLE_SECRET'],
           {
             image_size: 150,
             name: :google,
             access_type: 'offline',
             scope: %w(https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/calendar).join(' '),
             prompt: 'consent'
           }

とりま callback まできたとする

routes.rb
  get '/auth/google/callback', to: 'sessions#create'

として以下でOK。

sessions_conrtoller.rb

require 'google/api_client/client_secrets.rb'

class SessionsController < ApplicationController
  def create
    @user_info = request.env['omniauth.auth']
    secrets = Google::APIClient::ClientSecrets.new(
      web: {
        access_token:  @user_info.credentials.token,
        refresh_token: @user_info.credentials.refresh_token,
        client_id:     ENV['GOOGLE_CLIENT_ID'],
        client_secret: ENV['GOOGLE_SECRET']
      }
    )

    cal_service = Google::Apis::CalendarV3::CalendarService.new
    cal_service.authorization = secrets.to_authorization
    @calendar_list = cal_service.list_calendar_lists
    p @calendar_list
  end
end

ハマりどころ

前述したミソを正しく設定しないとコールバックされてきたパラメータ、ここでいう @user_infocredentials.refresh_token が含まれずにハマった。 prompt: consent を指定することでOAuth先でGoogle CalendarにアクセスOK?と問い合わせがでるので、どうもこれらを指定しないといけないようだ。

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