Migrate Users to Amazon Cognito: The User Migration Lambda Trigger vs CSV Import With Password Hashes (bcrypt, Argon2id), the SRP Catch and the 5-Second Limit

Logeshwaran
—

There are two ways to migrate users into Amazon Cognito without making everyone reset their password. The user migration Lambda trigger moves people one at a time: when someone who is not yet in your user pool signs in, Cognito hands their username and password to your function, the function checks them against your old system, and Cognito creates the user on the spot. The CSV import job moves everyone at once, and it can now carry existing password hashes (bcrypt, scrypt, Argon2id or PBKDF2-SHA256), so imported users sign in with the passwords they already have. The catch that stops most trigger migrations cold: the trigger only runs for sign-in flows that send the password (USER_PASSWORD_AUTH, ADMIN_USER_PASSWORD_AUTH, or USER_AUTH with a password). The SRP flow that the Amplify libraries use by default never reaches your function, so with default settings the trigger simply never fires. And whatever your function does, it has 5 seconds to answer, a limit you cannot change. This page covers choosing a method, the trigger code (including pool-to-pool moves), the CSV import with hashes, forgot-password, the user ID that changes, costs and every common error.

Jake's booking site had kept its customer logins in its own database since the shop opened, and Ethan wanted them in Cognito before adding repair-status texts. Moving 3,000 customers without a single "please reset your password" email was the goal. His first try went live on a Wednesday, and by Friday not one customer had been migrated, although plenty had signed in. "Is the function broken?" Jake asked. "It has never been called," Ethan said, staring at an empty log group. "Our login screen was too secure to use it." This page is what he changed, and the faster route he took for the rest.

⚡ Quick Answer

• Pick a method: trigger for lazy, one-by-one moves; CSV import (with hashes) for everyone at once. Compare.

• Trigger never runs? Enable ALLOW_USER_PASSWORD_AUTH and sign in with it; SRP never calls the trigger. The SRP catch.

• Trigger code: verify the password, return userAttributes, finalUserStatus: CONFIRMED, messageAction: SUPPRESS. Python example.

• Bulk with passwords: create-user-import-job --password-hashing-algorithm BCRYPT plus a password_hash column. Hash import.

• Watch out: 5-second limit, new sub per user, password policy not enforced during migration. Gotchas.

Pool to pool · CSV import steps · Forgot password · Cost · Troubleshooting.

New to Amazon Cognito? A user pool is Cognito's user directory: it stores accounts, checks passwords, sends verification codes and issues the tokens your app and APIs trust. An app client is your application's entry in the pool, and its settings decide which sign-in flows are allowed. A Lambda trigger is a Lambda function Cognito calls at a fixed moment, such as before sign-up or, here, when an unknown user signs in.

🧭 NEW HERE? READ THESE FIRST

New to Cognito, Lambda or IAM? These five pages cover the basics this migration builds on:

💡 Whatever method you choose, run it against a test user pool first; user pools cannot be renamed or have their sign-in attributes changed later.

Migration trigger vs CSV import vs admin API: which to use

 User migration Lambda triggerCSV import with password hashesCSV import without hashes
Who movesOnly users who sign in (or reset their password)Everyone in the fileEveryone in the file
PasswordsKept; your code checks them against the old systemKept, if hashed with bcrypt, scrypt, Argon2id or PBKDF2-SHA256 within the limitsLost; users must reset (RESET_REQUIRED)
Old system needed afterwardsYes, until everyone has signed in (often months)NoNo
Inactive usersNever migrated (often a feature)Imported; no MAU charge until they sign inImported; resets create MAUs
Sign-in flow restrictionPassword flows only, never SRPNo SRP until each user's first sign-inNone after the reset
EffortCode and a reachable old systemA CSV export and one jobA CSV export and one job

Rules of thumb. If your old system stores passwords as bcrypt, scrypt, Argon2id or PBKDF2-SHA256 and you can export the hashes, the CSV import with hashes is the simplest by far: one job, no code, no old system left running. If your hashes are in another format (salted SHA-1, MD5, a framework-specific scheme) or you cannot export them, the trigger is the way to keep passwords. And if the old directory is another Cognito user pool, the trigger can check passwords against it directly, which is the usual way to move to a new pool. A third, rarely needed option is scripting AdminCreateUser plus AdminSetUserPassword, which only works if you know each user's plain-text password, and you should not.

