Claude Skill

cognito

AWS Cognito user authentication and authorization service. Use when setting up user pools, configuring identity pools, implementing OAuth flows, managing user attributes, or integrating with social identity providers.

LLM Mart · 0 points · 0 views 0 listing impressions 0 install-command copies
Virus-scanned Reviewed automatically before listing.

Full trust report

Download itsmostafa-aws-agent-skills-skills_cognito-e786d25.zip · 6 KB
Part of itsmostafa/aws-agent-skills — 17 skills

Install

skills CLI npx skills add https://github.com/itsmostafa/aws-agent-skills/tree/main/skills/cognito
Claude Code claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install itsmostafa-aws-agent-skills@llmmart
Git git clone https://github.com/itsmostafa/aws-agent-skills.git

The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole itsmostafa/aws-agent-skills collection as a plugin from our marketplace. Git is the plain clone.

Skill manifest

AWS Cognito

Amazon Cognito provides authentication, authorization, and user management for web and mobile applications. Users can sign in directly or through federated identity providers.

Table of Contents

Core Concepts

User Pools

User directory for sign-up and sign-in. Provides:

  • User registration and authentication
  • OAuth 2.0 / OpenID Connect tokens
  • MFA and password policies
  • Customizable UI and flows

Identity Pools (Federated Identities)

Provide temporary AWS credentials to access AWS services. Users can be:

  • Cognito User Pool users
  • Social identity (Google, Facebook, Apple)
  • SAML/OIDC enterprise identity
  • Anonymous guests

Tokens

Token Purpose Lifetime
ID Token User identity claims 1 hour
Access Token API authorization 1 hour
Refresh Token Get new ID/Access tokens 30 days (configurable)

Common Patterns

Create User Pool

AWS CLI:

aws cognito-idp create-user-pool \
  --pool-name my-app-users \
  --policies '{
    "PasswordPolicy": {
      "MinimumLength": 12,
      "RequireUppercase": true,
      "RequireLowercase": true,
      "RequireNumbers": true,
      "RequireSymbols": true
    }
  }' \
  --auto-verified-attributes email \
  --username-attributes email \
  --mfa-configuration OPTIONAL \
  --user-attribute-update-settings '{
    "AttributesRequireVerificationBeforeUpdate": ["email"]
  }'

Create App Client

aws cognito-idp create-user-pool-client \
  --user-pool-id us-east-1_abc123 \
  --client-name my-web-app \
  --generate-secret \
  --explicit-auth-flows ALLOW_USER_SRP_AUTH ALLOW_REFRESH_TOKEN_AUTH \
  --supported-identity-providers COGNITO \
  --callback-urls https://myapp.com/callback \
  --logout-urls https://myapp.com/logout \
  --allowed-o-auth-flows code \
  --allowed-o-auth-scopes openid email profile \
  --allowed-o-auth-flows-user-pool-client \
  --access-token-validity 60 \
  --id-token-validity 60 \
  --refresh-token-validity 30 \
  --token-validity-units '{
    "AccessToken": "minutes",
    "IdToken": "minutes",
    "RefreshToken": "days"
  }'

Sign Up User

import boto3
import hmac
import hashlib
import base64

cognito = boto3.client('cognito-idp')

def get_secret_hash(username, client_id, client_secret):
    message = username + client_id
    dig = hmac.new(
        client_secret.encode('utf-8'),
        message.encode('utf-8'),
        digestmod=hashlib.sha256
    ).digest()
    return base64.b64encode(dig).decode()

response = cognito.sign_up(
    ClientId='client-id',
    SecretHash=get_secret_hash('user@example.com', 'client-id', 'client-secret'),
    Username='user@example.com',
    Password='SecurePassword123!',
    UserAttributes=[
        {'Name': 'email', 'Value': 'user@example.com'},
        {'Name': 'name', 'Value': 'John Doe'}
    ]
)

Confirm Sign Up

cognito.confirm_sign_up(
    ClientId='client-id',
    SecretHash=get_secret_hash('user@example.com', 'client-id', 'client-secret'),
    Username='user@example.com',
    ConfirmationCode='123456'
)

Authenticate User

