Amplify Auth のセットアップ
Amplify Auth は Amazon Cognito により提供されています。Cognito は、ユーザー登録、認証、アカウント復旧、その他の操作を処理する堅牢なユーザーディレクトリサービスです。概念を確認してさらに学ぶ。
認証リソースの定義を開始するには、認証リソースファイルを開くか作成します:
import { defineAuth } from "@aws-amplify/backend"
/** * Define and configure your auth resource * @see https://docs.amplify.aws/gen2/build-a-backend/auth */export const auth = defineAuth({ loginWith: { email: true, },})デフォルトでは、認証リソースは email をデフォルトのログインメカニズムとしてスキャフォルドされます。認証リソースを設定して以下でのサインインを許可することもできます:
- 電話番号
- 外部プロバイダー(Google、Facebook、Amazon、または Sign in with Apple)
認証リソースをデプロイ
認証リソースを選択して定義した後、以下のコマンドを実行して、個人用クラウドサンドボックスにリソースを作成します。
npx ampx sandbox --outputs-format dart --outputs-out-dir libデプロイが成功した後、このコマンドは出力ファイル(amplify_outputs.json)も生成します。これにより、フロントエンドアプリがバックエンドリソースに接続できるようになります。バックエンド認証リソースで設定する値は、生成された出力ファイルに設定され、フロントエンドの Authenticator 接続コンポーネント が自動的に設定されます。
アプリケーションコードを認証リソースに接続
サインインフローを作成して正しく実装することは、複雑で時間がかかることがあります。Amplify の Authenticator UI コンポーネントはこれを簡素化し、アプリ全体の認証フローを迅速に構築できるようにします。コンポーネントは amplify/auth/resource.ts の設定とシームレスに連携して、バックエンドリソースに自動的に接続します。
Amplify には React、Vue、Angular、React Native、Swift、Android、Flutter 向けの事前構築 UI コンポーネントがあります。このガイドでは、Web アプリケーション向けのコンポーネントに焦点を当てています。
まず、amplify_authenticator ライブラリをインストールします:
flutter pub add amplify_flutterflutter pub add amplify_auth_cognitoflutter pub add amplify_authenticatorまたは pubspec.yaml ファイルを以下で更新します:
dependencies: amplify_flutter: ^2.0.0 amplify_auth_cognito: ^2.0.0 amplify_authenticator: ^2.0.0そして以下のコマンドを実行してライブラリをダウンロードします。
flutter pub get次に、main.dart ファイルを以下で更新します:
import 'package:amplify_auth_cognito/amplify_auth_cognito.dart';import 'package:amplify_authenticator/amplify_authenticator.dart';import 'package:amplify_flutter/amplify_flutter.dart';import 'package:flutter/material.dart';
import 'amplify_outputs.dart';
Future<void> main() async { try { WidgetsFlutterBinding.ensureInitialized(); await _configureAmplify(); runApp(const MyApp()); } on AmplifyException catch (e) { runApp(Text("Error configuring Amplify: ${e.message}")); }}
Future<void> _configureAmplify() async { try { await Amplify.addPlugin(AmplifyAuthCognito()); await Amplify.configure(amplifyConfig); safePrint('Successfully configured'); } on Exception catch (e) { safePrint('Error configuring Amplify: $e'); }}
class MyApp extends StatelessWidget { const MyApp({super.key}); Widget build(BuildContext context) { return Authenticator( child: MaterialApp( builder: Authenticator.builder(), home: const Scaffold( body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ SignOutButton(), ], ), ), ), ), ); }}Authenticator コンポーネントをアプリに追加したら、サインアップ、サインイン、サインアウト機能をテストできます。また Authenticator 接続コンポーネントをカスタマイズ して、必要に応じて色とスタイルを調整することもできます。
次のステップ
Amplify アプリでメールとパスワードを使用した認証のセットアップが完了しました。さらに機能を追加したい場合は、以下について学ぶことをお勧めします: