注意
Google-api-ruby-clientのバージョンアップ(0.9への)により、以下のサンプルは動かなくなっています。
認証の取り方
一回やったのに忘れたので、ダイジェストでメモる。
手順(超)概要
-
GoogleのAPI Manager から
クライアントIDとクライアントシークレットを取得(備考に図) - 以下の
プログラム1を実行し、リフレッシュトークンを取得 - 取得した
リフレッシュトークンを使用し、プログラム2で永続的にアクセス
プログラムサンプル
プログラム1
require "rubygems"
require "google/api_client"
require "google_drive"
# Authorizes with OAuth and gets an access token.
client = Google::APIClient.new
auth = client.authorization
auth.client_id = "xxx" # Use My Client ID
auth.client_secret = "yyy" # Use My Client Secret
auth.scope = "https://www.googleapis.com/auth/drive.file"
# Use My Scope (about "Scope" see below.)
auth.redirect_uri = "urn:ietf:wg:oauth:2.0:oob"
print("1. Open this page:\n%s\n\n" % auth.authorization_uri)
print("2. Enter the authorization code shown in the page: ")
auth.code = $stdin.gets.chomp
auth.fetch_access_token!
access_token = auth.access_token
refresh_token = auth.refresh_token
session = GoogleDrive.login_with_oauth(access_token)
puts "your access_token is:\n#{access_token}"
puts "----"
puts "your refresh_token is:\n#{refresh_token}"
puts "----"
session.files.each do |file|
puts file.title
end
puts "----"
puts "done!"
プログラム2
client = Google::APIClient.new("aaa") # Use My AppName
auth = client.authorization
auth.client_id = "xxx"
auth.client_secret = "yyy"
auth.refresh_token = "zzz" # Use **THE** Refresh Token
auth.scope = "https://www.googleapis.com/auth/drive.file"
auth.fetch_access_token!
# Creates a session.
session = GoogleDrive.login_with_oauth(auth.access_token)
備考
Google Developer Console 画面
Google Developer Console API Manager

auth.scope
auth.scopeについては、以下に詳しい。
https://developers.google.com/drive/web/scopes