Open8

Amplify-React-Graphql その3 認証を追加する

marchanmarchan

Amplify ライブラリをインストールする

・aws-amplify ライブラリ
  AWSのバックエンドサービス(認証、ストレージ、APIなど)に簡単にアクセスできるよう
 ・@aws-amplify/ui-react ライブラリ
  ReactのAWS Amplify UIコンポーネントライブラリ

~amplifyapp (main) $ npm install aws-amplify @aws-amplify/ui-react

added 261 packages, changed 1 package, and audited 1821 packages in 27s

271 packages are looking for funding
run npm fund for details

8 vulnerabilities (2 moderate, 6 high)

To address all issues (including breaking changes), run:
npm audit fix --force

Run npm audit for details.

marchanmarchan

認証サービス(Cognito)を作成する

amplify add 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? Manual configuration
 Select the authentication/authorization services that you want to use: User Sign-Up, Sign-In, connected with AWS IAM control
s (Enables per-user Storage features for images or other content, Analytics, and more)
 Provide a friendly name for your resource that will be used to label this category in the project: AmplifyAppAuth
 Enter a name for your identity pool. amplifyappa3ce4fa5_identitypool_a3ce4fa5
 Allow unauthenticated logins? (Provides scoped down permissions that you can control via AWS IAM) Yes
 Do you want to enable 3rd party authentication providers in your identity pool? Yes
 Select the third party identity providers you want to configure for your identity pool: 
 Provide a name for your user pool: AmplifyAppAuthUserPool
 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 add User Pool Groups? Yes
? Provide a name for your user pool group: Admins
? Do you want to add another User Pool Group Yes
? Provide a name for your user pool group: Users
? Do you want to add another User Pool Group Yes
? Provide a name for your user pool group: Guests
? Do you want to add another User Pool Group No
✔ Sort the user pool groups in order of preference · Admins, Users, Guests
 Do you want to add an admin queries API? Yes
? Do you want to restrict access to the admin queries API to a specific Group Yes
? Select the group to restrict access with: Admins
 Multifactor authentication (MFA) user login options: OPTIONAL (Individual users can use MFA)
 For user login, select the MFA types: SMS Text Message, Time-Based One-Time Password (TOTP)
 Specify an SMS authentication message: Your authentication code is {####}
 Email based user registration/forgot password: Enabled (Requires per-user email entry at registration)
 Specify an email verification subject: Your verification code
 Specify an email verification message: Your verification code is {####}
 Do you want to override the default password policy for this User Pool? No
 Warning: you will not be able to edit these selections. 
 What attributes are required for signing up? Email
 Specify the app's refresh token expiration period (in days): 30
 Do you want to specify the user attributes this app can read and write? Yes
 Specify read attributes: Email
 Specify write attributes: 
 Do you want to enable any of the following capabilities? Email Verification Link with Redirect
 Do you want to use an OAuth flow? No
? Do you want to configure Lambda Triggers for Cognito? No

✔ Enter the URL that your users will be redirected to upon account confirmation: ·
✔ Enter the subject for your custom account confirmation email: ·
✔ Enter the body text for your custom account confirmation email (this will appear before the link URL): ·
✅ Successfully added resource AmplifyAppAuthCustomMessage locally.

✅ Next steps:
Check out sample function code generated in <project-dir>/amplify/backend/function/AmplifyAppAuthCustomMessage/src
"amplify function build" builds all of your functions currently in the project
"amplify mock function <functionName>" runs your function locally
To access AWS resources outside of this Amplify app, edit the /home/ec2-user/environment/amplify-react-graphql/amplifyapp/amplify/backend/function/AmplifyAppAuthCustomMessage/custom-policies.json
"amplify push" builds all of your local backend resources and provisions them in the cloud
"amplify publish" builds all of your local backend and front-end resources (if you added hosting category) and provisions them in the cloud
Successfully added the Lambda function locally
? Do you want to edit your verification-link function now? No
✅ Successfully added AdminQueries4562dd76 function locally
✅ Successfully added AdminQueries API locally
✅ Successfully added auth resource AmplifyAppAuth 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

⚠️ You have enabled SMS based auth workflow. Verify your SNS account mode in the SNS console: https://console.aws.amazon.com/sns/v3/home#/mobile/text-messaging
If your account is in "Sandbox" mode, you can only send SMS messages to verified recipient phone numbers.

marchanmarchan

認証サービスをデプロイする

$ amplify push

✔ Successfully pulled backend environment dev from the cloud.
Current Environment: dev
┌──────────┬─────────────────────────────┬───────────┬───────────────────┐
│ Category │ Resource name │ Operation │ Provider plugin │
├──────────┼─────────────────────────────┼───────────┼───────────────────┤
│ Auth │ userPoolGroups │ Create │ awscloudformation │
├──────────┼─────────────────────────────┼───────────┼───────────────────┤
│ Auth │ AmplifyAppAuth │ Create │ awscloudformation │
├──────────┼─────────────────────────────┼───────────┼───────────────────┤
│ Function │ AmplifyAppAuthCustomMessage │ Create │ awscloudformation │
├──────────┼─────────────────────────────┼───────────┼───────────────────┤
│ Function │ AdminQueries4562dd76 │ Create │ awscloudformation │
├──────────┼─────────────────────────────┼───────────┼───────────────────┤
│ Api │ AdminQueries │ Create │ awscloudformation │
└──────────┴─────────────────────────────┴───────────┴───────────────────┘

marchanmarchan

Amplify リソースを追加して Reactプロジェクトを設定する

  • /src/index.js に追加する。

import { Amplify } from 'aws-amplify';
import config from './aws-exports';
Amplify.configure(config);

marchanmarchan

App.js に認証フローを追加する

  • /src/App.js を変更する
import logo from "./logo.svg";
import "@aws-amplify/ui-react/styles.css";
import {
  withAuthenticator,
  Button,
  Heading,
  Image,
  View,
  Card,
} from "@aws-amplify/ui-react";

function App({ signOut }) {
  return (
    <View className="App">
      <Card>
        <Image src={logo} className="App-logo" alt="logo" />
        <Heading level={1}>We now have Auth!</Heading>
      </Card>
      <Button onClick={signOut}>Sign Out</Button>
    </View>
  );
}

export default withAuthenticator(App);

・withAuthenticator コンポーネントを使用
・[Sign Out] (サインアウト) ボタンも追加

marchanmarchan

アプリをローカルで実行する

  • Cloud9 開発サーバで実行する
npm start

marchanmarchan

フロントエンド・バックエンドのCI/CDを設定する

※ management Consoleに2つのアプリが作成されていたため作業変更