{"id":"cognito","name":"cognito","summary":"AWS Cognitoユーザー認証および認可サービス。ユーザープールの設定、アイデンティティプールの設定、OAuthフローの実装、ユーザー属性管理、ソーシャルアイデンティティプロバイダーとの統合などに使用されます。","body":"# AWS Cognito\n\nAmazon Cognito provides authentication, authorization, and user management for web and mobile applications. Users can sign in directly or through federated identity providers.\n\n## Table of Contents\n\n- [Core Concepts](#core-concepts)\n- [Common Patterns](#common-patterns)\n- [CLI Reference](#cli-reference)\n- [Best Practices](#best-practices)\n- [Troubleshooting](#troubleshooting)\n- [References](#references)\n\n## Core Concepts\n\n### User Pools\n\nUser directory for sign-up and sign-in. Provides:\n- User registration and authentication\n- OAuth 2.0 / OpenID Connect tokens\n- MFA and password policies\n- Customizable UI and flows\n\n### Identity Pools (Federated Identities)\n\nProvide temporary AWS credentials to access AWS services. Users can be:\n- Cognito User Pool users\n- Social identity (Google, Facebook, Apple)\n- SAML/OIDC enterprise identity\n- Anonymous guests\n\n### Tokens\n\n| Token | Purpose | Lifetime |\n|-------|---------|----------|\n| **ID Token** | User identity claims | 1 hour |\n| **Access Token** | API authorization | 1 hour |\n| **Refresh Token** | Get new ID/Access tokens | 30 days (configurable) |\n\n## Common Patterns\n\n### Create User Pool\n\n**AWS CLI:**\n\n```bash\naws cognito-idp create-user-pool \\\n  --pool-name my-app-users \\\n  --policies '{\n    \"PasswordPolicy\": {\n      \"MinimumLength\": 12,\n      \"RequireUppercase\": true,\n      \"RequireLowercase\": true,\n      \"RequireNumbers\": true,\n      \"RequireSymbols\": true\n    }\n  }' \\\n  --auto-verified-attributes email \\\n  --username-attributes email \\\n  --mfa-configuration OPTIONAL \\\n  --user-attribute-update-settings '{\n    \"AttributesRequireVerificationBeforeUpdate\": [\"email\"]\n  }'\n```\n\n### Create App Client\n\n```bash\naws cognito-idp create-user-pool-client \\\n  --user-pool-id us-east-1_abc123 \\\n  --client-name my-web-app \\\n  --generate-secret \\\n  --explicit-auth-flows ALLOW_USER_SRP_AUTH ALLOW_REFRESH_TOKEN_AUTH \\\n  --supported-identity-providers COGNITO \\\n  --callback-urls https://myapp.com/callback \\\n  --logout-urls https://myapp.com/logout \\\n  --allowed-o-auth-flows code \\\n  --allowed-o-auth-scopes openid email profile \\\n  --allowed-o-auth-flows-user-pool-client \\\n  --access-token-validity 60 \\\n  --id-token-validity 60 \\\n  --refresh-token-validity 30 \\\n  --token-validity-units '{\n    \"AccessToken\": \"minutes\",\n    \"IdToken\": \"minutes\",\n    \"RefreshToken\": \"days\"\n  }'\n```\n\n### Sign Up User\n\n```python\nimport boto3\nimport hmac\nimport hashlib\nimport base64\n\ncognito = boto3.client('cognito-idp')\n\ndef get_secret_hash(username, client_id, client_secret):\n    message = username + client_id\n    dig = hmac.new(\n        client_secret.encode('utf-8'),\n        message.encode('utf-8'),\n        digestmod=hashlib.sha256\n    ).digest()\n    return base64.b64encode(dig).decode()\n\nresponse = cognito.sign_up(\n    ClientId='client-id',\n    SecretHash=get_secret_hash('user@example.com', 'client-id', 'client-secret'),\n    Username='user@example.com',\n    Password='SecurePassword123!',\n    UserAttributes=[\n        {'Name': 'email', 'Value': 'user@example.com'},\n        {'Name': 'name', 'Value': 'John Doe'}\n    ]\n)\n```\n\n### Confirm Sign Up\n\n```python\ncognito.confirm_sign_up(\n    ClientId='client-id',\n    SecretHash=get_secret_hash('user@example.com', 'client-id', 'client-secret'),\n    Username='user@example.com',\n    ConfirmationCode='123456'\n)\n```\n\n### Authenticate User\n\n```python\nresponse = cognito.initiate_auth(\n    ClientId='client-id',\n    AuthFlow='USER_SRP_AUTH',\n    AuthParameters={\n        'USERNAME': 'user@example.com',\n        'SECRET_HASH': get_secret_hash('user@example.com', 'client-id', 'client-secret'),\n        'SRP_A': srp_a  # From SRP library\n    }\n)\n\n# For simple password auth (not recommended for production)\nresponse = cognito.admin_initiate_auth(\n    UserPoolId='us-east-1_abc123',\n    ClientId='client-id',\n    AuthFlow='ADMIN_USER_PASSWORD_AUTH',\n    AuthParameters={\n        'USERNAME': 'user@example.com',\n        'PASSWORD': 'password',\n        'SECRET_HASH': get_secret_hash('user@example.com', 'client-id', 'client-secret')\n    }\n)\n\ntokens = response['AuthenticationResult']\nid_token = tokens['IdToken']\naccess_token = tokens['AccessToken']\nrefresh_token = tokens['RefreshToken']\n```\n\n### Refresh Tokens\n\n```python\nresponse = cognito.initiate_auth(\n    ClientId='client-id',\n    AuthFlow='REFRESH_TOKEN_AUTH',\n    AuthParameters={\n        'REFRESH_TOKEN': refresh_token,\n        'SECRET_HASH': get_secret_hash('user@example.com', 'client-id', 'client-secret')\n    }\n)\n```\n\n### Create Identity Pool\n\n```bash\naws cognito-identity create-identity-pool \\\n  --identity-pool-name my-app-identities \\\n  --allow-unauthenticated-identities \\\n  --cognito-identity-providers \\\n    ProviderName=cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123,\\\nClientId=client-id,\\\nServerSideTokenCheck=true\n```\n\n### Get AWS Credentials\n\n```python\nimport boto3\n\ncognito_identity = boto3.client('cognito-identity')\n\n# Get identity ID\nresponse = cognito_identity.get_id(\n    IdentityPoolId='us-east-1:12345678-1234-1234-1234-123456789012',\n    Logins={\n        'cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123': id_token\n    }\n)\nidentity_id = response['IdentityId']\n\n# Get credentials\nresponse = cognito_identity.get_credentials_for_identity(\n    IdentityId=identity_id,\n    Logins={\n        'cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123': id_token\n    }\n)\n\ncredentials = response['Credentials']\n# Use credentials['AccessKeyId'], credentials['SecretKey'], credentials['SessionToken']\n```\n\n## CLI Reference\n\n### User Pool\n\n| Command | Description |\n|---------|-------------|\n| `aws cognito-idp create-user-pool` | Create user pool |\n| `aws cognito-idp describe-user-pool` | Get pool details |\n| `aws cognito-idp update-user-pool` | Update pool settings |\n| `aws cognito-idp delete-user-pool` | Delete pool |\n| `aws cognito-idp list-user-pools` | List pools |\n\n### Users\n\n| Command | Description |\n|---------|-------------|\n| `aws cognito-idp admin-create-user` | Create user (admin) |\n| `aws cognito-idp admin-delete-user` | Delete user |\n| `aws cognito-idp admin-get-user` | Get user details |\n| `aws cognito-idp list-users` | List users |\n| `aws cognito-idp admin-set-user-password` | Set password |\n| `aws cognito-idp admin-disable-user` | Disable user |\n\n### Authentication\n\n| Command | Description |\n|---------|-------------|\n| `aws cognito-idp initiate-auth` | Start authentication |\n| `aws cognito-idp respond-to-auth-challenge` | Respond to MFA |\n| `aws cognito-idp admin-initiate-auth` | Admin authentication |\n\n## Best Practices\n\n### Security\n\n- **Enable MFA** for all users (at least optional)\n- **Use strong password policies**\n- **Enable advanced security features** (adaptive auth)\n- **Verify email/phone** before allowing sign-in\n- **Use short token lifetimes** for sensitive apps\n- **Never expose client secrets** in frontend code\n\n### User Experience\n\n- **Use hosted UI** for quick implementation\n- **Customize UI** with CSS\n- **Implement proper error handling**\n- **Provide clear password requirements**\n\n### Architecture\n\n- **Use identity pools** for AWS resource access\n- **Use access tokens** for API Gateway\n- **Store refresh tokens securely**\n- **Implement token refresh** before expiry\n\n## Troubleshooting\n\n### User Cannot Sign In\n\n**Causes:**\n- User not confirmed\n- Password incorrect\n- User disabled\n- Account locked (too many attempts)\n\n**Debug:**\n\n```bash\naws cognito-idp admin-get-user \\\n  --user-pool-id us-east-1_abc123 \\\n  --username user@example.com\n```\n\n### Token Validation Failed\n\n**Causes:**\n- Token expired\n- Wrong user pool/client ID\n- Token signature invalid\n\n**Validate JWT:**\n\n```python\nimport jwt\nimport requests\n\n# Get JWKS\njwks_url = f'https://cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123/.well-known/jwks.json'\njwks = requests.get(jwks_url).json()\n\n# Decode and verify (use python-jose or similar)\nfrom jose import jwt\n\nclaims = jwt.decode(\n    token,\n    jwks,\n    algorithms=['RS256'],\n    audience='client-id',\n    issuer='https://cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123'\n)\n```\n\n### Hosted UI Not Working\n\n**Check:**\n- Callback URLs configured correctly\n- Domain configured for user pool\n- OAuth settings enabled\n\n```bash\n# Check domain\naws cognito-idp describe-user-pool \\\n  --user-pool-id us-east-1_abc123 \\\n  --query 'UserPool.Domain'\n```\n\n### Rate Limiting\n\n**Symptom:** `TooManyRequestsException`\n\n**Solutions:**\n- Implement exponential backoff\n- Request quota increase\n- Cache tokens appropriately\n\n## References\n\n- [Cognito Developer Guide](https://docs.aws.amazon.com/cognito/latest/developerguide/)\n- [Cognito User Pools API](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/)\n- [Cognito Identity API](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/)\n- [Cognito CLI Reference](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/)","author":"@itsmostafa","ownerProfile":null,"authorContacts":null,"sourceUrl":"https://github.com/itsmostafa/aws-agent-skills/tree/main/skills/cognito","license":"MIT","category":"design","lang":"en","tokens":2241,"stars":0,"calls30d":1,"claimed":false,"visibility":"public","origin":"crawler","version":"0.1.0","createdAt":"2026-08-22","updatedAt":"2026-08-22","files":[{"path":"auth-flows.md","size":9131,"sha256":"b6ed6140f1421335e54928bdcfcfc2d266966812d6d658627e90ca497ac3da1a"}],"requires":{"mcp":[],"tools":[]},"safety":{"flags":[],"scannedAt":"2026-08-22","hasScripts":false,"networkEndpoints":["cognito-idp.us-east-1.amazonaws.com","docs.aws.amazon.com","my-domain.auth.us-east-1.amazoncognito.com","myapp.com","schemas.xmlsoap.org"]}}