cognitoでサクッとログイン画面を作る

次世代デジタル基盤開発事業部の野口です。 本投稿は TECOTEC Advent Calendar 2022 の4日目の記事です。

業務でモバイルアプリを作成しておりますが、その際にcognitoを使用した認証の処理を行いました。 なので今回は簡単なログイン周りについて記述していきます。

Amazon Cognitoを準備

docs.aws.amazon.com

上記でcognitoのユーザプールを作成します。 1 点注意しないといけないのが、多要素認証の箇所のMFAの設定はオプションのMFAにする必要があります。

ユーザプールの「ユーザープール名」とアプリケーションの統合の下の「クライアントID」、リージョン(東京の場合はap-northeast-1)はflutterとcognitoのつなぎ込みの際に使用します。

ユーザプールID

クライアントID

ログイン機能の実装

flutterプロジェクトを作成します。

任意のフォルダ直下で flutter create <プロジェクト名> を実行します。

以下のパッケージを追加します

flutter pub add amplify_auth_cognito
flutter pub add amplify_authenticator
flutter pub add amplify_flutter

Amplifyの設定ファイルamplifyconfiguration.dartを作成します。 PoolId にユーザプールID、AppClientIdにクライアントID、 Region サーバの場所情報を記載します。

lib/amplifyconfiguration.dart

const amplifyconfig = '''{
  "auth": {
    "plugins": {
      "awsCognitoAuthPlugin": {
        "CognitoUserPool": {
          "Default": {
            "PoolId": "ap-northeast-1_cVyI3PGfg",
            "AppClientId": "27ptgssgmcvfg41lt5h43gmpjh",
            "Region": "ap-northeast-1"
          }
        },
        "Auth": {
          "Default": {
            "authenticationFlowType": "USER_SRP_AUTH",
            "socialProviders": [],
            "usernameAttributes": [],
            "signupAttributes": [],
            "passwordProtectionSettings": {
              "passwordPolicyMinLength": 8,
              "passwordPolicyCharacters": []
            }
          }
        }
      }
    }
  }
}''';

ログイン機能作成

ログイン機能を作成していきます。

main.dartを変更して、認証画面が立ち上がるか確認します Authenticatorのウィジェットがamplifyconfiguration.dartの設定に合わせてログイン画面を作成してくれます。 サインインが成功したら、Authenticator以下のウィジェットが表示されるようになります。

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 'amplifyconfiguration.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    _configureAmplify();
  }

  void _configureAmplify() async {
    try {
      await Amplify.addPlugin(AmplifyAuthCognito());
      await Amplify.configure(amplifyconfig);
      print('Successfully configured');
    } on Exception catch (e) {
      print('Error configuring Amplify: $e');
    }
  }
  
  Future<void> signOutCurrentUser() async {
    try {
      await Amplify.Auth.signOut();
    } on AuthException catch (e) {
      print(e.message);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Authenticator(
      child: MaterialApp(
        builder: Authenticator.builder(),
        home: Scaffold(
          appBar: AppBar(title: const Text('ホーム')),
          body:  Center(
            child: Column(
              children: [
                const Text('ログイン成功!', style: TextStyle(fontSize: 32.0)),
                ElevatedButton(
                    onPressed: () async{
                      await signOutCurrentUser();
                    }, child: const Text('ログアウト')),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

立ち上がりました。 サインアップなどをしてユーザープールにユーザが登録されればログイン機能完成です。 かなりサクッと作成できました!!!!

cognitoにはamplifyのAPIを使用して独自の画面に認証機能をつけることもできます。 メールアドレスやパスワードの変更もできるのぜひ試してみてください。

https://docs.amplify.aws/start/q/integration/flutter/

www.tecotec.co.jp