AWS Amplify authentication for Flutter

Amplify Auth Integration with Flutter: Secure Authentication and Development Guide

Discover the power of AWS Amplify Flutter authentication as we explore the step-by-step implementation of secure authentication in your Flutter apps. This comprehensive tutorial, featuring Amplify authentication in Flutter apps, provides insights into integrating Amplify Auth seamlessly with Flutter. Learn how to build robust and secure apps using AWS Amplify’s powerful authentication capabilities.


What is Amplify?

Amplify is an Amazon Web Services (AWS) comprehensive development framework that simplifies building scalable and robust cloud-powered applications. With Amplify, authentication, storage, APIs, and more are streamlined, reducing complexity and enabling faster development.

Understanding Flutter

Flutter, developed by Google, is an open-source UI toolkit for building natively compiled mobile, web, and desktop applications from a single codebase. Its rich widget set and tools facilitate the creation of beautiful and performant cross-platform apps, supporting multiple programming languages with Dart as the primary language for Flutter development.


Prerequisite

Before diving into the integration process, ensure that you have the following prerequisites in place:

1. A Flutter development environment is set up on your machine.

2. An active AWS account with the necessary permissions to create and configure Amplify services.


AWS Amplify Flutter Authentication: Step-by-Step Tutorial

Step 1 – Install Amplify CLI and set up Amplify in your Flutter project

  1. Install the Amplify CLI and Amplify Flutter plugin to simplify backend setup and configuration.
npm install -g @aws-amplify/cli
  1. To set up Amplify on your system, use the following command and enter your AWS Secret keys to access your AWS Account.
amplify configure

You can follow the steps provided at AWS Amplify Doc to configure the Amplify at your system

  1. Initialize Amplify to your Flutter Project using the below command
amplify init
  1. You must install the Amplify Flutter package to integrate Amplify Auth with your Flutter app. Open your project’s `pubspec.yaml` file and add the following dependency. Save the file and run `flutter pub get` to fetch the package
dependencies:
  amplify_flutter: 1.0.0

Step 2 – Configure and initialize Amplify within your app

To configure Amplify Auth, run the following command in the terminal:

amplify add auth

Follow the prompts to configure the authentication mechanism. Amplify Auth supports various authentication mechanisms such as email/password, social sign-in, and multi-factor authentication.

In this tutorial, we will utilize the Default Configuration, where the email will be the username.

Step 3 – Integrate Amplify Auth with your Flutter app

  1. Add the following dependencies to your Flutter project’s pubspec.yaml file. Save the file and run ‘flutter pub get‘ to fetch the package
dependencies:
  amplify_auth_cognito: 1.0.0
  1. Configure Amplify Auth by adding the following code to your main.dart file:
  static Future<void> configureAmplify() async {
    if (!Amplify.isConfigured) {
      // Add any Amplify plugins you want to use
      final authPlugin = AmplifyAuthCognito();
      await Amplify.addPlugins(authPlugin);
      // Once Plugins are added, configure Amplify
      // Note: Amplify can only be configured once.
      try {
        await Amplify.configure(amplifyconfig);
      } on AmplifyAlreadyConfiguredException {
        logger.e(
            "Exception occurred while configuring Amplify Library. It is alreaady configured");
      }
    }
  }
  • An instance of the AmplifyAuthCognito plugin is created and assigned to the authPlugin variable. This plugin represents the authentication functionality provided by Amplify using Amazon Cognito.
  • The authPlugin is added as a plugin to Amplify using the addPlugins method, enabling the authentication capabilities in the app.
  • To set up Amplify, add the plugin and call the configure method while passing the amplifyconfig variable as a parameter. This step will initialize Amplify with the settings you have specified.
  • In case of an AmplifyAlreadyConfiguredException while configuring Amplify, the logger object logs an error message indicating that Amplify is already configured and any attempt to configure it again is not permitted.

Step 3 – Utilize Amplify Auth’s APIs and UI components to implement authentication workflows

After completing the setup of Amplify and configuring the backend, the next step is to develop user authentication screens for your Flutter app. These screens usually consist of sign-up, sign-in, and account management (password reset) screens, which can be customized to match your app’s design and flow.