How the user migration trigger works, step by step

  1. A user who exists in your old system but not in the user pool signs in through your app with their username and password.
  2. Cognito checks whether the username (or an alias such as email) exists in the pool. It does not.
  3. Cognito invokes your migration function with triggerSource set to UserMigration_Authentication, passing the username and the password the user typed.
  4. Your function checks the credentials against the old system. If they are right, it returns the user's attributes and status; if not, it returns an error.
  5. Cognito creates the user in the pool with those attributes and, for a correct password, completes the sign-in and returns tokens, all within the same request.
  6. From then on, the user exists in the pool, so the trigger is never called for them again; Cognito checks their password itself.

The same trigger also runs, with triggerSource UserMigration_ForgotPassword, when an unknown user starts the forgot-password flow. That second path matters for anyone who has forgotten their old password, covered below.

The SRP catch: why the trigger never fires

Cognito can only give your function a password if the app actually sends one. That rules out the Secure Remote Password (SRP) flow, USER_SRP_AUTH, where the password never leaves the device in usable form. The trigger runs only for:

  • USER_PASSWORD_AUTH (client-side apps sending the password over TLS),
  • ADMIN_USER_PASSWORD_AUTH (server-side code using admin APIs),
  • USER_AUTH when the user chooses a password, and
  • the forgot-password flow.

It is never called for SRP sign-in and never for passwordless sign-in. The Amplify libraries use SRP unless told otherwise, so a migration built behind a default Amplify sign-in screen never runs, which was Ethan's empty log group. The fix has two parts:

  1. In the Cognito console, open the user pool, choose App clients, open your app client and edit Authentication flows to allow ALLOW_USER_PASSWORD_AUTH (or ALLOW_ADMIN_USER_PASSWORD_AUTH for server-side sign-in).
  2. Make the app use that flow. In Amplify JavaScript, pass options: { authFlowType: 'USER_PASSWORD_AUTH' } to signIn; with the SDK directly, call InitiateAuth with AuthFlow=USER_PASSWORD_AUTH.

Users who sign in through Cognito's managed login pages, rather than a screen you built, can be migrated by the trigger as well. Test that path separately with a test account from the old system, because it uses the app client's settings in its own way, and you want to see a migrated user appear from both routes before you announce anything.

You can switch back to SRP for everyone once the migration window closes. During the migration, the password travels to Cognito inside the TLS connection, which is how most web logins work anyway; just never log it in your function.

A migration trigger in Python

This function checks a password against an old database that stored bcrypt hashes, and returns what Cognito needs. Replace find_legacy_user with your lookup; keep the database credentials in Secrets Manager, not in the code:

import bcrypt                      # packaged with the function or in a layer

def find_legacy_user(username):
    """Look the user up in the old system; return None if absent.
    Example shape: {"email": "sam@example.com", "hash": "$2b$12$...", "name": "Sam"}"""
    raise NotImplementedError

def handler(event, context):
    source = event["triggerSource"]
    user = find_legacy_user(event["userName"])
    if user is None:
        raise Exception("User does not exist")

    if source == "UserMigration_Authentication":
        password = event["request"]["password"]
        if not bcrypt.checkpw(password.encode(), user["hash"].encode()):
            raise Exception("Bad password")
        event["response"]["finalUserStatus"] = "CONFIRMED"
    elif source != "UserMigration_ForgotPassword":
        raise Exception(f"Unexpected trigger source {source}")

    event["response"]["userAttributes"] = {
        "email": user["email"],
        "email_verified": "true",
        "name": user["name"],
    }
    event["response"]["messageAction"] = "SUPPRESS"
    return event

What each response field does:

  • userAttributes (required): every attribute the pool marks as required must be present, or Cognito does not create the profile. Custom attributes need the custom: prefix. Set email_verified (or phone_number_verified) to "true" if the old system had verified it, so the user can reset their password later.
  • finalUserStatus: CONFIRMED lets the user in with the password they just typed. Leave it out and the user is RESET_REQUIRED, and your app must handle PasswordResetRequiredException.
  • messageAction: SUPPRESS stops Cognito's welcome message. Without it, every migrated customer gets a welcome email or text, by SMS if you do not set desiredDeliveryMediums to EMAIL.
  • forceAliasCreation: if the email is already an alias of another user, true moves the alias to this user (the other user can no longer sign in with it); the default false fails the migration instead.
  • enableSMSMFA: require SMS MFA for this user; the pool must have MFA enabled and the attributes must include a phone number.

Raising an exception (or returning an error) tells Cognito the credentials are bad, and the sign-in fails for the user like any wrong password. Keep error messages generic so the function does not reveal which usernames exist in the old system.

The same trigger in Node.js

If your team works in JavaScript, the function looks like this. The structure is identical: check, fill in the response, return the event, or throw to reject the sign-in:

import bcrypt from "bcryptjs";
import { findLegacyUser } from "./legacy.js";   // your lookup against the old database

