Amplify Console でデプロイした Web アプリの PinPoint 認証メトリクスが計上されないときの対処方法

Web アプリケーションにて Analytics に関連する Amplify ライブラリを明示的に読み込む必要があります

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

困っていた内容

Amplify JS - Analytics カテゴリーを利用して Web アプリケーションを構築しており、Pinpoint における「認証メトリクス(Authentication metrics)」について検証を実施しています。 Amplify Auth で構築した Cognito のユーザー認証を用いており、その認証メトリクスを取得するため Amplify Analytics で Amazon Pinpoint のプロジェクトを作成しました。

認証メトリクスについて、Amplify アプリケーションをローカルで実行した場合はサインイン情報などが計上されることを確認しましたが、Amplify Console でホスティングしたところこちらのメトリクスが計上されなくなってしまいました。 こちらの事象の原因と解決策を教えて下さい。

どう対応すればいいの?

以下のように、Web アプリケーションにて Analytics に関連するライブラリを明示的に読み込む必要があります。

  • サンプルコード
import Amplify, {Analytics} from 'aws-amplify';
Amplify.configure(awsconfig);
console.log(Analytics)

なお、Amplify ライブラリにおいてソースコード上に明示的に Analytics カテゴリーにおけるライブラリ利用の記載がない場合、produciton build (npm run build)で作成された build 済みのアプリケーションには Analytics に関連するライブラリが含まれないという動作をします。

一方で、ローカルで実行した場合は Analytics カテゴリーの利用を特に明記しなくても、Analytics に関連するライブラリが読み込まれるという動作をします。

やってみた

以下のブログを参考に認証画面を作成します。

Amplify + Cognito でユーザ登録画面とユーザ認証までを試してみた | DevelopersIO

実装

作業ディレクトリ作成

$ mkdir amplify-push-analytics-app
$ cd amplify-push-analytics-app
$ npx create-react-app boyaki
$ cd boyaki

Amplify の初期化

Amplify プロジェクトとして初期化します。

$ amplify init

特別な指定がなければ、デフォルト値を入力します。

認証機能の追加

認証に Cognito を利用します。 以下のコマンドを実行することで、バックエンドに Cognito を利用するように Amplify が自動作成してくれます。

$ amplify add auth
Using service: Cognito, provided by: awscloudformation

 The current configured provider is Amazon Cognito.
 Do you want to use the default authentication and security configuration? Default configuration
 Warning: you will not be able to edit these selections.
 How do you want users to be able to sign in? Username
 Do you want to configure advanced settings? No, I am done.
$ amplify status
   Current Environment: staging

┌──────────┬──────────────────────────────┬───────────┬───────────────────┐
│ Category │ Resource name                │ Operation │ Provider plugin   │
├──────────┼──────────────────────────────┼───────────┼───────────────────┤
│ Auth     │ nakanopushanalyticsaf7483b72 │ Create    │ awscloudformation │
└──────────┴──────────────────────────────┴───────────┴───────────────────┘
$ amplify push
✔ Successfully pulled backend environment staging from the cloud.

    Current Environment: staging

┌──────────┬──────────────────────────────┬───────────┬───────────────────┐
│ Category │ Resource name                │ Operation │ Provider plugin   │
├──────────┼──────────────────────────────┼───────────┼───────────────────┤
│ Auth     │ nakanopushanalyticsaf7483b72 │ Create    │ awscloudformation │
└──────────┴──────────────────────────────┴───────────┴───────────────────┘
? Are you sure you want to continue? Yes

--- 省略 ---

✔ All resources are updated in the cloud

マネージメントコンソール上で、Cognito ユーザプールが作成されたことを確認します。

分析機能の追加

次に、Cognito による認証のメトリクスを PinPoint 側で受け付けるために、以下のコマンドを実行します。

$ amplify add analytics
? Select an Analytics provider Amazon Pinpoint
? Provide your pinpoint resource name: nakanopushanalyticsa
Auth configuration is required to allow unauthenticated users, but it is not configured properly.
Adding analytics would add the Auth category to the project if not already added.
? Apps need authorization to send analytics events. Do you want to allow guests and unauthenticated users to send analytics events? (we recommend you all
ow this when getting started) Yes
Successfully updated auth resource locally.
Successfully added resource nakanopushanalyticsa locally
$ amplify status

    Current Environment: staging

