ログイン画面を作る
前の節で登録したユーザーでログインし、アクセストークン を受け取る画面を作ります。API を呼ぶときに付けるのは、このアクセストークンです。
apps/ui/login.html を作成する
Section titled “apps/ui/login.html を作成する”1<!doctype html>2<html lang="ja">3<head>4 <meta charset="utf-8">5 <meta name="viewport" content="width=device-width, initial-scale=1">6 <title>ログイン</title>7 <link rel="stylesheet" href="./style.css">8</head>9<body>10 <h1>ログイン</h1>11
12 <form id="log-in">13 <label>メールアドレス <input name="email" type="email" required></label>14 <label>パスワード <input name="password" type="password" required></label>15 <button>ログイン</button>16 </form>17
18 <p id="message" class="message"></p>19
20 <section>21 <p>アクセストークン</p>22 <pre id="token"></pre>23 </section>24
25 <script type="module" src="./login.js"></script>26</body>27</html>apps/ui/login.js を作成する
Section titled “apps/ui/login.js を作成する”1import { cognito } from './lib/cognito.js';2
3const message = document.querySelector('#message');4
5// メールアドレスとパスワードを Cognito に送り、トークンを受け取る6document.querySelector('#log-in').addEventListener('submit', async (event) => {7 event.preventDefault();8 const form = new FormData(event.target);9 try {10 const result = await cognito('InitiateAuth', {11 AuthFlow: 'USER_PASSWORD_AUTH',12 AuthParameters: { USERNAME: form.get('email'), PASSWORD: form.get('password') },13 });14 // API を呼ぶときに付けるのは、アクセストークン15 document.querySelector('#token').textContent = result.AuthenticationResult.AccessToken;16 message.textContent = 'ログインできました';17 } catch (error) {18 message.textContent = error.message;19 }20});InitiateAuth…USER_PASSWORD_AUTHで、メールアドレスとパスワードを送りますAuthenticationResult.AccessToken… 受け取ったアクセストークンです。画面に出して、次の節から curl で使います
動作確認する
Section titled “動作確認する”画面は nginx がそのまま配るので、作り直さずに読み込み直すだけで使えます。http://localhost:3000/login.html を開き、alice@example.com と Passw0rd! で ログイン を押します。「ログインできました」と出て、eyJ で始まる長いアクセストークンが出れば大丈夫です。
参考にした公式ドキュメント
Section titled “参考にした公式ドキュメント”この節は、次の公式ドキュメントをもとに書いています。
- Amazon Cognito API: InitiateAuth …
USER_PASSWORD_AUTHとAuthenticationResult
この節を終えたときのディレクトリ
Section titled “この節を終えたときのディレクトリ”よくある質問
Section titled “よくある質問”NotAuthorizedException: Incorrect username or password と出る
メールアドレスかパスワードが違います。Floci を起動し直したときは、ユーザーも消えているので、サインアップからやり直してください。