OAuth による Google アカウントのリンク

アカウントは、業界標準の OAuth 2.0 の暗黙的フローと認証コードフローを使用してリンクされます。サービスが OAuth 2.0 準拠の承認トークン交換のエンドポイントをサポートしている必要があります。

In the implicit flow, Google opens your authorization endpoint in the user's browser. After successful sign in, you return a long-lived access token to Google. This access token is now included in every request sent from Google.

In the authorization code flow, you need two endpoints:

  • The authorization endpoint, which presents the sign-in UI to your users that aren't already signed in. The authorization endpoint also creates a short-lived authorization code to record users' consent to the requested access.

  • The token exchange endpoint, which is responsible for two types of exchanges:

    1. Exchanges an authorization code for a long-lived refresh token and a short-lived access token. This exchange happens when the user goes through the account linking flow.
    2. Exchanges a long-lived refresh token for a short-lived access token. This exchange happens when Google needs a new access token because the one it had expired.

Choose an OAuth 2.0 flow

Although the implicit flow is simpler to implement, Google recommends that access tokens issued by the implicit flow never expire. This is because the user is forced to link their account again after a token expires with the implicit flow. If you need token expiration for security reasons, we strongly recommend that you use the authorization code flow instead.

Design guidelines

This section describes the design requirements and recommendations for the user screen that you host for OAuth linking flows. After it's called by Google's app, your platform displays a sign in to Google page and account linking consent screen to the user. The user is directed back to Google's app after giving their consent to link accounts.

This figure shows the steps for a user to link their Google account
            to your authentication system. The first screenshot shows
            user-initiated linking from your platform. The second image shows
            user sign-in to Google, while the third shows the user consent and
            confirmation for linking their Google account with your app. The
            final screenshot shows a successfully linked user account in the
            Google app.
Figure 1. Account linking user sign in to Google and consent screens.

Requirements

  1. You must communicate that the user’s account will be linked to Google, not a specific Google product like Google Home or Google Assistant.

Recommendations

We recommend that you do the following:

  1. Display Google's Privacy Policy. Include a link to Google’s Privacy Policy on the consent screen.

  2. Data to be shared. Use clear and concise language to tell the user what data of theirs Google requires and why.

  3. Clear call-to-action. State a clear call-to-action on your consent screen, such as “Agree and link.” This is because users need to understand what data they're required to share with Google to link their accounts.

  4. Ability to cancel. Provide a way for users to go back or cancel, if they choose not to link.

  5. Clear sign-in process. Ensure that users have clear method for signing in to their Google account, such as fields for their username and password or Sign in with Google.

  6. Ability to unlink. Offer a mechanism for users to unlink, such as a URL to their account settings on your platform. Alternatively, you can include a link to Google Account where users can manage their linked account.

  7. Ability to change user account. Suggest a method for users to switch their account(s). This is especially beneficial if users tend to have multiple accounts.

    • If a user must close the consent screen to switch accounts, send a recoverable error to Google so the user can sign in to the desired account with OAuth linking and the implicit flow.
  8. Include your logo. Display your company logo on the consent screen. Use your style guidelines to place your logo. If you wish to also display Google's logo, see Logos and trademarks.

Create the project

To create your project to use account linking:

  1. Go to the Google API Console.
  2. [ プロジェクトを作成]をクリックします
  3. 名前を入力するか、生成された提案を受け入れます。
  4. 残りのフィールドを確認または編集します。
  5. 作成をクリックします

プロジェクトIDを表示するには:

  1. Go to the Google API Console.
  2. ランディングページの表でプロジェクトを見つけます。 ID列にプロジェクトIDが表示されます。

The Google Account Linking process includes a consent screen which tells users the application requesting access to their data, what kind of data they are asking for and the terms that apply. You will need to configure your OAuth consent screen before generating a Google API client ID.

  1. Open the OAuth consent screen page of the Google APIs console.
  2. If prompted, select the project you just created.
  3. On the "OAuth consent screen" page, fill out the form and click the “Save” button.

    Application name: The name of the application asking for consent. The name should accurately reflect your application and be consistent with the application name users see elsewhere. The application name will be shown on the Account Linking consent screen.

    Application logo: An image on the consent screen that will help users recognize your app. The logo is shown on Account linking consent screen and on account settings

    Support email: For users to contact you with questions about their consent.

    Scopes for Google APIs: Scopes allow your application to access your user's private Google data. For the Google Account Linking use case, default scope (email, profile, openid) is sufficient, you don’t need to add any sensitive scopes. It is generally a best practice to request scopes incrementally, at the time access is required, rather than up front. Learn more.

    Authorized domains: To protect you and your users, Google only allows applications that authenticate using OAuth to use Authorized Domains. Your applications' links must be hosted on Authorized Domains. Learn more.

    Application Homepage link: Home page for your application. Must be hosted on an Authorized Domain.

    Application Privacy Policy link: Shown on Google Account Linking consent screen. Must be hosted on an Authorized Domain.

    Application Terms of Service link (Optional): Must be hosted on an Authorized Domain.

    Figure 1. Google Account Linking Consent Screen for a fictitious Application, Tunery

  4. Check "Verification Status", if your application needs verification then click the "Submit For Verification" button to submit your application for verification. Refer to OAuth verification requirements for details.

OAuth サーバーを実装する

認証コードフローのOAuth 2.0のサーバーの実装では、あなたのサービスは、HTTPSで利用できるように2つのエンドポイント、から構成されています。最初のエンドポイントは承認エンドポイントであり、データアクセスについてユーザーからの同意を検索または取得する責任があります。承認エンドポイントは、まだサインインしていないユーザーにサインインUIを提示し、要求されたアクセスへの同意を記録します。 2番目のエンドポイントは、トークン交換エンドポイントです。これは、トークンと呼ばれる暗号化された文字列を取得するために使用され、ユーザーにサービスへのアクセスを許可します。

GoogleアプリケーションがサービスのAPIの1つを呼び出す必要がある場合、Googleはこれらのエンドポイントを一緒に使用して、ユーザーからユーザーに代わってこれらのAPIを呼び出す許可を取得します。

Googleによって開始されたOAuth2.0認証コードフローセッションには、次のフローがあります。

  1. Googleは、ユーザーのブラウザで認証エンドポイントを開きます。アクションの音声のみのデバイスでフローが開始された場合、Googleは実行を電話に転送します。
  2. ユーザーは、まだサインインしていない場合はサインインし、まだアクセス許可を付与していない場合は、APIを使用してデータにアクセスするためのGoogleアクセス許可を付与します。
  3. あなたのサービスは、認証コードを作成し、Googleにそれを返します。これを行うには、リクエストに認証コードを添付して、ユーザーのブラウザをGoogleにリダイレクトします。
  4. Googleは、コードの正当性を検証し、アクセストークンリフレッシュトークンを返し、あなたのトークン交換エンドポイントに認証コードを送信します。アクセストークンは、APIにアクセスするための資格情報としてサービスが受け入れる短期間のトークンです。更新トークンは、有効期限が切れたときにGoogleが保存して、新しいアクセストークンを取得するために使用できる長期間有効なトークンです。
  5. ユーザーがアカウントのリンクフローを完了すると、Googleから送信される後続のすべてのリクエストにアクセストークンが含まれます。

承認リクエストを処理する

OAuth 2.0認証コードフローを使用してアカウントのリンクを実行する必要がある場合、Googleは次のパラメータを含むリクエストを使用してユーザーを認証エンドポイントに送信します。

承認エンドポイントパラメータ
client_id Googleに割り当てたクライアントID。
redirect_uriこのリクエストへの応答を送信するURL。
stateリダイレクトURIで変更されずにGoogleに返される簿記の値。
scopeオプション:Googleがために許可を要求しているデータを指定範囲の文字列のスペース区切りのセット。
response_type応答で返す値のタイプ。 OAuth 2.0の認証コードの流れについては、応答タイプは常にあるcode
user_localeでGoogleアカウントの言語設定RFC5646のユーザーの優先言語でコンテンツをローカライズするために使用される形式、。

あなたの認可エンドポイントがで利用可能である場合たとえば、 https://myservice.example.com/auth 、要求は次のようになります。

GET https://myservice.example.com/auth?client_id=GOOGLE_CLIENT_ID&redirect_uri=REDIRECT_URI&state=STATE_STRING&scope=REQUESTED_SCOPES&response_type=code&user_locale=LOCALE

承認エンドポイントがサインイン要求を処理するには、次の手順を実行します。

  1. ていることを確認しclient_id Googleに割り当てられたクライアントIDと一致すること、およびredirect_uriあなたのサービスのためにGoogleが提供するリダイレクトURLと一致します。これらのチェックは、意図しないクライアントアプリや誤って構成されたクライアントアプリへのアクセスを許可しないようにするために重要です。あなたが複数のOAuth 2.0のフローをサポートしている場合、またことを確認response_typeあるcode
  2. ユーザーがサービスにサインインしているかどうかを確認します。ユーザーがサインインしていない場合は、サービスのサインインまたはサインアップフローを完了します。
  3. GoogleがAPIへのアクセスに使用する認証コードを生成します。認証コードには任意の文字列値を指定できますが、ユーザー、トークンの対象となるクライアント、およびコードの有効期限を一意に表す必要があり、推測できないようにする必要があります。通常、約10分後に有効期限が切れる認証コードを発行します。
  4. URLがで指定されていることを確認redirect_uriパラメータは次の形式を持っている:
      https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID
      https://oauth-redirect-sandbox.googleusercontent.com/r/YOUR_PROJECT_ID
      
  5. で指定されたURLにユーザーのブラウザをリダイレクトredirect_uriパラメータ。あなたが追加することによってリダイレクトするときにだけ生成された認証コードとオリジナルの、無修正の状態値を含めるcodestateのパラメータを。以下は、得られたURLの例です:
    https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID?code=AUTHORIZATION_CODE&state=STATE_STRING

トークン交換リクエストを処理する

サービスのトークン交換エンドポイントは、次の2種類のトークン交換を担当します。

  • アクセストークンと更新トークンの認証コードを交換します
  • 更新トークンをアクセストークンと交換する

トークン交換リクエストには、次のパラメータが含まれます。

トークン交換エンドポイントパラメーター
client_idリクエストの発信元をGoogleとして識別する文字列。この文字列は、Googleの一意の識別子としてシステム内に登録する必要があります。
client_secretサービスのためにGoogleに登録した秘密の文字列。
grant_type交換されるトークンのタイプ。それはどちらかだauthorization_codeまたはrefresh_token
codeときgrant_type=authorization_code 、このパラメータは、Googleがあなたのサインインまたはトークン交換エンドポイントのいずれかから受信したコードです。
redirect_uriときgrant_type=authorization_code 、このパラメータは、最初の認証要求で使用されるURLです。
refresh_tokenときgrant_type=refresh_token Googleがあなたのトークン交換エンドポイントから受信したトークンは、このパラメータは、リフレッシュです。
アクセストークンと更新トークンの認証コードを交換します

ユーザーがログインし、認証エンドポイントが短期間の認証コードをGoogleに返すと、Googleはトークン交換エンドポイントにリクエストを送信して、認証コードをアクセストークンと更新トークンに交換します。

これらの要求のために、の値grant_typeありauthorization_code 、との値code以前にGoogleに付与された認証コードの値です。次に、認証コードをアクセストークンと更新トークンに交換するリクエストの例を示します。

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

client_id=GOOGLE_CLIENT_ID&client_secret=GOOGLE_CLIENT_SECRET&grant_type=authorization_code&code=AUTHORIZATION_CODE&redirect_uri=REDIRECT_URI

アクセストークンとリフレッシュトークン、トークン交換エンドポイントの応答のための交換認証コードへPOSTは、次の手順を実行して要求:

  1. ことを確認しclient_id認可原点として要求元を識別し、そのclient_secret期待値と一致します。
  2. 認証コードが有効で有効期限が切れていないこと、および要求で指定されたクライアントIDが認証コードに関連付けられたクライアントIDと一致することを確認してください。
  3. URLがで指定されていることを確認redirect_uriパラメータは、最初の認証要求で使用される値と同じです。
  4. あなたが上記の基準のすべてを確認できない場合は、とHTTP 400不正な要求エラーを返す{"error": "invalid_grant"}ボディとして。
  5. それ以外の場合は、認証コードのユーザーIDを使用して、更新トークンとアクセストークンを生成します。これらのトークンは任意の文字列値にすることができますが、トークンの対象となるユーザーとクライアントを一意に表す必要があり、推測可能であってはなりません。アクセストークンの場合は、トークンの有効期限も記録します。これは通常、トークンを発行してから1時間後です。更新トークンは期限切れになりません。
  6. HTTPS応答の本文に以下のJSONオブジェクトを返します:
    {
    "token_type": "Bearer",
    "access_token": "ACCESS_TOKEN",
    "refresh_token": "REFRESH_TOKEN",
    "expires_in": SECONDS_TO_EXPIRATION
    }
    

Googleは、ユーザーのアクセストークンと更新トークンを保存し、アクセストークンの有効期限を記録します。アクセストークンの有効期限が切れると、Googleは更新トークンを使用してトークン交換エンドポイントから新しいアクセストークンを取得します。

更新トークンをアクセストークンと交換する

アクセストークンの有効期限が切れると、Googleはトークン交換エンドポイントにリクエストを送信して、更新トークンを新しいアクセストークンと交換します。

これらの要求のために、の値grant_typeされrefresh_token 、との値refresh_token以前にGoogleに付与されたリフレッシュトークンの値です。以下は、更新トークンをアクセストークンと交換するリクエストの例です。

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

client_id=GOOGLE_CLIENT_ID&client_secret=GOOGLE_CLIENT_SECRET&grant_type=refresh_token&refresh_token=REFRESH_TOKEN

