Amplify+Nuxt.js+Cognitoで認証機能を実装する
AmplifyのAuthentication機能を用いて認証機能を実装していきます。Nuxt.js、Amplifyともに初めてなので、備忘録としてできるだけ詳しく書いていきます。
前回の記事でNuxt.jsの初期画面を表示させるところまでできているので、そこに認証機能を追加していきます。
いざコーディング
amplify auth の追加
$ amplify add auth $ amplify push
このコマンドを打つことでcloudformationのスタックによってCognitoが設定されます。またaws-exports.jsにCognitoの接続情報が追記されます。
ライブラリのインストール
$ npm install aws-amplify @aws-amplify/ui-vue
「aws-amplify」はamplifyのコアライブラリ、「@aws-amplify/ui-vue」はamplifyのvue用UIコンポーネントライブラリです。
プラグインの設定
先ほどインストールしたライブラリをプラグインとして読み込ませます。
import Vue from 'vue' import Amplify from 'aws-amplify' import '@aws-amplify/ui-vue' import awsExports from '@/aws-exports' Amplify.configure(awsExports) Vue.use(Amplify)
※nuxt.config.jsへの追記はあとでまとめて記述します。
ミドルウェアの設定
サインイン画面についてindex.vueで一緒に記述することもできますが、今回はrouterを用いて別ページとして実装していきます。そのためミドルウェアでrouterの設定を記述します。
import { Auth } from 'aws-amplify'認証済ならルートにリダイレクト、未認証ならサインインページにリダイレクトさせています。export default async ({ route, redirect }) => { const userInfo = await Auth.currentUserInfo() if(route.path == '/signin') { if(userInfo){ redirect('/') } return } if(!userInfo){ redirect('/signin') } }
vueファイルの作成
まずはサインインページの実装
<template> <amplify-authenticator> </amplify-authenticator> </template>aws-amplifyにはHubというイベントをハンドリングしてくれるものが用意されています。Hub.listen('auth',callback関数)とすることで、authに関するイベントが発生した際、callback関数を呼んでくれます。詳しくは公式ドキュメントを参照してください。<script> import { Hub } from 'aws-amplify'
export default { created() { Hub.listen('auth', this.listener) }, destroyed() { Hub.remove('auth', this.listener) }, methods: { listener(data){ if(data.payload.event == 'signIn') { this.$router.push('/') } } } } </script>
index.vueでは同様にサインアウトボタンを記述します。元のコードに以下を追記します。
<template> 〜 <amplify-sign-out></amplify-sign-out> 〜 </template> <script> import { Hub } from 'aws-amplify'export default { created() { Hub.listen('auth', this.listener) }, destroyed() { Hub.remove('auth', this.listener) }, methods: { listener(data){ if(data.payload.event == 'signOut') { this.$router.push('/signin') } } } } </script> 〜
nuxt.config.jsの設定
プラグインとミドルウェアの設定を反映させます。以下を追記します。
plugins: [{ src: '~/plugins/amplify.js', ssr: false }], router: { middleware: ['auth'], },
動作確認
コーディングが完了したので動作確認してみましょう。ローカルホストに接続すると以下画面が表示されます。
アカウント作成も行えます。
サインインした結果がこちらです。
storeを用いたログイン状態の管理などもできますが、今回はなるべくシンプルな形で実装してみました。フロント、バックともにこんな簡単に実装できることに感動です。さすがAWSですね。ではまた!