┌───────────┬──────────────────────────────┬───────────┬───────────────────┐
│ Category  │ Resource name                │ Operation │ Provider plugin   │
├───────────┼──────────────────────────────┼───────────┼───────────────────┤
│ Analytics │ nakanopushanalyticsa         │ Create    │ awscloudformation │
├───────────┼──────────────────────────────┼───────────┼───────────────────┤
│ Auth      │ nakanopushanalyticsaf7483b72 │ Update    │ awscloudformation │
└───────────┴──────────────────────────────┴───────────┴───────────────────┘
$ amplify push
✔ Successfully pulled backend environment staging from the cloud.

    Current Environment: staging

┌───────────┬──────────────────────────────┬───────────┬───────────────────┐
│ Category  │ Resource name                │ Operation │ Provider plugin   │
├───────────┼──────────────────────────────┼───────────┼───────────────────┤
│ Analytics │ nakanopushanalyticsa         │ Create    │ awscloudformation │
├───────────┼──────────────────────────────┼───────────┼───────────────────┤
│ Auth      │ nakanopushanalyticsaf7483b72 │ Update    │ awscloudformation │
└───────────┴──────────────────────────────┴───────────┴───────────────────┘
? Are you sure you want to continue? Yes

--- 省略 ---

✔ All resources are updated in the cloud

Pinpoint URL to track events https://us-west-2.console.aws.amazon.com/pinpoint/home/?region=us-west-2#/apps/xxxxxxxxxxxxxxxxxx/analytics/overview

マネージメントコンソール上で、オレゴンリージョンに PinPoint のプロジェクトが作成されたことを確認します。 なお、東京リージョンで Amplify プロジェクトを作成した場合は、オレゴンリージョンに PinPoint プロジェクトが作成されます。

これで、認証と分析の機能をもつバックエンドを構築することができました。

認証機能と分析機能を備えたフロントエンド実装

  • インストール

関連ライブラリをインストールします。

$ npm install --save aws-amplify@ @aws-amplify/ui-react@
  • ./src/App.js

認証画面のフロントとして利用するソースコードを作成します。

import React from 'react';
import { AmplifyAuthenticator, AmplifySignUp, AmplifySignOut } from '@aws-amplify/ui-react';
import { AuthState, onAuthUIStateChange } from '@aws-amplify/ui-components';
import awsconfig from './aws-exports';

Amplify.configure(awsconfig);

const App = () => {
    const [authState, setAuthState] = React.useState();
    const [user, setUser] = React.useState();

    React.useEffect(() => {
        return onAuthUIStateChange((nextAuthState, authData) => {
            setAuthState(nextAuthState);
            setUser(authData)
        });
    }, []);

  return authState === AuthState.SignedIn && user ? (
      <div className="App">
          <div>Hello, {user.username}</div>
          <AmplifySignOut />
      </div>
    ) : (
      <AmplifyAuthenticator>
        <AmplifySignUp
          slot="sign-up"
          formFields={[
            { type: "username" },
            { type: "password" },
            { type: "email" }
          ]}
        />
      </AmplifyAuthenticator>
  );
}

export default App;

認証メトリクスが計上されない事象の再現

ローカルで認証

ローカルでサーバ実行して認証してみます。

$ npm start

http://localhost:3000 にアクセスし下記の画面を確認できます。

この画面で新規ユーザ登録します。

確認画面が表示されます。

登録したメール宛に認証コードが届いています。

コードを用いて、サインアップを行います。

ログインが成功します。さらに、サインアウト(SIGN OUT)ボタンをクリックします。

この状態で、PinPoint プロジェクトのマネージメントコンソールを開いて、認証メトリクスのサインインとサインアウトが 1 回ずつ計上されていることを確認します。 この結果から、ローカルでの実行の場合、認証メトリクスは正常に計上されることがわかりました。

Amplify Console で認証

次に、Amplify Console へアプリをホスティングします。 以下のコマンドを実行します。

$ amplify add hosting
? Select the plugin module to execute Hosting with Amplify Console (Managed hosting with custom domains, Continuous deployment)
? Choose a type Manual deployment

You can now publish your app using the following command:

Command: amplify publish
$ amplify status

    Current Environment: staging

┌───────────┬──────────────────────────────┬───────────┬───────────────────┐
│ Category  │ Resource name                │ Operation │ Provider plugin   │
├───────────┼──────────────────────────────┼───────────┼───────────────────┤
│ Hosting   │ amplifyhosting               │ Create    │ awscloudformation │
├───────────┼──────────────────────────────┼───────────┼───────────────────┤
│ Auth      │ nakanopushanalyticsaf7483b72 │ No Change │ awscloudformation │
├───────────┼──────────────────────────────┼───────────┼───────────────────┤
│ Analytics │ nakanopushanalyticsa         │ No Change │ awscloudformation │
└───────────┴──────────────────────────────┴───────────┴───────────────────┘

Pinpoint URL to track events https://us-west-2.console.aws.amazon.com/pinpoint/home/?region=us-west-2#/apps/xxxxxxxxxxxxxxxxxx/analytics/overview

No amplify console domain detected
$ amplify publish
✔ Successfully pulled backend environment staging from the cloud.

    Current Environment: staging

┌───────────┬──────────────────────────────┬───────────┬───────────────────┐
│ Category  │ Resource name                │ Operation │ Provider plugin   │
├───────────┼──────────────────────────────┼───────────┼───────────────────┤
│ Hosting   │ amplifyhosting               │ Create    │ awscloudformation │
├───────────┼──────────────────────────────┼───────────┼───────────────────┤
│ Auth      │ nakanopushanalyticsaf7483b72 │ No Change │ awscloudformation │
├───────────┼──────────────────────────────┼───────────┼───────────────────┤
│ Analytics │ nakanopushanalyticsa         │ No Change │ awscloudformation │
└───────────┴──────────────────────────────┴───────────┴───────────────────┘
? Are you sure you want to continue? Yes

--- 省略 ---

✔ Zipping artifacts completed.
✔ Deployment complete!
https://staging.d37u94l3ytjh40.amplifyapp.com

デプロイが完了したので、Amplify Console の URL へアクセスします。

サインイン画面で、意図的に認証失敗して PinPint の「認証の失敗」が計上されるか確認してみます。

認証が失敗すると以下のような画面に遷移します。

しばらく経っても、「認証の失敗」のメトリクスが計上されません。

認証メトリクスが計上されるように修正

それでは、認証メトリクスが計上されるようにソースコードを修正します。

ソースコード修正

修正箇所は、以下の 3 行目、10 行目です。 Analytics ライブラリを明示的に読み込みます。

  • ./src/App.js
import React from 'react';
// Analytics を明示的に指定
import Amplify ,{ Analytics } from 'aws-amplify';
import { AmplifyAuthenticator, AmplifySignUp, AmplifySignOut } from '@aws-amplify/ui-react';
import { AuthState, onAuthUIStateChange } from '@aws-amplify/ui-components';
import awsconfig from './aws-exports';

// PinPoint の authentication metrics へ送信
Amplify.configure(awsconfig);
console.log(Analytics)

const App = () => {
    const [authState, setAuthState] = React.useState();
    const [user, setUser] = React.useState();

    React.useEffect(() => {
        return onAuthUIStateChange((nextAuthState, authData) => {
            setAuthState(nextAuthState);
            setUser(authData)
        });
    }, []);

  return authState === AuthState.SignedIn && user ? (
      <div className="App">
          <div>Hello, {user.username}</div>
          <AmplifySignOut />
      </div>
    ) : (
      <AmplifyAuthenticator>
        <AmplifySignUp
          slot="sign-up"
          formFields={[
            { type: "username" },
            { type: "password" },
            { type: "email" }
          ]}
        />
      </AmplifyAuthenticator>
  );
}

export default App;

ソースコードを修正したので、手動で Amplify Console へデプロイします。

$ amplify publish

Amplify Console 上で認証してみる

それでは、再度、意図的に認証を失敗してみます。 今度は、Chrome の開発者ツールでネットワークを表示しながら確認してみます。 以下のように、PinPoint の Request URL へ イベントを POST していることからも、Amplify Console で分析機能が動作していることがわかります。

しばらくすると、以下のように認証メトリクスの「認証の失敗」にメトリクスが記録されました。

参考資料