Skip to content

AWS.Cognito reference

Source: src/AWS/Cognito/Group.ts

A group within an Amazon Cognito user pool. Groups organize users, appear in the cognito:groups token claim, and can carry an IAM role for identity-pool federation.

Basic Group

import * as Cognito from "alchemy/AWS/Cognito";
const pool = yield* Cognito.UserPool("Users", {});
const admins = yield* Cognito.Group("Admins", {
userPoolId: pool.userPoolId,
description: "Administrators",
});

Group with Role and Precedence

const admins = yield* Cognito.Group("Admins", {
userPoolId: pool.userPoolId,
roleArn: role.roleArn,
precedence: 1,
});

Source: src/AWS/Cognito/IdentityPool.ts

An Amazon Cognito identity pool (federated identities) — exchanges tokens from user pools, social providers, OIDC/SAML IdPs, or developer backends for temporary AWS credentials.

Identity Pool Federating a User Pool

import * as Cognito from "alchemy/AWS/Cognito";
import * as Output from "alchemy/Output";
const pool = yield* Cognito.UserPool("Users", {});
const client = yield* Cognito.UserPoolClient("Web", {
userPoolId: pool.userPoolId,
});
const identities = yield* Cognito.IdentityPool("Identities", {
cognitoIdentityProviders: [
{
providerName: Output.interpolate`cognito-idp.us-west-2.amazonaws.com/${pool.userPoolId}`,
clientId: client.clientId,
},
],
});

Guest (Unauthenticated) Access

const identities = yield* Cognito.IdentityPool("Identities", {
allowUnauthenticatedIdentities: true,
});
yield* Cognito.IdentityPoolRoleAttachment("Roles", {
identityPoolId: identities.identityPoolId,
roles: { authenticated: role.roleArn },
});

Source: src/AWS/Cognito/IdentityPoolAdmin.ts

Runtime binding for administrative Cognito identity pool operations — identity management and the developer-authenticated identities flow.

Bind this to an IdentityPool inside a function runtime to get a typed client for listing/deleting identities and for developer-provider token minting. The binding grants the corresponding cognito-identity:* IAM actions scoped to the pool’s ARN and injects the pool ID into pool-scoped calls.

const identities = yield* Cognito.IdentityPoolAdmin(identityPool);
const page = yield* identities.listIdentities({ MaxResults: 20 });
const first = page.Identities?.[0];
if (first?.IdentityId) {
const detail = yield* identities.describeIdentity({
IdentityId: first.IdentityId,
});
}

IdentityPoolAdmin: Developer-Authenticated Identities

Section titled “IdentityPoolAdmin: Developer-Authenticated Identities”
const token = yield* identities.getOpenIdTokenForDeveloperIdentity({
Logins: { "my.developer.provider": userId },
});

Source: src/AWS/Cognito/IdentityPoolAuth.ts

Runtime binding for the public (token-based) Cognito identity pool flows — the credentials-vending data plane.

Bind this to an IdentityPool inside a function runtime to exchange user pool / social / OIDC tokens (or nothing, for guest access) for an identity ID and temporary AWS credentials. These operations are unauthenticated (Cognito does not evaluate IAM for them), so the binding grants no IAM policy — it injects the identity pool ID into getId.

Guest (Unauthenticated) Credentials

const identity = yield* Cognito.IdentityPoolAuth(identityPool);
const { IdentityId } = yield* identity.getId();
const creds = yield* identity.getCredentialsForIdentity({
IdentityId: IdentityId!,
});

Credentials for a User Pool Sign-In

const provider = `cognito-idp.${region}.amazonaws.com/${userPoolId}`;
const { IdentityId } = yield* identity.getId({
Logins: { [provider]: idToken },
});
const creds = yield* identity.getCredentialsForIdentity({
IdentityId: IdentityId!,
Logins: { [provider]: idToken },
});

Source: src/AWS/Cognito/IdentityPoolRoleAttachment.ts

