12
10

More than 5 years have passed since last update.

google-api-ruby-clientのメモ

Last updated at Posted at 2015-11-04

注意

Google-api-ruby-clientのバージョンアップ(0.9への)により、以下のサンプルは動かなくなっています。

認証の取り方

一回やったのに忘れたので、ダイジェストでメモる。

手順(超)概要

  1. GoogleのAPI Manager からクライアントIDクライアントシークレットを取得(備考に図)
  2. 以下のプログラム1を実行し、リフレッシュトークンを取得
  3. 取得したリフレッシュトークンを使用し、プログラム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
02.png

auth.scope

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

12
10
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
12
10