export const handler = async (event) => {
  const user = await findLegacyUser(event.userName);
  if (!user) throw new Error("User does not exist");

  if (event.triggerSource === "UserMigration_Authentication") {
    const ok = await bcrypt.compare(event.request.password, user.hash);
    if (!ok) throw new Error("Bad password");
    event.response.finalUserStatus = "CONFIRMED";
  } else if (event.triggerSource !== "UserMigration_ForgotPassword") {
    throw new Error(`Unexpected trigger source ${event.triggerSource}`);
  }

  event.response.userAttributes = {
    email: user.email,
    email_verified: "true",
    "custom:legacy_id": String(user.id),
  };
  event.response.messageAction = "SUPPRESS";
  return event;
};

Attribute values are always strings, even numbers and booleans, which is why the ID is wrapped in String() and the flag is "true" in quotes. A number or a real boolean in userAttributes is a common reason the response is rejected and no user is created.

Prepare custom attributes before you migrate

Any custom attribute your trigger or CSV sets, such as custom:legacy_id, must already exist in the user pool's schema. Add them first (user pool, Sign-up experience, Custom attributes, or add-custom-attributes in the CLI). Three properties of custom attributes matter for a migration: a pool can have up to 50 of them, they can never be removed once added, and each is either mutable or immutable. An immutable attribute can only be set when the user is created, which is exactly right for an old system's user ID: the migration writes it once and nothing can change it afterwards. Remember to allow your app client to read the attributes your application needs, or they will not appear in tokens and user info.

Security checklist for the migration function

For a while, this function handles every returning customer's password in plain text. Treat it accordingly:

  • Never log the request. Logging the whole event writes passwords into CloudWatch Logs. Log the username and the outcome only.
  • Return the same error for "no such user" and "wrong password", so the function cannot be used to discover which accounts exist.
  • Keep the old system's credentials in Secrets Manager and give the function's role access to that one secret and nothing else.
  • Allow only Cognito to invoke it, with a resource policy scoped to your user pool ARN, as shown above.
  • Reach the old database privately (the function in a VPC with a security group the database allows), not over the internet.
  • Remove the function when the migration is done. A password-checking endpoint for a system you have retired is a liability with no benefit.

Connect the trigger: console, CLI and permissions

In the console, open the user pool, choose Extensions (Lambda triggers), Add Lambda trigger, pick the Migrate user trigger type, and select a function in the same Region as the pool. The console adds the resource-based permission that lets Cognito call the function. With the CLI or infrastructure code, add it yourself, scoped to your pool:

aws lambda add-permission --function-name cognito-migrate \
  --statement-id cognito-migrate --action lambda:InvokeFunction \
  --principal cognito-idp.amazonaws.com \
  --source-arn arn:aws:cognito-idp:us-east-1:111122223333:userpool/us-east-1_EXAMPLE

aws cognito-idp update-user-pool --user-pool-id us-east-1_EXAMPLE \
  --lambda-config UserMigration=arn:aws:lambda:us-east-1:111122223333:function:cognito-migrate

One warning about that second command: update-user-pool resets any setting you do not pass back to its default, including other Lambda triggers. Read the current configuration with describe-user-pool first and include everything you want to keep, or make the change in the console. A missing add-permission is the classic reason a trigger defined in Terraform or CloudFormation silently fails while the console version works.

The gotchas: 5 seconds, a new user ID, and the password policy

Five seconds, no exceptions. Cognito calls triggers synchronously and waits 5 seconds for an answer. If the function is slower, Cognito may retry, and if every attempt times out the sign-in fails. You cannot raise this limit. A migration function that connects to a database in a private network, has a cold start, and runs a slow hash check can get close. Keep it fast: create database connections outside the handler so warm invocations reuse them, give the function enough memory (CPU scales with it, and bcrypt is CPU-heavy), keep the old system's response time low, and consider provisioned concurrency during the first busy weeks.

Every migrated user gets a new sub. Cognito generates the sub attribute, the user's permanent unique ID, when it creates the user. You cannot set it, so it will not match any ID your old system used, and a user migrated from one pool to another gets a different sub in the new pool. If your app stores data by user ID, keep the old ID in a custom attribute (for example custom:legacy_id) set by the trigger or the CSV, and map it in your application before you switch your data to sub.

The password policy is not enforced during migration. Cognito accepts whatever password the migrated user had, even if it breaks the pool's minimum length or character rules, so migration does not lock people out. If you want to enforce the policy, check the password's strength in your function and return RESET_REQUIRED instead of CONFIRMED for weak ones; those users then set a new, compliant password at their next sign-in.

