LoginSignup
11
8

More than 3 years have passed since last update.

AWS amplify Reactでログイン画面作成

Posted at

amplifyとやらが便利そうなので入門として、TODOリストでも作ってみようかなと思った、第一弾です。
次は、Cognito認証付きAPIを作ろうと思います。

0. 環境

$ node -v
v10.16.3
$ npm -v
6.9.0

1. Amplify CLIインストール(準備)

公式: https://aws-amplify.github.io/docs/

$ sudo npm install -g @aws-amplify/cli
$ amplify configure
Scanning for plugins...
Plugin scan successful
Follow these steps to set up access to your AWS account:

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

## ここでブラウザが開き、ログイン画面が出るのでログインする。
## すでにログインしている場合は、AWSマネジメントコンソールが開く。
## ログインできたら、エンターを押す。

Specify the AWS Region
? region:
  eu-west-1
  eu-west-2
  eu-central-1
❯ ap-northeast-1

## 上・下カーソルで選択できるので、入力。

? user name:  [任意の名前を入れる]
Complete the user creation using the AWS console
https://console.aws.amazon.com/iam/home?region=undefined#/users$new?step=final&accessKey&userNames=************************************
Press Enter to continue

## ブラウザが開くのでそのまま登録(プログラムによるアクセスだけチェック入っていればOKです)

Enter the access key of the newly created user:
? accessKeyId:  ******************
? secretAccessKey:  *******************************
This would update/create the AWS Profile in your local machine
? Profile Name:  default
## ~/.aws/credentials が更新されるので、すでにdefault登録ずみの場合は注意。

Successfully set up the new user.

2. ReactJS生成

マニュアル: https://aws-amplify.github.io/docs/js/start?platform=react

今回はReactでマニュアルに則って作ってみます。

$ npx create-react-app mytodo
$ cd mytodo
$ npm install aws-amplify
$ npm install aws-amplify-react
$ npm start

ここまでで一旦Reactのデフォルト画面が表示されます。

3. バックエンドのセットアップ

3-1. 初期設定

★★のところが自分で入力できる箇所です。
★★★のところはそのままenterでOKです。

$ amplify init
Scanning for plugins...
Plugin scan successful
Note: It is recommended to run this command from the root of your app directory
? Enter a name for the project mytodo  ★★
? 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 react  ★★
? Source Directory Path:  src  ★★★
? Distribution Directory Path: build  ★★★
? Build Command:  npm run-script build  ★★★
? Start Command: npm run-script start  ★★★
Using default provider  awscloudformation

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

? Do you want to use an AWS profile? Yes  ★★
? Please choose the profile you want to use default  ★★←ここはamplify configureで設定したProfile Nameを入力.
⠼ 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!

Some next steps:
"amplify status" will show you what you've added already and if it's locally configured or deployed
"amplify <category> add" will allow you to add features like user login or a backend API
"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

Pro tip:
Try "amplify add api" to create a backend API and then "amplify publish" to deploy everything

3-2. auth(Cognito)の設定

3-2-1. Cognito作成

Emailでのログインを設定しました。

$ 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  ★★
 Warning: you will not be able to edit these selections.
 How do you want users to be able to sign in? Email  ★★
 Do you want to configure advanced settings? No, I am done.  ★★
Successfully added resource mytodo 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

以下コマンドでCloudFormation Stackが作成されます。
一度作ってみて、ログイン機能の確認をしてみます。

$ amplify push

3-2-2. ログイン機能の実装

公式: https://aws-amplify.github.io/docs/js/authentication

SignUp/Inページ自体は、以下をのコードをApp.jsに追加するだけでできます。
ログイン後、先ほどのデフォルトページが表示さるようになります。

App.js
import Amplify, { Auth } from 'aws-amplify';
import { withAuthenticator } from 'aws-amplify-react';
import awsconfig from './aws-exports';

Amplify.configure(awsconfig);

const signUpConfig = {
    header: 'MyTodo SignUp',
    hideAllDefaults: true,
    defaultCountryCode: 1,
    signUpFields: [
        {
            label: 'email',
            key: 'username',
            required: true,
            displayOrder: 1,
            type: 'email'
        },
        {
            label: 'password',
            key: 'password',
            required: true,
            displayOrder: 2,
            type: 'password'
        },
    ]
}

うまくいかないときは、src/aws-wxports.jsの設定が正しいか確認してください。
自分は、この設定が別プロジェクトのものになっていて詰まりました(´-`)

また、

<button onClick={() => Auth.signOut()}>Sign Out</button>

を追加してあげるとログアウトできます。

4. おわり

おそらく、この通りにやれば10分~30分程度でログイン画面ができてしまいます。便利な世の中になりましたね。
今回は以上です。

11
8
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
11
8