response = cognito.initiate_auth(
    ClientId='client-id',
    AuthFlow='USER_SRP_AUTH',
    AuthParameters={
        'USERNAME': 'user@example.com',
        'SECRET_HASH': get_secret_hash('user@example.com', 'client-id', 'client-secret'),
        'SRP_A': srp_a  # From SRP library
    }
)

# For simple password auth (not recommended for production)
response = cognito.admin_initiate_auth(
    UserPoolId='us-east-1_abc123',
    ClientId='client-id',
    AuthFlow='ADMIN_USER_PASSWORD_AUTH',
    AuthParameters={
        'USERNAME': 'user@example.com',
        'PASSWORD': 'password',
        'SECRET_HASH': get_secret_hash('user@example.com', 'client-id', 'client-secret')
    }
)

tokens = response['AuthenticationResult']
id_token = tokens['IdToken']
access_token = tokens['AccessToken']
refresh_token = tokens['RefreshToken']

Refresh Tokens

response = cognito.initiate_auth(
    ClientId='client-id',
    AuthFlow='REFRESH_TOKEN_AUTH',
    AuthParameters={
        'REFRESH_TOKEN': refresh_token,
        'SECRET_HASH': get_secret_hash('user@example.com', 'client-id', 'client-secret')
    }
)

Create Identity Pool

aws cognito-identity create-identity-pool \
  --identity-pool-name my-app-identities \
  --allow-unauthenticated-identities \
  --cognito-identity-providers \
    ProviderName=cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123,\
ClientId=client-id,\
ServerSideTokenCheck=true

Get AWS Credentials

import boto3

cognito_identity = boto3.client('cognito-identity')

# Get identity ID
response = cognito_identity.get_id(
    IdentityPoolId='us-east-1:12345678-1234-1234-1234-123456789012',
    Logins={
        'cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123': id_token
    }
)
identity_id = response['IdentityId']

# Get credentials
response = cognito_identity.get_credentials_for_identity(
    IdentityId=identity_id,
    Logins={
        'cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123': id_token
    }
)

credentials = response['Credentials']
# Use credentials['AccessKeyId'], credentials['SecretKey'], credentials['SessionToken']

CLI Reference

User Pool

Command Description
aws cognito-idp create-user-pool Create user pool
aws cognito-idp describe-user-pool Get pool details
aws cognito-idp update-user-pool Update pool settings
aws cognito-idp delete-user-pool Delete pool
aws cognito-idp list-user-pools List pools

Users

Command Description
aws cognito-idp admin-create-user Create user (admin)
aws cognito-idp admin-delete-user Delete user
aws cognito-idp admin-get-user Get user details
aws cognito-idp list-users List users
aws cognito-idp admin-set-user-password Set password
aws cognito-idp admin-disable-user Disable user

Authentication

Command Description
aws cognito-idp initiate-auth Start authentication
aws cognito-idp respond-to-auth-challenge Respond to MFA
aws cognito-idp admin-initiate-auth Admin authentication

Best Practices

Security

  • Enable MFA for all users (at least optional)
  • Use strong password policies
  • Enable advanced security features (adaptive auth)
  • Verify email/phone before allowing sign-in
  • Use short token lifetimes for sensitive apps
  • Never expose client secrets in frontend code

User Experience

  • Use hosted UI for quick implementation
  • Customize UI with CSS
  • Implement proper error handling
  • Provide clear password requirements

Architecture

  • Use identity pools for AWS resource access
  • Use access tokens for API Gateway
  • Store refresh tokens securely
  • Implement token refresh before expiry

Troubleshooting

User Cannot Sign In

Causes:

  • User not confirmed
  • Password incorrect
  • User disabled
  • Account locked (too many attempts)

Debug:

aws cognito-idp admin-get-user \
  --user-pool-id us-east-1_abc123 \
  --username user@example.com

Token Validation Failed

Causes:

  • Token expired
  • Wrong user pool/client ID
  • Token signature invalid

Validate JWT:

import jwt
import requests

# Get JWKS
jwks_url = f'https://cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123/.well-known/jwks.json'
jwks = requests.get(jwks_url).json()

# Decode and verify (use python-jose or similar)
from jose import jwt

claims = jwt.decode(
    token,
    jwks,
    algorithms=['RS256'],
    audience='client-id',
    issuer='https://cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123'
)

Hosted UI Not Working

Check:

  • Callback URLs configured correctly
  • Domain configured for user pool
  • OAuth settings enabled