"So the old password still works even if it is 'jake123'?" Jake asked. "For now," Ethan said. "And the function knows to ask for a better one."

Users who forgot their old password

Someone who has not been migrated yet and cannot remember their password starts the forgot-password flow. Cognito does not know them, so it calls your function with UserMigration_ForgotPassword. There is no password in this request; your function only confirms the user exists in the old system and returns their attributes. Then Cognito creates the user and sends a reset code.

The code needs somewhere to go, so the returned attributes must include a verified email address or phone number (email_verified: "true" or phone_number_verified: "true"). Return an unverified one and the user is created but cannot receive a code. If you are not sure the old system's emails were verified, returning email_verified: "true" is a judgment call: it lets real users reset their password, but it trusts whatever address the old system holds. If codes do not arrive, our verification email guide covers the email side.

Usernames, email sign-in and aliases

How users type their identity decides what the function must return:

  • Email as the username (the pool's sign-in identifier is email): the userName in the event is the email the user typed. Return attributes as usual; Cognito uses that value.
  • A username plus email or phone as aliases: when the user signs in with an alias, the function must put the received value in the matching alias attribute (for example email) and set its own value for username in the response, a unique username for the pool.
  • A plain username: the response's username, if you return one, must exactly match the request, or be left out.

Usernames must be unique in the pool, and pools treat them case-insensitively by default for new pools, so two old accounts named Sam and sam will collide. Find and settle duplicates in the old system before migrating.

Migrate users from one Cognito user pool to another

User pools have settings you cannot change after creation (the sign-in identifiers, required attributes, and some others), so the usual fix is a new pool. The migration trigger on the new pool can check passwords against the old pool, so users move over the first time they sign in:

import os, boto3

idp = boto3.client("cognito-idp")
OLD_POOL = os.environ["OLD_POOL_ID"]
OLD_CLIENT = os.environ["OLD_CLIENT_ID"]      # an app client on the old pool with ADMIN_USER_PASSWORD_AUTH, no secret

def handler(event, context):
    username = event["userName"]
    if event["triggerSource"] == "UserMigration_Authentication":
        # raises NotAuthorizedException for a wrong password, UserNotFoundException if absent
        idp.admin_initiate_auth(UserPoolId=OLD_POOL, ClientId=OLD_CLIENT,
                                AuthFlow="ADMIN_USER_PASSWORD_AUTH",
                                AuthParameters={"USERNAME": username, "PASSWORD": event["request"]["password"]})
        event["response"]["finalUserStatus"] = "CONFIRMED"
    old = idp.admin_get_user(UserPoolId=OLD_POOL, Username=username)
    attrs = {a["Name"]: a["Value"] for a in old["UserAttributes"] if a["Name"] != "sub"}
    attrs["custom:old_sub"] = next(a["Value"] for a in old["UserAttributes"] if a["Name"] == "sub")
    event["response"]["userAttributes"] = attrs
    event["response"]["messageAction"] = "SUPPRESS"
    return event

The function's role needs cognito-idp:AdminInitiateAuth and cognito-idp:AdminGetUser on the old pool. If the old app client has a client secret, the call also needs a SECRET_HASH; creating a dedicated client without a secret for the migration is simpler. Two more details: an old user who never confirmed their account fails AdminInitiateAuth, and a user with MFA on the old pool gets a challenge instead of tokens, which your function should treat as a correct password (the password was accepted) and let the new pool's own MFA take over. The custom:old_sub attribute must exist in the new pool's schema first.

If you would rather move everyone at once, export the old pool with list-users (paginated) into the CSV format below. Cognito never exports password hashes, so a pool-to-pool CSV import always lands users in RESET_REQUIRED; the trigger is the only way to keep their passwords.

Bulk import from a CSV file, step by step

  1. Create a CloudWatch Logs role that Cognito can assume (trust cognito-idp.amazonaws.com), allowing logs:CreateLogGroup, logs:CreateLogStream, logs:DescribeLogStreams and logs:PutLogEvents on /aws/cognito/*. The console can create it for you when you create the job.
  2. Get the header for your pool's schema: aws cognito-idp get-csv-header --user-pool-id us-east-1_EXAMPLE, or download template.csv from Users, Import users, Create an import job.
  3. Fill in the CSV from your old system: one row per user, every required attribute, cognito:username, and cognito:mfa_enabled. Up to 500,000 users and 100 MB per file, rows up to 16,000 characters, updated_at in epoch seconds.
  4. Create the job: aws cognito-idp create-user-import-job --job-name customers-1 --user-pool-id us-east-1_EXAMPLE --cloud-watch-logs-role-arn ROLE_ARN (add --password-hashing-algorithm to keep passwords, below). The response includes a PreSignedUrl valid for 15 minutes.
  5. Upload the file to that URL: curl -v -T "customers.csv" -H "x-amz-server-side-encryption:aws:kms" "PRE_SIGNED_URL".
  6. Start the job: aws cognito-idp start-user-import-job --user-pool-id us-east-1_EXAMPLE --job-id JOB_ID, and watch describe-user-import-job move from Pending to InProgress to Succeeded (or Failed). A job created but not started within 24 to 48 hours becomes Expired.
  7. Read the results in CloudWatch Logs under /aws/cognito/: each failed row is logged with its reason, and the job reports imported, skipped and failed counts.

Users imported this way keep their attributes, but the creation date is the import date. Without password hashes they are all RESET_REQUIRED: at their first sign-in, Cognito returns PasswordResetRequiredException, and your app must run the forgot-password flow for them (send the code, take the new password). Test that path in your app before importing real users, or nobody can sign in.

Importing users with their password hashes

This is the newer, nicer route when your hashes are in a supported format. You choose the algorithm once per job and add a password_hash column; users are created CONFIRMED and can sign in immediately with their existing password. On each user's first sign-in, Cognito checks the password against the imported hash and then moves it into its own native format.

AlgorithmHash formatMaximum parameters
BCRYPT$2b$10$... (2a, 2b, 2x, 2y)Cost factor 12
SCRYPTN$r$p$hexSalt$hexHashN = 65536, r = 8, p = 1
ARGON2ID$argon2id$v=19$m=...,t=...,p=...$salt$hashm = 19456 KiB, t = 2, p = 1
PBKDF2_SHA256$pbkdf2-sha256$iterations$salt$hash600,000 iterations
aws cognito-idp create-user-import-job \
  --job-name customers-with-passwords \
  --user-pool-id us-east-1_EXAMPLE \
  --cloud-watch-logs-role-arn arn:aws:iam::111122223333:role/CognitoUserImportRole \
  --password-hashing-algorithm BCRYPT

The rules that trip people up: all hashes in one job must use the same algorithm (split mixed exports into several jobs); a row with an empty password_hash is imported RESET_REQUIRED; a malformed hash, or one with parameters above the limits (bcrypt cost 13 or 14, for example), fails that user and is logged; and until a user's first sign-in, SRP does not work for them, so the app must use USER_PASSWORD_AUTH or ADMIN_USER_PASSWORD_AUTH during the migration period, the same catch as the trigger.

Jake's old database used bcrypt with cost 10, so Ethan exported the 3,000 customers with their hashes, ran one job, and switched the sign-in screen to USER_PASSWORD_AUTH. Everyone was in the pool that afternoon. "We did not need the Lambda after all?" Jake asked. "We needed it to learn which button to press," Ethan said.

User statuses you will see during a migration

Every user in a pool has a status, and migrations produce three of them. Knowing which one a user is in tells you exactly what your app must do at sign-in:

StatusHow a user gets itWhat happens at sign-in
CONFIRMEDMigration trigger returned CONFIRMED, or a CSV row with a valid password hashNormal sign-in with their password
RESET_REQUIREDCSV import without a hash, or a trigger response without finalUserStatusPasswordResetRequiredException; the app runs forgot-password (code, then new password)
FORCE_CHANGE_PASSWORDCreated by an administrator with AdminCreateUser and a temporary passwordA NEW_PASSWORD_REQUIRED challenge; the app collects a new password and answers it
UNCONFIRMEDSigned up but never entered the verification codeUserNotConfirmedException; resend the code
EXTERNAL_PROVIDERSigned in through Google, Apple, Facebook, Amazon, SAML or OIDCSigns in at the provider; no Cognito password

The two "change your password" statuses look alike but need different code in your app: RESET_REQUIRED means the user proves who they are with a code sent to their email or phone, while FORCE_CHANGE_PASSWORD means they already know a temporary password and simply pick a new one. A sign-in screen built only for normal users handles neither, which is why imported users sometimes report that "the login just does nothing". You can list users by status with aws cognito-idp list-users --user-pool-id us-east-1_EXAMPLE --filter 'cognito:user_status = "RESET_REQUIRED"'.

Creating a few users by hand with the admin API

For a handful of accounts, such as staff or test users, the admin API is quicker than either migration route. Create the user without sending Cognito's invitation, then set a permanent password so they are CONFIRMED straight away:

aws cognito-idp admin-create-user --user-pool-id us-east-1_EXAMPLE \
  --username sam@example.com \
  --user-attributes Name=email,Value=sam@example.com Name=email_verified,Value=true \
  --message-action SUPPRESS

aws cognito-idp admin-set-user-password --user-pool-id us-east-1_EXAMPLE \
  --username sam@example.com --password 'A-strong-password-1' --permanent

Without --permanent, the password is temporary and the user lands in FORCE_CHANGE_PASSWORD. This route needs you to choose the password, so it is for accounts you control, not for customers: you should never know a customer's password. With boto3, the same calls are admin_create_user and admin_set_user_password.

Export users from an existing pool or system to the CSV format

When the old directory is another user pool, this script writes its users to a CSV with the new pool's header, ready for an import job. It keeps every attribute the new pool knows, stores the old sub in a custom attribute, and leaves out the sub itself:

import csv, boto3

idp = boto3.client("cognito-idp")
OLD, NEW = "us-east-1_OLDPOOL", "us-east-1_NEWPOOL"
header = idp.get_csv_header(UserPoolId=NEW)["CSVHeader"]

with open("users.csv", "w", newline="") as f:
    w = csv.DictWriter(f, fieldnames=header, extrasaction="ignore")
    w.writeheader()
    for page in idp.get_paginator("list_users").paginate(UserPoolId=OLD):
        for u in page["Users"]:
            row = {a["Name"]: a["Value"] for a in u["Attributes"]}
            if "custom:old_sub" in header:
                row["custom:old_sub"] = row.get("sub", "")
            row.pop("sub", None)
            row["cognito:username"] = u["Username"]
            row["cognito:mfa_enabled"] = "false"
            w.writerow(row)

Every column in the header must be present in each row (empty is fine for optional ones), booleans are written as true or false, and any attribute marked required in the new pool must have a value. From a SQL database, the same idea is a SELECT that names its columns after the CSV header, plus the password_hash column if you are importing hashes.

Test the migration trigger before real users hit it

You can call the function with a hand-made event that looks exactly like Cognito's, before connecting it to the pool. Save this as event.json with a test account from the old system:

{
  "version": "1",
  "triggerSource": "UserMigration_Authentication",
  "region": "us-east-1",
  "userPoolId": "us-east-1_EXAMPLE",
  "userName": "test.customer@example.com",
  "callerContext": { "awsSdkVersion": "aws-sdk-unknown-unknown", "clientId": "exampleclientid" },
  "request": { "password": "the-test-password", "validationData": null, "clientMetadata": null },
  "response": { "userAttributes": null, "finalUserStatus": null, "messageAction": null,
                "desiredDeliveryMediums": null, "forceAliasCreation": null, "enableSMSMFA": null }
}
aws lambda invoke --function-name cognito-migrate \
  --cli-binary-format raw-in-base64-out --payload file://event.json out.json
cat out.json

A correct password should return the event with userAttributes, finalUserStatus: "CONFIRMED" and messageAction: "SUPPRESS" filled in; a wrong one should return an error. Check the Duration in the function's log too, cold and warm; anything near 5,000 ms needs work before launch. Then connect the trigger to a test user pool and sign in through your real app with USER_PASSWORD_AUTH, which is the only test that proves the flow end to end.

Users who signed in with Google, Apple or a company login

Users who never had a password in your old system, because they signed in with a social or enterprise provider, cannot be migrated with either password method. In Cognito they sign in through a configured identity provider instead, and Cognito creates them automatically, with the EXTERNAL_PROVIDER status, the first time they do. If you want such a person's federated identity and an existing password account to be the same Cognito user, link them with AdminLinkProviderForUser before their first federated sign-in; otherwise Cognito creates a separate user and your app sees two accounts for one person.

Check your old hashes before you choose

The first thing to look at is one row of your old password column. The beginning of the stored value usually tells you the format, and the format decides whether a hash import is possible:

Stored value starts withTypical sourceRoute
$2a$, $2b$, $2y$ + two-digit costbcrypt from PHP, Laravel, Rails, Node.js and many othersHash import, if the cost is 12 or lower
$argon2id$Modern frameworks and librariesHash import, if memory, time and parallelism are within the limits
$pbkdf2-sha256$Libraries using that standard string formatHash import, up to 600,000 iterations
A number, then $ (for example 65536$8$1$)scrypt in the N$r$p$salt$hash layoutHash import, within N = 65536, r = 8, p = 1
Anything else (plain hex, a framework-specific prefix, a binary blob)Older or custom schemes, salted SHA or MD5, framework formatsMigration trigger, which checks passwords with your old code

Two practical points. Cost and iteration counts creep upward as frameworks raise their defaults, so check the actual numbers in your data rather than the format alone; a bcrypt cost of 13 or 14, or PBKDF2 above 600,000 iterations, fails the import for that user. And a format that is mathematically the same but written differently (a different prefix, or base64 where hex is expected) has to be rewritten into Cognito's layout exactly before import; test a handful of known passwords in a test pool before you import everyone. If anything does not fit, the trigger is always the fallback, because it runs your old system's own password check.

What the migration costs

Cognito bills by monthly active users (MAUs), users who sign in, refresh tokens or change their password in a month. US East (N. Virginia), October 2026:

Feature planPrice per MAUFree tier
Lite$0.0055 (lower at higher volumes)10,000 MAUs
Essentials$0.01510,000 MAUs
Plus$0.02None

Importing users from a CSV does not create MAUs; an imported user costs nothing until they are active. Password resets do count, so importing 200,000 users without hashes and emailing them all to reset would turn a free import into a bill: at Essentials, 190,000 billable MAUs would be about $2,850 for that month. With hashes, or with the trigger, only people who actually sign in become MAUs, which they would anyway. The migration Lambda itself costs very little: a few milliseconds of compute per migrated user.

Finishing the migration and switching off the old system

A trigger-based migration never really "ends" by itself; the people who never sign in never move. Plan the finish:

  1. Track progress: compare the pool's user count (describe-user-pool shows an estimated number) with the old system's.
  2. After a few months, export the users who have not migrated and import them by CSV, with hashes if you can.
  3. Remove the migration trigger, so a failure in the old system can no longer block sign-ins, and switch the app back to SRP if you prefer it.
  4. Delete the old system's password data once nothing reads it. A database of password hashes you no longer need is pure risk.

Cognito user migration problems, by symptom

The migration trigger is never invoked

The app signs in with SRP, the user already exists in the pool, or the app client does not allow USER_PASSWORD_AUTH. Allow the flow and use it in the app.

Sign-in fails after the function returns success

The response is missing userAttributes or a required attribute, so no profile is created. Return every required attribute in the exact shape Cognito expects.

"PasswordResetRequiredException" on first sign-in

The user was created RESET_REQUIRED: the trigger did not set finalUserStatus to CONFIRMED, or the CSV had no password hash. Run the forgot-password flow in your app, or fix the response or the import.

The sign-in times out during migration

The function took longer than 5 seconds, often a cold start plus a slow database. Reuse connections, add memory and consider provisioned concurrency.

The trigger works from the console but not when deployed with Terraform

The Lambda resource-based permission for cognito-idp.amazonaws.com is missing. Add it with the user pool ARN as the source.

Forgot password creates the user but no code arrives

The returned email or phone was not marked verified. Return email_verified or phone_number_verified as "true".

"An account with the given email already exists" style failures

The email is already an alias of another user. Merge the accounts in the old system, or set forceAliasCreation to true if moving the alias is intended.

Some rows fail in the CSV import

Check the import's CloudWatch log: missing required attributes, a malformed hash, hash parameters above the limits, or a duplicate username. Fix those rows and run a new job with only them.

The function returns attributes but Cognito rejects them

A value is not a string (a number or a real boolean), a custom attribute is missing from the pool's schema, or an attribute is not writable by the app client. Send strings only and add the attribute to the pool first.

Imported users with hashes cannot sign in with SRP

Until their first sign-in converts the hash, those users need USER_PASSWORD_AUTH or ADMIN_USER_PASSWORD_AUTH. Switch the app's flow for the migration period, then back to SRP.

The import job shows Expired

It was created but not started within 24 to 48 hours, and its data was deleted. Create a new job and start it after the upload.

My app's user IDs no longer match

Cognito generated a new sub. Store the old ID in a custom attribute and map it in your app.

Cognito user migration: frequently asked questions

What is the Cognito user migration Lambda trigger?

A Lambda function Cognito calls when a user who is not in the user pool signs in or starts forgot-password. The function checks them against your old system and returns their attributes, and Cognito creates the user.

Why is my Cognito migration trigger not being called?

It runs only for USER_PASSWORD_AUTH, ADMIN_USER_PASSWORD_AUTH, USER_AUTH with a password and forgot-password, never for SRP. Allow USER_PASSWORD_AUTH on the app client and use it in the app.

Can I import users into Cognito with their passwords?

Yes, if you have bcrypt, scrypt, Argon2id or PBKDF2-SHA256 hashes within Cognito's limits. Create the import job with --password-hashing-algorithm and include a password_hash column.

How do I import users into Cognito from a CSV file?

Create a CloudWatch Logs role, download the CSV header with get-csv-header, fill it in, create an import job, upload the file to the presigned URL and start the job.

What happens to passwords in a CSV import without hashes?

They are not imported. Users are created RESET_REQUIRED and must reset their password at first sign-in.

How many users can a Cognito CSV import job handle?

Up to 500,000 users and 100 MB per file, with rows up to 16,000 characters. Split larger exports into several jobs.

How do I migrate users from one Cognito user pool to another?

Add a migration trigger to the new pool that calls AdminInitiateAuth against the old pool to check the password, then copies the user's attributes from AdminGetUser.

Can I export users and passwords from Cognito?

You can export users and attributes with list-users, but Cognito never exports passwords or hashes. Use the migration trigger to keep passwords when moving between pools.

What is the timeout for Cognito Lambda triggers?

5 seconds, and it cannot be changed. Cognito may retry a call that times out; if all attempts fail, the request fails.

Does the Cognito migration keep the same user ID (sub)?

No. Cognito generates a new sub for every user it creates. Store the old ID in a custom attribute if your data depends on it.

Does Cognito enforce the password policy during migration?

No. Migrated passwords are accepted even if they break the policy. Check strength in your function and return RESET_REQUIRED for weak ones.

How do I stop the welcome email for migrated users?

Return messageAction set to SUPPRESS from the migration function. Without it, Cognito sends its welcome message, by SMS unless you choose EMAIL.

Do imported users count as monthly active users?

No. CSV import does not create MAUs; users count only when they sign in or reset their password.

What does finalUserStatus CONFIRMED do?

It creates the migrated user as confirmed, so they can sign in with the password they just used. Without it, the user must reset their password.

Can I use SRP with imported password hashes?

Not until each user's first sign-in. Use USER_PASSWORD_AUTH or ADMIN_USER_PASSWORD_AUTH for users whose imported hash has not been converted yet.

How much does Amazon Cognito cost per user?

In us-east-1, $0.0055 per MAU on Lite and $0.015 on Essentials after 10,000 free MAUs, and $0.02 on Plus. Imported but inactive users are free.

For readers preparing for an AWS certification

We have been covering AWS certifications alongside our fixes, so here is a short extra for readers studying for one. If you only came for the fix, you already have it; feel free to skip this part.

Exams that test this topic: Developer – Associate (DVA-C03 from December 1, 2026) • Security – Specialty (SCS-C03) • Solutions Architect – Associate (SAA-C03).

Here are the exam-style questions this topic tends to raise, with the reasoning you need to answer them:

1. Users must move from a legacy database to a Cognito user pool without resetting passwords, and the legacy hashes cannot be exported. What should you use?

A user migration Lambda trigger that verifies each password against the legacy system at first sign-in and returns the user's attributes.

2. A migration trigger is configured but never invoked when users sign in through the Amplify UI. Why?

The app uses SRP (USER_SRP_AUTH), which never sends the password to the trigger; allow and use USER_PASSWORD_AUTH during the migration.

3. Which response values make a migrated user able to sign in immediately without a welcome message?

finalUserStatus set to CONFIRMED and messageAction set to SUPPRESS, plus all required userAttributes.

4. How long does Cognito wait for a Lambda trigger to respond?

5 seconds; the limit cannot be changed, so the trigger must be fast.

5. 500,000 users with bcrypt hashes must be moved into Cognito in one operation, keeping their passwords. What is the simplest method?

A CSV user import job created with --password-hashing-algorithm BCRYPT and a password_hash column.

6. After migrating users, application records keyed by the Cognito sub no longer match. What happened?

Cognito generates a new sub for every created user; store the legacy ID in a custom attribute and map it.

Exam codes and dates change often. Our AWS certification changes page keeps track of what is current.

πŸ“š ALSO READ

Where to go next, from sign-in errors to authorizers:

📌 Bookmark this; the hash-format table is the part you will check against your old database.

The repair-status texts went out the following week to customers who had signed in with the same password they had used for years. The migration trigger stayed in place for a month, for the handful of customers whose accounts had been added after the export, then Ethan removed it and switched the app back to SRP. Jake asked whether anyone had noticed the move. "Nobody," Ethan said. "Which is the only review a migration should get."

📌 If you keep one line from this page

Import everyone with their password hashes if they are bcrypt, scrypt, Argon2id or PBKDF2-SHA256, otherwise use the migration trigger; either way, sign in with USER_PASSWORD_AUTH during the move (SRP never calls the trigger), answer within 5 seconds, return CONFIRMED and SUPPRESS, and keep the old user ID in a custom attribute.

5-second trigger limit · 500,000 users / 100 MB per CSV · bcrypt cost ≤ 12 · CSV import creates no MAUs.

Revision note. Written October 22, 2026, with Amazon Cognito's migration trigger, import job behavior and US East (N. Virginia) prices of that date. "Don't change horses in midstream," the proverb says; with users, you can, if they never feel the saddle move.

Related