AWS Amplifyを触ってみる。withAuthenticator編
目次
インフラ力を高めつつ、スケールしやすい構成を自分で作れるようになりたいと思ったので、AWSのAmplifyの勉強始めました。今回は環境構築から一番簡単そうなwithAuthenticatorについて。
プロジェクトの設定
- お好みのプロジェクトを作ります。最近はReact周回遅れ気味だったので、Reactで
npx create-react-app --template typescript
- Amplify周りで利用するものをインストール
yarn add aws-amplify aws-amplify-react
typeファイルは含まれてるので @types/hoge
は大丈夫です
AWS周りの設定
npm install -g @aws-amplify/cli
でamplify cliを使えるようにするamplify configure
で アプリに使うAWS IAMの設定を行う。
コマンドを叩くとAWSの管理画面に遷移するので、リージョンや、ユーザー名を選択・入力し、accessKeyID, secretAccessKeyをターミナルにコピペする。

3. amplify add auth
する
コマンドを叩くとaws cloud formationからCognitoが用意される。
いろいろ聞かれるのでユーザー名で簡単に認証するようにしてみる
Do you want to use the default authentication and security configuration? Default configuration How do you want users to be able to sign in? Username Do you want to configure advanced settings? No, I am done.
cognitoのリソースがローカルで作られるので amplify push
とすると、AWS側のCognitoユーザープールに先ほど作った設定が反映されます

アプリに組み込んでみる
src/index.tsx
にAmplifyの設定ファイルを読み込む
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; // NOTE 追加 import Amplify from 'aws-amplify' import config from './aws-exports' // NOTE 追加 Amplify.configure(config); ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') ); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
src/App.tsx
にログイン機能を追加する
import React from 'react'; // NOTE 追加 import {withAuthenticator} from 'aws-amplify-react'; function App() { return ( <div className="App" /> ); } // NOTE 追加 export default withAuthenticator(App);
この状態でアプリを立ち上げるとログイン画面が表示される。

withAuthenticator
を使うことで、aws-amplifyが提供しているUIが表示される。
既にユーザーがある場合はこんな感じで簡単にできる。
が、新規登録などが必要な場合こんな感じのフローを作る必要がある。(ざっくりですが。)
公式ドキュメントはこちら
.png&blockId=ebcfb8c2-fe2a-4900-931c-a9f77009448c)
続きは別の記事で