アクセストークンのリフレッシュトークン、トークン交換エンドポイントの応答を交換するにはPOST次のステップを実行することにより、要求:

  1. ていることを確認しclient_idグーグルとして要求元に識別し、そのclient_secret期待値と一致しました。
  2. 更新トークンが有効であること、および要求で指定されたクライアントIDが更新トークンに関連付けられたクライアントIDと一致することを確認します。
  3. あなたが上記の基準のすべてを確認できない場合は、とHTTP 400不正な要求エラーを返す{"error": "invalid_grant"}ボディとして。
  4. それ以外の場合は、更新トークンのユーザーIDを使用してアクセストークンを生成します。これらのトークンは任意の文字列値にすることができますが、トークンの対象となるユーザーとクライアントを一意に表す必要があり、推測可能であってはなりません。アクセストークンの場合は、トークンの有効期限も記録します。通常は、トークンを発行してから1時間後です。
  5. HTTPS応答の本文で次のJSONオブジェクトを返します。
    {
    "token_type": "Bearer",
    "access_token": " ACCESS_TOKEN ",
    "expires_in": SECONDS_TO_EXPIRATION
    }
userinfoリクエストを処理する

ユーザー情報エンドポイントは、リンクされたユーザについての戻り主張OAuth 2.0の保護されたリソースです。次のユースケースを除いて、userinfoエンドポイントの実装とホスティングはオプションです。

トークンエンドポイントからアクセストークンが正常に取得されると、Googleはuserinfoエンドポイントにリクエストを送信して、リンクされたユーザーに関する基本的なプロファイル情報を取得します。

userinfoエンドポイントリクエストヘッダー
Authorization headerタイプBearerのアクセストークン。

たとえば、あなたのuserinfoエンドポイントがで利用可能な場合https://myservice.example.com/userinfo 、要求は次のようになります。

GET /userinfo HTTP/1.1
Host: myservice.example.com
Authorization: Bearer ACCESS_TOKEN

userinfoエンドポイントでリクエストを処理するには、次の手順を実行します。

  1. Authorizationヘッダーからアクセストークンを抽出し、アクセストークンに関連付けられているユーザーの情報を返します。
  2. アクセストークンが無効である場合は、使用してHTTP 401不正なエラーを返すWWW-Authenticate応答ヘッダを。以下のユーザー情報のエラー応答の例である:
    HTTP/1.1 401 Unauthorized
    WWW-Authenticate: error="invalid_token",
    error_description="The Access Token expired"
    
    401不正な、または他の任意の失敗エラー応答をリンク処理中に返された場合、エラーが回復不能、検索されたトークンは廃棄されることになり、ユーザが持っているであろうリンクプロセスを再開します。
  3. アクセストークンが有効であれば、リターンおよびHTTPS応答の本文に以下のJSONオブジェクトとHTTP 200応答:

    {
    "sub": "USER_UUID",
    "email": "EMAIL_ADDRESS",
    "given_name": "FIRST_NAME",
    "family_name": "LAST_NAME",
    "name": "FULL_NAME",
    "picture": "PROFILE_PICTURE",
    }
    
    あなたのuserinfoエンドポイントがHTTP 200の成功応答を返した場合、トークン取得し、クレームはユーザーのGoogleに対して登録されていますアカウント。

    userinfoエンドポイント応答
    subシステム内のユーザーを識別する一意のID。
    emailユーザーのメールアドレス。
    given_nameオプション:ユーザーのファーストネーム。
    family_nameオプション:ユーザーの姓。
    nameオプション:ユーザーのフルネーム。
    pictureオプション:ユーザーのプロフィール画像。

実装の検証

あなたは使用して実装を検証することができOAuth 2.0の遊び場のツールを。

ツールで、次の手順を実行します。

  1. 設定をクリックし OAuth 2.0の設定]ウィンドウを開きます。
  2. OAuthの流れ場では、クライアント側を選択します。
  3. OAuthのエンドポイント]フィールドで、[カスタム]を選択します。
  4. OAuth2.0エンドポイントとGoogleに割り当てたクライアントIDを対応するフィールドに指定します。
  5. ステップ1セクションでは、すべてのGoogleサービスのスコープを選択しないでください。代わりに、このフィールドを空白のままにするか、サーバーに有効なスコープ(または、OAuthスコープを使用しない場合は任意の文字列)を入力してください。設定が完了したら、承認のAPIをクリックします。
  6. ステップ2ステップ3のセクションでは、OAuth 2.0のフローを通過し、意図したように各ステップが動作することを確認。

あなたは使用して実装を検証することができ、Googleアカウントのリンクデモツールを。

ツールで、次の手順を実行します。

  1. Googleのボタンでサインインしをクリックしてください。
  2. リンクするアカウントを選択してください。
  3. サービスIDを入力します。
  4. オプションで、アクセスを要求する1つ以上のスコープを入力します。
  5. スタートデモをクリックしてください。
  6. プロンプトが表示されたら、リンク要求に同意して拒否できることを確認します。
  7. プラットフォームにリダイレクトされていることを確認します。