Cognito + Amplify Auth Flows
Building Secure, Scalable Sign-In with Google & Apple for Apps
Introduction
Every great app starts with a simple promise: “Log in, and your world syncs instantly.”
Behind that seamless experience is a complex system of user authentication, token management, and identity federation.
With AWS Cognito + Amplify gives you a powerful, production-ready foundation for managing users — from classic email/password logins to social sign-ins like Google and Apple.
In this post, we’ll walk through what Cognito is, how it works with Amplify, and how to set up a complete Flutter authentication flow — including Hosted UI, Pre-Sign-Up triggers, and social identity providers — step by step.
Goal of This Tutorial
By the end, you’ll have:
- A working Cognito User Pool connected to your Flutter app
- Secure email/password and Google + Apple sign-in options
- A Pre-Sign-Up Lambda to customize onboarding rules
- Clear insight into tokens, triggers, and federated flows
1. Understanding Cognito: The Foundation
Amazon Cognito is AWS’s managed service for user authentication and identity federation.
It comes with two core components:
User Pool
A user directory that stores users' credentials, handles sign-up/sign-in, password reset, email/phone verification, MFA, and returns secure JWT tokens (ID, Access, Refresh).
Identity Pool
Used to grant temporary AWS credentials (via IAM roles) so users can directly access AWS resources like S3 or DynamoDB.
Why It Matters
Cognito abstracts away the security-heavy parts of auth: password hashing, verification flows, token lifecycle, and compliance (HIPAA, GDPR). It scales to millions of users with minimal backend code.
Architecture Diagram:
Show “Flutter App → Amplify SDK → Cognito User Pool → Lambda Trigger → AWS APIs”. Caption: “Cognito Auth architecture flow with Amplify.”
2. How Cognito Keeps You Logged In
When a user signs in, Cognito returns three JWTs:
| Token Type | Purpose | Typical Expiry |
|---|---|---|
| ID Token | Contains user claims (name, email, etc.) | 1 hour |
| Access Token | Authorizes calls to Cognito APIs | 1 hour |
| Refresh Token | Used to get new tokens silently | Up to 30 days |
Amplify automatically handles refreshing tokens — your app just needs to check the session status.
3. Setting Up Cognito + Amplify in Flutter
Step 1. Initialize Amplify in Your Project
amplify init -> Choose your environment, editor, and default AWS region.
Step 2. Add Auth
amplify add auth -> Select the Default configuration with Social Provider, and choose Google and Apple.
Step 3. Push Changes
amplify push -> This creates your User Pool, optional Identity Pool, and generates a amplifyconfiguration.dart file for Flutter.
4. Integrate Amplify in Flutter
Add Dependencies
dependencies:
amplify_flutter: ^1.6.2
amplify_auth_cognito: ^1.6.2
Initialize in main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Amplify.addPlugin(AmplifyAuthCognito());
await Amplify.configure(amplifyconfig);
runApp(const MyApp());
}
Basic Auth Calls
// Sign Up
await Amplify.Auth.signUp(
username: email,
password: password,
options: CognitoSignUpOptions(userAttributes: {
CognitoUserAttributeKey.email: email,
}),
);
// Confirm
await Amplify.Auth.confirmSignUp(
username: email,
confirmationCode: code,
);
// Sign In
await Amplify.Auth.signIn(username: email, password: password);
5. Adding Google Sign-In (Hosted UI)
Google Sign-In uses OAuth2 federation through Cognito’s Hosted UI.
Here’s how to connect everything.
Step 1. Create a Google OAuth Client
- Go to Google Cloud Console → APIs & Services → Credentials
- Create OAuth Client ID
- Set bundle ID for iOS or package name + SHA-1 for Android
- Add redirect URI:
https://<your-cognito-domain>.auth.<region>.amazoncognito.com/oauth2/idpresponse
Step 2. Configure Google IdP in Cognito
Cognito → User Pool → Federation → Identity providers → Google
Paste client ID/secret and select scopes (openid, email, profile).
Step 3. Map Attributes
Map Google claims → Cognito attributes (email, given_name, etc.).
Step 4. Callback & Sign-Out URLs
Add both mobile deep links and the Cognito redirect in App Client Settings.
Step 5. Trigger Sign-In from Flutter,
await Amplify.Auth.signInWithWebUI(provider: AuthProvider.google);
Google Sign-In Flow:
“User → Cognito Hosted UI (Google OAuth) → Cognito → Amplify Flutter → App”
6. Adding Sign In with Apple (Hosted UI)
Apple requires all iOS apps offering third-party sign-in to also support Sign in with Apple.
Step 1. Apple Developer Setup
- Create a Services ID in Apple Developer Portal
- Generate Sign-in with Apple Key (
.p8) and note Key ID & Team ID - Add redirect URI:
https://<your-cognito-domain>.auth.<region>.amazoncognito.com/oauth2/idpresponse
Step 2. Configure Apple IdP in Cognito
Cognito → User Pool → Federation → Identity providers → Apple
Enter the IDs, upload .p8, select scopes (name, email).
Step 3. Sign in from Flutter
await Amplify.Auth.signInWithWebUI(provider: AuthProvider.apple);
Social Federation Overview:
Diagram comparing Google vs Apple sign-in paths, ending at the same Cognito User Pool.
7. Pre-Sign-Up Lambda: Customizing Registration
Cognito triggers let you hook custom logic into its lifecycle.
The Pre Sign-Up trigger runs before a user is created.
Common Use Cases
- Auto-confirm trusted domains (e.g.,
@hoomanely.com) - Block disposable emails
- Auto-verify emails from social logins
- Merge federated + native users
Example: Auto-Confirm and Block Temp Emails
exports.handler = async (event) => { const email = (event.request.userAttributes.email || '').toLowerCase(); const blocked = ['mailinator.com', 'tempmail.com']; const allowed = ['hoomanely.com']; if (blocked.some(d => email.endsWith(d))) { throw new Error('Disposable emails not allowed.');
} if (allowed.some(d => email.endsWith(d)) || event.triggerSource === 'PreSignUp_ExternalProvider') { event.response.autoConfirmUser = true; event.response.autoVerifyEmail = true;
} return event;
};
Attach this under:
User Pool → Triggers → Pre Sign-Up → Lambda Function.
8. MFA, Password Policy & Security
Cognito makes it easy to enforce security settings:
| Feature | Options | Notes |
|---|---|---|
| MFA | Off / Optional / Required | SMS or TOTP |
| Password Policy | Length, symbols, caps | Configurable in console |
| Adaptive Auth | Detects unusual login patterns | Paid tier |
| Token Lifetimes | Adjustable per client | Keep Access ≤ 1 hr |
Amplify handles token refresh automatically.
9. Identity Pools (Optional)
If your app uploads directly to S3, create an Identity Pool to map authenticated users to specific IAM roles.
Example IAM policy:
{
"Effect": "Allow",
"Action": ["s3:PutObject", "s3:GetObject"],
"Resource": ["arn:aws:s3:::your-bucket/public/${cognito-identity.amazonaws.com:sub}/*"]
}
Add it via:
amplify update auth
10. Deep Links & Redirect Configuration
| Platform | Callback URL | Setup |
|---|---|---|
| Web | https://yourapp.com/callback | Add in Cognito App Client |
| Android | myapp://auth/ | Add intent filter |
| iOS | applinks:link.yourapp.com | Enable Associated Domains |
Check your Google & Apple console redirect URIs match the Cognito domain exactly.
11. Verify Sessions & Sign Out
final session = await Amplify.Auth.fetchAuthSession() as CognitoAuthSession;
if (session.isSignedIn) {
print('Access token: ${session.userPoolTokens?.accessToken}');
}
await Amplify.Auth.signOut(options: const SignOutOptions(globalSignOut: true));
12. Common Issues & Fixes
| Issue | Cause | Fix |
|---|---|---|
| Invalid redirect URI | Mismatch in Cognito & provider | Copy exact URL |
| Apple name missing | Apple returns name only once | Store on first login |
| Email not verified | Federation users bypass verification | Use Pre Sign-Up trigger |
| Android Google errors | Wrong SHA-1 fingerprint | Regenerate in console |
| iOS Universal Links fail | AASA misconfigured | Verify domain JSON |
13. Quick Go-Live Checklist
- User Pool domain and Callback/Sign-Out URLs configured
- Google and Apple identity providers are properly linked
- Pre-Sign-Up Lambda trigger attached and tested
- MFA and Password Policy set according to your security standards
- Amplify Flutter integration verified on both iOS and Android
- (Optional) Identity Pool created for direct S3 access or other AWS resources
- Deep Links / Universal Links fully tested end-to-end across platforms
Key Takeaways
- Cognito + Amplify = Serverless Auth — secure, scalable, and quick to integrate.
- The Hosted UI simplifies OAuth with Google / Apple/others.
- Pre-Sign-Up Lambdas let you enforce domain rules or auto-verify social logins.
- Once configured, Amplify handles token refresh, MFA, and session management seamlessly.
End-to-End Auth Flow:
Diagram: “Flutter UI → Amplify Auth → Cognito → Lambda Triggers → AWS Services → User Session Persisted”.
Hoomanely Context: Why This Matters
At Hoomanely, we believe seamless onboarding is the gateway to better pet care experiences.
Our products — from the EverWiz app to Everbowl and personalized Paw Pulse insights — rely on frictionless, secure sign-in flows that let users switch devices and access their pet data effortlessly.
By building our authentication layer on AWS Cognito + Amplify, we ensure:
- Security that scales with our user base
- Compliance-ready infrastructure for sensitive pet data
- Single Sign-On experiences across Hoomanely’s ecosystem
Reference Documents:
Amazon Cognito Documentation — “Getting started” page: docs.aws.amazon.com/cognito/getting-started Amazon Web Services, Inc.
Cognito User Pools: Using Social/External Identity Providers (Google, Apple, etc.): docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-identity-provider.html AWS Documentation+1