メインコンテンツまでスキップ

2. 認証を有効にしたAPIを作成

まずはAmplifyの通常手順で認証機能を有効にしたAPIを作成します。

認証の追加

shell
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 auth resource amplifyvitereactv244ad4f7e 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

APIの追加

shell
amplify add api
? Select from one of the below mentioned services: REST
✔ Provide a friendly name for your resource to be used as a label for this category in the project: · apib4e3de0f

✔ Provide a path (e.g., /book/{isbn}): · /items
Only one option for [Choose a Lambda source]. Selecting [Create a new Lambda function].
? Provide an AWS Lambda function name: amplifyvitereactv2967482db
? Choose the runtime that you want to use: NodeJS
? Choose the function template that you want to use: Hello World

Available advanced settings:
- Resource access permissions
- Scheduled recurring invocation
- Lambda layers configuration
- Environment variables configuration
- Secret values configuration

? Do you want to configure advanced settings? No
? Do you want to edit the local lambda function now? No
Successfully added resource amplifyvitereactv2967482db locally.

Next steps:
Check out sample function code generated in <project-dir>/amplify/backend/function/amplifyvitereactv2967482db/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 /workspaces/2303-amplify-cognito-userpool/0403-2/amplify-vite-react/amplify/backend/function/amplifyvitereactv2967482db/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
✅ Succesfully added the Lambda function locally
✔ Restrict API access? (Y/n) · yes
✔ Who should have access? · Authenticated users only
✔ What permissions do you want to grant to Authenticated users? · create, read, update, delete
✔ Do you want to add another path? (y/N) · no
✅ Successfully added resource apib4e3de0f 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

Lambdaのレスポンスを変更し、CORSアクセスを有効化します。

amplify/backend/function/amplifyvitereactv2967482db/src/index.js
/**
* @type {import('@types/aws-lambda').APIGatewayProxyHandler}
*/
exports.handler = async (event) => {
console.log(`EVENT: ${JSON.stringify(event)}`);
return {
statusCode: 200,
// Uncomment below to enable CORS requests
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*"
},
body: JSON.stringify('Hello from Lambda!'),
};
};

Pushする

shell
amplify push
⠏ Fetching updates to backend environment: dev from the cloud.⠋ Building resource auth/amplifyvitereactv244a
✔ Successfully pulled backend environment dev from the cloud.

Current Environment: dev

┌──────────┬────────────────────────────┬───────────┬───────────────────┐
│ Category │ Resource name │ Operation │ Provider plugin │
├──────────┼────────────────────────────┼───────────┼───────────────────┤
│ Auth │ amplifyvitereactv244ad4f7e │ Create │ awscloudformation │
├──────────┼────────────────────────────┼───────────┼───────────────────┤
│ Function │ amplifyvitereactv2967482db │ Create │ awscloudformation │
├──────────┼────────────────────────────┼───────────┼───────────────────┤
│ Api │ apib4e3de0f │ Create │ awscloudformation │
└──────────┴────────────────────────────┴───────────┴───────────────────┘
✔ Are you sure you want to continue? (Y/n) · yes

Deployment state saved successfully.

REST API endpoint: https://l46jey0x1g.execute-api.ap-northeast-1.amazonaws.com/dev

フロントエンドの修正

組み込みの認証画面を有効にし、認証後の画面でAPI呼び出しを行います。

  • 組み込み認証画面の有効化
src/App.tsx
import { useState } from 'react'

import { Authenticator } from '@aws-amplify/ui-react';
import '@aws-amplify/ui-react/styles.css';

function App() {

return (
<Authenticator>
{({ signOut, user }) => (
<main>
<h1>Hello {user!.username}</h1>
<button onClick={signOut}>Sign out</button>
</main>
)}
</Authenticator>
)
}

export default App

ログイン画面

image.png

認証後画面

image.png

  • APIアクセスを追加
src/App.tsx
import { useState } from 'react';

import { API } from 'aws-amplify';

import { Authenticator, Button, Card, TextAreaField } from '@aws-amplify/ui-react';
import '@aws-amplify/ui-react/styles.css';

function App() {

const [message, setMessage] = useState('')

async function callApi() {
const response = await API.get('apib4e3de0f', '/items', {})
setMessage(response)

}
return (
<Authenticator>
{({ signOut, user }) => (
<main>
<h1>Hello {user!.username}</h1>
<button onClick={signOut}>Sign out</button>

<Card variation='outlined'>
<Button onClick={callApi}>Call API</Button>
<TextAreaField label='response' value={message} readOnly></TextAreaField>
</Card>
</main>
)}
</Authenticator>
)
}

export default App

image.png

認証つきでAPIアクセスができました。

リクエストヘッダーを見ると署名付きリクエストとなっています。

image.png

API Gatewayの認可の部分もAWS IAMとなっています。

image.png

この状態からCognito User Pool認証に変更します。