LoginSignup
3
4

More than 3 years have passed since last update.

Nuxt.js+AmplifyでGoogleソーシャルログインを複数環境に構築(aws-exportsはコミットせず環境変数で管理)

Last updated at Posted at 2021-02-26

Nuxt.js+AmplifyでGoogleソーシャルログインを複数環境に構築(aws-exportsはコミットせず環境変数で管理)

はじめに

以下を サクッ と作る手順を記します。

  1. Nuxt.jsでWebアプリを作る (create nuxt-app利用)
  2. Amplifyをセットアップする
  3. Amplifyのenvで開発環境と本番環境を構築する
  4. AmplifyコンソールでフロントエンドのみGitHub連携する
  5. AmplifyのauthでGoogleソーシャルログインできるようにする
  6. Googleソーシャルログインして取得した名前,プロフィール画像,メールアドレスを表示する
  7. aws-exportsのバックエンド情報を環境変数で管理する

では、いってみましょう!

環境準備

npm, yarn, aws-amplify/cliが必要です。このサンプル構築時のバージョンも記しておきます。

$ nvm install v14.15.4
$ nvm alias default v14.15.4
$ npm update -g npm
$ npm i -g npm

$ npm -v
6.14.11

$ npm install -g yarn
$ yarn -v
1.22.10

$ npm install -g @aws-amplify/cli
$ amplify -v
4.41.2

Nuxt.jsでWebアプリを作る (create nuxt-app利用)

sample-nuxt-googleauthという名前で新規作成します。

$ yarn create nuxt-app sample-nuxt-googleauth
create-nuxt-app v3.5.2
✨  Generating Nuxt.js project in sample-nuxt-googleauth
? Project name: sample-nuxt-googleauth
? Programming language: JavaScript
? Package manager: Yarn
? UI framework: Vuetify.js
? Nuxt.js modules: (Press <space> to select, <a> to toggle all, <i> to invert selection)
? Linting tools: (Press <space> to select, <a> to toggle all, <i> to invert selection)
? Testing framework: None
? Rendering mode: Single Page App
? Deployment target: Static (Static/JAMStack hosting)
? Development tools: (Press <space> to select, <a> to toggle all, <i> to invert selection)
? What is your GitHub username? {{Your GitHub Account}}
? Version control system: Git
 :
🎉  Successfully created project sample-nuxt-googleauth

ビルドして実行できることを確認。

$ cd sample-nuxt-googleauth
$ yarn dev

Webアプリを新規作成して、実行することができました。
image.png

Amplifyをセットアップする

amplify configuresample-nuxt-googleauthというユーザーを作成する。

$ amplify configure
Sign in to your AWS administrator account:
https://console.aws.amazon.com/
Press Enter to continue

Specify the AWS Region
? region:  ap-northeast-1
Specify the username of the new IAM user:
? user name:  sample-nuxt-googleauth
Complete the user creation using the AWS console
https://console.aws.amazon.com/iam/home?region=ap-northeast-1#/users$new?step=final&accessKey&userNames=sample-nuxt-googleauth&permissionType=policies&policies=arn:aws:iam::aws:policy%2FAdministratorAccess
Press Enter to continue

Enter the access key of the newly created user:
? accessKeyId:  ********************
? secretAccessKey:  ****************************************
This would update/create the AWS Profile in your local machine
? Profile Name:  sample-nuxt-googleauth

Successfully set up the new user.

amplify initでプロジェクトに対してAmplifyを初期化する。

$ amplify init
Note: It is recommended to run this command from the root of your app directory
? Enter a name for the project samplenuxtgoogleauth
? Enter a name for the environment dev
? Choose your default editor: Visual Studio Code
? Choose the type of app that you're building javascript
Please tell us about your project
? What javascript framework are you using vue
? Source Directory Path:  
? Distribution Directory Path: dist
? Build Command:  yarn run generate
? Start Command: yarn start
Using default provider  awscloudformation

For more information on AWS Profiles, see:
https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html

? Do you want to use an AWS profile? Yes
? Please choose the profile you want to use sample-nuxt-googleauth
Adding backend environment dev to AWS Amplify Console app: xxxxxxxxxxxxxx
⠇ Initializing project in the cloud...
 :
✔ Successfully created initial AWS cloud resources for deployments.
✔ Initialized provider successfully.
Initialized your environment successfully.

Your project has been successfully initialized and connected to the cloud!
 :

初期化完了。この時点でAmplifyには何も入ってない。

$ amplify status

Current Environment: dev

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

Amplifyのenvで開発環境と本番環境を構築する

セットアップ時に作成したdev環境とは別にprod環境を追加する。
最初はdev環境のみ。

$ amplify env list

| Environments |
| ------------ |
| *dev         |

prod環境をaddする。

$ amplify env add
Note: It is recommended to run this command from the root of your app directory
? Do you want to use an existing environment? No
? Enter a name for the environment prod
Using default provider  awscloudformation

For more information on AWS Profiles, see:
https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html

? Do you want to use an AWS profile? Yes
? Please choose the profile you want to use sample-nuxt-googleauth
Adding backend environment prod to AWS Amplify Console app: d3t41btwle18h1
⠧ Initializing project in the cloud...
 :

devとprodの2環境になりました。

$ amplify env list

| Environments |
| ------------ |
| dev          |
| *prod        |

作成したprodが選択されたのでdevを選択しなおしておきます。

$ amplify env checkout dev
✔ Initialized provider successfully.
Initialized your environment successfully.
$ amplify env list

| Environments |
| ------------ |
| *dev         |
| prod         |

AmplifyコンソールでフロントエンドのみGitHub連携する

まず最初に .gitignoreへ以下の2ファイルを追加しておきます。

  • amplify/team-provider-info.json
  • aws-exports.js

バックエンドもAmplifyコンソールで管理したい場合aws-exportsをコミットする必要があります。(あってる?)
またその場合はprivateリポジトリとすることが推奨されています。
今回はフロントエンドのみAmplifyコンソールで管理しますのでコミットしません。
今後、authなどを加えていくなかで環境毎のパラメータがaws-exportsへ設定されますが、それらは環境変数で対応します。

GitHubにリポジトリを作成します。名前はWebアプリのプロジェクト同様 sample-nuxt-googleauth としました。
image.png
GitHubに作成したリポジトリへmainブランチを作成し、プロジェクトをコミット、プッシュします。

$ git add .
$ git commit -m "1st commit"
$ git branch -M main
$ git remote add origin https://github.com/{{your account}}/sample-nuxt-googleauth.git
$ git push -u origin main

devブランチも作成しておきます。

$ git branch dev
$ git checkout dev
$ git push origin dev

amplifyでホスティングをセットアップします。

$ amplify add hosting
? Select the plugin module to execute Hosting with Amplify Console (Managed hosting with custom domains, Continuous deployment)
? Choose a type (Use arrow keys)
❯ Continuous deployment (Git-based deployments)
  Manual deployment
  Learn more

Continuous deployment (Git-based deployments)を選択すると
? Continuous deployment is configured in the Amplify Console. Please hit enter once you connect your repository
というメッセージで止まります。
この状態で、AWSコンソール > AWS Amplify を見てみると、セットアップ中のアプリが追加されています。

セットアップ中のアプリ(samplenuxtgoogleauth)を選択し設定してゆきます。
Frontend environmentsタブからGitHubを選択し、Connect branchボタンを押下。

image.png

リポジトリとブランチを選択。ブランチは、どちらからでもいいですが、まずはdevブランチを選択して進めてゆきましょう。
image.png

ビルド設定の構成
バックエンドはコンソールで管理しないため、以下のチェックボックスはOFFにします。
Deploy updates to backend resources with your frontend on every code commit

image.png

保存してデプロイ
image.png

あと、ビルドの設定を編集する必要もありました。
build commandsyarn run buildからyarn run generateへ変更するのと、bseDirectory/から/distへ変更しています。
image.png

AmplifyコンソールでNuxtのWebアプリを公開する手順については、以前もう少し詳細に記したものがありますので良ければ参照ください。
Nuxt.js+Vuetifyで新規作成したPWA対応済みWebアプリをAmplify Consoleで公開

コンソールに戻ります。エンターキー押下で完了します。

? Continuous deployment is configured in the Amplify Console. Please hit enter once you connect your rep
ository 
Amplify hosting urls: 
┌──────────────┬───────────────────────────────────────────┐
│ FrontEnd Env │ Domain                                    │
├──────────────┼───────────────────────────────────────────┤
│ dev          │ https://dev.xxxxxxxxxxxxxx.amplifyapp.com │
└──────────────┴───────────────────────────────────────────┘