# Check domain
aws cognito-idp describe-user-pool \
  --user-pool-id us-east-1_abc123 \
  --query 'UserPool.Domain'

Rate Limiting

Symptom: TooManyRequestsException

Solutions:

  • Implement exponential backoff
  • Request quota increase
  • Cache tokens appropriately

References

Files (aws-agent-skills)
  • auth-flows.md 8.9 KB
    # Cognito Authentication Flows
    
    Detailed authentication flows and OAuth configurations.
    
    ## Authentication Flows
    
    ### USER_SRP_AUTH (Recommended)
    
    Secure Remote Password protocol - password never sent over network.
    
    ```python
    import boto3
    from warrant.aws_srp import AWSSRP
    
    cognito = boto3.client('cognito-idp')
    
    # Use warrant library for SRP
    aws_srp = AWSSRP(
        username='user@example.com',
        password='password',
        pool_id='us-east-1_abc123',
        client_id='client-id',
        client_secret='client-secret'
    )
    
    tokens = aws_srp.authenticate_user()
    ```
    
    ### USER_PASSWORD_AUTH
    
    Direct username/password (requires enabling in client settings).
    
    ```python
    response = cognito.initiate_auth(
        ClientId='client-id',
        AuthFlow='USER_PASSWORD_AUTH',
        AuthParameters={
            'USERNAME': 'user@example.com',
            'PASSWORD': 'password',
            'SECRET_HASH': get_secret_hash(...)
        }
    )
    ```
    
    ### CUSTOM_AUTH
    
    Custom authentication flow with Lambda triggers.
    
    ```python
    # Step 1: Initiate
    response = cognito.initiate_auth(
        ClientId='client-id',
        AuthFlow='CUSTOM_AUTH',
        AuthParameters={
            'USERNAME': 'user@example.com'
        }
    )
    
    # Step 2: Respond to challenge
    response = cognito.respond_to_auth_challenge(
        ClientId='client-id',
        ChallengeName='CUSTOM_CHALLENGE',
        Session=response['Session'],
        ChallengeResponses={
            'USERNAME': 'user@example.com',
            'ANSWER': 'custom-answer'
        }
    )
    ```
    
    ## OAuth 2.0 Flows
    
    ### Authorization Code Flow (Recommended for web)
    
    ```
    1. Redirect to authorize endpoint:
       https://my-domain.auth.us-east-1.amazoncognito.com/oauth2/authorize?
       response_type=code&
       client_id=CLIENT_ID&
       redirect_uri=https://myapp.com/callback&
       scope=openid+email+profile
    
    2. User authenticates, redirected back with code:
       https://myapp.com/callback?code=AUTHORIZATION_CODE
    
    3. Exchange code for tokens:
    ```
    
    ```python
    import requests
    
    response = requests.post(
        'https://my-domain.auth.us-east-1.amazoncognito.com/oauth2/token',
        data={
            'grant_type': 'authorization_code',
            'client_id': 'CLIENT_ID',
            'client_secret': 'CLIENT_SECRET',
            'code': 'AUTHORIZATION_CODE',
            'redirect_uri': 'https://myapp.com/callback'
        },
        headers={'Content-Type': 'application/x-www-form-urlencoded'}
    )
    
    tokens = response.json()
    ```
    
    ### Authorization Code Flow with PKCE (Mobile/SPA)
    
    ```python
    import secrets
    import hashlib
    import base64
    
    # Generate PKCE values
    code_verifier = secrets.token_urlsafe(64)
    code_challenge = base64.urlsafe_b64encode(
        hashlib.sha256(code_verifier.encode()).digest()
    ).decode().rstrip('=')
    
    # Step 1: Authorization URL with PKCE
    auth_url = (
        f'https://my-domain.auth.us-east-1.amazoncognito.com/oauth2/authorize?'
        f'response_type=code&'
        f'client_id={client_id}&'
        f'redirect_uri={redirect_uri}&'
        f'scope=openid+email&'
        f'code_challenge={code_challenge}&'
        f'code_challenge_method=S256'
    )
    
    # Step 2: Exchange code with verifier
    response = requests.post(
        'https://my-domain.auth.us-east-1.amazoncognito.com/oauth2/token',
        data={
            'grant_type': 'authorization_code',
            'client_id': client_id,
            'code': authorization_code,
            'redirect_uri': redirect_uri,
            'code_verifier': code_verifier
        }
    )
    ```
    
    ### Implicit Flow (Legacy, not recommended)
    
    ```
    https://my-domain.auth.us-east-1.amazoncognito.com/oauth2/authorize?
    response_type=token&
    client_id=CLIENT_ID&
    redirect_uri=https://myapp.com/callback&
    scope=openid+email
    
    Callback: https://myapp.com/callback#id_token=TOKEN&access_token=TOKEN
    ```
    
    ### Client Credentials Flow (Machine-to-Machine)
    
    ```bash
    # Create resource server
    aws cognito-idp create-resource-server \
      --user-pool-id us-east-1_abc123 \
      --identifier api.myapp.com \
      --name "My API" \
      --scopes ScopeName=read,ScopeDescription="Read access" \
              ScopeName=write,ScopeDescription="Write access"
    
    # Create client for M2M
    aws cognito-idp create-user-pool-client \
      --user-pool-id us-east-1_abc123 \
      --client-name service-client \
      --generate-secret \
      --allowed-o-auth-flows client_credentials \
      --allowed-o-auth-scopes api.myapp.com/read api.myapp.com/write \
      --allowed-o-auth-flows-user-pool-client
    ```
    
    ```python
    import requests
    import base64
    
    credentials = base64.b64encode(f'{client_id}:{client_secret}'.encode()).decode()
    
    response = requests.post(
        'https://my-domain.auth.us-east-1.amazoncognito.com/oauth2/token',
        data={
            'grant_type': 'client_credentials',
            'scope': 'api.myapp.com/read api.myapp.com/write'
        },
        headers={
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': f'Basic {credentials}'
        }
    )
    ```
    
    ## MFA Flows
    
    ### SMS MFA
    
    ```python
    # After initial auth, if MFA required:
    if response.get('ChallengeName') == 'SMS_MFA':
        response = cognito.respond_to_auth_challenge(
            ClientId='client-id',
            ChallengeName='SMS_MFA',
            Session=response['Session'],
            ChallengeResponses={
                'USERNAME': 'user@example.com',
                'SMS_MFA_CODE': '123456',
                'SECRET_HASH': get_secret_hash(...)
            }
        )
    ```
    
    ### TOTP MFA
    
    ```python
    # Associate TOTP
    response = cognito.associate_software_token(
        AccessToken=access_token
    )
    secret_code = response['SecretCode']
    
    # Verify TOTP
    cognito.verify_software_token(
        AccessToken=access_token,
        UserCode='123456',
        FriendlyDeviceName='My Phone'
    )
    
    # Set as preferred
    cognito.set_user_mfa_preference(
        AccessToken=access_token,
        SoftwareTokenMfaSettings={
            'Enabled': True,
            'PreferredMfa': True
        }
    )
    ```
    
    ## Lambda Triggers
    
    ### Pre Sign-up
    
    ```python
    def handler(event, context):
        # Auto-confirm users from specific domains
        email = event['request']['userAttributes'].get('email', '')
        if email.endswith('@mycompany.com'):
            event['response']['autoConfirmUser'] = True
            event['response']['autoVerifyEmail'] = True
    
        return event
    ```
    
    ### Pre Authentication
    
    ```python
    def handler(event, context):
        # Block specific users
        username = event['userName']
        if is_blocked(username):
            raise Exception('User is blocked')
    
        return event
    ```
    
    ### Post Confirmation
    
    ```python
    def handler(event, context):
        # Add user to group after confirmation
        cognito = boto3.client('cognito-idp')
    
        cognito.admin_add_user_to_group(
            UserPoolId=event['userPoolId'],
            Username=event['userName'],
            GroupName='Users'
        )
    
        return event
    ```
    
    ### Custom Message
    
    ```python
    def handler(event, context):
        if event['triggerSource'] == 'CustomMessage_SignUp':
            event['response']['emailSubject'] = 'Welcome to MyApp!'
            event['response']['emailMessage'] = f'''
                Hi {event['request']['userAttributes']['name']},
                Your verification code is {event['request']['codeParameter']}
            '''
    
        return event
    ```
    
    ### Define Auth Challenge
    
    ```python
    def handler(event, context):
        if len(event['request']['session']) == 0:
            # First challenge
            event['response']['challengeName'] = 'CUSTOM_CHALLENGE'
            event['response']['issueTokens'] = False
            event['response']['failAuthentication'] = False
        elif event['request']['session'][-1]['challengeResult']:
            # Challenge passed
            event['response']['issueTokens'] = True
            event['response']['failAuthentication'] = False
    
        return event
    ```
    
    ## Social Identity Providers
    
    ### Configure Google
    
    ```bash
    aws cognito-idp create-identity-provider \
      --user-pool-id us-east-1_abc123 \
      --provider-name Google \
      --provider-type Google \
      --provider-details '{
        "client_id": "google-client-id",
        "client_secret": "google-client-secret",
        "authorize_scopes": "profile email openid"
      }' \
      --attribute-mapping '{
        "email": "email",
        "name": "name",
        "picture": "picture"
      }'
    ```
    
    ### Configure SAML
    
    ```bash
    aws cognito-idp create-identity-provider \
      --user-pool-id us-east-1_abc123 \
      --provider-name MySAML \
      --provider-type SAML \
      --provider-details '{
        "MetadataFile": "<SAML metadata XML>",
        "IDPSignout": "true"
      }' \
      --attribute-mapping '{
        "email": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"
      }'
    ```
    
    ## Token Management
    
    ### Verify Token
    
    ```python
    import jwt
    from jwt import PyJWKClient
    
    def verify_cognito_token(token, user_pool_id, client_id, region='us-east-1'):
        jwks_url = f'https://cognito-idp.{region}.amazonaws.com/{user_pool_id}/.well-known/jwks.json'
        issuer = f'https://cognito-idp.{region}.amazonaws.com/{user_pool_id}'
    
        jwk_client = PyJWKClient(jwks_url)
        signing_key = jwk_client.get_signing_key_from_jwt(token)
    
        claims = jwt.decode(
            token,
            signing_key.key,
            algorithms=['RS256'],
            audience=client_id,
            issuer=issuer
        )
    
        return claims
    ```
    
    ### Revoke Tokens
    
    ```python
    cognito.revoke_token(
        Token=refresh_token,
        ClientId='client-id',
        ClientSecret='client-secret'
    )
    ```
    
    ### Global Sign Out
    
    ```python
    cognito.global_sign_out(
        AccessToken=access_token
    )
    ```
    
  • SKILL.md 9 KB
    ---
    name: cognito
    description: AWS Cognito user authentication and authorization service. Use when setting up user pools, configuring identity pools, implementing OAuth flows, managing user attributes, or integrating with social identity providers.
    last_updated: "2026-01-07"
    doc_source: https://docs.aws.amazon.com/cognito/latest/developerguide/
    ---
    
    # AWS Cognito
    
    Amazon Cognito provides authentication, authorization, and user management for web and mobile applications. Users can sign in directly or through federated identity providers.
    
    ## Table of Contents
    
    - [Core Concepts](#core-concepts)
    - [Common Patterns](#common-patterns)
    - [CLI Reference](#cli-reference)
    - [Best Practices](#best-practices)
    - [Troubleshooting](#troubleshooting)
    - [References](#references)
    
    ## Core Concepts
    
    ### User Pools
    
    User directory for sign-up and sign-in. Provides:
    - User registration and authentication
    - OAuth 2.0 / OpenID Connect tokens
    - MFA and password policies
    - Customizable UI and flows
    
    ### Identity Pools (Federated Identities)
    
    Provide temporary AWS credentials to access AWS services. Users can be:
    - Cognito User Pool users
    - Social identity (Google, Facebook, Apple)
    - SAML/OIDC enterprise identity
    - Anonymous guests
    
    ### Tokens
    
    | Token | Purpose | Lifetime |
    |-------|---------|----------|
    | **ID Token** | User identity claims | 1 hour |
    | **Access Token** | API authorization | 1 hour |
    | **Refresh Token** | Get new ID/Access tokens | 30 days (configurable) |
    
    ## Common Patterns
    
    ### Create User Pool
    
    **AWS CLI:**
    
    ```bash
    aws cognito-idp create-user-pool \
      --pool-name my-app-users \
      --policies '{
        "PasswordPolicy": {
          "MinimumLength": 12,
          "RequireUppercase": true,
          "RequireLowercase": true,
          "RequireNumbers": true,
          "RequireSymbols": true
        }
      }' \
      --auto-verified-attributes email \
      --username-attributes email \
      --mfa-configuration OPTIONAL \
      --user-attribute-update-settings '{
        "AttributesRequireVerificationBeforeUpdate": ["email"]
      }'
    ```
    
    ### Create App Client
    
    ```bash
    aws cognito-idp create-user-pool-client \
      --user-pool-id us-east-1_abc123 \
      --client-name my-web-app \
      --generate-secret \
      --explicit-auth-flows ALLOW_USER_SRP_AUTH ALLOW_REFRESH_TOKEN_AUTH \
      --supported-identity-providers COGNITO \
      --callback-urls https://myapp.com/callback \
      --logout-urls https://myapp.com/logout \
      --allowed-o-auth-flows code \
      --allowed-o-auth-scopes openid email profile \
      --allowed-o-auth-flows-user-pool-client \
      --access-token-validity 60 \
      --id-token-validity 60 \
      --refresh-token-validity 30 \
      --token-validity-units '{
        "AccessToken": "minutes",
        "IdToken": "minutes",
        "RefreshToken": "days"
      }'
    ```
    
    ### Sign Up User
    
    ```python
    import boto3
    import hmac
    import hashlib
    import base64
    
    cognito = boto3.client('cognito-idp')
    
    def get_secret_hash(username, client_id, client_secret):
        message = username + client_id
        dig = hmac.new(
            client_secret.encode('utf-8'),
            message.encode('utf-8'),
            digestmod=hashlib.sha256
        ).digest()
        return base64.b64encode(dig).decode()
    
    response = cognito.sign_up(
        ClientId='client-id',
        SecretHash=get_secret_hash('user@example.com', 'client-id', 'client-secret'),
        Username='user@example.com',
        Password='SecurePassword123!',
        UserAttributes=[
            {'Name': 'email', 'Value': 'user@example.com'},
            {'Name': 'name', 'Value': 'John Doe'}
        ]
    )
    ```
    
    ### Confirm Sign Up
    
    ```python
    cognito.confirm_sign_up(
        ClientId='client-id',
        SecretHash=get_secret_hash('user@example.com', 'client-id', 'client-secret'),
        Username='user@example.com',
        ConfirmationCode='123456'
    )
    ```
    
    ### Authenticate User
    
    ```python
    response = cognito.initiate_auth(
        ClientId='client-id',
        AuthFlow='USER_SRP_AUTH',
        AuthParameters={
            'USERNAME': 'user@example.com',
            'SECRET_HASH': get_secret_hash('user@example.com', 'client-id', 'client-secret'),
            'SRP_A': srp_a  # From SRP library
        }
    )
    
    # For simple password auth (not recommended for production)
    response = cognito.admin_initiate_auth(
        UserPoolId='us-east-1_abc123',
        ClientId='client-id',
        AuthFlow='ADMIN_USER_PASSWORD_AUTH',
        AuthParameters={
            'USERNAME': 'user@example.com',
            'PASSWORD': 'password',
            'SECRET_HASH': get_secret_hash('user@example.com', 'client-id', 'client-secret')
        }
    )
    
    tokens = response['AuthenticationResult']
    id_token = tokens['IdToken']
    access_token = tokens['AccessToken']
    refresh_token = tokens['RefreshToken']
    ```
    
    ### Refresh Tokens
    
    ```python
    response = cognito.initiate_auth(
        ClientId='client-id',
        AuthFlow='REFRESH_TOKEN_AUTH',
        AuthParameters={
            'REFRESH_TOKEN': refresh_token,
            'SECRET_HASH': get_secret_hash('user@example.com', 'client-id', 'client-secret')
        }
    )
    ```
    
    ### Create Identity Pool
    
    ```bash
    aws cognito-identity create-identity-pool \
      --identity-pool-name my-app-identities \
      --allow-unauthenticated-identities \
      --cognito-identity-providers \
        ProviderName=cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123,\
    ClientId=client-id,\
    ServerSideTokenCheck=true
    ```
    
    ### Get AWS Credentials
    
    ```python
    import boto3
    
    cognito_identity = boto3.client('cognito-identity')
    
    # Get identity ID
    response = cognito_identity.get_id(
        IdentityPoolId='us-east-1:12345678-1234-1234-1234-123456789012',
        Logins={
            'cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123': id_token
        }
    )
    identity_id = response['IdentityId']
    
    # Get credentials
    response = cognito_identity.get_credentials_for_identity(
        IdentityId=identity_id,
        Logins={
            'cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123': id_token
        }
    )
    
    credentials = response['Credentials']
    # Use credentials['AccessKeyId'], credentials['SecretKey'], credentials['SessionToken']
    ```
    
    ## CLI Reference
    
    ### User Pool
    
    | Command | Description |
    |---------|-------------|
    | `aws cognito-idp create-user-pool` | Create user pool |
    | `aws cognito-idp describe-user-pool` | Get pool details |
    | `aws cognito-idp update-user-pool` | Update pool settings |
    | `aws cognito-idp delete-user-pool` | Delete pool |
    | `aws cognito-idp list-user-pools` | List pools |
    
    ### Users
    
    | Command | Description |
    |---------|-------------|
    | `aws cognito-idp admin-create-user` | Create user (admin) |
    | `aws cognito-idp admin-delete-user` | Delete user |
    | `aws cognito-idp admin-get-user` | Get user details |
    | `aws cognito-idp list-users` | List users |
    | `aws cognito-idp admin-set-user-password` | Set password |
    | `aws cognito-idp admin-disable-user` | Disable user |
    
    ### Authentication
    
    | Command | Description |
    |---------|-------------|
    | `aws cognito-idp initiate-auth` | Start authentication |
    | `aws cognito-idp respond-to-auth-challenge` | Respond to MFA |
    | `aws cognito-idp admin-initiate-auth` | Admin authentication |
    
    ## Best Practices
    
    ### Security
    
    - **Enable MFA** for all users (at least optional)
    - **Use strong password policies**
    - **Enable advanced security features** (adaptive auth)
    - **Verify email/phone** before allowing sign-in
    - **Use short token lifetimes** for sensitive apps
    - **Never expose client secrets** in frontend code
    
    ### User Experience
    
    - **Use hosted UI** for quick implementation
    - **Customize UI** with CSS
    - **Implement proper error handling**
    - **Provide clear password requirements**
    
    ### Architecture
    
    - **Use identity pools** for AWS resource access
    - **Use access tokens** for API Gateway
    - **Store refresh tokens securely**
    - **Implement token refresh** before expiry
    
    ## Troubleshooting
    
    ### User Cannot Sign In
    
    **Causes:**
    - User not confirmed
    - Password incorrect
    - User disabled
    - Account locked (too many attempts)
    
    **Debug:**
    
    ```bash
    aws cognito-idp admin-get-user \
      --user-pool-id us-east-1_abc123 \
      --username user@example.com
    ```
    
    ### Token Validation Failed
    
    **Causes:**
    - Token expired
    - Wrong user pool/client ID
    - Token signature invalid
    
    **Validate JWT:**
    
    ```python
    import jwt
    import requests
    
    # Get JWKS
    jwks_url = f'https://cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123/.well-known/jwks.json'
    jwks = requests.get(jwks_url).json()
    
    # Decode and verify (use python-jose or similar)
    from jose import jwt
    
    claims = jwt.decode(
        token,
        jwks,
        algorithms=['RS256'],
        audience='client-id',
        issuer='https://cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123'
    )
    ```
    
    ### Hosted UI Not Working
    
    **Check:**
    - Callback URLs configured correctly
    - Domain configured for user pool
    - OAuth settings enabled
    
    ```bash
    # Check domain
    aws cognito-idp describe-user-pool \
      --user-pool-id us-east-1_abc123 \
      --query 'UserPool.Domain'
    ```
    
    ### Rate Limiting
    
    **Symptom:** `TooManyRequestsException`
    
    **Solutions:**
    - Implement exponential backoff
    - Request quota increase
    - Cache tokens appropriately
    
    ## References
    
    - [Cognito Developer Guide](https://docs.aws.amazon.com/cognito/latest/developerguide/)
    - [Cognito User Pools API](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/)
    - [Cognito Identity API](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/)
    - [Cognito CLI Reference](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/)
    

Comments (0)

Sign in to join the conversation.

No comments yet.

Reviews (0)

No reviews yet.

Related