OAuth によるアカウント リンク(Dialogflow)

OAuthOAuth リンクタイプは、インプリシットOAuth フローと認可OAuthコードフローの 2 通りの業界標準 OAuth 2.0 フローをサポートします。

In the implicit code 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 the Assistant to your Action.

In the authorization code flow, you need two endpoints:

  • The authorization endpoint, which is responsible for presenting the sign-in UI to your users that aren't already signed in and recording consent to the requested access in the form of a short-lived authorization code.
  • 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.

Although the implicit code flow is simpler to implement, Google recommends that access tokens issued using the implicit flow never expire, because using token expiration with the implicit flow forces the user to link their account again. If you need token expiration for security reasons, you should strongly consider using the auth code flow instead.

OAuth によるアカウント リンクを実装する

プロジェクトを構成する

プロジェクトで OAuth によるアカウント リンクを使用するよう構成するには、次の手順に従います。

  1. Actions Console を開き、使用するプロジェクトを選択します。
  2. [Develop](開発)タブをクリックして、[Account linking](アカウント リンク)を選択します。
  3. [アカウントのリンク] の横にあるスイッチを有効にします。
  4. [アカウントの作成] セクションで、[いいえ、自分のウェブサイトでのアカウントの作成のみを許可します] を選択します。

  5. [Linking type] で、[OAuth] と [Implicit] を選択します。

  6. [クライアント情報] で、次の操作を行います。

    • [Actions to Google に発行するクライアント ID] に値を割り当てます。これは、Google からのリクエストを識別する値です。
    • 認可エンドポイントとトークン交換エンドポイントの URL を挿入します。
  1. [保存] をクリックします。

OAuth サーバーを実装する

OAuth 2.0 暗黙的フローをサポートするため、サービスは HTTPS で認可エンドポイントを使用できるようにします。このエンドポイントは、データアクセスについてユーザーの認証と同意の取得を行います。認可エンドポイントは、ログインしていないユーザーにログイン用の UI を表示し、リクエストされたアクセスへの同意を記録します。

アクションからサービスの API を呼び出す必要がある場合、Google はこのエンドポイントを使用して、API の呼び出し許可をユーザーから取得します。

通常、Google が開始する OAuth 2.0 インプリシット フローのセッションは次のような流れになります。

  1. Google がユーザーのブラウザで認可エンドポイントを開きます。ユーザーがログインし(ログインしていない場合)、Google が API を使用してデータにアクセスすることを承諾します(まだ許可していない場合)。
  2. サービスがアクセス トークンを作成します。そのトークンを含むリクエストを送信して、ユーザーのブラウザを Google にリダイレクトし、Google にアクセス トークンを返します。
  3. Google はサービスの API を呼び出し、各リクエストにアクセス トークンを付与します。サービスが、アクセス トークンによって Google に API へのアクセスを許可することを確認し、API 呼び出しを完了します。

認可リクエストの処理

アクションで OAuth2 インプリシット フローを介してアカウント リンクを行う必要がある場合、Google は、次のパラメータを含むリクエストを使用して、ユーザーを認可エンドポイントに送信します。

認可エンドポイントのパラメータ
client_id Google に割り当てたクライアント ID。
redirect_uri このリクエストに対するレスポンスを送信する URL。
state リダイレクト URL で変更されずに Google に返される会計上の値。
response_type レスポンスで返される値のタイプ。OAuth 2.0 暗黙的フローの場合、レスポンス タイプは常に token です。

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

GET https://myservice.example.com/auth?client_id=GOOGLE_CLIENT_ID&redirect_uri=REDIRECT_URI&state=STATE_STRING&response_type=token