同じ要領で AmplifyコンソールのFrontend environmentsタブでブランチの接続ボタン押下からmainブランチも連携しておきます。
amplify statusで確認するとhosting urlsにmainブランチも追加されていることが確認できます。

$ amplify status

Current Environment: dev

| Category | Resource name  | Operation | Provider plugin |
| -------- | -------------- | --------- | --------------- |
| Hosting  | amplifyhosting | No Change |                 |


Amplify hosting urls: 
┌──────────────┬────────────────────────────────────────────┐
│ FrontEnd Env │ Domain                                     │
├──────────────┼────────────────────────────────────────────┤
│ dev          │ https://dev.xxxxxxxxxxxxxx.amplifyapp.com  │
├──────────────┼────────────────────────────────────────────┤
│ main         │ https://main.xxxxxxxxxxxxxx.amplifyapp.com │
└──────────────┴────────────────────────────────────────────┘

この時点で、フロントエンドの2環境(dev/main)とバックエンドの2環境(dev/prod)の間に関連はない状態です。
authを加えた後に環境変数で関連付けをしてゆくことになります。

AmplifyのauthでGoogleソーシャルログインできるようにする

amplifyでWebアプリに対して認証機能を加えてゆきます。

GCPでOAuth2.0クライアントIDを作成

Googleアカウントによるソーシャルログインができるようにしたいので、まずは、GCPでOAuth2.0クライアントIDを環境の数だけ作成します。

GCPコンソール > APIとサービス > 認証情報を作成 > OAuthクライアントID
image.png

(Auth同意画面を作成していない場合はまず作成する必要がありますが、ここでは割愛。)

アプリケーションの種類にはウェブアプリケーションを選択し、名前には環境を識別するための名前を設定します。(devとprodにします)
承認済みのリダイレクト URIは、AWS Cognitoのセットアップの後に設定が必要になりますが、今は未設定のままで良いです。
image.png

OAuthクライアントIDを作成すると クライアント IDクライアント シークレット を入手することができます。これはamplify auth(cognito)セットアップ時に必要となります。
dev環境用とprod環境用、2つのOAuthクライアントIDを作成しておいてください。
image.png

Amplifyのauthをセットアップ

GCPでOAuth2.0クライアントIDを環境の数だけ作成しました。
続いては、Webアプリのプロジェクトへamplifyの認証機能(auth)を加えてゆきます。

$ 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? yourappdomainname
 Enter your redirect signin URI: http://localhost:8080/
? Do you want to add another redirect signin URI Yes
 Enter your redirect signin URI: https://dev.xxxxxxxxxxxxxx.amplifyapp.com/
? Do you want to add another redirect signin URI Yes
 Enter your redirect signin URI: https://main.xxxxxxxxxxxxxx.amplifyapp.com/
? 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 Yes
 Enter your redirect signout URI: https://dev.xxxxxxxxxxxxxx.amplifyapp.com/
? Do you want to add another redirect signout URI Yes
 Enter your redirect signout URI: https://main.xxxxxxxxxxxxxx.amplifyapp.com/
? 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:  000000000000-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com
 Enter your Google Web Client Secret for your OAuth flow:  xxxxxxxxxxxxxxxxxxxxxxxx
Successfully added auth resource samplenuxtgoogleauthf564322e 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

redirect signin URIredirect signout URIにはそれぞれ、デバッグ環境、dev環境、prod(main)環境、合計3種類のアドレスを設定します。
Google Web Client IDGoogle Web Client Secretには、先ほどGCPで作成したOAuthクライアントIDのうちdevのものを設定します。これは現在amplify envでdevが選択されているからです。

環境をprodへ切り替えると(env checkout)、再びGoogle Web Client IDGoogle Web Client Secretの入力を促されるので、prodのものを設定してください。

$ amplify env checkout prod
✔ Initialized provider successfully.

 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:  888888888888-yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy.apps.googleusercontent.com
 Enter your Google Web Client Secret for your OAuth flow:  yyyyyyyyyyyyyyyyyyyyyyyy
Initialized your environment successfully.

それではいよいよamplify pushしてゆきましょう。prodとdevそれぞれpushします。

$ amplify push
✔ Successfully pulled backend environment prod from the cloud.

Current Environment: prod

| Category | Resource name                | Operation | Provider plugin   |
| -------- | ---------------------------- | --------- | ----------------- |
| Auth     | samplenuxtgoogleauthf564322e | Create    | awscloudformation |
| Hosting  | amplifyhosting               | No Change |                   |
? Are you sure you want to continue? Yes
⠋ Updating resources in the cloud. This may take a few minutes...
 :
