Front-End Web & Mobile

AWS Amplify supports Time-Based One-Time Password (TOTP) for MFA on Android, Swift, and Flutter

We’re excited to announce that AWS Amplify now supports TOTP (Time-based One-Time Password) as a multifactor authentication method for Swift, Android, and Flutter apps. This enables you to easily add TOTP as a two-factor authentication method to your mobile and cross-platform apps built with Amplify.

Implementing TOTP strengthens the security of your app by requiring users to enter a code from an authenticator app in addition to their username and password when signing in. You can now enable TOTP for individual users or make it a requirement for all users in your Amazon Cognito userpools with just a few lines of code.

With this streamlined TOTP integration, you can focus on the core features of your app, rather than implementing additional layers of security for your authentication flow. In this blog post, we will show you how to add TOTP to a new Flutter project, and then use the Amplify Flutter Authenticator connected UI component to scaffold the sign up and sign in experience with less than 10 lines of code.

Authenticator TOTP GIF

Prerequisites

To follow this tutorial, you need the following prerequisites installed:

  • Flutter SDK version 3.10.0 or higher
  • An AWS Account with AWS Amplify CLI setup. You can follow this documentation to setup the Amplify CLI.

Create your App and add the Amplify libraries

You can get started by creating a new Flutter app. Go to your terminal and create a new Flutter app, then navigate to that new app

flutter create myapp
cd myapp

We will now install the Amplify libraries for communication with the authentication resources which we will set up in a later step. We will also use the Authenticator connected UI component, which will take care of scaffolding the sign up and sign in experience for us. In this tutorial, we will be running the app on an iOS and Android device. To learn more about using Amplify Flutter to target web or desktop you can visit Amplify Flutter platform setup documentation.

First, go to your iOS folder in your project folder, and find your Podfile. Then, change your iOS version to the following:

platform :ios, '13.0'

For targeting Android, go to your Android/app/gradle.build file, and change the minsdkVersion version to 25.

defaultConfig {
        applicationId "com.example.totp"
        minSdkVersion 25

Then, go to your pubspec.yaml file, and add the following libraries. Save the file, and these libraries will get installed in your app.

dependencies:
  amplify_auth_cognito: ^1.0.0
  amplify_authenticator: ^1.0.0
  amplify_flutter: ^1.0.0
  flutter:
    sdk: flutter

Now, go to your lib/main.dart file and replace its content with the following code. Your materialWidget is wrapped with the Authenticator which will handle the sign up and sign in flow, registering your TOTP device, and validating your identity.

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({super.key});

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

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

  // Configure Amplify and add Auth
  void _configureAmplify() async {
    try {
      await Amplify.addPlugin(AmplifyAuthCognito());
      await Amplify.configure(amplifyconfig);
      safePrint('Successfully configured');
    } on Exception catch (e) {
      safePrint('Error configuring Amplify: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Authenticator(
      child: MaterialApp(
        theme: ThemeData(useMaterial3: true),
        // Wrap the entry point of the app with the Authenticator
        builder: Authenticator.builder(),
        home: Scaffold(
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Text('You are logged in!'),
                ElevatedButton(
                    onPressed: () async => await Amplify.Auth.signOut(),
                    child: const Text("SignOut"))
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Now that your Flutter UI is setup to handle your authentication flow, let’s set up the necessary backend resources.

Setting up your backend resources

Now we will use the Amplify CLI to add backend resources, in our case we will configure the Amplify Auth category for handling user sign in and registration. You can initialize a new Amplify project by navigating to the root directory of your Flutter project in your terminal. Run the following command:

amplify init

You can then follow the prompts from the CLI — you can use the default configuration options you are presented with.

? Enter a name for the project MyAmplifyApp
The following configuration will be applied:

Project information
| Name: MyAmplifyApp
| Environment: dev
| Default editor: Visual Studio Code
| App type: ios


? Initialize the project with the above configuration? Yes
Using default provider awscloudformation
? Select the authentication method you want to use: AWS profile

Deployment state saved successfully.
✔ Initialized provider successfully.
✅ Initialized your environment successfully.

You can now add authentication with Amazon Cognito to your app. You can run amplify add auth in your terminal and select “manual configuration” when prompted. Select email as your login mechanism for users, and turn on MFA for all users that try to sign in to the app using TOTP. You also have the ability to turn on SMS MFA if you need it in your app.

amplify add auth

Do you want to use the default authentication and security configuration? Manual configuration
 
Select the authentication/authorization services that you want to use: User Sign-Up, Sign-In, connected with AW
S IAM controls (Enables per-user Storage features for images or other content, Analytics, and more)
Allow unauthenticated logins? (Provides scoped down permissions that you can control via AWS IAM) No
Do you want to enable 3rd party authentication providers in your identity pool? No
Do you want to add User Pool Groups? No
Do you want to add an admin queries API? No
Multifactor authentication (MFA) user login options: ON
For user login, select the MFA types: Time-Based One-Time Password (TOTP)
Specify an SMS authentication message: Your authentication code is {####}
Email based user registration/forgot password: Enabled (Requires per-user email entry at registration)
Specify an email verification subject: Your verification code
Specify an email verification message: Your verification code is {####}
Do you want to override the default password policy for this User Pool? No
Specify the app's refresh token expiration period (in days): 30
Do you want to specify the user attributes this app can read and write? No
Do you want to enable any of the following capabilities? 
Do you want to use an OAuth flow? No
? Do you want to configure Lambda Triggers for Cognito? Yes
? Which triggers do you want to enable for Cognito 
 
 Multifactor authentication (MFA) user login options: ON (Required for all logins, can not be enable
d later)
 For user login, select the MFA types: Time-Based One-Time Password (TOTP)
   
✅ Successfully added auth resource auth locally

To deploy your authentication resources run the following command in your terminal:

amplify push

Your backend is now set up and ready to be used for authentication and enforcing MFA with TOTP for all your users. You can run your Flutter app in your IDE, sign up new users, and set up an authenticator app.

Clean up

To ensure that you don’t have any unused resources in you AWS account, run the following command to delete all the resources that were created in this project if you don’t intend to keep them.

amplify delete

What we’ve built

Integrating TOTP support in AWS Amplify makes adding robust two-factor authentication simple for mobile and cross-platform apps. By enabling TOTP with just a few lines of code, you can now easily implement secure authentication flows for your users

To build apps with AWS Amplify you can visit our Amplify Auth documentation. To stay connected with our community, follow us on Github, and join our Discord server.