Cognito Basics
Seven examples to get you started with Amazon Cognito User Pools via SDK - five basic and two intermediate.
Busca en todas las páginas de la documentación
Seven examples to get you started with Amazon Cognito User Pools via SDK - five basic and two intermediate.
Each example shows the same operation in both Python (boto3) and TypeScript (AWS SDK for JavaScript v3), using the cognito-idp service (Cognito Identity Provider).
pip install boto3 (boto3 1.43.x, Python 3.10+). TypeScript: npm install @aws-sdk/client-cognito-identity-provider (Node.js 18+).cognito-idp:* actions used below, scoped to the pools you manage.A user pool is the managed directory that stores your users and runs sign-up/sign-in.
# --- Python (boto3) ---
import boto3
cognito = boto3.client("cognito-idp")
pool = cognito.create_user_pool(
PoolName="acme-app-users",
AutoVerifiedAttributes=["email"],
)
print(pool["UserPool"]["Id"]) # e.g. us-east-1_AbC123xyz// --- TypeScript (AWS SDK v3) ---
import { CognitoIdentityProviderClient, CreateUserPoolCommand } from "@aws-sdk/client-cognito-identity-provider";
const cognito = new CognitoIdentityProviderClient({});
const pool = await cognito.send(new CreateUserPoolCommand({
PoolName: "acme-app-users",
AutoVerifiedAttributes: ["email"],
}));
console.log(pool.UserPool?.Id);AutoVerifiedAttributes tells Cognito to send a verification code and require it before an email/phone counts as confirmed.Id (e.g. us-east-1_AbC123xyz) is required by every other operation on this pool.Related: Cognito's User Pool vs Identity Pool Split - what a user pool is for.
An app client is the credential your application uses to talk to the pool.
# --- Python (boto3) ---
import boto3
cognito = boto3.client("cognito-idp")
client = cognito.create_user_pool_client(
UserPoolId="us-east-1_AbC123xyz",
ClientName="acme-web-app",
ExplicitAuthFlows=["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],
)
print(client["UserPoolClient"]["ClientId"])// --- TypeScript (AWS SDK v3) ---
import { CognitoIdentityProviderClient, CreateUserPoolClientCommand } from "@aws-sdk/client-cognito-identity-provider";
const cognito = new CognitoIdentityProviderClient({});
const client = await cognito.send(new CreateUserPoolClientCommand({
UserPoolId: "us-east-1_AbC123xyz",
ClientName: "acme-web-app",
ExplicitAuthFlows: ["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],
}));
console.log(client.UserPoolClient?.ClientId);ExplicitAuthFlows opts the client into specific sign-in flows; without it, InitiateAuth calls are rejected.GenerateSecret unset.ClientId returned here is used on every SignUp and InitiateAuth call.SignUp registers a new user and triggers a confirmation code.
# --- Python (boto3) ---
import boto3
cognito = boto3.client("cognito-idp")
cognito.sign_up(
ClientId="1a2b3c4d5e6f7g8h9i0j",
Username="jane@example.com",
Password="Str0ng!Passw0rd",
UserAttributes=[{"Name": "email", "Value": "jane@example.com"}],
)// --- TypeScript (AWS SDK v3) ---
import { CognitoIdentityProviderClient, SignUpCommand } from "@aws-sdk/client-cognito-identity-provider";
const cognito = new CognitoIdentityProviderClient({});
await cognito.send(new SignUpCommand({
ClientId: "1a2b3c4d5e6f7g8h9i0j",
Username: "jane@example.com",
Password: "Str0ng!Passw0rd",
UserAttributes: [{ Name: "email", Value: "jane@example.com" }],
}));UNCONFIRMED status and cannot sign in yet.SignUp is a public, unauthenticated call - it only needs the app client ID, not admin credentials.ConfirmSignUp activates the account using the code the user received.
# --- Python (boto3) ---
import boto3
cognito = boto3.client("cognito-idp")
cognito.confirm_sign_up(
ClientId="1a2b3c4d5e6f7g8h9i0j",
Username="jane@example.com",
ConfirmationCode="123456",
)// --- TypeScript (AWS SDK v3) ---
import { CognitoIdentityProviderClient, ConfirmSignUpCommand } from "@aws-sdk/client-cognito-identity-provider";
const cognito = new CognitoIdentityProviderClient({});
await cognito.send(new ConfirmSignUpCommand({
ClientId: "1a2b3c4d5e6f7g8h9i0j",
Username: "jane@example.com",
ConfirmationCode: "123456",
}));UNCONFIRMED to CONFIRMED.ExpiredCodeException or CodeMismatchException - your UI should let the user request a new code.AdminConfirmSignUp with elevated IAM permissions instead.InitiateAuth sign-in.InitiateAuth with USER_PASSWORD_AUTH exchanges a username and password for JWTs.
# --- Python (boto3) ---
import boto3
cognito = boto3.client("cognito-idp")
resp = cognito.initiate_auth(
ClientId="1a2b3c4d5e6f7g8h9i0j",
AuthFlow="USER_PASSWORD_AUTH",
AuthParameters={"USERNAME": "jane@example.com", "PASSWORD": "Str0ng!Passw0rd"},
)
tokens = resp["AuthenticationResult"]
print(tokens["IdToken"][:20], "...")// --- TypeScript (AWS SDK v3) ---
import { CognitoIdentityProviderClient, InitiateAuthCommand } from "@aws-sdk/client-cognito-identity-provider";
const cognito = new CognitoIdentityProviderClient({});
const resp = await cognito.send(new InitiateAuthCommand({
ClientId: "1a2b3c4d5e6f7g8h9i0j",
AuthFlow: "USER_PASSWORD_AUTH",
AuthParameters: { USERNAME: "jane@example.com", PASSWORD: "Str0ng!Passw0rd" },
}));
console.log(resp.AuthenticationResult?.IdToken?.slice(0, 20), "...");IdToken, AccessToken, and RefreshToken under AuthenticationResult.USER_PASSWORD_AUTH sends the password to Cognito over TLS; USER_SRP_AUTH is the alternative that never transmits the raw password.ChallengeName instead of tokens, and you must respond to the challenge next.ALLOW_USER_PASSWORD_AUTH enabled, or this call is rejected.Related: User Pools: Sign-Up, Sign-In & MFA - the full lifecycle and MFA challenge flow.
GetUser returns the caller's own attributes using their access token - no admin rights required.
# --- Python (boto3) ---
import boto3
cognito = boto3.client("cognito-idp")
user = cognito.get_user(AccessToken=access_token)
attrs = {a["Name"]: a["Value"] for a in user["UserAttributes"]}
print(user["Username"], attrs.get("email"))// --- TypeScript (AWS SDK v3) ---
import { CognitoIdentityProviderClient, GetUserCommand } from "@aws-sdk/client-cognito-identity-provider";
const cognito = new CognitoIdentityProviderClient({});
const user = await cognito.send(new GetUserCommand({ AccessToken: accessToken }));
const attrs = Object.fromEntries((user.UserAttributes ?? []).map((a) => [a.Name, a.Value]));
console.log(user.Username, attrs.email);GetUser takes the access token, not the ID token - the two are not interchangeable.AdminGetUser instead, which does require IAM permissions.GlobalSignOut revokes all of a user's issued tokens across every device.
# --- Python (boto3) ---
import boto3
cognito = boto3.client("cognito-idp")
cognito.global_sign_out(AccessToken=access_token)// --- TypeScript (AWS SDK v3) ---
import { CognitoIdentityProviderClient, GlobalSignOutCommand } from "@aws-sdk/client-cognito-identity-provider";
const cognito = new CognitoIdentityProviderClient({});
await cognito.send(new GlobalSignOutCommand({ AccessToken: accessToken }));AdminUserGlobalSignOut, lets a backend force sign-out without the user's own access token.Related: Cognito via SDK Best Practices - token lifetime and MFA defaults.
Stack versions: This page was written for boto3 1.43.x (Python 3.10+) and the AWS SDK for JavaScript v3 (Node.js 18+).
Revisado por Chris St. John·Última actualización: 25 jul 2026