レベルエンター山本大のブログ

面白いプログラミング教育を若い人たちに

BLOCKVROCKリファレンス目次はこちら

GoogleAPI利用のためにOAuth2.0を使う(Using OAuth 2.0 for Installed Applications)

問題に直面しているため、
https://developers.google.com/accounts/docs/OAuth2InstalledApp
を意訳。

The Google OAuth 2.0 endpoint supports applications that are installed on a device (e.g. Mobile, Mac, PC). These applications are distributed to individual machines, and it is assumed that these applications cannot keep secrets. These applications may access a Google API while the user is present at the application or when the application is running in the background for long periods of time without direct interaction with the user. This flow requires that the application has access to the system browser or the ability to embed a browser control in the application.

GoogleのOAuth 2.0は、モバイルやMac、PCなどのデバイスにインストールされたアプリケーションもサポートしています。
こういったアプリケーションは、個々のマシンに配備され「シークレットファイル」をローカルな領域に保持出来ないと仮定します。
こういったアプリケーションは、ユーザが利用してる間中GoogleAPIにアクセスしますし、ユーザが使っていない間もバックグラウンドで長い期間アクセスし続けます。
このフローでは、システムブラウザまたはアプリに組み込み可能なブラウザコントロールからのアクセスが必要になります。

If the application does not have access to a browser or a browser control, then see the OAuth 2.0 for Devices.

もしも、あなたのアプリケーションがブラウザやブラウザコントロールからアクセスしないのであれば、「OAuth 2.0 for Devices」を参照してください。

The sequence is similar to the one shown in the Using OAuth 2.0 for Web Server Applications, but there are three exceptions:

基本的な手順は、「OAuth 2.0 for Web Server Applications」で示したものを同じですが、以下の3つの違いがあります。

When registering the application, you specify that the application is a Installed application. This results in a different value for the redirect_uri parameter.
The client_id and client_secret obtained during registration are embedded in the source code of your application. In this context, the client_secret is obviously not treated as a secret.
The authorization code can be returned to your application in the title bar of the browser or to an http://localhost port in the query string.
This sequence starts by redirecting a browser (system browser or embedded in the application as a web view) to a Google URL with a set of query parameters that indicate the type of Google API access the application requires. Like other scenarios, Google handles the user authentication and consent, but the result of the sequence is an authorization code. The authorization code is returned in the title bar of the browser or as a query string parameter (depends on the parameters sent in the request).

アプリケーションを登録するとき、「 Installed application(インストールされたアプリケーション)」と指定します。この結果、「redirect_uri」パラメータの値に違いがでます。
登録時に獲得した「client_id」と「client_secret」を、アプリケーションのソースコードの中に組み込みます。これに関しては「client_secret」は明らかに機密として扱われていません。
「認可コード(authorization code)」は、あなたのアプリケーションのブラウザタイトルバーか、またはクエリストリングのhttp://localhostのポートに戻ることができます。
この手順はブラウザ(システムブラウザまたはアプリケーションに組み込んだWebView)が、GoogleURLへのリダイレクトによって開始します。このリダイレクトはGoogleAPIへのアクセスに必要な型を表すクエリパラメーターの集まりを伴っています。
他のシナリオでは、Googleはユーザの認可と同意を処理します。しかしこの手順の結果は認可コードです。認可コードは、ブラウザのタイトルバーかまたクエリストリングパラメータとして戻ってきます。(リクエストとして送ったパラメータに依存します。)

After receiving the authorization code, the application can exchange the code for an access token and a refresh token. The application presents its client_id and client_secret (obtained during application registration) and the authorization code during this exchange. Upon receipt of the refresh token, the application should store it for future use. The access token gives your application access to a Google API.

認可コードを受け取った後、アプリケーションはコードを「アクセストークン」と「リフレッシュトークン」に変換します。アプリケーションはこの変換の間に、「client_id」と「(アプリケーション登録時に得られた)client_secret」と、認可コードを提供します。
リフレッシュトークンの受け取ったら、アプリケーションでは今後の利用のためにそれを保存しておく必要があります。アクセストークンは、アプリケーションからGoogleAPIにアクセスする許可を与えます。

Forming the URL(URLの書式)

The URL used when authenticating a user is https://accounts.google.com/o/oauth2/auth. This endpoint is accessible over SSL, and HTTP (non-SSL) connections are refused.

ユーザの認可の際に利用されたURLは、「https://accounts.google.com/o/oauth2/auth」です。このサイトはSSLでアクセス出来、SSL上ではないHTTPの接続は拒否します。

Endpoint Description(認可サイトの説明)

https://accounts.google.com/o/oauth2/auth
This endpoint is the target of the initial request for an access token. It handles active session lookup, authenticating the user, and user consent. The result of requests of this endpoint include access tokens, refresh tokens, and authorization codes.
The set of query string parameters supported by the Google Authorization Server for web server applications are:

このサイトは、アクセストークンによる最初のリクエストのためのものです。アクティブなセッションを参照し、ユーザを認可、承認するという処理を行います。このサイトのリクエストの結果にはアクセストークン、リフレッシュトークン、そして認可コードが含まれます。
クエリストリングパラメータの集まりは、WebサーバーアプリケーションのためのGoogleの認可サーバーによってサポートされています。

Parameter Values Description
response_type code Determines if the Google OAuth 2.0 endpoint returns an authorization code. For installed applications, a value of code should be used.
client_id the client_id obtained from the APIs Console Indicates the client that is making the request. The value passed in this parameter must exactly match the value shown in the APIs Console.
redirect_uri one of the redirect_uri values registered at the APIs Console Determines where the response is sent. The value of this parameter must exactly match one of the values registered in the APIs Console (including the http or https schemes, case, and trailing '/'). You may choose between urn:ietf:wg:oauth:2.0:oob or an http://localhost port. See choosing a redirect_uri for more details.
scope space delimited set of permissions the application requests Indicates the Google API access your application is requesting. The values passed in this parameter inform the consent page shown to the user. There is an inverse relationship between the number of permissions requested and the likelihood of obtaining user consent.
state any string Indicates any state which may be useful to your application upon receipt of the response. The Google Authorization Server roundtrips this parameter, so your application receives the same value it sent.
パラメータ 詳細
response_type コード Google OAuth2.0のエンドポイントが認可コードを返してきたときに決定します。インストールされたアプリケーションでは、このコードの値が使われなければなりません。
client_id APIコンソールで取得したクライアントID リクエストによって作られたクライアントを示します。このパラメータ値はAPIコンソールで表された値と正確に一致しなくてはなりません。
redirect_uri APIコンソールに登録したredirect_uriの値の一つ レスポンスが返される場所を決定します。このパラメータ値はAPIコンソールで表された値と正確に一致しなくてはなりません。(httpやhttpsといったスキーム、大文字小文字、後端の"/"を含めてです。)ここでは「urn:ietf:wg:oauth:2.0:oob」か「http://localhostのポート」かを選ぶことができます。
scope スペース区切りでアプリケーションが求める許可の集合 アプリケーションが求めるGoogleAPIへのアクセスを表します。このパラメータ値は、ユーザに示される同意ページに渡されます。ここではいくつかの権限を求めることとユーザの同意を得る見込みの間の関係が逆転しています。
state 任意の文字列 レスポンスを受信したあなたのアプリケーションが使いやすいような、任意の状態を示します。Google認証サーバは、このパラメータをラウンドトリップします。そのためあなたのアプリケーションでは、送った時と同じ値を受け取ることが出来ます。

An example URL is shown below.

参考のURLを下記に記載します。

https://accounts.google.com/o/oauth2/auth?
scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&
redirect_uri=urn:ietf:wg:oauth:2.0:oob&
response_type=code&
client_id=812741506391-h38jh0j4fv0ce1krdkiq0hfvt6n5amrf.apps.googleusercontent.com

If the user logs in and grants access via a URL similar to the one shown above, the result will be a dialog similar to the following:

上記で示したURLと同じものを介してユーザがログインし、権限を獲得したら、結果は以下のダイアログのようになります。

https://developers.google.com/accounts/images/installedresult.png

An example of another URL is shown below:

他のURLで見ると以下です。

https://accounts.google.com/o/oauth2/auth?
scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&
redirect_uri=http://localhost:9004&
response_type=code&
client_id=812741506391-h38jh0j4fv0ce1krdkiq0hfvt6n5amrf.apps.googleusercontent.com

The difference between these two URLs is the redirect_uri parameter. The first one results in an authorization code in the title of the page, and the second one results in the authorization code sent to a http://localhost address as part of the query string.

この2つのURLの違いは、redirect_uriパラメータにあります。最初の方の結果は、認可コードがページのタイトルにあります。そして2つ目の方の結果は、「http://localhost」アドレスにクエリストリングパラメータとして送られます。

Choosing a Redirect URI(リダイレクト URIを選ぶ)

When you register your installed application in the APIs Console, two redirect_uris are created for you: urn:ietf:wg:oauth:2.0:oob and http://localhost. The value your application uses determines how the authorization code is returned to your application.

APIコンソールで「インストールされたアプリケーション」を選んだ場合、「urn:ietf:wg:oauth:2.0:oob」と「http://localhost」の、2つの「redirect_uri」が作られます。あなたのアプリケーションに対して、どのように認可コードを返したいかによって使う方を決めてください。

http://localhost (http://localhostの場合)

This value signals to the Google Authorization Server that the authorization code should be returned as a query string parameter to the web server on the client. You may specify a port number without changing the APIs Console configuration. To receive the authorization code on this URL, your application must be listening on the local web server. This is possible on many, but not all platforms. In some cases, it is possible, but other software (e.g. Windows firewall) prevents delivery of the message without significant client configuration. If your platform supports it, this is the recommended mechanism for obtaining the authorization code.

この値は「認可コード」を、クライアントのWebサーバーのクエリストリングのパラメータとして返すことをGoogle認証サーバーに伝えます。ポート番号は、APIコンソールの設定で変更せずとも特定されます。認可コードをこのURLで受け取るために、あなたのアプリケーションはローカルwebサーバをリスニングする必要があります。これは多くの場合可能ですが、すべてのプラットフォームで可能とは言えません。その他のケースとしては、他のソフトウェア(例えばWindowsファイアウォールなど)は、かなりのクライアント設定をしないとメッセージの配送を防止してしまうことが考えられます。
もしあなたのプラットフォームがこの方法をサポートしているなら、認可コードを獲得する方法として推奨です。

urn:ietf:wg:oauth:2.0:oob(urn:ietf:wg:oauth:2.0:oobを使う場合)

This value signals to the Google Authorization Server that the authorization code should be returned in the title bar of the browser. This is useful when the client cannot listen on an HTTP port without significant client configuration. Windows applications possess this characteristic.

この値は「認可コード」を、ブラウザのタイトルバーとして返すことをGoogle認証サーバーに伝えます。これはクライアント設定をかなり変えないことにはHTTPポートをリッスンできないという場合に便利です。Windowsアプリケーションは、この特徴がありがちです。

When this value is used, your application can sense that the page has loaded and the title of the HTML page contains the authorization code. It is then up to your application to close the browser window if you want to ensure that the user never sees the page that contains the authorization code. The mechanism for doing this varies from platform to platform.

この値を使うときは、ページがロードされ、HTMLページのタイトルに認可コードが含まれることを検知するようにアプリケーションで考慮する必要があります。ユーザに認可コードを含むページを見せたくないというときは、アプリケーションでブラウザウィンドウを閉じてください。
このメカニズムは、異なるプラットフォーム同士でやり取りするためにあります。

Handling the Response (レスポンスを処理する)

After the application receives the authorization code, it may exchange the authorization code for an access token and a refresh token. This request is an HTTP post, and includes the following parameters:

認可コードを受け取ったら、アクセストークンとリフレッシュトークンへ認可コードを変換します。このリクエストはHTTPポストであり、以下のようなパラメータを含みます。

Field Description
code The authorization code returned from the initial request
client_id The client_id obtained during application registration
client_secret The client secret obtained during application registration
redirect_uri The URI registered with the application
grant_type As defined in the OAuth 2.0 specification, this field must contain a value of authorization_code
Field Description
code 最初のリクエストから返された認可コードです
client_id アプリケーション登録時に得られたクライアントIDです。
client_secret アプリケーションの登録時に得られたクライアントシークレットです
redirect_uri アプリケーションとともに登録されたURIです
grant_type OAuth2.0の仕様で決められたものです。このフィールドは認可コードの値に含む必要があります

The actual request might look like:

現物のリクエストは以下のような形です。

POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded

code=4/v6xr77ewYqhvHSyW6UJ1w7jKwAzu&
client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
redirect_uri=https://oauth2-login-demo.appspot.com/code&
grant_type=authorization_code

A successful response to this request contains the following fields:

このリクエストによる成功のレスポンスには以下のようなフィールドが含まれています。

Field Description
access_token The token that can be sent to a Google API
refresh_token A token that may be used to obtain a new access token, and are included by default for installed applications. Refresh tokens are valid until the user revokes access.
expires_in The remaining lifetime on the access token
token_type Indicates the type of token returned. At this time, this field will always have the value Bearer

Note: Other fields may be included in the response. Your application should allow additional fields to be returned in the response. The set shown above is the minimum set.

