Page updated Mar 6, 2024

Set up Amplify Auth

The Amplify Auth category provides an interface for authenticating a user. Behind the scenes, it provides the necessary authorization to the other Amplify categories. It comes with default, built-in support for Amazon Cognito User Pool and Identity Pool. The Amplify CLI helps you create and configure the auth category with an authentication provider.

Goal

To setup and configure your application with Amplify Auth and go through a simple api to check the current auth session.

Prerequisites

A Flutter application targeting Flutter SDK >= 3.3.0 with Amplify libraries integrated.

Amplify requires a minimum target platform for iOS (13.0), Android (API level 24), and macOS (10.15). Additional setup is required for some target platforms. Please see the platform setup guide for more details on platform specific setup.

Install Amplify Libraries

Add the following dependency to your app's pubspec.yaml along with others you added above in Prerequisites:

1environment:
2 sdk: ">=2.18.0 <4.0.0"
3 flutter: ">=3.3.0"
4
5dependencies:
6 flutter:
7 sdk: flutter
8
9 amplify_flutter: ^1.0.0
10 amplify_auth_cognito: ^1.0.0

Set Up Backend Resources

The most common way to use Authentication with Amplify is via the Amplify CLI, which allows you to create new Amazon Cognito resources or import existing ones. However, you can also use the Amplify Studio console to configure authentication or use the Amplify.configure() method to set up authentication with existing resources.

Prerequisites: Install and configure the Amplify CLI in addition to the Amplify libraries and necessary dependencies.

To start provisioning auth resources in the backend, go to your project directory and execute the command:

1amplify add auth

Enter the following when prompted:

1? Do you want to use the default authentication and security configuration?
2 `Default configuration`
3? How do you want users to be able to sign in?
4 `Username`
5? Do you want to configure advanced settings?
6 `No, I am done.`

If you have previously enabled an Amplify category that uses Auth behind the scenes (e.g. API category), you can run the amplify update auth command to edit your configuration if needed.

To push your changes to the cloud, execute the command:

1amplify push

Upon completion, amplifyconfiguration.dart should be updated to reference provisioned backend auth resources. Note that these files should already be a part of your project if you followed the Project setup walkthrough.

Prerequisites: Install and configure the Amplify CLI in addition to the Amplify libraries and necessary dependencies.

To import existing Amazon Cognito resources into your Amplify project, execute the command:

1amplify import auth
1? What type of auth resource do you want to import?
2 Cognito User Pool and Identity Pool
3 Cognito User Pool only

Once you've selected an option, you'll be able to search for and import an existing Cognito User Pool and Identity Pool (or User Pool only) within your AWS account. The amplify import auth command will also do the following:

  • Automatically populate your Amplify Library configuration file (amplifyconfiguration.dart) with your chosen Amazon Cognito resource information
  • Provide your designated existing Cognito resource as the authentication & authorization mechanism for all auth-dependent categories (API, Storage and more)
  • Enable Lambda functions to access the chosen Cognito resource if you permit it

If you have previously enabled an Amplify category that uses Auth behind the scenes (e.g. API category), you can run the amplify update auth command to edit your configuration if needed.

After configuring your Authentication options, update your backend and deploy the service by running the push command:

1amplify push

Now, the authentication service has been deployed and you can start using it. To view the deployed services in your project at any time, go to Amplify Console by running the following command:

1amplify console

For more details, see how to Use an existing Cognito User Pool and Identity Pool.

Prerequisites: Install and configure the Amplify CLI in addition to the Amplify libraries and necessary dependencies.

Amplify Studio allows you create auth resources, set up authorization rules, implement Multi-factor authentication (MFA), and more via an intuitive UI. To set up Authentication through the Amplify Studio, take the following steps:

  1. Sign in to the AWS Management Console and open AWS Amplify.
  2. In the navigation pane, choose an application.
  3. On the application information page, choose the Backend environments tab, then choose Launch Studio.
  4. On the Set up menu, choose Authentication.
  5. In the Configure log in section, choose a login mechanism to add from the Add login mechanism list. Valid options are Username, Phone number, Facebook, Google, Amazon, and Sign in with Apple. If you choose one of the social sign-in mechanisms (i.e. Facebook, Google, Amazon, or Sign in with Apple), you will also need to enter your App ID, App Secret, and redirect URLs.
  6. (Optional) Add multi-factor authentication (MFA). MFA is set to Off by default. To turn on MFA, do the following in the Multi-factor authentication section:
  • Choose Enforced to require MFA for all users or choose Optional to allow individual users to enable MFA.
  • (Optional) Choose SMS, and enter your SMS message.
  • (Optional) Choose Authenticator Application if you want your app to load with an authentication flow that includes sign up and sign in.
  1. In the Configure sign up section, expand Password protection settings and customize the password policy settings to enforce. u6. Choose Save and Deploy. This starts a CloudFormation deployment with the progress displayed in the upper right corner of the page.
  2. After creating and configuring your auth resources, you'll need to pull them down from Amplify Studio. To do so, simply click on "Local setup instructions" in the upper right hand corner of the Studio console and execute the CLI command it provides at the root directory of your app.

You can also import existing Amazon Cognito resources and manage users and groups through the Amplify Studio UI.

Existing Authentication resources from AWS (e.g. Amazon Cognito UserPools or Identity Pools) can be used with the Amplify Libraries by calling the Amplify.configure() method.

If you are not using the Amplify CLI, a Cognito User Pool and Identity Pool can be used by referencing them in your amplifyconfiguration.dart file:

1const amplifyconfig = ''' {
2 "UserAgent": "aws-amplify-cli/2.0",
3 "Version": "1.0",
4 "auth": {
5 "plugins": {
6 "awsCognitoAuthPlugin": {
7 "IdentityManager": {
8 "Default": {}
9 },
10 "CredentialsProvider": {
11 "CognitoIdentity": {
12 "Default": {
13 "PoolId": "[COGNITO IDENTITY POOL ID]",
14 "Region": "[REGION]"
15 }
16 }
17 },
18 "CognitoUserPool": {
19 "Default": {
20 "PoolId": "[COGNITO USER POOL ID]",
21 "AppClientId": "[COGNITO USER POOL APP CLIENT ID]",
22 "Region": "[REGION]"
23 }
24 },
25 "Auth": {
26 "Default": {
27 "authenticationFlowType": "USER_SRP_AUTH",
28 "OAuth": {
29 "WebDomain": "[YOUR COGNITO DOMAIN ]",
30 "AppClientId": "[COGNITO USER POOL APP CLIENT ID]",
31 "SignInRedirectURI": "[CUSTOM REDIRECT SCHEME AFTER SIGN IN, e.g. myapp://]",
32 "SignOutRedirectURI": "[CUSTOM REDIRECT SCHEME AFTER SIGN OUT, e.g. myapp://]",
33 "Scopes": [
34 "phone",
35 "email",
36 "openid",
37 "profile",
38 "aws.cognito.signin.user.admin"
39 ]
40 }
41 }
42 }
43 }
44 }
45 }
46}''';
  • CredentialsProvider:
    • Cognito Identity:
      • Default:
        • PoolID: ID of the Amazon Cognito Identity Pool (e.g. us-east-1:123e4567-e89b-12d3-a456-426614174000)
        • Region: AWS Region where the resources are provisioned (e.g. us-east-1)
  • CognitoUserPool:
    • Default:
      • PoolId: ID of the Amazon Cognito User Pool (e.g. us-east-1_abcdefghi)
      • AppClientId: ID for the client used to authenticate against the user pool
      • Region: AWS Region where the resources are provisioned (e.g. us-east-1)
  • Auth:
    • Default:
      • authenticationFlowType: The authentication flow type, takes values USER_SRP_AUTH, CUSTOM_AUTH, and USER_PASSWORD_AUTH. Default is USER_SRP_AUTH.
      • OAuth: Hosted UI Configuration (only include this if using the Hosted UI flow)
        • Scopes: Scopes should match the scopes enables in Cognito under "App client settings"

If you are using a Cognito User Pool without a Cognito Identity Pool, you can omit the CredentialsProvider section in the configuration.

Initialize Amplify Auth

Add the Auth plugin, along with any other plugins you may have added as described in the Prerequisites section. To complete initialization call Amplify.configure().

Your code should look like this:

1import 'package:amplify_flutter/amplify_flutter.dart';
2import 'package:amplify_auth_cognito/amplify_auth_cognito.dart';
3import 'package:flutter/material.dart';
4
5import 'amplifyconfiguration.dart';
6
7void main() {
8 runApp(const MyApp());
9}
10
11class MyApp extends StatefulWidget {
12 const MyApp({super.key});
13
14
15 State<MyApp> createState() => _MyAppState();
16}
17
18class _MyAppState extends State<MyApp> {
19
20 void initState() {
21 super.initState();
22 _configureAmplify();
23 }
24
25 Future<void> _configureAmplify() async {
26 try {
27 final auth = AmplifyAuthCognito();
28 await Amplify.addPlugin(auth);
29
30 // call Amplify.configure to use the initialized categories in your app
31 await Amplify.configure(amplifyconfig);
32 } on Exception catch (e) {
33 safePrint('An error occurred configuring Amplify: $e');
34 }
35 }
36
37
38 Widget build(BuildContext context) {
39 return const MaterialApp(
40 home: Scaffold(
41 body: SizedBox(),
42 ),
43 );
44 }
45}

Authentication with Amplify

There are 2 options to add authentication capabilities to your application:

  • Option 1: Use Amplify Authenticator UI Library
  • Option 2: Call Authentication APIs manually

Option 1: Use Authenticator UI Library

The Amplify Authenticator UI library allows you to quickly create an authentication/registration flow within your app. The experience generated within your app will be determined by the amplifyconfiguration.dart file that is automatically generated for you after initializing your app, and adding auth or other categories.

Visit https://ui.docs.amplify.aws/flutter/components/authenticator to get started.

Option 2: Call Authentication APIs manually

Follow the instructions in Sign In to learn about how to integrate these authentication flows in your application with the Auth APIs.

Check the current auth session

You can now check the current auth session.

After implementing Authentication in your app, you can check if a user is logged in. CognitoAuthSession will have the isSignedIn property set to false if the user has not signed in to your app. You can see how it works by using the below function:

1Future<bool> isUserSignedIn() async {
2 final result = await Amplify.Auth.fetchAuthSession();
3 return result.isSignedIn;
4}

In case you want to get the current user information, you can use the code below:

1Future<AuthUser> getCurrentUser() async {
2 final user = await Amplify.Auth.getCurrentUser();
3 return user;
4}

AuthUser will have the userId and username will have the user details if they were logged in.

The isSignedIn property of the authSession will be false since you haven't signed in to the category yet.

Next Steps

Congratulations! You've successfully setup AWS Cognito Auth plugin. Check out the following links to see other Amplify Auth use cases: