AWS Cognito
source: https://www.youtube.com/watch?v=rrCF2sd1FGQ
Amazon Cognito Authentication Implementation in Flutter Using AWS Amplify¶
Overview¶
This guide covers implementing Amazon Cognito authentication in a Flutter app using AWS Amplify, divided into two main parts:
- Creating an Amazon Cognito User Pool
- Integrating Cognito authentication in a Flutter app
Part 1: Creating Amazon Cognito User Pool¶
What is Amazon Cognito User Pool¶
A user directory where all application users are registered. It simplifies implementation of:
- Login/registration
- Forgot password functionality
- Multi-factor authentication
Creating the User Pool¶
Step 1: Initial Configuration - Navigate to AWS Console and search for "Cognito" - Select "Create user pool" - Choose authentication provider: Cognito user pool (not Federated identity providers) - Sign-in option: Email - Password policy: Cognito defaults - Multi-factor authentication: No MFA (for demo purposes)
Step 2: User Attributes - Required attributes: Name and Email - Email is automatically mandatory when selected as sign-in option
Step 3: Email Configuration - Select "Send email with Cognito"
Step 4: User Pool Settings - User pool name: Provide unique name (e.g., "cognito_flutter_demo") - Hosted UI: Not needed - Initial app client: Public client - Do not generate client secret
Step 5: Important Information to Save - Cognito User Pool ID - App Client ID (found in App Integration → App Client List)
Part 2: Flutter App Integration¶
Creating Flutter Application¶
Option 1: Command Line
Option 2: VS Code - Press Ctrl+Shift+P - Type "Flutter" - Select "Flutter: New Project" - Choose "Application" - Select folder location - Provide project name in lowercase with underscores
Installing Required Packages¶
Install Amplify libraries:
These commands automatically update pubspec.yaml file.
Install UI components:
Configuring Amplify¶
Step 1: Create Configuration File
- Create amplifyconfiguration.dart in the lib folder
- Add the following configuration:
const amplifyconfig = '''{
"UserAgent": "aws-amplify-cli/2.0",
"Version": "1.0",
"auth": {
"plugins": {
"awsCognitoAuthPlugin": {
"IdentityManager": {
"Default": {}
},
"CognitoUserPool": {
"Default": {
"PoolId": "YOUR_USER_POOL_ID",
"AppClientId": "YOUR_APP_CLIENT_ID",
"Region": "ap-south-1"
}
},
"Auth": {
"Default": {
"authenticationFlowType": "USER_SRP_AUTH",
"usernameAttributes": ["EMAIL"],
"signupAttributes": ["EMAIL", "NAME"],
"passwordProtectionSettings": {
"passwordPolicyMinLength": 8,
"passwordPolicyCharacters": []
}
}
}
}
}
}
}''';
Important Configuration Notes:
- Remove credential provider section (for Cognito Identity Pool) if not using AWS services
- Remove hosted UI section if not using hosted authentication
- Include usernameAttributes, signupAttributes, and passwordProtectionSettings to avoid runtime errors
Step 2: Update Main Application File
Replace main.dart content with:
import 'package:amplify_flutter/amplify_flutter.dart';
import 'package:amplify_auth_cognito/amplify_auth_cognito.dart';
import 'package:amplify_authenticator/amplify_authenticator.dart';
import 'amplifyconfiguration.dart';
Future<void> _configureAmplify() async {
try {
await Amplify.addPlugin(AmplifyAuthCognito());
await Amplify.configure(amplifyconfig);
} on Exception catch (e) {
safePrint('Error configuring Amplify: $e');
}
}
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();
}
@override
Widget build(BuildContext context) {
return Authenticator(
child: MaterialApp(
builder: Authenticator.builder(),
home: const Scaffold(
body: Center(
child: Text('You are logged in'),
),
),
),
);
}
}
Customizing Sign-Up Form¶
To control field order and appearance:
Authenticator(
signUpForm: SignUpForm.custom(
fields: [
SignUpFormField.name(required: true),
SignUpFormField.email(required: true),
SignUpFormField.password(),
SignUpFormField.passwordConfirmation(),
],
),
child: // your child widget
)
Running the Application¶
Web Browser:
- Press Ctrl+Shift+P
- Type "Flutter: Select Device"
- Choose Chrome
- Run from main.dart
Android Emulator: - Open Android Studio Device Manager - Start desired emulator - Select device in VS Code - Run application
Common Android Issues:
Update android/app/build.gradle:
Accessing User Information¶
Amplify provides libraries to access: - Current user session - User attributes - ID tokens and access tokens - AWS credentials
Reference the AWS Amplify Flutter documentation for specific methods.
Key Features¶
- User registration with email verification
- User login/logout
- Password validation
- Automatic UI component generation
- Cross-platform support (Web, Android, iOS)
- No need to manually manage user directories
Important Notes¶
- Amplify configuration must include
usernameAttributes,signupAttributes, andpasswordProtectionSettings - Email is automatically required when set as sign-in option
- Custom attributes marked as required in User Pool must be included in
signupAttributes - Amplify Authenticator provides pre-built UI components
- No need for Amplify CLI; manual resource creation provides more control