Attaches the authenticated/unauthenticated IAM roles to an Amazon Cognito identity pool. A singleton child of the pool — one attachment manages the pool’s role configuration.

IdentityPoolRoleAttachment: Attaching Roles

Section titled “IdentityPoolRoleAttachment: Attaching Roles”
import * as Cognito from "alchemy/AWS/Cognito";
const identities = yield* Cognito.IdentityPool("Identities", {});
const role = yield* IAM.Role("AuthenticatedRole", {
assumeRolePolicyDocument: {
Version: "2012-10-17",
Statement: [
{
Effect: "Allow",
Principal: { Federated: "cognito-identity.amazonaws.com" },
Action: "sts:AssumeRoleWithWebIdentity",
Condition: {
StringEquals: {
"cognito-identity.amazonaws.com:aud": identities.identityPoolId,
},
},
},
],
},
});
yield* Cognito.IdentityPoolRoleAttachment("Roles", {
identityPoolId: identities.identityPoolId,
roles: { authenticated: role.roleArn },
});

Source: src/AWS/Cognito/IdentityProvider.ts

A third-party identity provider (SAML, OIDC, or social) attached to an Amazon Cognito user pool, enabling federated sign-in through managed login.

IdentityProvider: Creating Identity Providers

Section titled “IdentityProvider: Creating Identity Providers”

OIDC Provider

import * as Cognito from "alchemy/AWS/Cognito";
const pool = yield* Cognito.UserPool("Users", {});
const oidc = yield* Cognito.IdentityProvider("Corporate", {
userPoolId: pool.userPoolId,
providerType: "OIDC",
providerDetails: {
client_id: "my-client-id",
client_secret: Redacted.make("my-client-secret"),
authorize_scopes: "openid email",
oidc_issuer: "https://accounts.google.com",
attributes_request_method: "GET",
},
attributeMapping: { email: "email", username: "sub" },
});

Wire the IdP to an App Client

const client = yield* Cognito.UserPoolClient("Web", {
userPoolId: pool.userPoolId,
supportedIdentityProviders: ["COGNITO", oidc.providerName],
});

Source: src/AWS/Cognito/ManagedLoginBranding.ts

A managed login branding style for an Amazon Cognito user pool app client. Assigning a style (even just Cognito’s provided defaults) is what activates the hosted managed login pages — a UserPoolDomain with managedLoginVersion: 2 serves them end-to-end without any console step.

ManagedLoginBranding: Activating Managed Login

Section titled “ManagedLoginBranding: Activating Managed Login”
import * as Cognito from "alchemy/AWS/Cognito";
const pool = yield* Cognito.UserPool("Users", {});
const client = yield* Cognito.UserPoolClient("Web", {
userPoolId: pool.userPoolId,
callbackUrls: ["https://example.com/callback"],
allowedOAuthFlowsUserPoolClient: true,
allowedOAuthFlows: ["code"],
allowedOAuthScopes: ["openid", "email"],
});
const domain = yield* Cognito.UserPoolDomain("AuthDomain", {
userPoolId: pool.userPoolId,
managedLoginVersion: 2,
});
yield* Cognito.ManagedLoginBranding("Branding", {
userPoolId: pool.userPoolId,
clientId: client.clientId,
});
yield* Cognito.ManagedLoginBranding("Branding", {
userPoolId: pool.userPoolId,
clientId: client.clientId,
settings: brandingSettings, // designer-exported JSON document
assets: [{
category: "FORM_LOGO",
colorMode: "LIGHT",
extension: "PNG",
bytes: logoBytes,
}],
});

Source: src/AWS/Cognito/ResourceServer.ts

An OAuth 2.0 resource server for an Amazon Cognito user pool. Resource servers declare custom scopes that app clients can request in client_credentials and authorization-code flows.

ResourceServer: Creating a Resource Server

Section titled “ResourceServer: Creating a Resource Server”

API with Custom Scopes

import * as Cognito from "alchemy/AWS/Cognito";
const pool = yield* Cognito.UserPool("Users", {});
const api = yield* Cognito.ResourceServer("Api", {
userPoolId: pool.userPoolId,
identifier: "https://api.example.com",
scopes: [
{ scopeName: "read", scopeDescription: "Read access" },
{ scopeName: "write", scopeDescription: "Write access" },
],
});

Client Requesting Resource-Server Scopes

const client = yield* Cognito.UserPoolClient("Machine", {
userPoolId: pool.userPoolId,
generateSecret: true,
allowedOAuthFlowsUserPoolClient: true,
allowedOAuthFlows: ["client_credentials"],
allowedOAuthScopes: ["https://api.example.com/read"],
});

Source: src/AWS/Cognito/User.ts

A user within an Amazon Cognito user pool, created administratively via AdminCreateUser. The invitation message is always suppressed (MessageAction: SUPPRESS) — declaratively managed users never trigger invite emails/SMS; set a permanent password to make the account usable immediately.

Basic User

import * as Cognito from "alchemy/AWS/Cognito";
const pool = yield* Cognito.UserPool("Users", {});
const user = yield* Cognito.User("Admin", {
userPoolId: pool.userPoolId,
attributes: { email: "admin@example.com", email_verified: "true" },
});

Confirmed User with a Permanent Password

import * as Redacted from "effect/Redacted";
const user = yield* Cognito.User("ServiceAccount", {
userPoolId: pool.userPoolId,
username: "service-account",
password: Redacted.make("A-Str0ng-Passw0rd!"),
attributes: { email: "svc@example.com", email_verified: "true" },
});
// user.userStatus === "CONFIRMED"

Source: src/AWS/Cognito/UserPool.ts

An Amazon Cognito user pool — a managed user directory that handles sign-up, sign-in, and token issuance (OIDC-compliant JWTs) for your application.

Basic User Pool

import * as Cognito from "alchemy/AWS/Cognito";
const pool = yield* Cognito.UserPool("Users", {});

Email Sign-In with Password Policy

const pool = yield* Cognito.UserPool("Users", {
usernameAttributes: ["email"],
autoVerifiedAttributes: ["email"],
passwordPolicy: {
minimumLength: 12,
requireSymbols: false,
},
});

Admin-Only User Creation

const pool = yield* Cognito.UserPool("Users", {
adminCreateUserOnly: true,
accountRecovery: [{ name: "admin_only", priority: 1 }],
});
const pool = yield* Cognito.UserPool("Users", {
schema: [
{ name: "tenantId", mutable: false },
{ name: "plan", attributeDataType: "String" },
],
});
const identity = yield* SES.EmailIdentity("Sender", {
emailIdentity: "mail.example.com",
});
// allow Cognito to send through the identity
yield* SES.EmailIdentityPolicy("CognitoSend", {
emailIdentity: identity.emailIdentity,
policyName: "cognito",
policy: {
Version: "2012-10-17",
Statement: [{
Effect: "Allow",
Principal: { Service: "cognito-idp.amazonaws.com" },
Action: ["ses:SendEmail", "ses:SendRawEmail"],
Resource: identity.identityArn,
}],
},
});
const pool = yield* Cognito.UserPool("Users", {
usernameAttributes: ["email"],
autoVerifiedAttributes: ["email"],
emailConfiguration: {
emailSendingAccount: "DEVELOPER",
sourceArn: identity.identityArn,
from: "My App <no-reply@mail.example.com>",
replyToEmailAddress: "support@example.com",
},
});

UserPool: Email OTP with a Custom Email Sender