✔ All resources are updated in the cloud

$ amplify env checkout dev
✔ Initialized provider successfully.
Initialized your environment successfully.

$ amplify push
✔ Successfully pulled backend environment dev from the cloud.

Current Environment: dev

| Category | Resource name                | Operation | Provider plugin   |
| -------- | ---------------------------- | --------- | ----------------- |
| Auth     | samplenuxtgoogleauthf564322e | Create    | awscloudformation |
| Hosting  | amplifyhosting               | No Change |                   |
? Are you sure you want to continue? Yes
⠋ Updating resources in the cloud. This may take a few minutes...
 :
✔ All resources are updated in the cloud

AWSコンソール > Cognito > ユーザープールの管理
2つのユーザープールが作成されています。
samplenuxtgoogleauthf888888e_userpool_f888888e-dev
samplenuxtgoogleauthf888888e_userpool_f888888e-prod
image.png

ユーザープール > アプリの統合 > ドメイン
ここに設定されているアドレスの後ろに/oauth2/idpresponseを加えたアドレスを、 GCPに作成したOAuthクライアントIDの承認済みのリダイレクト URIへ設定します。

例 : https://yourappdomainname-dev.auth.ap-northeast-1.amazoncognito.com/oauth2/idpresponse

devとprodそれぞれに対して行ってください。
(dev用ユーザープールのドメインはdev用OAuthクライアントIDへ、prod用ユーザープールのドメインはprod用OAuthクライアントIDへ、設定する。)
image.png
image.png

続いて、これは必須ではないのですが、ログイン時にプロフィールの名前やアイコンも取得できるように設定しておきたいと思います。
ユーザープール > フェデレーション > 属性マッピング
Googleタブで、nameとpictureにユーザープール属性の割り当てを行い、変更の保存ボタンを押下します。
image.png
これも、dev環境とprod環境、それぞれに設定を行っておきます。

Webアプリに認証機能を実装

GCPでOAuth2.0クライアントIDを環境の数だけ作成しました。amplifyのauthもセットアップしました。
それではいよいよ、Webアプリに認証機能を実装してゆきます。

  • Vue用のUIパッケージをインストールする。
$ yarn add aws-amplify
yarn add v1.22.10
[1/4] Resolving packages...
 :
[4/4] Building fresh packages...
success Saved lockfile.
success Saved 70 new dependencies.
info Direct dependencies
└─ aws-amplify@3.3.20
info All dependencies
 :
Done in 18.90s.
  • Webアプリのプロジェクトにplugins/amplify.jsファイルを加える。
plugins/amplify.js
import Vue from 'vue'
import Amplify from 'aws-amplify'
//import awsmobile from '@/aws-exports'
const awsmobile = {
    "aws_project_region": "ap-northeast-1",
    "aws_cognito_identity_pool_id": "ap-northeast-1:88888888-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    "aws_cognito_region": "ap-northeast-1",
    "aws_user_pools_id": "ap-northeast-1_XXXXXXXXX",
    "aws_user_pools_web_client_id": "xxxxxxxxxxxxxxxxxxxxxxxxxx",
    "oauth": {
        "domain": "yourappdomainname-dev.auth.ap-northeast-1.amazoncognito.com",
        "scope": [
            "phone",
            "email",
            "openid",
            "profile",
            "aws.cognito.signin.user.admin"
        ],
        "redirectSignIn": "http://localhost:8080/",
        "redirectSignOut": "http://localhost:8080/",
        "responseType": "code"
    },
    "federationTarget": "COGNITO_USER_POOLS"
};
Amplify.configure(awsmobile)
Vue.use(Amplify)

このファイル、まだGitHubにコミットしないでくださいね。

3行目にコメントアウトしてあえて残してますが、
//import awsmobile from '@/aws-exports'
このようにaws-exports.jsに定義されているJSONを読み込んでAmplifyを初期化するという書き方が一般的です。
しかし、あえてそうせずに、直接ここにaws-exports.jsのJSONを記載しています。

なぜかというと、aws-exports.jsはコミットせず、これらの値を環境変数で管理するということをやりたいからです。(詳細は次の章にて)

また、ソーシャルログイン対応のauthをセットアップした際に複数環境のredirectSignInredirectSignOutを設定しましたが、amplify authは複数のコールバックURLに対応していません。
aws-exports.jsには3環境分(デバッグ環境, Dev環境, Prod環境)のURLがカンマ区切りで設定されていますが、plugins/amplify.jsでAmplifyへ設定する際には1環境のみ(ここではデバッグ環境のみ)にしておく必要があります。

下記の情報も参考にさせていただきました。
参考 : Amplify auth は複数のコールバックURLに対応していない
参考 : How to support multiple redirect URLs of Auth with Amplify

繰り返しになりますが、このファイル、まだGitHubにコミットしないでくださいね。後ほど環境変数から設定できるようにしますので、それまでコミットしないでくださいね。

  • nuxt.config.jspluginplugins/amplify.jsを加える。
nuxt.config.js
 :
  // Plugins to run before rendering page (https://go.nuxtjs.dev/config-plugins)
  plugins: [
    {
      src: '~/plugins/amplify.js', ssr: false
    }
  ],
 :
  • pages/index.vueを編集する

既存のコードは削除し、ログイン状態によって表示/非表示されるログインボタンとログアウトボタンを設置します。

pages/index.vue
<template>
  <section align="center" v-if="!userInfo">
    <v-btn @click="signin">Login(Google)</v-btn>
  </section>
  <section align="center" v-else>
    <v-btn @click="signout">Logout</v-btn>
  </section>
</template>
<script>
import { Auth } from 'aws-amplify'
export default {
  data() {
    return {
      userInfo: null,
    }
  },
  mounted () {
    this.getUserInfo()
  },
  methods: {
    async getUserInfo() {
      this.userInfo = await Auth.currentUserInfo()
      console.log(this.userInfo)
    },
    signin() {
      Auth.federatedSignIn({ provider: 'Google' })
    },
    signout() {
      Auth.signOut()
    },
  },
}
</script>

実行して、ボタン押下によりログイン/ログアウトできることを確認してください。
image.png
ログイン時にユーザー情報をログ出力するようにしておきました。どのような情報が返ってきているのか確認しておきましょう。
image.png
名前やメールアドレスやプロフィール画像、そしてCognitoに登録された際のユーザーIDなどの情報が返ってきています。

AWS Cognitoのコンソール > ユーザープール > 全般設定 > ユーザーとグループ
こちらも確認しましょう。
ユーザーが1件追加されていますね。
image.png
image.png

Googleソーシャルログインして取得した名前,プロフィール画像,メールアドレスを表示する

これはおまけの実装ですが、ソーシャルログインして取得できたプロフィール画像とメールアドレスをWebUI上に表示しましょう。

pages/index.vue
<template>
  <section align="center" v-if="!userInfo">
    <v-btn @click="signin">Login(Google)</v-btn>
  </section>
  <section align="center" v-else>
    <v-avatar size="160">
      <v-img :src="imageAddress" />
    </v-avatar>
    <v-text-field readonly v-model="name" />
    <v-text-field readonly v-model="email" />
    <v-btn @click="signout">Logout</v-btn>
  </section>
</template>
<script>
import { Auth } from 'aws-amplify'
export default {
  data() {
    return {
      userInfo: null,
      name: null,
      imageAddress: null,
      email: null,
    }
  },
  mounted () {
    this.getUserInfo()
  },
  methods: {
    async getUserInfo() {
      this.userInfo = await Auth.currentUserInfo()
      if (this.userInfo) {
        const user = JSON.parse(JSON.stringify(this.userInfo))
        this.name = user.attributes["name"]
        this.imageAddress = user.attributes["picture"]
        this.email = user.attributes["email"]
        console.log(this.userInfo)
      }
    },
    signin() {
      Auth.federatedSignIn({ provider: 'Google' })
    },
    signout() {
      Auth.signOut()
    },
  },
}
</script>

はい、できました。
image.png

aws-exportsのバックエンド情報を環境変数で管理する

いよいよ最後の項目です。
plugins/amplify.jsにaws-exportsのJSON情報を直接書いてしまっており、このままではコミットできません。
環境毎に、環境変数として設定をします。環境は3つあります。

  1. デバッグ環境 => .envファイルへ設定します
  2. dev環境 => Amplifyコンソールの環境変数へ設定します。
  3. prod環境 => Amplifyコンソールの環境変数へ設定します。

Webアプリ側への設定は以下の通り。

