Skip to content

Commit e205a50

Browse files
AWS-LanDingrlhagerm
authored andcommitted
Add a new web demo application for Amazon Cognito identity pool
1 parent 708c376 commit e205a50

File tree

23 files changed

+7053
-0
lines changed

23 files changed

+7053
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
FRONTEND_URL=http://localhost:8001
2+
3+
# Amazon Cognito configuration: replace these example values with your actual AWS configuration
4+
AWS_REGION=us-east-1
5+
AWS_ACCOUNT_ID=123456789012
6+
7+
# Amazon Cognito identity pools configuration: replace with your actual identity pool ID from the Amazon Cognito console
8+
COGNITO_IDENTITY_POOL_ID=us-east-1:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
9+
10+
# IAM role ARN for authenticated users: it grants permissions to users who have signed in
11+
AUTHENTICATED_ROLE_ARN=arn:aws:iam::123456789012:role/Cognito_IdentityPoolAuth_Role
12+
# IAM role ARN for unauthenticated users: it grants limited permissions to anonymous users
13+
UNAUTHENTICATED_ROLE_ARN=arn:aws:iam::123456789012:role/Cognito_IdentityPoolUnauth_Role
14+
15+
# Amazon Cognito user pool configuration
16+
COGNITO_USER_POOL_ID=us-east-1_EXAMPLE123
17+
COGNITO_APP_CLIENT_ID=1234567890abcdefEXAMPLE
18+
COGNITO_APP_CLIENT_SECRET=1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p7q8r9s0tEXAMPLE
19+
COGNITO_DOMAIN=example-domain
20+
21+
# Social identity providers: configure the social identity providers you want to use
22+
# 1. Google OAuth 2.0 configuration: obtain these values from the Google Cloud Console
23+
GOOGLE_CLIENT_ID=123456789012-abcdefghijklmnopqrstuvwxyzEXAMPLE.apps.googleusercontent.com
24+
GOOGLE_CLIENT_SECRET=GOCSPX-AbCdEfGhIjKlMnOpQrStUvWxYzEXAMPLE
25+
26+
# 2. Facebook login configuration: obtain these values from Facebook for developers
27+
FACEBOOK_APP_ID=1234567890123456
28+
FACEBOOK_APP_SECRET=a1b2c3d4e5f6g7h8i9j0k1l2m3n4oEXAMPLE
29+
30+
# 3. Login with Amazon configuration: obtain these values from the Amazon Developer Portal
31+
AMAZON_CLIENT_ID=amzn1.application-oa2-client.a1b2c3d4e5f6g7h8i9j0k1l2m3n4oEXAMPLE
32+
AMAZON_CLIENT_SECRET=amzn1.oa2-cs.v1.a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5zEXAMPLE
33+
34+
# Enterprise identity providers: configure enterprise identity providers for corporate authentication
35+
# 1. OpenID Connect (OIDC) provider configuration: replace with your OIDC provider's configuration
36+
37+
# For Okta, these would typically be:
38+
# OIDC_AUTHORIZATION_ENDPOINT=https://your-domain.okta.com/oauth2/default/v1/authorize
39+
# OIDC_TOKEN_ENDPOINT=https://your-domain.okta.com/oauth2/default/v1/token
40+
41+
# # For Auth0, these would typtically be:
42+
# OIDC_AUTHORIZATION_ENDPOINT=https://your-domain.us.auth0.com/authorize
43+
# OIDC_TOKEN_ENDPOINT=https://your-domain.us.auth0.com/oauth/token
44+
45+
OIDC_CLIENT_ID=oidc_client_1234567890abcdefEXAMPLE
46+
OIDC_CLIENT_SECRET=oidc_secret_a1b2c3d4e5f6g7h8i9j0k1l2m3n4oEXAMPLE
47+
OIDC_AUTHORIZATION_ENDPOINT=https://your-oidc-provider.com/oauth2/authorize
48+
OIDC_TOKEN_ENDPOINT=https://your-oidc-provider.com/oauth2/token
49+
OIDC_ISSUER=https://your-oidc-provider.com
50+
51+
# 2. SAML 2.0 provider configuration: replace with your SAML provider's configuration
52+
# For Okta SAML, these would typically be:
53+
# OKTA_DOMAIN=your-domain.okta.com
54+
# OKTA_APP_ID=exkABCDEF123456789
55+
SAML_SSO_URL=https://example.com/saml/sso
56+
SAML_ENTITY_ID=urn:amazon:cognito:sp:us-east-1:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
57+
SAML_PROVIDER=ExampleSAMLProvider
58+
SAML_PROVIDER_ARN=arn:aws:iam::123456789012:saml-provider/ExampleSAMLProvider
59+
60+
# Custom developer provider configuration: replace with your custom developer provider name
61+
DEVELOPER_PROVIDER_NAME=ExampleDeveloperProvider
62+
AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
63+
AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Lines changed: 278 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,278 @@
1+
# Amazon Cognito identity pools authentication flows demo
2+
3+
This interactive web application demonstrates how to use Amazon Cognito identity pools with multiple identity providers. The demo shows both enhanced flow and basic flow authentication patterns, providing developers with hands-on examples of real-world integration.
4+
5+
## About this demo
6+
7+
Amazon Cognito identity pools enable you to create unique identities for your users and federate them with identity providers. This demo focuses on:
8+
9+
* Demonstrating both enhanced and basic authentication flows in identity pools with detailed API call breakdowns
10+
* Implementing guest (unauthenticated) access to provide limited AWS service access without requiring sign-in
11+
* Integrating supported identity providers for different use cases:
12+
* Social identity providers (Facebook, Amazon, and Google) for consumer access
13+
* Enterprise identity providers (through OIDC or SAML) for corporate users
14+
* Amazon Cognito user pools for direct user management
15+
* Showing how to exchange identity provider tokens for temporary AWS credentials
16+
* Demonstrating how to use these credentials to access AWS services securely
17+
18+
**Note:** This demo is designed for educational purposes to help you understand identity pools and choose the right authentication approach for your applications.
19+
20+
## What's included
21+
22+
This demo includes the following features:
23+
24+
### Authentication flows
25+
* **Enhanced flow** – The recommended authentication flow that combines `GetId` and `GetCredentialsForIdentity` operations into a streamlined process
26+
* **Basic flow** – The traditional authentication flow with separate `GetId`, `GetOpenIdToken`, and `AssumeRoleWithWebIdentity` operations
27+
* **Interactive comparison** – Side-by-side demonstration of both flows with detailed API call visualization
28+
29+
### Supported identity providers
30+
31+
#### Social identity providers
32+
* **Google** – OAuth 2.0 implementation with Google Sign-In
33+
* **Facebook** – Facebook Login integration
34+
* **Login with Amazon** – Amazon OAuth 2.0 implementation
35+
36+
#### Enterprise identity providers
37+
* **OpenID Connect (OIDC)** – Generic OIDC provider support
38+
* **SAML 2.0** – Enterprise SAML integration with example Okta configuration
39+
40+
#### Amazon Cognito services
41+
* **Amazon Cognito user pools** – Username and password authentication with hosted UI
42+
43+
#### Custom authentication
44+
* **Developer provider** – Custom authentication system demonstration
45+
* **Unauthenticated access** – Guest credentials for anonymous users
46+
47+
### Key features
48+
* **Modal dialogs** – Educational content explaining flow differences and provider limitations
49+
* **Flow decision guidance** – Interactive help for choosing the right authentication approach
50+
* **Real-time results** – Live AWS credentials with proper expiration handling
51+
* **Security best practices** – Server-side token exchange and secure credential handling
52+
* **Comprehensive error handling** – User-friendly error messages and troubleshooting guidance
53+
54+
55+
## Prerequisites
56+
57+
Before you begin, ensure you have the following:
58+
59+
* **An AWS account** with access to Amazon Cognito. If you do not have an AWS account, see [Getting started with AWS](https://aws.amazon.com/getting-started/) to sign up for an AWS account and create a user with administrative access
60+
* **Python 3.8 or later** installed on your development machine
61+
* **Git** installed for cloning the repository
62+
* **AWS credentials configured** with appropriate permissions for making authenticated requests to AWS services.
63+
* **Developer accounts** for the identity providers you want to use (optional - you can start with one provider)
64+
65+
For detailed instructions on implementing AWS credentials and identity pool federation in your specific SDK, see the [Getting credentials documentation](https://docs.aws.amazon.com/cognito/latest/developerguide/getting-credentials.html).
66+
67+
## Quick Start
68+
69+
### Step 1. environment setup
70+
71+
1. Clone the repository and navigate to the web directory:
72+
```bash
73+
git clone <repository-url>
74+
cd identity_pools_example_demo/web
75+
```
76+
77+
2. Install the required dependencies:
78+
```bash
79+
pip install -r requirements.txt
80+
```
81+
82+
3. Create a `.env` file based on the `.env.example` template:
83+
```bash
84+
cp .env.example .env
85+
```
86+
87+
### 2. Configure your environment
88+
89+
Update the `.env` file with your AWS region, Identity Pool ID, and social provider credentials
90+
91+
### Step 3: Run the application
92+
93+
1. Start the backend server:
94+
```bash
95+
python backend/oauth_server.py
96+
```
97+
98+
You should see output similar to:
99+
```
100+
Starting OAuth server on port 8006...
101+
Server is running at http://localhost:8006
102+
```
103+
104+
2. In a new terminal, navigate to the frontend directory and start the frontend server:
105+
```bash
106+
cd frontend
107+
python -m http.server 8001
108+
```
109+
110+
You should see output similar to:
111+
```
112+
Serving HTTP on 0.0.0.0 port 8001 (http://0.0.0.0:8001/) ...
113+
```
114+
115+
3. Open your web browser and navigate to `http://localhost:8001`
116+
117+
If successful, you should see the demo application interface with options to explore different authentication flows.
118+
119+
## Identity pool setup
120+
121+
### Create identity pool
122+
123+
1. Open [Amazon Cognito Console](https://console.aws.amazon.com/cognito/)
124+
2. Choose **Identity pools****Create identity pool**
125+
3. Configure:
126+
* **User access**: Enable both **Authenticated** and **Guest access**
127+
* **Identity sources**: Select providers you plan to use
128+
4. Create IAM roles:
129+
* **Authenticated role**: `Cognito_IdentityPoolsDemo_Auth_Role`
130+
* **Guest role**: `Cognito_IdentityPoolsDemo_Unauth_Role`
131+
5. **Important**: Under **Basic (classic) authentication**, select **Activate basic flow**
132+
6. Note your **Identity Pool ID** and **Region**
133+
134+
### Configure identity providers
135+
136+
Add your configured providers to the identity pool:
137+
138+
1. In your identity pool, choose **Identity providers**
139+
2. Configure each provider with the appropriate App ID/Client ID
140+
3. For SAML: Add your SAML provider ARN
141+
4. For OIDC: Add your OIDC provider URL
142+
143+
## Provider configuration
144+
145+
### Google OAuth 2.0
146+
147+
1. [Google Cloud Console](https://console.cloud.google.com/)**Credentials**
148+
2. Create **OAuth client ID** (Web application)
149+
3. Add redirect URI: `http://localhost:8006/auth/google/callback`
150+
4. Note Client ID and Client Secret
151+
152+
### Facebook login
153+
154+
1. [Facebook for Developers](https://developers.facebook.com/) → Create App
155+
2. Add **Facebook Login** product
156+
3. Add redirect URI: `http://localhost:8006/auth/facebook/callback`
157+
4. Note App ID and App Secret
158+
159+
### SAML 2.0 (Example: Okta)
160+
161+
1. Okta Admin Console → Create SAML 2.0 app
162+
2. Single Sign On URL: `http://localhost:8006/auth/saml/callback`
163+
3. Configure attribute statements for AWS role mapping
164+
4. AWS IAM Console → Create SAML identity provider
165+
5. Upload Okta metadata document
166+
167+
### User pools
168+
169+
1. Cognito Console → **User pools** → Create or select pool
170+
2. **App integration** → Configure Hosted UI
171+
3. Callback URL: `http://localhost:8001/`
172+
4. Note User Pool ID, App Client ID, and App Client Secret
173+
174+
## How it works
175+
176+
### Enhanced flow (recommended)
177+
```
178+
User Authentication → Provider Token → GetCredentialsForIdentity → AWS Credentials
179+
```
180+
181+
**Benefits:**
182+
- Single API call
183+
- Simplified implementation
184+
- Better performance
185+
- Automatic role selection
186+
187+
### Basic Flow (Traditional)
188+
```
189+
User Authentication → Provider Token → GetId → GetOpenIdToken → AssumeRoleWithWebIdentity → AWS Credentials
190+
```
191+
192+
**Benefits:**
193+
- Granular control
194+
- Custom role selection
195+
- Token inspection capability
196+
- Legacy compatibility
197+
198+
### Flow selection guidance
199+
200+
The application provides interactive guidance:
201+
202+
* **Enhanced flow**: Recommended for new applications, mobile apps, and when you want simplified implementation
203+
* **Basic flow**: Choose when you need custom role selection logic or token inspection
204+
* **SAML limitation**: SAML providers only work with enhanced flow due to automatic role selection requirements
205+
206+
## Architecture
207+
208+
```
209+
Frontend (8001) Backend (8006) AWS Services
210+
├── Interactive UI ├── OAuth Server ├── Cognito Identity Pools
211+
├── Flow Demonstrations ├── Token Exchange ├── IAM Roles
212+
├── Educational Modals ├── Security Handling └── STS (Credentials)
213+
└── Real-time Results └── Provider Integration
214+
```
215+
216+
## Security features
217+
218+
* **Server-side token exchange** – Client secrets never exposed to browser
219+
* **Temporary credentials** – All AWS credentials have expiration times
220+
* **CORS protection** – Proper cross-origin request handling
221+
* **Error sanitization** – Sensitive information filtered from error messages
222+
223+
## Troubleshooting
224+
225+
### Common issues
226+
227+
**"Identity pool not found"**
228+
- Verify `IDENTITY_POOL_ID` in `.env` file
229+
- Check AWS region matches your identity pool
230+
231+
**"Provider not configured"**
232+
- Ensure provider is added to identity pool in AWS Console
233+
- Verify App ID/Client ID matches between provider and identity pool
234+
235+
**SAML "Basic flow not supported"**
236+
- SAML only works with enhanced flow
237+
- Modal dialog explains this limitation with documentation links
238+
239+
**OAuth callback errors**
240+
- Verify callback URLs match exactly in provider developer portals
241+
- Check that both servers are running (ports 8001 and 8006)
242+
243+
### Debug information
244+
245+
* Browser console shows detailed client-side logs
246+
* Server terminal displays backend processing information
247+
* API visualizer shows actual AWS API calls and responses
248+
249+
## What you'll learn
250+
251+
* **Flow Comparison** – When to use enhanced vs basic flow
252+
* **Provider Integration** – Real OAuth 2.0, SAML, and OIDC implementations
253+
* **Security Patterns** – Proper credential handling and token exchange
254+
* **AWS API Usage** – Direct interaction with Cognito and STS APIs
255+
* **Error Handling** – Production-ready error management
256+
* **Decision Making** – Interactive guidance for architecture choices
257+
258+
## Production Considerations
259+
260+
Before deploying to production:
261+
262+
1. **HTTPS Configuration** – Enable SSL/TLS
263+
2. **Environment Variables** – Use secure secret management
264+
3. **CORS Configuration** – Restrict to your domain
265+
4. **Error Handling** – Implement comprehensive logging
266+
5. **Rate Limiting** – Add request throttling
267+
6. **Monitoring** – Set up CloudWatch metrics
268+
269+
## Additional Resources
270+
271+
* [Amazon Cognito Identity Pools Developer Guide](https://docs.aws.amazon.com/cognito/latest/developerguide/identity-pools.html)
272+
* [Authentication Flow Documentation](https://docs.aws.amazon.com/cognito/latest/developerguide/authentication-flow.html)
273+
* [AWS SDK for Python (Boto3)](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html)
274+
* [OAuth 2.0 Security Best Practices](https://tools.ietf.org/html/draft-ietf-oauth-security-topics)
275+
276+
## License
277+
278+
This project is licensed under the Apache License 2.0. See the LICENSE file for details.
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
import os
5+
from dotenv import load_dotenv
6+
7+
# Load .env file from web directory
8+
web_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
9+
load_dotenv(os.path.join(web_dir, '.env'), override=True)
10+
11+
COGNITO_CONFIG = {
12+
'REGION': os.getenv('AWS_REGION'),
13+
'USER_POOL_ID': os.getenv('COGNITO_USER_POOL_ID'),
14+
'IDENTITY_POOL_ID': os.getenv('COGNITO_IDENTITY_POOL_ID'),
15+
'APP_CLIENT_ID': os.getenv('COGNITO_APP_CLIENT_ID'),
16+
'APP_CLIENT_SECRET': os.getenv('COGNITO_APP_CLIENT_SECRET'),
17+
'DOMAIN': os.getenv('COGNITO_DOMAIN'),
18+
'ACCOUNT_ID': os.getenv('AWS_ACCOUNT_ID'),
19+
'SAML_PROVIDER': os.getenv('SAML_PROVIDER'),
20+
'OIDC_PROVIDER_URL': os.getenv('OIDC_PROVIDER_URL'),
21+
'DEVELOPER_PROVIDER_NAME': os.getenv('DEVELOPER_PROVIDER_NAME'),
22+
'AUTHENTICATED_ROLE_ARN': os.getenv('AUTHENTICATED_ROLE_ARN'),
23+
'UNAUTHENTICATED_ROLE_ARN': os.getenv('UNAUTHENTICATED_ROLE_ARN')
24+
}
25+
26+
# Validate required configuration
27+
try:
28+
from backend.config.env_config import validate_required_env_vars
29+
validate_required_env_vars()
30+
except ImportError:
31+
pass

0 commit comments

Comments
 (0)