React + Amplify環境構築手順
ReactでCognito認証を作成したため、本記事にまとめました。
Amplifyは、AWSが提供するWebアプリの開発を支援するためのフレームワークで、Cognito認証などがAPIとして提供されているもので、
他にもホスティングの機能などもありますが、今回は使用しないため、Cognito認証に特化して手順を説明します。
WebアプリのフレームワークはReact(Typescript)とする。
[前提条件]
create-react-appでReact実行環境は作成済みの状態とする。
1. Amplifyのインストール
$ npm install aws-amplify aws-amplify-react @aws-amplify/ui-react
2. index.tsxにAmplifyの認証情報追加
import Amplify from 'aws-amplify';
Amplify.configure({
Auth: {
region: 'ap-northeast-1',
userPoolId: 'ユーザープールID',
userPoolWebClientId: 'アプリクライアントID'
}
});
ユーザプールIDとアプリクライアントIDは、AWSコンソールのCognitoの画面から取得できる。
AWSのサービスを直接Webアプリから制御する場合は、IDプールの設定も必要だが、API Gatewayに対するREST APIでのみ制御するので、一旦IDプールの指定は不要とする。
3. 認証
aws-amplifyのAuthオブジェクトの各関数をコールすることで、サインインやサインアウトはできた。
import { Auth } from 'aws-amplify';
//サインイン
Auth.signIn(userSigninInfo.name, userSigninInfo.password)
//サインアウト
Auth.signOut()
4.トークン取得
AuthでcurrentSessionで取得できた。
import { Auth } from 'aws-amplify';
useEffect(() => {
Auth.currentSession()
.then((data: any) => {
setIdToken(data.getIdToken().getJwtToken());
}).finally(() => {
setLoading(true);
});
}, []);
上記取得したトークンをAPI GatewayのREST APIコール時にヘッダに付与すると、API GatewayでCognitoで認可していた場合、正常に動作する。
[参考URL]
・Amplify使い方1
https://qiita.com/herohit-tool/items/7a7e7bf3cbfa5b7ddff6
・Amplify使い方2
https://qiita.com/Engineer_Grotle/items/fa37a3924d1e66082889
・トークン取得
https://dev.classmethod.jp/articles/swagger-ui-with-amplify-react/
・Amplify公式
https://docs.amplify.aws/ui/auth/authenticator/q/framework/react#custom-form-fields
・AmplifyをHook化
https://qiita.com/G-awa/items/99cb84c62fcd113943a6