質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Google API

Googleは多種多様なAPIを提供していて、その多くはウェブ開発者向けのAPIです。それらのAPIは消費者に人気なGoogleのサービス(Google Maps, Google Earth, AdSense, Adwords, Google Apps,YouTube等)に基づいています。

OAuth 2.0

OAuth 2.0(Open Authorization 2.0)は、APIを通して保護されたリソース(サードパーティのアプリケーション)へアクセスする為のオープンプロトコルです。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

2回答

2410閲覧

Google API におけるServer to Server OAuth2 をFree Gmail で利用できるのか?

teranotwu

総合スコア13

Google API

Googleは多種多様なAPIを提供していて、その多くはウェブ開発者向けのAPIです。それらのAPIは消費者に人気なGoogleのサービス(Google Maps, Google Earth, AdSense, Adwords, Google Apps,YouTube等)に基づいています。

OAuth 2.0

OAuth 2.0(Open Authorization 2.0)は、APIを通して保護されたリソース(サードパーティのアプリケーション)へアクセスする為のオープンプロトコルです。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

1クリップ

投稿2018/11/08 00:31

編集2018/11/08 10:02

#動作環境

  • Google API/Drive API
  • google api client for python
  • python3
  • atom

#背景
Google API で DriveAPI を使用して自分のGoogle Driveからファイルを取得/アップロードしようとしています。その際にServer to ServerにおけるOAuth2を利用したいと考えています。

こちらのサンプルコードを利用しているのですが、access token が払い出されません。
・Server to Server
https://developers.google.com/api-client-library/python/auth/service-accounts