認可エンドポイントでログイン リクエストを処理する場合は、次の手順に従います。

  1. client_idredirect_uri の値を確認して、意図しないクライアント アプリまたは誤って構成されたクライアント アプリへのアクセスを許可しないようにします。

    • client_id が、Google に割り当てられたクライアント ID と一致することを確認します。
    • redirect_uri パラメータで指定された URL が次の形式になっていることを確認します。
      https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID
      YOUR_PROJECT_ID は、Actions Console の [プロジェクトの設定] ページに表示されている ID です。
  2. ユーザーがサービスにログインしているかどうか確認します。ユーザーがログインしていない場合は、サービスのログインまたは登録フローを完了します。

  3. Google が API へのアクセスに使用するアクセス トークンを生成します。アクセス トークンには任意の文字列値を使用できますが、トークンを使用するユーザーとクライアントを一意に表している必要があります。また、推測できない値は使用できません。

  4. redirect_uri パラメータで指定された URL にユーザーのブラウザをリダイレクトする HTTP レスポンスを送信します。URL フラグメントに次のパラメータをすべて含めます。

    • access_token: 生成したアクセス トークン
    • token_type: 文字列 bearer
    • state: 元のリクエストの変更前の状態の値。結果の URL の例を次に示します。
      https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID#access_token=ACCESS_TOKEN&token_type=bearer&state=STATE_STRING

Google の OAuth 2.0 リダイレクト ハンドラがアクセス トークンを受け取り、state 値が変更されていないことを確認します。Google はサービスのアクセス トークンを取得した後、そのトークンを AppRequest の一部として後続のアクションの呼び出しに追加します。

認証フローを開始する

アカウント ログイン ヘルパー インテントを使用して認証フローを開始します。次のコード スニペットは、Dialogflow と Actions SDK でこのヘルパーを使用してレスポンスを送信する方法を示します。

Dialogflow:

Node.js
const {dialogflow, SignIn} = require('actions-on-google');
const app = dialogflow({
  // REPLACE THE PLACEHOLDER WITH THE CLIENT_ID OF YOUR ACTIONS PROJECT
  clientId: CLIENT_ID,
});
// Intent that starts the account linking flow.
app.intent('Start Signin', (conv) => {
  conv.ask(new SignIn('To get your account details'));
});
Java
@ForIntent("Start Signin")
public ActionResponse text(ActionRequest request) {
  ResponseBuilder rb = getResponseBuilder(request);
  return rb.add(new SignIn().setContext("To get your account details")).build();
}
JSON
{
  "payload": {
    "google": {
      "expectUserResponse": true,
      "richResponse": {
        "items": [
          {
            "simpleResponse": {
              "textToSpeech": "PLACEHOLDER"
            }
          }
        ]
      },
      "userStorage": "{\"data\":{}}",
      "systemIntent": {
        "intent": "actions.intent.SIGN_IN",
        "data": {
          "@type": "type.googleapis.com/google.actions.v2.SignInValueSpec",
          "optContext": "To get your account details"
        }
      }
    }
  },
  "outputContexts": [
    {
      "name": "/contexts/_actions_on_google",
      "lifespanCount": 99,
      "parameters": {
        "data": "{}"
      }
    }
  ]
}

Actions SDK:

Node.js
const {actionssdk, SignIn} = require('actions-on-google');
const app = actionssdk({
  // REPLACE THE PLACEHOLDER WITH THE CLIENT_ID OF YOUR ACTIONS PROJECT
  clientId: CLIENT_ID,
});
// Intent that starts the account linking flow.
app.intent('actions.intent.TEXT', (conv) => {
  conv.ask(new SignIn('To get your account details'));
});
Java
@ForIntent("actions.intent.TEXT")
public ActionResponse text(ActionRequest request) {
  ResponseBuilder rb = getResponseBuilder(request);
  return rb.add(new SignIn().setContext("To get your account details")).build();
}
JSON
{
  "expectUserResponse": true,
  "expectedInputs": [
    {
      "inputPrompt": {
        "richInitialPrompt": {
          "items": [
            {
              "simpleResponse": {
                "textToSpeech": "PLACEHOLDER"
              }
            }
          ]
        }
      },
      "possibleIntents": [
        {
          "intent": "actions.intent.SIGN_IN",
          "inputValueData": {
            "@type": "type.googleapis.com/google.actions.v2.SignInValueSpec",
            "optContext": "To get your account details"
          }
        }
      ]
    }
  ],
  "conversationToken": "{\"data\":{}}",
  "userStorage": "{\"data\":{}}"
}

データアクセス リクエストを処理する

アシスタントのリクエストにアクセス トークンが含まれている場合は、まずそのアクセス トークンが有効で期限切れになっていないことを確認してから、関連付けられているユーザー アカウントをデータベースから取得します。