AWS Cognito authentication CLI tool for seamless AWS CLI integration with temporary credential management.
Project description
AWS Cognito Authoriser
A robust command-line tool that provides seamless authentication with AWS Cognito User Pool and Identity Pool, automatically obtaining temporary AWS credentials that work without requiring local AWS profile configuration.
๐ Overview
The AWS Cognito Authoriser solves a critical problem in AWS authentication workflows: obtaining temporary AWS credentials for CLI and SDK usage without requiring pre-configured AWS profiles or permanent credentials. It leverages AWS Cognito's User Pool for authentication and Identity Pool for credential exchange, with an optional Lambda proxy for extended credential duration.
Key Features
- ๐ Secure Authentication: Authenticates users via AWS Cognito User Pool
- โฑ๏ธ Flexible Credential Duration: 1-hour (Identity Pool) or up to 12-hour (Lambda proxy) credentials
- ๐ก๏ธ No AWS Profile Required: Works in environments without pre-configured AWS credentials
- ๐ฆ Multiple Service Integration: Supports S3, DynamoDB, Lambda, and other AWS services
- ๐ง Automated Setup: Helper scripts for complete AWS infrastructure deployment
- ๐ Role Management: Built-in tools for managing IAM policies and permissions
- ๐ฏ Profile Management: Updates standard AWS credentials and config files
- ๐ Graceful Fallback: Always provides working credentials with intelligent upgrading
๐๏ธ Architecture
The system consists of three main components:
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ CLI Tool โโโโโถโ Cognito Identity โโโโโถโ Lambda Proxy โ
โ โ โ Pool (1hr creds) โ โ (12hr creds) โ
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ โ โ
โผ โผ โผ
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ User Pool Auth โ โ IAM Role โ โ Long-lived Role โ
โ โ โ (Cognito Auth) โ โ (Extended) โ
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
Authentication Flow
- User Authentication: Authenticate with Cognito User Pool using username/password
- Identity Pool Exchange: Exchange ID token for 1-hour AWS credentials via Identity Pool
- Lambda Upgrade (Optional): Attempt to upgrade to 12-hour credentials via Lambda proxy
- Credential Storage: Update AWS credentials file for seamless CLI/SDK usage
๐ฆ Installation
Prerequisites
- Python 3.7+
- AWS account with Cognito services
- Basic understanding of AWS IAM roles and policies
Quick Start
-
Clone the repository:
git clone <repository-url> cd aws-authoriser
-
Install the package:
pip install -e .
-
Configure the tool:
cogauth configure -
Login and get credentials:
cogauth login -u your-username
โ๏ธ Configuration
Method 1: Interactive Configuration
cogauth configure
Method 2: Environment Variables
export COGNITO_USER_POOL_ID="us-east-1_xxxxxxxxx"
export COGNITO_CLIENT_ID="your-client-id"
export COGNITO_IDENTITY_POOL_ID="us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
export AWS_REGION="us-east-1"
Method 3: Configuration File
Create ~/.cognito-cli-config.json:
{
"user_pool_id": "us-east-1_xxxxxxxxx",
"client_id": "your-client-id",
"identity_pool_id": "us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"region": "us-east-1"
}
๐ฏ Usage
Authentication Client Commands
# Check configuration status
cogauth status
# Configure authentication settings
cogauth configure
# Login with username prompt
cogauth login
# Login with specific username
cogauth login -u your-username
# Login and update specific AWS profile
cogauth login -u your-username --profile my-profile
# Skip Lambda proxy and use only Identity Pool credentials
cogauth login -u your-username --no-lambda-proxy
# Set credential duration (Lambda proxy only)
cogauth login -u your-username --duration 8
# Get help
cogauth --help
Administrative Commands
# View Identity Pool role information
cogadmin role info
# Create S3 access policy for a bucket
cogadmin policy create-s3-policy --bucket-name my-bucket
# Create S3 policy with user isolation (Cognito identity-based)
cogadmin policy create-s3-policy --bucket-name my-bucket --user-specific
# Create DynamoDB access policy with user isolation
cogadmin policy create-dynamodb-policy --table-name my-table
# Apply custom policy from JSON file
cogadmin role apply-policy --policy-file custom-policy.json --policy-name MyPolicy
# Deploy Lambda credential proxy
cogadmin lambda deploy --access-key-id AKIA... --secret-access-key ...
# Create new IAM user for Lambda proxy (requires admin permissions)
cogadmin lambda deploy --create-user
# Set up new Cognito Identity Pool interactively
cogadmin setup-identity-pool
# Get help for admin commands
cogadmin --help
Example Workflow
# 1. Configure once
cogauth configure
# 2. Login and get credentials
cogauth login -u myuser
# Sample output:
# ๐ซ Getting temporary credentials from Cognito Identity Pool...
# โ
Successfully obtained Identity Pool credentials (expires at 2025-08-12 14:30:00 PST)
# ๐ซ Attempting to upgrade to longer-lived credentials via Lambda proxy...
# โ
Successfully upgraded to longer-lived credentials (expires at 2025-08-13 01:30:00 PST)
# 3. Use AWS CLI commands
aws s3 ls
aws sts get-caller-identity
aws s3 sync s3://my-bucket/my-folder ./local-folder
๐ ๏ธ AWS Infrastructure Setup
Option 1: Automated Setup (Recommended)
Use the provided administrative commands:
# Deploy complete Lambda infrastructure with new IAM user
cogadmin lambda deploy --create-user
# Or deploy with existing IAM user credentials
cogadmin lambda deploy --access-key-id AKIA... --secret-access-key ...
# Set up new Cognito Identity Pool interactively
cogadmin setup-identity-pool
# View current role configuration
cogadmin role info
Option 2: Manual Setup
If you prefer to set up AWS infrastructure manually, follow these steps:
1. Cognito User Pool
Create a User Pool with the following settings:
- Sign-in options: Username
- Password policy: As per your security requirements
- MFA: Optional but recommended
- App client:
- Client type: Public client
- Authentication flows:
ALLOW_USER_PASSWORD_AUTH,ALLOW_REFRESH_TOKEN_AUTH
Required information:
- User Pool ID (format:
us-east-1_xxxxxxxxx) - App Client ID
2. Cognito Identity Pool
Create an Identity Pool with:
- Authentication providers: Cognito User Pool
- User Pool ID: Your User Pool ID from step 1
- App Client ID: Your App Client ID from step 1
Required information:
- Identity Pool ID (format:
us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
3. IAM Roles
The Identity Pool creates two roles automatically. You need to configure the authenticated role:
Minimum permissions for Cognito authenticated role:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "cognito-identity:GetCredentialsForIdentity",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "lambda:InvokeFunction",
"Resource": "arn:aws:lambda:REGION:ACCOUNT:function:cognito-credential-proxy"
}
]
}
4. Lambda Proxy (Optional - for 12-hour credentials)
Create a Lambda function with:
- Runtime: Python 3.9+
- Code: Use
src/aws_cognito_auth/lambda_function.py - Environment variables:
IAM_USER_ACCESS_KEY_ID: IAM user access key IDIAM_USER_SECRET_ACCESS_KEY: IAM user secret access keyDEFAULT_ROLE_ARN: Long-lived role ARN
IAM User for Lambda (minimum permissions):
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"sts:AssumeRole",
"sts:TagSession"
],
"Resource": "arn:aws:iam::ACCOUNT:role/CognitoLongLivedRole"
}
]
}
Long-lived Role Trust Policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::ACCOUNT:user/cognito-proxy-user"
},
"Action": "sts:AssumeRole",
"Condition": {
"StringEquals": {
"aws:RequestedRegion": ["us-east-1", "us-west-2", "ap-southeast-1"]
}
}
}
]
}
๐ Role and Policy Management
Role Manager Tool
The project includes comprehensive administrative tools for handling IAM policies and AWS infrastructure:
# View current Identity Pool role information
cogadmin role info
# Create S3 policy with user isolation (Cognito identity-based)
cogadmin policy create-s3-policy --bucket-name my-bucket --user-specific
# Create S3 policy with full bucket access
cogadmin policy create-s3-policy --bucket-name my-bucket
# Create DynamoDB policy with user isolation
cogadmin policy create-dynamodb-policy --table-name my-table
# Apply custom policy from JSON file
cogadmin role apply-policy --policy-file my-policy.json --policy-name MyPolicy
# Deploy Lambda credential proxy infrastructure
cogadmin lambda deploy --create-user
Service-Specific Permissions
S3 Access (User Isolation)
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
"Resource": "arn:aws:s3:::BUCKET/${cognito-identity.amazonaws.com:sub}/*"
},
{
"Effect": "Allow",
"Action": "s3:ListBucket",
"Resource": "arn:aws:s3:::BUCKET",
"Condition": {
"StringLike": {
"s3:prefix": "${cognito-identity.amazonaws.com:sub}/*"
}
}
}
]
}
DynamoDB Access
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:GetItem",
"dynamodb:PutItem",
"dynamodb:UpdateItem",
"dynamodb:DeleteItem",
"dynamodb:Query"
],
"Resource": "arn:aws:dynamodb:REGION:ACCOUNT:table/TABLE_NAME",
"Condition": {
"ForAllValues:StringEquals": {
"dynamodb:LeadingKeys": "${cognito-identity.amazonaws.com:sub}"
}
}
}
]
}
Lambda Execution
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "lambda:InvokeFunction",
"Resource": [
"arn:aws:lambda:REGION:ACCOUNT:function:user-function-*",
"arn:aws:lambda:REGION:ACCOUNT:function:cognito-credential-proxy"
]
}
]
}
๐ง Advanced Configuration
Environment Variables
# Cognito Configuration
export COGNITO_USER_POOL_ID="us-east-1_xxxxxxxxx"
export COGNITO_CLIENT_ID="your-client-id"
export COGNITO_IDENTITY_POOL_ID="us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
export AWS_REGION="us-east-1"
# Note: Lambda proxy credentials are configured in the Lambda function environment,
# not in the client application for security reasons
Multiple Environment Setup
# Development environment
cogauth login -u dev-user --profile development
# Production environment
cogauth login -u prod-user --profile production
# Use with different profiles
aws --profile development s3 ls
aws --profile production s3 ls
โ๏ธ Admin Configuration
Configuration System
The AWS Cognito Authoriser uses a hierarchical configuration system for administrative settings that allows you to customize AWS service names and parameters without modifying code.
Configuration Files
- Global Admin Config:
~/.cognito-admin-config.json- User-level settings - Local Project Config:
admin-config.json- Project-specific overrides - Default Values: Built-in defaults for all services
Interactive Configuration
Set up admin configuration interactively:
cogadmin configure
This command will prompt you to configure:
- AWS service names (IAM users, roles, Lambda functions)
- AWS configuration parameters (regions, timeouts, session duration)
- Policy names for all components
Configuration Template
Create admin-config.json in your project directory or ~/.cognito-admin-config.json in your home directory:
{
"aws_service_names": {
"iam_user_name": "CognitoCredentialProxyUser",
"lambda_execution_role_name": "CognitoCredentialProxyRole",
"long_lived_role_name": "CognitoLongLivedRole",
"lambda_function_name": "cognito-credential-proxy",
"identity_pool_name": "CognitoAuthIdentityPool",
"policy_names": {
"lambda_user_policy": "CognitoCredentialProxyPolicy",
"lambda_execution_policy": "CognitoCredentialProxyPolicy",
"s3_access_policy": "S3AccessPolicy"
}
},
"aws_configuration": {
"default_region": "ap-southeast-1",
"lambda_runtime": "python3.9",
"lambda_timeout": 30,
"max_session_duration": 43200,
"default_bucket": "my-s3-bucket"
}
}
Environment-Specific Configurations
Development Environment:
{
"aws_service_names": {
"long_lived_role_name": "CognitoDevRole",
"lambda_function_name": "cognito-proxy-dev"
},
"aws_configuration": {
"default_bucket": "my-dev-bucket"
}
}
Production Environment:
{
"aws_service_names": {
"long_lived_role_name": "CognitoProdRole",
"lambda_function_name": "cognito-proxy-prod"
},
"aws_configuration": {
"default_bucket": "my-prod-bucket",
"max_session_duration": 28800
}
}
Configuration Loading Priority
- Built-in defaults (lowest priority)
- Global config (
~/.cognito-admin-config.json) - Local project config (
admin-config.json) (highest priority)
Configurable Components
AWS Service Names
- IAM User Name: User for Lambda proxy authentication
- Lambda Execution Role: Role for Lambda function execution
- Long-lived Role: Role users assume for extended credentials
- Lambda Function Name: Name of the credential proxy function
- Identity Pool Name: Cognito Identity Pool name
AWS Configuration Parameters
- Default Region: Primary AWS region for deployments
- Lambda Runtime: Python version for Lambda functions
- Lambda Timeout: Function execution timeout in seconds
- Max Session Duration: Maximum credential lifetime (up to 12 hours)
- Default Bucket: S3 bucket for basic access policies
Policy Names
- Lambda User Policy: Policy for Lambda IAM user
- Lambda Execution Policy: Basic execution policy
- S3 Access Policy: Default S3 access policy name
Admin Features
The administrative tool provides comprehensive AWS infrastructure management:
# Configure admin settings interactively
cogadmin configure
# View Identity Pool role configuration
cogadmin role info
# Create service-specific policies
cogadmin policy create-s3-policy --bucket-name my-bucket --user-specific
cogadmin policy create-dynamodb-policy --table-name my-table
# Apply custom policies
cogadmin role apply-policy --policy-file custom-policy.json --policy-name MyPolicy
# Deploy Lambda infrastructure
cogadmin lambda deploy --create-user
# Set up new Cognito Identity Pool
cogadmin setup-identity-pool
๐ Monitoring and Logging
CloudWatch Logs
Monitor Lambda proxy execution:
aws logs tail /aws/lambda/cognito-credential-proxy --follow
Debug Mode
Enable detailed logging:
export BOTO_DEBUG=1
cogauth login -u username
โ Troubleshooting
Common Issues
| Issue | Solution |
|---|---|
| "Missing configuration" | Run configure command or set environment variables |
| "Invalid username or password" | Verify credentials in Cognito console; check if password reset needed |
| "Access denied" with AWS commands | Check IAM policies on Identity Pool authenticated role |
| "Lambda proxy failed" | Check Lambda function logs; verify IAM user permissions |
| "Unable to locate credentials" | Ensure fallback credentials are configured; check Lambda environment variables |
Error Messages
"Identity Pool configuration error"
- Solution: Configure Identity Pool to accept tokens from your User Pool
- Check: AWS Console โ Cognito โ Identity Pool โ Authentication providers
"AssumeRoleWithWebIdentity" access denied
- Solution: Update role trust policy to allow web identity federation
- Check: IAM role trust policy for Identity Pool authenticated role
"Lambda function not found"
- Solution: Deploy Lambda function using
cogadmin lambda deploy - Verify: Function name matches your configuration (default:
cognito-credential-proxy)
Testing Setup
# Test configuration
cogauth status
# Test authentication (will show detailed error messages)
cogauth login -u test-user
# Test AWS access
aws sts get-caller-identity
aws s3 ls
๐ Security Considerations
- Credentials Storage: Temporary credentials are stored in standard AWS credentials file
- Password Handling: Passwords are never logged or stored persistently
- Network Security: All communications use HTTPS/TLS
- Access Control: IAM policies enforce least-privilege access
- Credential Expiration: Automatic credential expiration (1-12 hours)
- Audit Trail: CloudTrail logs all AWS API calls made with temporary credentials
๐ Additional Resources
Project Files
src/aws_cognito_auth/client.py- Main authentication clientsrc/aws_cognito_auth/admin.py- Administrative tools for AWS infrastructuresrc/aws_cognito_auth/lambda_function.py- Lambda proxy functionpolicies/- IAM policy templates (JSON files)pyproject.toml- Project configuration and dependencies
AWS Services Used
- AWS Cognito User Pool: User authentication and management
- AWS Cognito Identity Pool: Temporary credential exchange
- AWS Lambda: Extended credential duration (optional)
- AWS IAM: Role and policy management
- AWS STS: Security Token Service for temporary credentials
๐ License
This project is provided as-is for educational and development purposes. Please review and adapt the code according to your security requirements before using in production environments.
๐ค Contributing
Contributions are welcome! Please ensure:
- Follow existing code style and patterns
- Add appropriate error handling
- Update documentation for new features
- Test thoroughly with different AWS configurations
โก Quick Start Summary:
pip install -e .cogauth configurecogauth login -u username- Use AWS CLI commands normally!
Repository initiated with fpgmaas/cookiecutter-uv.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file aws_cognito_auth-0.0.1.tar.gz.
File metadata
- Download URL: aws_cognito_auth-0.0.1.tar.gz
- Upload date:
- Size: 120.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.6.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d12986c0220d55fbfc192eb0f2d58466b99f901c7712185ac6d5d41d37daadbc
|
|
| MD5 |
3a157ed31a6ae4355a8ea45089c40985
|
|
| BLAKE2b-256 |
20f6326f9d842dc7e6f7f5a898fc86250c6461dbb8cb1af642290114a7b70229
|
File details
Details for the file aws_cognito_auth-0.0.1-py3-none-any.whl.
File metadata
- Download URL: aws_cognito_auth-0.0.1-py3-none-any.whl
- Upload date:
- Size: 23.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.6.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
af746f6bf5caf4bf74aba82849f2a1f316e1d48be61ba39513f59a4fe804f6b2
|
|
| MD5 |
e581a04163a73909280b635e412d3380
|
|
| BLAKE2b-256 |
f425d2324903603c4f18cea54a53433c024bfaa7d46cd6b80631540f6ded4a80
|