Field Description
access_token Google APIに送ることが出来るトークンです
refresh_token 新しいアクセストークンを取得する時に利用するトークンです、インストールされたアプリケーションのためのデフォルト値が含まれています。リフレッシュトークンは、あなたのアクセスが失効するまで有効です。
expires_in アクセストークンを覚えておく残時間です
token_type 返されたトークンの種類を表します。現時点ではこの値は常に「Bearer」で固定されています

備考: レスポンスに他のフィールド含まれることがあります。あなたのアプリケーションでは追加のフィールドがレスポンスに帰ってくることを見越しておいてください。上記のリストは最小限のものです。

A successful response is returned as a JSON array, similar to the following:

成功した場合は、下記のようなJSON形式の配列が帰ってきます。

{
  "access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
  "expires_in":3920,
  "token_type":"Bearer",
  "refresh_token":"1/xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
}

Calling a Google API (Google APIを呼び出す)

After your application has obtained an access token, your application can access a Google API by including it in either an access_token query parameter or an Authorization: Bearer HTTP header.

For example, a call to the UserInfo API using the access_token query string parameter looks like the following:

アクセストークンを取得できたら、アクセストークンをクエリパラメータまたはHTTPヘッダの「Authorization: Bearer 」のいずれかに含めることで、GoogleAPIにアクセスすることが出来ます。
例えば、クエリパラメータにアクセストークンを含めて「ユーザ情報API」にアクセスするは以下のようになります。

GET https://www.googleapis.com/oauth2/v1/userinfo?access_token=1/fFBGRNJru1FQd44AzqT3Zg

A call to the same API using the access_token Authorization: Bearer HTTP header looks like the following:

おなじAPIをHTTPヘッダの「Authorization: Bearer 」に含めると以下のようになります。

GET /oauth2/v1/userinfo HTTP/1.1
Authorization: Bearer 1/fFBGRNJru1FQd44AzqT3Zg
Host: googleapis.com

You can try either out in the CURL command line application. Here's an example of the query string parameter option:

CURLというコマンドラインアプリケーションを利用して試してみることが出来ます。ここでは食えリストリングパラメータオプションの例を上げます。

curl https://www.googleapis.com/oauth2/v1/userinfo?access_token=1/fFBGRNJru1FQd44AzqT3Zg

And the HTTP header option:

HTTPヘッダでのやり方は以下です。

curl -H "Authorization: Bearer {accessToken}" https://www.googleapis.com/oauth2/v1/userinfo

Using a Refresh Token(リフレッシュトークンを利用する)

Obtaining a new access token is simple. To obtain a new access token, make an HTTPs POST to https://accounts.google.com/o/oauth2/token. These requests must include the following parameters:

新しいアクセストークンを取るのは簡単です。新しいアクセストークンを取得するためには、次のHTTP Postを作成します。「 https://accounts.google.com/o/oauth2/token」これは以下のようなパラメータを含める必要があります。

Field Description
refresh_token The refresh token returned from the authorization code exchange
client_id The client_id obtained during application registration
client_secret The client secret obtained during application registration
grant_type As defined in the OAuth2 specification, this field must contain a value of refresh_token
Field Description
refresh_token 認可コードの変換で返却されたリフレッシュトークンです
client_id アプリケーション登録時に取得したクライアントID
client_secret アプリケーション登録時に取得したクライアントシークレット
grant_type OAuth2.0の仕様で定義された権限タイプです。このフィールドは、リフレッシュトークンの値を含む必要があります

Such a request will look similar to the following:

そのようなリクエストは以下のような形になります

POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded

client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
refresh_token=1/6BMfW9j53gdGImsiyUH5kU5RsR4zwI9lUVX-tqf8JXQ&
grant_type=refresh_token

As long as the user has not revoked the access granted to your application, the response includes a new access token. A response from such a request is shown below:

ユーザが権限を失効せずに利用可能な権限が与えられている期間なら、レスポンスには新しいアクセストークンを含みます。上記のリクエストに対するレスポンスは以下です。

{
  "access_token":"1/fFBGRNJru1FQd44AzqT3Zg",
  "expires_in":3920,
  "token_type":"Bearer"
}

Client libraries

The following client libraries make implementing OAuth 2.0 simpler by integrating with popular frameworks:

以下のクライアントライブラリは、OAuth2.0を一般的なフレームワークと簡単に統合できるようにしてくれています。

Google APIs Client Library for Java
Google APIs Client Library for Python
Google APIs Client Library for .NET
Google APIs Client Library for Ruby
Google APIs Client Library for PHP
OAuth 2.0 Library for Google Web Toolkit
Google Toolbox for Mac OAuth 2.0 Controllers