LoginSignup
24
20

More than 3 years have passed since last update.

AWS Amplify(Cognito)でGoogleソーシャルログインする

Last updated at Posted at 2020-07-05

Amplifyは、高速でアプリを開発できる開発プラットフォームです。
Amplifyで作成したVue.jsアプリでGoogleとのログイン連携を試したので、メモしておきます。

作成したもの

ezgif-1-2260dc7f05e4.gif

上のイメージの通りですが、Googleログイン済でない場合は、Googleへのログインを挟んでログイン処理を行います。

スクリーンショット 2020-07-05 9.05.55.png

ソースコードの全量はGitHubにあります。
https://github.com/Thirosue/amplify-sns-fedaration

前提

  • Amplifyの設定が完了していること(amplify configureamplify initおよびamplify pushが済んでいること)
  • Amplifyで作成したVue.jsアプリが存在すること(aws-amplifyaws-amplify-vueの導入・設定が済んでいること)

Amplifyの状態は以下のとおり(amplify status

$ amplify status

Current Environment: prod

| Category | Resource name | Operation | Provider plugin |
| -------- | ------------- | --------- | --------------- |

Amplifyのバージョンはv4

% amplify -v
4.21.3

Amplifyの設定はこちらを参照してください。
AWS 怠惰なプログラマ向けお手軽アプリ開発手法 2019
https://feature-webpush.dma9ecr5ksxts.amplifyapp.com/

手順

Googleとのログイン連携はAmplify CLIでサポートされているので、手順はこれだけです。

  1. GCP側の設定
  2. 認証モジュールの追加(amplify add auth
  3. GCP側にリダイレクトURLの設定

1. GCP側の設定

Step1. GCPにログインします

1.jpg

Step2. 認証情報(OAuthクライアント)を作成します

Step2-1. 認証情報設定画面に移動します

「APIとサービス」-「認証情報」を選択して進みます。

スクリーンショット 2020-07-05 10.13.42.png

Step2-2. 認証情報を作成します

「+ 認証情報を作成」-「OAuth クライアント ID」を選択します。

スクリーンショット 2020-07-05 10.18.59.png

Step2-3. 認証情報の設定

  • ウェブアプリケーションを選択

スクリーンショット 2020-07-05 10.21.42.png

  • 作成する

スクリーンショット 2020-07-05 10.23.37.png

作成した「OAuth クライアント」の「クライアント ID」と「クライアント シークレット」は2. 認証モジュールの追加で利用するので、メモしておきましょう。

2.jpg

2. 認証モジュールの追加(amplify add auth

認証機能をコマンドライン(Amplify CLI)で追加していきます。
以下コマンドで認証モジュール(Cognito)を追加します。

amplify add auth

Step1. Do you want to use the default authentication and security configuration? (Use arrow keys)

Default configuration with Social Provider (Federation)を選択

 Do you want to use the default authentication and security configuration?
  Default configuration
❯ Default configuration with Social Provider (Federation)
  Manual configuration
  I want to learn more.

Step2. How do you want users to be able to sign in? (Use arrow keys)

どれでもいいですが、Usernameを選択

 How do you want users to be able to sign in? (Use arrow keys)
❯ Username
  Email
  Phone Number
  Email or Phone Number
  I want to learn more.

Step3. Do you want to configure advanced settings? (Use arrow keys)

デフォルトのまま進む

 Do you want to configure advanced settings? (Use arrow keys)
❯ No, I am done.
  Yes, I want to make some additional changes.

Step4. What domain name prefix do you want to use?

ドメインはデフォルトのまま

 What domain name prefix do you want to use? (amplifysnsfedarationYYYYY-XXXXX)

Step5. Enter your redirect signin URI:

ローカルで試すので、http://localhost:8080/を入力

Enter your redirect signin URI: http://localhost:8080/

Step6. Do you want to add another redirect signin URI (y/N)

ローカルで試すので、その他のリダイレクトURLは不要

Do you want to add another redirect signin URI (y/N) N

Step7. Enter your redirect signout URI:

ローカルで試すので、http://localhost:8080/を入力

Enter your redirect signout URI: http://localhost:8080/

Step8. ? Do you want to add another redirect signout URI (y/N)

ローカルで試すので、その他のサインアウトURLは不要

? Do you want to add another redirect signout URI (y/N) N

Step9. Select the social providers you want to configure for your user pool:

Googleを選択

 Select the social providers you want to configure for your user pool:
 ◯ Facebook
❯◉ Google
 ◯ Login With Amazon

Step10. Enter your Google Web Client ID for your OAuth flow:

1. GCP側の設定で作成したアプリケーションの「クライアント ID」を入力

 Enter your Google Web Client ID for your OAuth flow: xxxxxxxxx

Step11. Enter your Google Web Client Secret for your OAuth flow:

1. GCP側の設定で作成したアプリケーションの「クライアント シークレット」を入力

 Enter your Google Web Client Secret for your OAuth flow: yyyyyyyyyy

Step12. 設定の反映(AWSリソースの作成)

以下コマンドで設定を反映(AWSリソースの作成)します。

amplify push

実行結果

正常に認証モジュールが追加されていることを以下コマンド(amplify status)で確認します。

$ amplify status

Current Environment: prod

| Category | Resource name                | Operation | Provider plugin   |
| -------- | ---------------------------- | --------- | ----------------- |
| Auth     | amplifysnsfedarationXXXXXXXX | No Change | awscloudformation |

設定の全量

% 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 with Social Provider (Federation)
 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.
 What domain name prefix do you want to use?
 Enter your redirect signin URI: http://localhost:8080/
? Do you want to add another redirect signin URI No
 Enter your redirect signout URI: http://localhost:8080/
? Do you want to add another redirect signout URI No
 Select the social providers you want to configure for your user pool: Google

 You've opted to allow users to authenticate via Google.  If you haven't already, you'll need to go to https://developers.google.com/identity and create an App ID.

 Enter your Google Web Client ID for your OAuth flow:  xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 Enter your Google Web Client Secret for your OAuth flow:  yyyyyyyyyyyyyyyyyyyyyyyyyyy
Successfully added resource amplifysnsfedarationc74d4543 locally

Some next steps:
"amplify push" will build all your local backend resources and provision it in the cloud
"amplify publish" will build all your local backend and frontend resources (if you have hosting category added) and provision it in the cloud

3. GCP側にリダイレクトURLの設定

1. GCP側の設定で作成した「認証情報(OAuthクライアント)」にCognitoで作成された認証のリダイレクトURLを設定します。

Step1. Amplifyの設定ファイル(aws-exports.js)を確認して、Cognitoのドメインを確認します。

2. 認証モジュールの追加の結果作成された、Amplifyの設定ファイル(aws-exports.js)のCognitoのドメインの箇所を確認します。

% cat src/aws-exports.js | grep domain
        "domain": "amplifysnsfedarationyyyyyyy-xxxxxxx-prod.auth.ap-northeast-1.amazoncognito.com",

Step2. 1. GCP側の設定で作成した「認証情報(OAuthクライアント)」に「認証のリダイレクトURL」を設定します。

設定する値はhttps://(Step1で確認したドメイン)/oauth2/idpresponseです。
上の例の場合は、https://amplifysnsfedarationyyyyyyy-xxxxxxx-prod.auth.ap-northeast-1.amazoncognito.com/oauth2/idpresponseとなります。

4.jpg

アプリケーションの修正

App.vueを修正します。

ログインに付随する細かい処理(ダイアログ出力、状態の管理(ローディング、サインイン)など)の説明は割愛します。
詳細は、全量のソースコード(GitHub)を確認してください。
https://github.com/Thirosue/amplify-sns-fedaration

htmlの修正

「Googleでログイン」のリンクを追加

<a href="#" @click="signIn('Google')">Googleでログイン</a>

サインインで画面切り替え

サインイン状態(signedIn)で表示を切り替えます。

      <!-- サインイン状態はstoreかdataに設定する -->
      <template v-if="signedIn">
        <h1>Logged in</h1>
        <a href="#" @click="signOut"><font color="gray">Sign Out</font></a>
      </template>
      <template v-else>
        <amplify-authenticator v-bind:authConfig="authConfig" />
        <ul>
          <li><a href="#" @click="signIn('Google')">Googleでログイン</a></li>
        </ul>
      </template>

methodの追加

ログイン処理を追加します。

Vue.js
import { Auth, Hub } from "aws-amplify";
//(...中略...)

  methods: {
    async signIn(provider) {
      this.$store.dispatch("loading", true); //処理中表示(処理開始)
      const res = await Auth.federatedSignIn({ provider });
      console.log(res);
    },

イベントフックを追加

Vue.js
import { Auth, Hub } from "aws-amplify";
//(...中略...)

  async beforeCreate() {
    //サインインイベントフックを追加
    Hub.listen("auth", async (data) => {
      switch (data.payload.event) {
        case "signIn": { // サインインイベントをフック
          const cognitoUser = await Auth.currentAuthenticatedUser();
          console.log(`signed in ... ${cognitoUser.username}`);
          this.$store.dispatch("signedIn", true);
          this.$store.dispatch("loading", false); //処理中表示(処理終了)
          Swal.fire({ // ダイアログ表示
            position: "top-end",
            icon: "success",
            title: "ログインしました",
            showConfirmButton: false,
            timer: 1500,
          });
          break;
        }
        default:
          break;
      }
    });
  },

確認

アプリケーションの起動

以下コマンド(yarn serve)でアプリケーションを起動します

yarn serve

http://localhost:8080/へアクセスして確認します。

「Googleでログイン」リンクをクリックすると、Googleへログインした後、ログイン後状態に遷移します。

ezgif-1-2260dc7f05e4.gif

最後に

Amplify CLIを利用すると容易にソーシャルログインが実現できます。
LINE(OpenID)やFaceBookへの連携も容易に実現でき、「モバイルアプリケーションとウェブアプリケーションを最速で構築する方法 」の説明は伊達ではないですね。

参考リンク

24
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
20