・実行結果:
{'token': None, 'expiry': None, '_scopes': ['https://www.googleapis.com/auth/drive'],(以下省略)

実際にDrive API でファイル名を取得しようとしますが、やはり取得できませんでした。
・以下のサンプルコードを利用しています。
https://developers.google.com/drive/api/v3/search-parameters
※取得結果が「None」になります。

切り分けとして、認証方式をInstalled Application のものに変えたところ、うまく動いたので、認証ができていないのだと、想定しています。
・Installed Application のサンプルコード
https://developers.google.com/api-client-library/python/auth/installed-app

より詳しく確認したところ、Server to Server の方式では、G Suite(GoogleApps)の管理者コンソール上で、サービスアカウントにGoogle Driveの権限(スコープ?)を割り当てる必要があるように見えます。
https://developers.google.com/api-client-library/python/auth/service-accounts

  1. Go to your Google Apps domain’s Admin console.

  2. Select Security from the list of controls. If you don't see Security listed, select More controls from the gray bar at the bottom of the page, then select Security from the list of controls. If you can't see the controls, make sure you're signed in as an administrator for the domain.

  3. Select Advanced settings from the list of options.

  4. Select Manage third party OAuth Client access in the Authentication section.

  5. In the Client name field enter the service account's Client ID.

  6. In the One or More API Scopes field enter the list of scopes that your application should be granted access to. For example, if your application needs domain-wide access to the Google Drive API and the Google Calendar API, enter: https://www.googleapis.com/auth/drive, https://www.googleapis.com/auth/calendar.

  7. Click Authorize.

ただ、ここで問題が生じました。
GSuiteの管理者アカウントはフリーのgmailアカウントでは使用できないようで、おそらく、ここが問題だと考えています。

#質問:
フリーのgmailアドレスでServer to Serverの方式は使用できないのでしょうか?
もし、使用している方がいれば、教えていただきたく。

※或いはもし他に原因があれば、指摘いただきたいです。

よろしくお願いします。

#追加切り分け ※11/8追記
頂いた回答を元にして、もう少し切り分けしてみました。
結果、OAuth2の認証は動いているようですが、出力結果としては初期のGettingStartのファイルしか出力されていないことが分かりました。なので、やはり、認証関連で何かがおかしいように見えます。。。

####実行内容

#encoding : utf-8 # Authorize server-to-server interactions from Google Compute Engine. import json #1 認証系 from google.oauth2 import service_account SCOPES = ['https://www.googleapis.com/auth/drive'] SERVICE_ACCOUNT_FILE = (サービスアカウントのjsonファイルへのパス) credentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES) print('CREDENTIALs:',credentials.__dict__) #2 サービスの構築:実行したいAPI種類を選択し、認証はこのタイミングで実施される from apiclient.discovery import build service = build('drive', 'v3', credentials = credentials) print('SERVICE:',service.__dict__)\ page_token = None while True: response = service.files().list(spaces='drive', fields='nextPageToken, files(id, name)', pageToken=page_token).execute() print(response.get('nextPageToken')) for file in response.get('files', []): # Process change ; 最初の流儀 #print('Found file: %s (%s)' % (file.get('name'), file.get('id'))) print(file) page_token = response.get('nextPageToken', None) if page_token is None: break

####実行結果

(CREDENTIALS、SERVICE は省略) None ←nextPageToken。 {'id': (※GoogleDriveのファイルID), 'name': 'Getting started'}

####原因追及
こちらが参考になりそうなので、これを元に、もう少し、調査してみようと思います。
https://www.daimto.com/google-drive-api-with-a-service-account/

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

サービスアカウントを作るのはここから
https://console.developers.google.com/iam-admin/serviceaccounts

G Suite使ってないならG Suite関連の部分は何も関係ない。

ただしサービスアカウントでの認証は結構ややこしいしAPIによっては使えないので
普通にOAuth認証してrefresh_tokenを取得して毎回access_tokenを新しくしたほうが簡単。

access_tokenが払い出されないという所から何か間違ってる。サービスアカウントの場合はjsonファイルに認証情報が入っててtokenの代わり。

投稿2018/11/08 01:06

kawax

総合スコア10377

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

teranotwu

2018/11/08 10:03

回答ありがとうございます! URLもありがとうございます。ただ、ここからサービスアカウントは作成していたのですが、なぜか、うまくいかない状況でした。 >ただしサービスアカウントでの認証は結構ややこしいしAPIによっては使えないので  使える/使えないがドキュメントで出ていると嬉しいのですが、、、  Drive API だと、使用可能なのか、ご存じないでしょうか? >access_tokenが払い出されないという所から何か間違ってる。サービスアカウントの場合はjsonファイルに認証情報が入っててtokenの代わり。  そうだったのですね。ありがとうございます、勉強になります! いただいた情報をもとにして、もう少し調査の幅と切り分けを進めてみました。 上記に状況を追記してみました。 ==== 結果、OAuth2の認証は動いているようですが、出力結果としては初期のGettingStartのファイルしか出力されていないことが分かりました。なので、やはり、認証か、権限の関連で何かがおかしいように見えます。。。 ==== もし、何かご存じのことがあれば、また教えていただけると助かります。
guest

0

自己解決

解決しました!
原因はサービスアカウントはgmailアカウントとは別のアカウントとして認識されるため、日常的に使用しているGoogle Driveへアクセスする権限を持たないため、OAuth2 のServer to Server で認証できても、Google Drive上のファイルへのアクセスができないようです。
公式ドキュメントは見当たりませんでしたが、上記の「原因追及」のURLに従って、Google Driveのフォルダ共有をサービスアカウントに対して行うことで、解決しました。

https://www.daimto.com/google-drive-api-with-a-service-account/

A few important things to note about a service account is that it is not you. Just because you created the service account does not mean that it has access to the files you have stored in your Google drive.
You can take the service account email address and give it access to a directory on your Google drive. It will then be allowed to upload to that directory, but you wont have access to the files. You will need to complete a second step and give yourself personally permission to access those files by updating or patching the file permissions.

Another option would be to have the service account grate your Google account access to a directory on its account then you will be able to see the files on your Google drive. Again permissions will probably need to be set to allow you to access the files.

投稿2018/11/08 16:16

teranotwu

総合スコア13

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問