Section titled “UserPool: Email OTP with a Custom Email Sender”
const key = yield* KMS.Key("CodeKey", {});
const sender = yield* Lambda.Function("EmailSender", {
main: import.meta.url,
});
yield* Lambda.Permission("CognitoInvoke", {
functionName: sender.functionName,
action: "lambda:InvokeFunction",
principal: "cognito-idp.amazonaws.com",
});
const pool = yield* Cognito.UserPool("Auth", {
tier: "ESSENTIALS",
usernameAttributes: ["email"],
signInPolicy: { allowedFirstAuthFactors: ["PASSWORD", "EMAIL_OTP"] },
customEmailSender: { lambdaArn: sender.functionArn },
kmsKeyId: key.keyArn,
});
const pool = yield* Cognito.UserPool("Users", {});
const client = yield* Cognito.UserPoolClient("Web", {
userPoolId: pool.userPoolId,
explicitAuthFlows: ["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],
});

Source: src/AWS/Cognito/UserPoolAdmin.ts

Runtime binding for administrative Cognito user pool operations.

Bind this to a UserPool inside a function runtime to get a typed client for user management and admin auth flows. The binding grants the corresponding cognito-idp:* IAM actions scoped to the pool’s ARN and injects the pool ID into every call.

Create a User with a Permanent Password

const admin = yield* Cognito.UserPoolAdmin(pool);
yield* admin.adminCreateUser({
Username: "user@example.com",
MessageAction: "SUPPRESS",
UserAttributes: [
{ Name: "email", Value: "user@example.com" },
{ Name: "email_verified", Value: "true" },
],
});
yield* admin.adminSetUserPassword({
Username: "user@example.com",
Password: "Sup3r-secret!",
Permanent: true,
});

Look Up and Delete a User

const user = yield* admin.adminGetUser({ Username: "user@example.com" });
yield* admin.adminDeleteUser({ Username: "user@example.com" });
yield* admin.adminAddUserToGroup({
Username: "user@example.com",
GroupName: "Admins",
});
const admins = yield* admin.listUsersInGroup({ GroupName: "Admins" });
const groups = yield* admin.adminListGroupsForUser({
Username: "user@example.com",
});

Link a Federated Identity to a Native User

yield* admin.adminLinkProviderForUser({
DestinationUser: {
ProviderName: "Cognito",
ProviderAttributeValue: "user@example.com",
},
SourceUser: {
ProviderName: "Google",
ProviderAttributeName: "Cognito_Subject",
ProviderAttributeValue: googleSub,
},
});

List a User’s Remembered Devices

const devices = yield* admin.adminListDevices({
Username: "user@example.com",
});

Source: src/AWS/Cognito/UserPoolAuth.ts

Runtime binding for the public (client-side) Cognito user pool auth flows.

Bind this to a UserPoolClient inside a function runtime to get a typed client for sign-up, sign-in, and token flows. These operations are unauthenticated (Cognito does not evaluate IAM for them), so the binding grants no IAM policy — it injects the app client ID into every call.

Username/Password Sign-In

const auth = yield* Cognito.UserPoolAuth(client);
const result = yield* auth.initiateAuth({
AuthFlow: "USER_PASSWORD_AUTH",
AuthParameters: { USERNAME: username, PASSWORD: password },
});
const idToken = result.AuthenticationResult?.IdToken;

Sign-Up and Confirmation

yield* auth.signUp({
Username: "user@example.com",
Password: "Sup3r-secret!",
UserAttributes: [{ Name: "email", Value: "user@example.com" }],
});
yield* auth.confirmSignUp({
Username: "user@example.com",
ConfirmationCode: code,
});

Read the Signed-In User

const user = yield* auth.getUser({ AccessToken: accessToken });

UserPoolAuth: Self-Service Account Management

Section titled “UserPoolAuth: Self-Service Account Management”

Change Password and Update Attributes

yield* auth.changePassword({
AccessToken: accessToken,
PreviousPassword: oldPassword,
ProposedPassword: newPassword,
});
yield* auth.updateUserAttributes({
AccessToken: accessToken,
UserAttributes: [{ Name: "nickname", Value: "sam" }],
});

Refresh Tokens

const refreshed = yield* auth.getTokensFromRefreshToken({
RefreshToken: refreshToken,
});

Source: src/AWS/Cognito/UserPoolClient.ts

An app client of an Amazon Cognito user pool. Applications authenticate against the pool through a client, which controls the allowed auth flows, token lifetimes, and OAuth settings.

Public Client with Password Auth

import * as Cognito from "alchemy/AWS/Cognito";
const pool = yield* Cognito.UserPool("Users", {});
const client = yield* Cognito.UserPoolClient("Web", {
userPoolId: pool.userPoolId,
explicitAuthFlows: ["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],
});

Confidential Client with a Secret

const server = yield* Cognito.UserPoolClient("Server", {
userPoolId: pool.userPoolId,
generateSecret: true,
explicitAuthFlows: ["ALLOW_ADMIN_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"],
});
const client = yield* Cognito.UserPoolClient("Web", {
userPoolId: pool.userPoolId,
accessTokenValidity: 30,
idTokenValidity: 30,
refreshTokenValidity: 7,
tokenValidityUnits: {
accessToken: "minutes",
idToken: "minutes",
refreshToken: "days",
},
});
const client = yield* Cognito.UserPoolClient("Web", {
userPoolId: pool.userPoolId,
allowedOAuthFlowsUserPoolClient: true,
allowedOAuthFlows: ["code"],
allowedOAuthScopes: ["openid", "email"],
callbackUrls: ["https://example.com/callback"],
supportedIdentityProviders: ["COGNITO"],
});

Source: src/AWS/Cognito/UserPoolDomain.ts

A domain for an Amazon Cognito user pool’s managed login and OAuth 2.0 authorization server. Cognito-prefix domains (<prefix>.auth.<region>.amazoncognito.com) provision in seconds; custom domains require an ACM certificate in us-east-1 and can take 15-60 minutes.

Cognito-Prefix Domain

import * as Cognito from "alchemy/AWS/Cognito";
const pool = yield* Cognito.UserPool("Users", {});
const domain = yield* Cognito.UserPoolDomain("AuthDomain", {
userPoolId: pool.userPoolId,
});

Explicit Prefix

const domain = yield* Cognito.UserPoolDomain("AuthDomain", {
userPoolId: pool.userPoolId,
domain: "my-app-auth",
});
const domain = yield* Cognito.UserPoolDomain("AuthDomain", {
userPoolId: pool.userPoolId,
domain: "auth.example.com",
certificateArn: certificate.certificateArn, // must be us-east-1
});

Source: src/AWS/Cognito/UserPoolTriggerEventSource.ts

Event source connecting a Cognito UserPool Lambda trigger to the hosting Lambda function.

At deploy time the Lambda implementation (Lambda.UserPoolTriggerEventSource) injects the function ARN into the pool’s LambdaConfig (via the pool’s binding contract) and creates the lambda:InvokeFunction Permission for cognito-idp.amazonaws.com; at runtime it dispatches matching trigger events to the handler and returns the handler’s (mutated) event to Cognito.

Use the onUserPoolTrigger helper (or the per-slot shorthands onPreSignUp, onPostConfirmation, onPreTokenGeneration, onCustomMessage) rather than the service directly, and provide Lambda.UserPoolTriggerEventSource on the hosting function.

UserPoolTriggerEventSource: Handling User Pool Triggers

Section titled “UserPoolTriggerEventSource: Handling User Pool Triggers”
export default AuthFunction.make(
{ main: import.meta.url },
Effect.gen(function* () {
const pool = yield* Cognito.UserPool("Users", {});
// deploy: wires PreSignUp in the pool's LambdaConfig + invoke Permission
// runtime: dispatches PreSignUp_* events to this handler
yield* Cognito.onPreSignUp(pool, (event) =>
Effect.sync(() => Cognito.autoConfirmUser(event, { verifyEmail: true })),
);
return {};
}).pipe(Effect.provide(Lambda.UserPoolTriggerEventSource)),
);