/plugins/amplify.js
import Vue from 'vue'
import Amplify from 'aws-amplify'
//import awsmobile from '@/aws-exports'
const awsmobile = {
    "aws_project_region": "ap-northeast-1",
    "aws_cognito_identity_pool_id": "",
    "aws_cognito_region": "ap-northeast-1",
    "aws_user_pools_id": "",
    "aws_user_pools_web_client_id": "",
    "oauth": {
        "domain": "",
        "scope": [
            "phone",
            "email",
            "openid",
            "profile",
            "aws.cognito.signin.user.admin"
        ],
        "redirectSignIn": "",
        "redirectSignOut": "",
        "responseType": "code"
    },
    "federationTarget": "COGNITO_USER_POOLS"
};
awsmobile.aws_cognito_identity_pool_id          = process.env.ENVVAL_AWS_EXPORTS_aws_cognito_identity_pool_id;
awsmobile.aws_user_pools_id                     = process.env.ENVVAL_AWS_EXPORTS_aws_user_pools_id;
awsmobile.aws_user_pools_web_client_id          = process.env.ENVVAL_AWS_EXPORTS_aws_user_pools_web_client_id;
awsmobile.oauth.domain                          = process.env.ENVVAL_AWS_EXPORTS_oauth_domain;
awsmobile.oauth.redirectSignIn                  = process.env.ENVVAL_AWS_EXPORTS_oauth_redirectSignIn;
awsmobile.oauth.redirectSignOut                 = process.env.ENVVAL_AWS_EXPORTS_oauth_redirectSignOut;

Amplify.configure(awsmobile)
Vue.use(Amplify)
/nuxt.config.js
 :
  // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
  plugins: [
    {
      src: '~/plugins/amplify.js', ssr: false
    }
  ],
  env: {
    ENVVAL_AWS_EXPORTS_aws_cognito_identity_pool_id: process.env.ENVVAL_AWS_EXPORTS_aws_cognito_identity_pool_id,
    ENVVAL_AWS_EXPORTS_aws_user_pools_id: process.env.ENVVAL_AWS_EXPORTS_aws_user_pools_id,
    ENVVAL_AWS_EXPORTS_aws_user_pools_web_client_id: process.env.ENVVAL_AWS_EXPORTS_aws_user_pools_web_client_id,
    ENVVAL_AWS_EXPORTS_oauth_domain: process.env.ENVVAL_AWS_EXPORTS_oauth_domain,
    ENVVAL_AWS_EXPORTS_oauth_redirectSignIn: process.env.ENVVAL_AWS_EXPORTS_oauth_redirectSignIn,
    ENVVAL_AWS_EXPORTS_oauth_redirectSignOut: process.env.ENVVAL_AWS_EXPORTS_oauth_redirectSignOut,
  }
 :

.envファイルを作成します。

/.env
ENVVAL_AWS_EXPORTS_aws_cognito_identity_pool_id         = ap-northeast-1:88888888-xxxx-xxxx-xxxx-xxxxxxxxxxxx
ENVVAL_AWS_EXPORTS_aws_user_pools_id                    = ap-northeast-1_XXXXXXXXX
ENVVAL_AWS_EXPORTS_aws_user_pools_web_client_id         = xxxxxxxxxxxxxxxxxxxxxxxxxx
ENVVAL_AWS_EXPORTS_oauth_domain                         = yourappdomainname-dev.auth.ap-northeast-1.amazoncognito.com
ENVVAL_AWS_EXPORTS_oauth_redirectSignIn                 = http://localhost:8080/
ENVVAL_AWS_EXPORTS_oauth_redirectSignOut                = http://localhost:8080/

実行して、問題なく動作することを確認してください。
これでやっと、Gitへコミットできますね!コミットすると、Amplifyコンソールのビルドが走りますが、まだ環境変数を設定していないのでちゃんと動きません。

ということでAmplifyコンソールへ、dev/mainブランチごとに、dev/prod用の設定を環境変数として設定します。
ちょっと面倒なんですが、がんばって入力します。
image.png

設定が済んだら、再デプロイして動作確認して、完了です!
おつかれさまでした!!

サンプルで作成したアプリのコードと環境毎にデプロイしたアドレスは以下となります。
良ければご覧ください。
https://github.com/ww2or3ww/sample-nuxt-googleauth
https://main.d3t41btwle18h1.amplifyapp.com/
https://dev.d3t41btwle18h1.amplifyapp.com/

3
4
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
3
4