Skip to content

From Amazon Cognito

For: an operator and a developer who move an app from Amazon Cognito to authtempo.

What it does: you import the users of a Cognito user pool. Cognito exports no hash, so core asks Cognito once, at each user’s first password sign-in, and then keeps its own hash.

  • An API with authtempo. Do a getting started tutorial first.
  • The AWS CLI, with read access to the user pool.
  • An app client of the pool that lists ALLOW_USER_PASSWORD_AUTH in its auth flows. password.legacyVerify of Passwords calls it.
  • A pool that accepts the address as a user name or as an alias. password.legacyVerify of Passwords sends the address.
  • @authtempo/cli and @authtempo/legacy-hashes in the app’s workspace. authtempo import is a command of the first.
  1. Export the users, and keep the whole output with its Users array.
Terminal window
aws cognito-idp list-users --user-pool-id "$POOL" --output json > users.json

Cognito exports no hash. Core checks each password against Cognito once, at the user’s first password sign-in.

  1. Set password.legacyVerify in the API with the region and the app client of the pool.
The API with the check against Cognito
import { createAuth, type MailPort, type StorageAdapter } from "@authtempo/core";
import { createCognitoLegacyVerify } from "@authtempo/legacy-hashes/cognito";
/**
* The API after an import from Amazon Cognito. Cognito exports no hash, so
* core asks Cognito once per user, at the first password sign-in, and then
* writes its own hash. Remove `legacyVerify` when the migration ends.
*/
export function createCognitoAuth(
deps: { storage: StorageAdapter; mail: MailPort; secret: string },
// The global fetch in the app. The test passes a fake Cognito.
fetchImpl: typeof fetch = globalThis.fetch,
) {
return createAuth({
baseURL: "https://api.example.com",
trustedOrigins: [],
secret: deps.secret,
storage: deps.storage,
mail: deps.mail,
password: {
legacyVerify: {
verify: createCognitoLegacyVerify({
region: "eu-west-1",
// The app client must allow ALLOW_USER_PASSWORD_AUTH.
clientId: "example-app-client-id",
fetch: fetchImpl,
}),
// Every failed password sign-in answers no earlier than this, so a
// migrated and an unmigrated address look the same.
timeoutMs: 2000,
},
},
});
}
  1. Pass clientSecret too, when the app client has a secret.
  2. On Workers, pass waitUntil, so the failure line outlives the response.
  1. Run the import as a dry run, and read the report.
  2. Cognito exports no hash, so the hashes: line counts legacy-verify markers and none only.

The @authtempo packages are on npm. Add the CLI to your app with pnpm add -D @authtempo/cli, and run each command as pnpm exec authtempo ….

Terminal window
authtempo import cognito --users users.json --legacy-verify --target postgres --url-env DATABASE_URL --dry-run

Run the real import on a copy of the database only. The one real import into the real database runs at step 9 of The cutover, after the old sign-ins stop. If it runs earlier, a password, an address, or a delete that changes in the old system after it is lost. One real import tells why.

  1. Make the copy. On Postgres, create an empty database, set COPY_URL to its URL, and load the real one into it with pg_dump --no-owner "$DATABASE_URL" | psql "$COPY_URL".
  2. On D1, load the real database into the empty local copy of the import Worker with wrangler d1 export <database> --remote --output copy.sql and wrangler d1 execute <database> --local --file copy.sql.
  3. Run both in the folder of the import Worker. Delete its .wrangler/state first, or the load stops on a table that exists.
  4. Run the same command without --dry-run, with --url-env COPY_URL. On D1, run the import Worker without "remote": true, so it writes the local copy.
Terminal window
authtempo import cognito --users users.json --legacy-verify --target postgres --url-env COPY_URL
  1. Run authtempo import verify with the same files on the copy. It exits 0 only when the copy holds the whole export.
  2. Run authtempo check <base url> against the API.
  3. Sign in once with a known user. Sign in once more with a user whose Cognito address has capital letters. Do it at step 13 of The cutover: before that step, the real database holds no user.
  4. Drop the copy, and on D1 delete copy.sql, when import verify exits 0. The copy holds every user of the export.
Terminal window
authtempo import verify cognito --users users.json --legacy-verify --target postgres --url-env COPY_URL
authtempo check https://api.example.com

The test below imports one Cognito user against a fake Cognito.

