Note: If you are new to OAuth 2.0, we recommend that you read the OAuth 2.0 overview before getting started. The overview summarizes OAuth 2.0 flows that
Google supports, which can help you to ensure that you've selected the right flow for your application.
This document explains how applications installed on devices like phones, tablets, and computers use Google's OAuth 2.0 endpoints to authorize access to Google APIs. OAuth 2.0 allows users to share specific data with an application while keeping their usernames, passwords, and other information private. For example, an application can use OAuth 2.0 to obtain permission from users to store files in their Google Drives.
Installed apps are distributed to individual devices, and it is assumed that these apps cannot keep secrets. They can access Google APIs while the user is present at the app or when the app is running in the background.
This authorization flow is similar to the one used for web server applications. The main difference is that installed apps must open the system browser and supply a local redirect URI to handle responses from Google's authorization server.
Alternatives
For mobile apps, you may prefer to use Google Sign-in for
Android or iOS. The Google Sign-in client libraries handle authentication and user authorization, and they may be simpler to implement than the lower-level protocol described here.
For apps running on devices that do not support a system browser or that have limited input capabilities, such as TVs, game consoles, cameras, or printers, see OAuth 2.0 for TVs & Devices or Google Sign-in for devices.
ライブラリと、ここで書いている Oauth 2.0 flow の実装サンプル
- AppAuth for Android library and codelab
- AppAuth for iOS library
- OAuth for Apps: Windows Samples
必要条件(Prerequisites)
Enable APIs for your project
Any application that calls Google APIs needs to enable those APIs in the API Console. To enable the appropriate APIs for your project:
Open the Library page in the API Console.
Select the project associated with your application. Create a project if you do not have one already.
Use the Library page to find each API that your application will use. Click on each API and enable it for your project.
OAuth2.0 を使って Google APIs にアクセスするアプリケーションはアプリ特定するための認証証明書が必要。プロジェクトに証明書を作成するステップを説明(すでにプロジェクトがある前提)
- API Console の認証情報ページを開き
- 「認証情報を作成」 > 「Oauth クライアント ID」
- フォームを埋める。この部分は、Google の認証がサポートするリダイレクト方法を記述する。アプリケーションに対し推奨される方法を一つ選び、適切な内容を記述する。
Option 1: Custom URI scheme (Android, iOS, UWP)
推奨適用先 |
Android apps, iOS apps, Universal Windows Platform (UWP) apps |
Form values |
アプリケーションの種類に Android, iOS, その他を選択する。 また、パッケージ名 もしくは bundle ID (アプリケーションの種類に依るが、リダイレクトに使うカスタム URI(例えば com.example.app))を入力する。 |
SHA-1 fingerprint
- JDKのbinフォルダに移動する(か、環境変数のパスを仕込んでおく)
- keytool -list -v -keystore "/Users/{ユーザー名}/.android/debug.keystore" -alias androiddebugkey -storepass android -keypass android
UWPアプリでは、スキーム名は39文字以下にする
Note : redirect_uri は com.example.app:redirect_uri_path で構成。path は /(バックスラッシュ)で始まること。加えて、the libraries and samples demonstrate some platform-specific implementations of custom URI scheme redirects.
Option 2: Loopback IP address (macOS, Linux, Windows desktop)
ローカルウェブサーバを立てることができる場合は、これができる。
推奨適用先 |
macOS, Linux, and Windows デスクトップアプリ (UWP以外) |
Form values |
Other |
Note: See the redirect_uri parameter definition for more information about the loopback IP address. It is also possible to use localhost in place of the loopback IP, but this may cause issues with client firewalls. Most, but not all, firewalls allow loopback communication.
Option 3: Manual copy/paste
Important: カスタムURI と ルーブバック IP アドレスのほうが信頼性が高く、セキュアであるし、ユーザーフレンドリな方法になる。この方法は将来的にサポートしないかもしれない。
この方法では、HTMLページの <title> フィールドに認証コードを載せる。ユーザーがマニュアルでコピーをする。
Traditionally, apps that used this option programmatically extracted the authorization code from the HTML page. The copy/paste option served as a fallback in case the value could not be parsed.
推奨適用先 |
自動リダイレクトなどを備えていないプラットフォームのもの。テレビとか。 |
Form values |
Other |
Option 4: Programmatic extraction
Important: 手動コピー・ペーストだが、認証コードのコピー・ペーストを指示できないもの。代わりに、認証ページ側で、ユーザーにウィンドウを閉じるように指示する。
※非推奨、組込ブラウザや web-view 用。
▸See programmatic extraction details
Scopes enable your application to only request access to the resources that it needs while also enabling users to control the amount of access that they grant to your application. Thus, there may be an inverse relationship between the number of scopes requested and the likelihood of obtaining user consent.
Before you start implementing OAuth 2.0 authorization, we recommend that you identify the scopes that your app will need permission to access.
The OAuth 2.0 API Scopes document contains a full list of scopes that you might use to access Google APIs.
Note: Incremental authorization is not supported for installed apps or devices.
The following steps show how your application interacts with Google's OAuth 2.0 server to obtain a user's consent to perform an API request on the user's behalf. Your application must have that consent before it can execute a Google API request that requires user authorization.
- Google's authorization server にリクエストを送る
- This endpoint handles active session lookup, authenticates the user, and obtains user consent. The endpoint is only accessible over SSL, and it refuses HTTP (non-SSL) connections.
The URLs are identical except for the value of the redirect_uri parameter. The URLs also contain the required response_type and client_id parameters as well as the optional state parameter. Each URL contains line breaks and spaces for readability.
CUSTOM URI SCHEMEの場合
パラメータ
認証では、組込アプリに対して、以下のクエリ文字列パラメータを扱う
パラメータ |
client_id |
必須 アプリケーションの client ID。API コンソールで見られる。 |
redirect_uri |
必須 認証後のリダイレクト先 |
|
The table below shows the appropriate redirect_uri parameter value for each method: |
redirect_uri values |
Custom URI scheme |
com.example.app:redirect_uri_path com.example.app は管理下にあるドメインの DNS 表記の逆順。The custom scheme must contain a period to be valid. redirect_uri_path は /oauth2redirect のような任意のパス。パスはシングルスラッシュ "/" で始めること。 |
Loopback IP address |
http://127.0.0.1:port or http://[::1]:port -Query your platform for the relevant loopback IP address and start an HTTP listener on a random available port. Substitute port with the -actual port number your app is listening on. |
Manual copy/paste |
urn:ietf:wg:oauth:2.0:oob |
Programmatic extraction |
urn:ietf:wg:oauth:2.0:oob:auto |
response_type |
必須 code にする。Google OAuth 2.0 endpoint が認証コードを返すかどうか、を決定している |
scope |
必須 アプリケーションがアクセスするユーザー情報。Google の確認画面で表示される。半角スペースで区切られたリストで指定する。
The OAuth 2.0 API Scopes に scope の種類情報あり。 |
state |
推奨 Specifies any string value that your application uses to maintain state between your authorization request and the authorization server's response. The server returns the exact value that you send as a name=value pair in the hash (#) fragment of the redirect_uri after the user consents to or denies your application's access request. You can use this parameter for several purposes, such as directing the user to the correct resource in your application, sending nonces, and mitigating cross-site request forgery. Since your redirect_uri can be guessed, using a state value can increase your assurance that an incoming connection is the result of an authentication request. If you generate a random string or encode the hash of a cookie or another value that captures the client's state, you can validate the response to additionally ensure that the request and response originated in the same browser, providing protection against attacks such as cross-site request forgery. See the OpenID Connect documentation for an example of how to create and confirm a state token. |
login_hint |
任意 If your application knows which user is trying to authenticate, it can use this parameter to provide a hint to the Google Authentication Server. The server uses the hint to simplify the login flow either by prefilling the email field in the sign-in form or by selecting the appropriate multi-login session. |
Set the parameter value to an email address or sub identifier.
Note: Due to the fact that the client cannot keep the client_secret confidential, you cannot do incremental authorization with installed apps.
Step 2: Google prompts user for consent
このステップで、ユーザーがアプリケーションのアクセス要求を受け入れるかどうか決める。このステージで、 Google は確認ウィンドウを表示し、 Google API はユーザーの認証証明書とともにアクセスする権限を提供する。ユーザーはアプリケーションのアクセスを承認するか拒否するか決める。
Your application doesn't need to do anything at this stage as it waits for the response from Google's OAuth 2.0 server indicating whether the access was granted. That response is explained in the following step.
Step 3: Handle the OAuth 2.0 server response
アプリケーションが認証レスポンスを受ける方法は、これを扱うリダイレクトURIスキームに依存する。スキームによらず、レスポンスは認証コードかエラーを含む。たとえば、 error=access_denied なら要求が拒否されたことを示す。もし、ユーザーがアクセスを許可したら、認証コードをアクセストークンと交換し、リフレッシュトークン(後述)を受け取る。
Step 4: 認証コードとトークンを交換する (Exchange authorization code for refresh and access tokens)
認証コードとアクセストークンを交換するために
に次のパラメタをセットし送る。
Fields
- code : 最初に受け取った code
- client_id : API Console で確認したクライアントID
- client_secret : API Console で受け取った Client Secred。ただし、Android, iOS, Chrome applications では不要。
- redirect_uri : One of the redirect URIs listed for your project in the API Console.
- grant_type : authorization_code.
The following snippet shows a sample request:
POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded
code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=your_client_id&
client_secret=your_client_secret&
redirect_uri=https://oauth2.example.com/code&
grant_type=authorization_code
Google responds to this request by returning a
JSON object that contains a short-lived access token and a refresh token.
The response contains the following fields:
Fields
access_token The token that your application sends to authorize a Google API request.
id_token Note: This property is only returned if your request included an identity scope, such as openid, profile, or email. The value is a JSON Web Token (JWT) that contains digitally signed identity information about the user.
refresh_token A token that you can use to obtain a new access token. Refresh tokens are valid until the user revokes access. Note that refresh tokens are always returned for installed applications.
expires_in The remaining lifetime of the access token in seconds.
token_type The type of token returned. At this time, this field's value is always set to Bearer.
Important: Your application should store both tokens in a secure, long-lived location that is accessible between different invocations of your application. The refresh token enables your application to obtain a new access token if the one that you have expires. As such, if your application loses the refresh token, the user will need to repeat the OAuth 2.0 consent flow so that your application can obtain a new refresh token.
レスポンスサンプル
{
"access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
"expires_in":3920,
"token_type":"Bearer",
"refresh_token":"1/xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
}
関係ないレスポンスは無視してよし
Calling Google APIs
After your application obtains an access token, you can use the token to make calls to a Google API on behalf of a given user account or service account. To do this, include the access token in a request to the API by including either an access_token query parameter or an Authorization: Bearer HTTP header. When possible, the HTTP header is preferable, because query strings tend to be visible in server logs. In most cases you can use a client library to set up your calls to Google APIs (for example, when calling the Drive API).
You can try out all the Google APIs and view their scopes at the OAuth 2.0 Playground.
HTTP GET examples
A call to the drive.files endpoint (the Drive API) using the Authorization: Bearer HTTP header might look like the following. Note that you need to specify your own access token:
GET /drive/v2/files HTTP/1.1
Authorization: Bearer <access_token>
Host: www.googleapis.com/
Here is a call to the same API for the authenticated user using the access_token query string parameter:
You can test these commands with the curl command-line application. Here's an example that uses the HTTP header option (preferred):
Access tokens periodically expire. You can refresh an access token without prompting the user for permission (including when the user is not present) if you requested offline access to the scopes associated with the token.
Fields
refresh_token The refresh token returned from the authorization code exchange.
client_id The client ID obtained from the API Console.
client_secret The client secret obtained from the API Console. (The client_secret is not applicable to requests from clients registered as Android, iOS, or Chrome applications.)
grant_type As defined in the OAuth 2.0 specification, this field must contain a value of refresh_token.
The following snippet shows a sample request:
POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded
client_id=<your_client_id>&
client_secret=<your_client_secret>&
refresh_token=<refresh_token>&
grant_type=refresh_token
As long as the user has not revoked the access granted to the application, the token server returns a JSON object that contains a new access token. The following snippet shows a sample response:
{
"access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
"expires_in":3920,
"token_type":"Bearer"
}
Note that there are limits on the number of refresh tokens that will be issued; one limit per client/user combination, and another per user across all clients. You should save refresh tokens in long-term storage and continue to use them as long as they remain valid. If your application requests too many refresh tokens, it may run into these limits, in which case older refresh tokens will stop working.
Revoking a token
In some cases a user may wish to revoke access given to an application. A user can revoke access by visiting Account Settings. It is also possible for an application to programmatically revoke the access given to it. Programmatic revocation is important in instances where a user unsubscribes or removes an application. In other words, part of the removal process can include an API request to ensure the permissions granted to the application are removed.
curl -H "Content-type:application/x-www-form-urlencoded" \
https://accounts.google.com/o/oauth2/revoke?token={token}
The token can be an access token or a refresh token. If the token is an access token and it has a corresponding refresh token, the refresh token will also be revoked.
If the revocation is successfully processed, then the status code of the response is 200. For error conditions, a status code 400 is returned along with an error code.
Note: Following a successful revocation response, it might take some time before the revocation has full effect.
Further Reading
The Internet-Draft Best Current Practice: OAuth 2.0 for Native Apps establishes many of the best practices documented here.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 3.0 License, and code samples are licensed under the Apache 2.0 License. For details, see our Site Policies.
Java is a registered trademark of Oracle and/or its affiliates.
AndroidでGoogle認証の準備をする
プロジェクトを作る
Projectを作る
どのAPIを使うのか(とりあえず)
*
OAuth2.0 を使って Google APIs にアクセスするアプリケーションはアプリ特定するための認証証明書が必要。プロジェクトに証明書を作成するステップを説明(すでにプロジェクトがある前提)
- API Console の認証情報ページを開き
- 「認証情報を作成」 > 「Oauth クライアント ID」
- フォームを埋める。この部分は、Google の認証がサポートするリダイレクト方法を記述する。アプリケーションに対し推奨される方法を一つ選び、適切な内容を記述する。
SHA-1 fingerprint を取得する
Projectで、認証キーの発行に必要になる SHA-1 fingerprint を取得する
- debug.keystoreの場所を確認する
- 通常は /Users/{ユーザー名}/.android/debug.keystore
- JDKのbinフォルダに移動する(か、環境変数のパスを仕込んでおく)
- keytool -list -v -keystore "/Users/{ユーザー名}/.android/debug.keystore" -alias androiddebugkey -storepass android -keypass android
最終更新:2017年04月16日 20:50