認証リクエスト
Google APIにリクエストを送るには、アプリケーションの「identify」が必要で、その方法は2つある。
- OAuth 2.0 token (which also authorizes the request)
- API key
どちらをつかうのか、は以下で決まる。
- プライベートデータを使うときは、OAuth 2.0 token でなければならない。アプリケーションには API key も配布されるが必須でない。
- パブリックデータを使うときは the API key でも OAuth 2.0 token 使いやすい方で良い, or both—whatever option is most convenient for you.
OAuth2.0 の概要
WebサーバアプリケーションのOauth 2.0認証
Google Identity Platform
Using OAuth 2.0 for Web Server Applications
Google APIsを使うために、Google API Client Libraries or Google OAuth 2.0 endpoints が使える。
OAuth 2.0 で、ユーザは、ユーザ名やパスワードをプログラムに渡すことなく、Google アプリケーションのデータが使える。
概要
- まず、APIコンソールでプロジェクトの「web application credentials」をつくる。
- アプリケーションがユーザーデータにアクセスする必要がある場合は、ユーザーはGoogle's OAuth 2.0 serverにリダイレクトされる。OAuth 2.0 server はユーザ承認をして、アプリケーションからのデータアクセスに必要な「consent」を得る。
- OAuth 2.0 serverはユーザーをアプリケーションにリダイレクトする(戻す)。このとき、承認コードを返す。アプリケーションで承認コードをアクセストークンに交換する。
- アプリケーションは承認コードを使って、Google API にアクセスする。
When you use a Google API Client Library to handle your application's OAuth 2.0 flow, the client library keeps track of when a stored access token can be used and when the application must re-acquire consent, generates correct redirect URLs, and helps to implement redirect handlers that exchange authorization codes for access tokens. An application that carries out the OAuth 2.0 flow without using a client library must correctly complete the same steps.
Client libraries
The language-specific examples on this page make use of the Google API Client Libraries, which make API authorization with OAuth 2.0 simpler. To run the example code, you must first install the client library for your language.
認証プロトコルについて
OAuth 2.0しかないが、Google Sign-In が使えるアプリケーションなら、違う「扱い方」をすることが可能
OAuth 2.0 による認証
Requests to the Google Sheets API for non-public user data must be authorized by an authenticated user.
The details of the authorization process, or "flow," for OAuth 2.0 vary somewhat depending on what kind of application you're writing. The following general process applies to all application types:
- アプリケーションを作成したら、Google API Console に使用登録をする。
- (Sheets API を使うのであれば)Google Sheets API を Google API Console でアクティベートする。(使用する API がリストになければ、このステップは飛ばす)
- アプリケーションがユーザーデータを必要とするのであれば、Google に アクセススコープを要求する。
- Google はユーザーに確認画面を表示し、アプリケーションを認証するか尋ねる。
- ユーザが認証したら、Google がアプリケーションにアクセストークンを発行する。
- アプリケーションがユーザーデータ(プライベートデータ)を要求する場合は、アクセストークンをつけて要求する。
- Google はリクエストとトークンが有効と判断したら、要求されたデータを返す
以上が基本の流れで、ところどころ追加ステップが必要になる。例えば、トークンの有効期限が切れた場合のリフレッシュ作業など。
いろんな言語のライブラリ
省略
web application credentialsを作る
All web applications that use OAuth 2.0 must have credentials that identify the application to the OAuth 2.0 server. Applications that have these credentials can access the APIs that you enabled for your project.
web application credentials を得るステップ
- APIコンソールの認証情報ページへ。
- (まだ作っていなければ)「認証情報を作成」をクリックして、OAuth クライアント ID を選択する。
- 次に、クライアントIDとクライアントSecretを探す。
- リダイレクトURIも編集。
- リダイレクトURIはエンドポイントで、レスポンスに乗ってくる情報を処理する。ローカルマシンで試す場合は、http://localhost:8080みたいなのも可。
- client_secrets.jsonファイルをダウンロードしてセキュリティ性を保って保管する(ほうがいい)
Important: Do not store the client_secrets.json file in a publicly-accessible location, and if you share the source code to your application—for example, on
GitHub—store the client_secrets.json file outside of your source tree to avoid inadvertently sharing your client credentials.
Preparing to start the OAuth 2.0 flow
If you are using a Google API client library to handle the OAuth 2.0 flow, configure the client object, which you will use to make OAuth 2.0 requests. If you are handling the flow by directly accessing the OAuth 2.0 endpoints, just take note of the client ID that you created in the previous step and the scopes you need to request.
To configure the client object:
HTTP/REST
Take note of the following values:
Your app's client ID and client secret, which you created in Creating web application credentials.
The scopes that your app needs to request. See the documentation for the APIs your app uses for the required scopes.
Google's OAuth 2.0 サーバにリダイレクト
HTTP/REST
HTTP はだめ。HTTPSで。
https://accounts.google.com/o/oauth2/v2/auth?
scope=email%20profile&
state=security_token%3D138r5719ru3e1%26url%3Dhttps://oa2cb.example.com/myHome&
redirect_uri=https%3A%2F%2Foauth2.example.com%2Fcode&,
response_type=code&
client_id=812741506391.apps.googleusercontent.com
The set of query string parameters supported by the Google Authorization Server for web server applications are:
Parameter |
Values |
Description |
response_type |
code |
Determines whether the Google OAuth 2.0 endpoint returns an authorization code. Web server applications should use code. |
client_id |
クライアントID |
リクエストを出したクライアントの特定 required |
redirect_uri |
コンソールで登録したリダイレクトURIの一つ |
登録されたURIとピッタリ合わないとだめ。(http / https も |
scope |
アプリケーションにリクエストするパーミッション(スペース区切り) |
使うスコープは承認画面でユーザーに公開される。要求されたパーミッション数と、ユーザーの同意を得る可能性との間には逆の可能性があります。使えるスコープの種類は、APIs Explorerで確認のこと。It is generally a best practice to request scopes incrementally, at the time access is required, rather than up front. 例えば、For example, an app that wants to support purchases should not request Google Wallet access until the user presses the “buy” button; see Incremental authorization. |
state |
Any string |
Provides any state that might 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. To mitigate against cross-site request forgery (CSRF), it is strongly recommended to include an anti-forgery token in the state, and confirm it in the response. See OpenID Connect for an example of how to do this. |
access_type |
online / offline |
Indicates whether your application needs to access a Google API when the user is not present at the browser. This parameter defaults to online. If your application needs to refresh access tokens when the user is not present at the browser, then use offline. This will result in your application obtaining a refresh token the first time your application exchanges an authorization code for a user. |
prompt |
Space-delimited, case-sensitive list of prompts to present the user. If you don't specify this parameter, the user will be prompted only the first time your app requests access. |
可能なあたいとして、"none" : 画面を出さないMust not be specified with other values. consent Prompt the user for consent select_account Prompt the user to select an account |
login_hint |
email address or sub identifier |
When your application knows which user it is trying to authenticate, it can provide this parameter as a hint to the Authentication Server. Passing this hint will either pre-fill the email box on the sign-in form or select the proper multi-login session, thereby simplifying the login flow. |
include_granted_scopes |
true / false |
If this is provided with the value true, and the authorization request is granted, the authorization will include any previous authorizations granted to this user/application combination for other scopes; see Incremental Authorization. |
After you create the request URL, redirect the user to it.
Google's OAuth 2.0 server will authenticate the user and obtain consent from the user for your application to access the requested scopes. The response will be sent back to your application using the redirect URL you specified.
OAuth 2.0 serverのレスポンスを扱う
ユーザがアクセス要求を承認すると、認証コードが送られてくる。
承認しなければ、レスポンスにはエラーメッセージが含まれてくる。
All responses are returned to the web server on the query string, as shown below:
エラー
承認
Important: If your response endpoint renders an HTML page, any resources on that page will be able to see the authorization code in the URL. Scripts can read the URL directly, and all resources may be sent the URL in the Referer HTTP header. Carefully consider if you want to send authorization credentials to all resources on that page (especially third-party scripts such as social plugins and analytics). To avoid this issue, we recommend that the server first handle the request, then redirect to another URL that doesn't include the response parameters.
認証コードを受け取ったら、アクセストークンと交換
ここにアクセス
使用するパラメータ
Field |
Description |
code |
The authorization code returned from the initial request. |
client_id |
The client ID obtained from the API Console. |
client_secret |
The client secret obtained from the API Console. |
redirect_uri |
One of the redirect URIs listed for this project in the API Console. |
grant_type |
As defined in the OAuth 2.0 specification, this field must contain a value of authorization_code. |
リクエスト例
POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded
code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
redirect_uri=
https://oauth2.example.com/code&
grant_type=authorization_code
リクエストが通ると以下のレスポンスが戻る
Field |
Description |
access_token |
Google APIにアクセスするためのトークン |
refresh_token |
新しいアクセストークンを得るためのトークン。ユーザが承認を取り消すまで有効。このフィールドは access_type=offline が認証コードリクエストに含まれていれば、only present |
expires_in |
The remaining lifetime of the access token. |
token_type |
Identifies the type of token returned. At this time, this field will always have the value Bearer. |
{
"access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
"expires_in":3920,
"token_type":"Bearer"
}
Note: Other fields may be included in the response, and your application should not treat this as an error. The set shown above is the minimum set.
Google APIsを呼び出す
HTTP/REST
access tokenを使って、APIを呼び出す。access token は (サーバログに残ってしまうので良くないが)"access_token" としてパラメータに含めるか、 (推奨は)HTTPヘッダの Authorization: Bearer に含める。
You can try out all the Google APIs and view their scopes at the OAuth 2.0 Playground.
例
A call to the drive.files endpoint (the Drive API) using the access_token query string parameter might look like the following, though you'll need to specify your own access token:
Authorization: Bearer HTTP header を使って同じことをすると
GET /drive/v2/files HTTP/1.1
Authorization: Bearer 1/fFBGRNJru1FQd44AzqT3Zg
Host: googleapis.com
You can try out with the curl command-line application. Here's an example using the HTTP header option (preferred):
サンプル完全版
The following example prints a JSON-formatted list of files in a user's Google Drive after the user authenticates and gives consent for the application to access the user's Drive files.
HTTP/REST
This example in
Python uses the Flask framework and the Requests library to demonstrate the OAuth 2.0 web flow. Note that using the Python client library is easier and is the recommended way to implement this flow.
import json
import flask
import requests
app = flask.Flask(__name__)
@app.route('/')
def index():
if 'credentials' not in flask.session:
return flask.redirect(flask.url_for('oauth2callback'))
credentials = json.loads(flask.session['credentials'])
if credentials['expires_in'] <= 0:
return flask.redirect(flask.url_for('oauth2callback'))
else:
headers = {'Authorization': 'Bearer {}'.format(credentials['access_token'])}
req_uri = 'https://www.googleapis.com/drive/v2/files'
r = requests.get(req_uri, headers=headers)
return r.text
@app.route('/oauth2callback')
def oauth2callback():
if 'code' not in flask.request.args:
auth_uri = ('https://accounts.google.com/o/oauth2/v2/auth?response_type=code'
'&client_id={}&redirect_uri={}&scope={}').format(CLIENT_ID, REDIRECT_URI, SCOPE)
return flask.redirect(auth_uri)
else:
auth_code = flask.request.args.get('code')
data = {'code': auth_code,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'redirect_uri': REDIRECT_URI,
'grant_type': 'authorization_code'}
r = requests.post('https://www.googleapis.com/oauth2/v4/token', data=data)
flask.session['credentials'] = r.text
return flask.redirect(flask.url_for('index'))
if __name__ == '__main__':
import uuid
app.secret_key = str(uuid.uuid4())
app.debug = False
app.run()
Incremental authorization
In the OAuth 2.0 protocol, your app requests authorization to access resources which are identified by scopes, and assuming the user is authenticated and approves, your app receives short-lived access tokens which let it access those resources, and (optionally) refresh tokens to allow long-term access.
It is considered a best user-experience practice to request authorization for resources at the time you need them. For example, an app that lets people sample music tracks and create mixes might need very few resources at sign-in time, perhaps nothing more than the name of the person signing in. However, saving a completed mix would require access to their Google Drive. Most people would find it natural if they only were asked for access to their Google Drive at the time the app actually needed it.
In this case, at sign-in time the app might request the profile scope to perform basic sign-in, and then later request the
https://www.googleapis.com/auth/drive.file scope at the time of the first request to save a mix.
Using the procedures described in Using OpenID Connect and Using OAuth 2.0 to Access Google APIs would normally result in your app having to manage two different access tokens.
To avoid this complexity, you can include previously granted scopes in your authorization requests. For example:
scope=https://www.googleapis.com/auth/drive.file&
state=security_token%3D138r5719ru3e1%26url%3Dhttps://oa2cb.example.com/myHome&
redirect_uri=https%3A%2F%2Fmyapp.example.com%2Fcallback&
response_type=code&
client_id=8127352506391.apps.googleusercontent.com&
prompt=consent&
include_granted_scopes=true
Let's call the resulting authorization the "combined authorization"; the following apply:
You can use the access tokens you get to access the resources corresponding to any of the scopes that are rolled into the combined authorization.
When you use the refresh token for a combined authorization, the new access tokens represent the combined authorization and can be used for any of its scopes.
The combined authorization includes any previously granted authorizations even if they were requested from different clients. For example, if you requested the profile scope from a desktop app, and then issued the request in the example URI above for the same user from a mobile app, and it was granted, the combined authorization would include both scopes.
When you revoke a token which represents a combined authorization, all of the authorizations are revoked simultaneously; this means that if you retain a token for one of the previous authorizations, it will stop working.
When you make an authorization request with granted scopes included, the Google authorization server rolls the authorization request together with all the previous authorizations granted to the requesting user from the requesting app.
Offline access
ユーザが使っていない場合でもAPIにアクセスする必要がある場合があるかも。たとえば、バックアップの場合や「月曜8時にBlobをポスト」のような場合。
このタイプのアクセスを「offline」と呼び、ウェブサーバアプリはオフラインリクエストができる。
これに対し、通常のアクセスはonlineである。
HTTP/REST
If your application needs offline access to a Google API, then the request for an authorization code should include the access_type parameter, where the value of that parameter is offline. For example:
scope=email%20profile&
state=security_token%3D138r5719ru3e1%26url%3Dhttps://oa2cb.example.com/myHome&
redirect_uri=https%3A%2F%2Foauth2.example.com%2Fcode&
response_type=code&
client_id=812741506391.apps.googleusercontent.com&
access_type=offline
The first time a given user's browser is sent to this URL, they see a consent page. If they grant access, then the response includes an authorization code which may be redeemed for an access token and a refresh token.
An example of an authorization code exchange is shown below:
POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded
code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
redirect_uri=
https://oauth2.example.com/code&
grant_type=authorization_code
If this is the first time the application has exchanged an authorization code for a user, then the response includes an access token and a refresh token, as shown below:
{
"access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
"expires_in":3920,
"token_type":"Bearer",
"refresh_token":"1/xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
}
Important: When your application receives a refresh token, it is important to store that refresh token for future use. If your application loses the refresh token, it will have to re-prompt the user for consent before obtaining another refresh token. If you need to re-prompt the user for consent, include the prompt parameter in the authorization code request, and set the value to consent.
After your application receives the refresh token, it can obtain new access tokens at any time. See the section on refresh tokens for more information.
The next time your application requests an authorization code for that user, the user will not be asked to grant consent (assuming they previously granted access, and you are asking for the same scopes). As expected, the response includes an authorization code which may be redeemed. However, unlike the first time an authorization code is exchanged for a given user, a refresh token will not be returned from the authorization code exchange. The following is an example of such a response:
{
"access_token":"1/fFAGRNJru1FQd77BzhT3Zg",
"expires_in":3920,
"token_type":"Bearer",
}
Using a refresh token
As indicated in the previous section, a refresh token is obtained in offline scenarios during the first authorization code exchange. In these cases, your application may obtain a new access token by sending a refresh token to the Google OAuth 2.0 Authorization server.
Field Description
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.
grant_type As defined in the OAuth 2.0 specification, this field must contain a value of refresh_token.
Such a request will look similar to the following:
POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.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",
}
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.
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.
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.
- まず、API使用が登録済みであること。
- client id, client secret等々をもらっておく
- Authorization codeをもらう
- "code"を使って access token を要求する
- AuthorizationCodeFlow.newTokenRequest(String)でアクセストークン(access token)を要求。
- レスポンスからaccess tokenを取得
トークンのリクエスト
リクエスト先
リクエストに加えるのは
Parameter |
Values |
必須 |
Description |
response_type |
"code" |
◯ |
Webサーバアプリケーションでは code で決め打ち |
client_id |
client_id |
◯ |
API使用の登録で貰ったID.忘れていたらconsoleで確認 |
redirect_uri |
One of the redirect_uri |
◯? |
リダイレクト先は複数登録されているので、どこにリダイレクトするのかここで書いておく。 |
scope |
Space-delimited set of permissions that the application requests. |
◯ |
APIでどこまでユーザーのデータにアクセスするか(できるか)。複数ある場合はスペース区切り。どのような値を入れるかは、各APIのリファレンスページ(the APIs Explorer)参照。極力「最小」にしておく。必要なら後で追加認証をする感じで。 |
state |
Any string |
|
レスポンスを受け取る際に使える「状態」。cross-site request forgery (CSRF)の対策?なので、強く推奨。レスポンスを受け取って、これを確認すれば、変なとこで使われていないか、確認できる。 |
access_type |
offline or online |
|
ユーザがブラウザを使ってない時でもアプリケーションがアクセスするかどうか。自動的にトークンのリフレッシュが必要ならoffline。 |
approval_prompt |
force or auto |
optional デフォルトでauto |
接続の度にプロンプトを出して訊くかどうか? |
login_hint |
email address or sub identifier |
optional |
どのユーザが認証を行おうとしているかアプリケーション側でわかっている場合、(例えばそのユーザのemailアドレスを)パラメータとして渡すことができる。 |
include_granted_scopes |
true or false |
optional |
If this is provided with the value true, and the authorization request is granted, the authorization will include any previous authorizations granted to this user/application combination for other scopes; see Incremental Authorization. |
リクエストのスペース等々はエスケープする。
java.net.URLEncoder とか
サンプル(改行は見やすくするため)
リクエストが正しく通れば、以下が返ってくる
- access tokens
- refresh tokens
- authorization codes.
java?
AuthorizationCodeFlow.newAuthorizationUrl()が使える?
リダイレクトのURLから、codeを処理する
Handling the response
The response will be sent to the redirect_uri as specified in the request URL. If the user approves the access request, then the response contains an authorization code and the state parameter (if included in the request). If the user does not approve the request, the response contains an error message. All responses are returned to the web server on the query string, as shown below:
認証失敗
認証成功
リダイレクト先が通常のHTMLページの場合は、そのままURLが見える、つまりcodeが見えてしまう。
Scripts can read the URL directly, and all resources may be sent the URL in the Referer HTTP header. Carefully consider if you want to send authorization credentials to all resources on that page (especially third-party scripts such as social plugins and analytics).
この問題を避けるために、サーバでリクエストを扱って、それからパラメータを含まない形で別のURLにリダイレクトするべき。
authorization code と access token の交換
After the web server receives the authorization code, it may exchange the authorization code for an access token and a refresh token. This request is an HTTPS POST to the URL
https://www.googleapis.com/oauth2/v3/token, and includes the following parameters:
Field |
Description |
code |
authorization code |
client_id |
The client ID |
client_secret |
The client secret obtained from the Developers Console |
redirect_uri |
One of the redirect URIs |
grant_type |
ここでは "authorization_code" の決め打ち |
レスポンス例(成功時)
{ "access_token" : "ya29.vAHSwBFxEzkYKAeqk461biUJ9dqSD8KglnarHgBaR7q7Ih_4TlT71KEh07QBR6_tfLVv", "token_type" : "Bearer", "expires_in" : 3600}
最終更新:2017年03月25日 09:32