The test of this guide
import { LEGACY_VERIFY_HASH } from "@authtempo/core";
import { importUsers, readSource } from "@authtempo/import";
import { FIXTURE_EXPORTS } from "@authtempo/import/testing";
import { describe, expect, it } from "vitest";
import { call, type Harness, harness } from "../support/harness.ts";
import { createCognitoAuth } from "./cognito.ts";
// The fixture export of the Cognito reader holds Cara, one CONFIRMED user, with no hash.
const f = FIXTURE_EXPORTS.cognito;
/** A fake Cognito: InitiateAuth passes for one password and refuses every other. */
function fakeCognito(password: string) {
const calls: string[] = [];
const impl = (async (_url: RequestInfo | URL, init?: RequestInit) => {
const body = JSON.parse(String(init?.body)) as {
AuthParameters: { USERNAME: string; PASSWORD: string };
};
calls.push(body.AuthParameters.USERNAME);
return body.AuthParameters.PASSWORD === password
? Response.json({ AuthenticationResult: { AccessToken: "cognito-access-token" } })
: Response.json({ __type: "NotAuthorizedException" }, { status: 400 });
}) as typeof fetch;
return { impl, calls };
}
/** Reads the hash of the one password row in the database. */
async function onlyHash(h: Harness): Promise<string> {
const rows = await h.storage.findMany("password", []);
expect(rows.length).toBe(1);
return rows[0]?.hash ?? "";
}
describe("move users from Amazon Cognito", () => {
it("imports the fixture export with the marker", async () => {
const h = harness();
const report = await importUsers(h.storage, await readSource(f.bundle), {
formats: [],
legacyVerify: true,
});
expect(report.created.password).toBe(1);
// Core reads this marker as "ask the old system".
expect(await onlyHash(h)).toBe(LEGACY_VERIFY_HASH);
const cognito = fakeCognito("right horse battery");
const auth = createCognitoAuth(h, cognito.impl);
const res = await call(auth, "POST", "/auth/password/sign-in", {
email: "cara@example.com",
password: "right horse battery",
});
expect(res.status).toBe(200);
expect(cognito.calls).toEqual(["cara@example.com"]);
expect((await onlyHash(h)).startsWith("pbkdf2-sha256$")).toBe(true);
});
it("asks Cognito once at the first sign-in, then signs in with core's own hash", async () => {
const h = harness();
const report = await importUsers(h.storage, await readSource(f.bundle), {
formats: [],
legacyVerify: true,
});
expect(report.created.password).toBe(1);
const cognito = fakeCognito("right horse battery");
const auth = createCognitoAuth(h, cognito.impl);
const signIn = (password: string) =>
call(auth, "POST", "/auth/password/sign-in", { email: "cara@example.com", password });
expect((await signIn("right horse battery")).status).toBe(200);
expect((await signIn("right horse battery")).status).toBe(200);
expect(cognito.calls).toEqual(["cara@example.com"]);
});
it("answers invalid_credentials when Cognito refuses the password", async () => {
const h = harness();
await importUsers(h.storage, await readSource(f.bundle), {
formats: [],
legacyVerify: true,
});
const auth = createCognitoAuth(h, fakeCognito("right horse battery").impl);
const res = await call(auth, "POST", "/auth/password/sign-in", {
email: "cara@example.com",
password: "wrong",
});
expect(res.status).toBe(401);
expect(await res.json()).toEqual({ error: "invalid_credentials" });
});
});
  1. Change each auth call of the app with the table of The calls.
  1. Do the steps of The cutover.
  2. Remove legacyVerify from the API when the migration ends.
Amplify authtempo
signIn({ username, password }) client.password.signIn({ email, password })
signUp({ username, password }) client.password.signUp({ email, password })
signInWithRedirect({ provider: "Google" }) Send the browser to /auth/social/google/start?next=/ on the API.
resetPassword({ username }) client.password.requestReset({ email })
confirmResetPassword(input) client.password.reset({ token, password }), with the token of the reset link
signOut() client.signOut()
getCurrentUser(), fetchAuthSession() client.session()
The ID token of fetchAuthSession() client.jwt.token()
  • Only a CONFIRMED user gets the marker. Every other status skips the user, and the reason names the status.
  • Only the built-in providers Google and SignInWithApple map to an identity.
  • Core calls Cognito only for a user whose password row holds the marker. A right answer writes core’s own hash over it.
  • Every failed password sign-in answers no earlier than timeoutMs. So the response time does not show an address that is not yet migrated.
  • A claim of the address deletes the marker, and a reset overwrites it.
  • Each Cognito challenge answers false, the second factor and NEW_PASSWORD_REQUIRED among them. Such a user resets the password.
  • invalid_credentials for every user: the app client does not allow USER_PASSWORD_AUTH, or the pool does not take the address as a user name. The log line names the Cognito error.
  • The command exits 1 with legacy-verify refusals: the run has no --legacy-verify.
  • The command stops at start: users.json holds a bare array. Save the whole list-users output.