Several popular packages, such as flutter_auth_ui or flutter_login, provide pre-built authentication UI components. You can use these packages as a starting point and customize them according to your needs.

The Amplify Authenticator UI, recently launched by AWS Amplify, is a component that effortlessly integrates full authentication processes into your app with minimal setup.

You can either user the Amplify Authenticator to set Auth API or you can develop your own authentication flow. For this article, we are building our own Authentication Flow using Flutter

How about we incorporate the Amplify Auth API into the Flutter code?

  • Sign Up User – Allow users to create new accounts using email/password or social identity providers
Future<SignUpResult> signUp(
      String name, String email, String phoneNumber, String password) async {
    try {
      final userAttributes = <CognitoUserAttributeKey, String>{
        CognitoUserAttributeKey.email: email,
        CognitoUserAttributeKey.phoneNumber: getPhoneNumber(phoneNumber),
        CognitoUserAttributeKey.name: name,
        // additional attributes as needed
      };
      final result = await Amplify.Auth.signUp(
        username: email,
        password: password,
        options: CognitoSignUpOptions(userAttributes: userAttributes),
      );
      return result;
    } on AuthException catch (e) {
      safePrint(e.message);
      rethrow;
    }
  }
  • Verify OTP Code – After successful user sign-up, Amplify Auth API will send a verification code to the registered email or phone number. The user must verify this code to complete the sign-up process.
optVerfication(
      {required String email,
      required String otp,
      required String password}) async {
    try {
      SignUpResult res = await Amplify.Auth.confirmSignUp(
        username: email,
        confirmationCode: otp,
      );
      if (res.isSignUpComplete) {
        await Amplify.Auth.signIn(username: email, password: password);
      }
      return res.isSignUpComplete;
    } on AuthException {
      rethrow;
    }
  }
  • Sign-In User – Amplify provides an API enabling users to sign in to a Flutter app seamlessly.
  Future<SignInResult> signInUser(
      String emailOrPhoneNumber, String password) async {
    try {
      await logOut();
      final result = await Amplify.Auth.signIn(
          username: emailOrPhoneNumber, password: password);
      return result;
    } on AuthException catch (e) {
      safePrint(e.message);
      rethrow;
    }
  }
  • Password Recovery – If the user forgets their password, Amplify provides an option to reset it.
// Start Password Recovery Process
  Future<ResetPasswordResult> forgetPassword(String email) async {
    try {
      return await Amplify.Auth.resetPassword(username: email);
    } on AuthException catch (e) {
      safePrint(e.message);
      rethrow;
    }
  }

// Confirm Reset Password
  Future<UpdatePasswordResult> resetPassword(
      String email, String newPassword, String confirmationCode) async {
    try {
      return await Amplify.Auth.confirmResetPassword(
        username: email,
        newPassword: newPassword,
        confirmationCode: confirmationCode,
      );
    } on AuthException catch (e) {
      safePrint(e.message);
      rethrow;
    }
  }
  • User Log Out – Amplify allows you to log out from the application seamlessly.
 logOut() async {
    try {
      await Amplify.Auth.signOut();
    } on AuthException {
      safePrint("Exception While Logging out");
    }
  }

With Amplify, you can easily integrate Flutter widgets into your app’s user interface. These widgets, like the `AmplifyAuthCognitoProvider` and `AmplifySignOutButton` can simplify the authentication process.

Conclusion

In this step-by-step guide, we explored the integration of Amplify Auth with Flutter, enabling secure authentication for your applications. By leveraging AWS Amplify’s authentication capabilities, you can ensure robust user data security while accelerating development. Follow this comprehensive tutorial to build powerful and secure Flutter apps with a seamless authentication experience.

Integrate AWS Amplify Flutter authentication today and unlock the potential of secure app development.

AWS Community Builder | Software Architect @ Gigaforce | Serverless | Aspiring Entrepreneur | Quirky Introvert­čśé

Leave a Reply

Your email address will not be published. Required fields are marked *