Engineering & Architecture
Amazon Cognito gotchas I'd tell anyone starting out
A soft, steady sound, a bit like rain, that helps some people focus while they read.
Some Google accounts don't have a surname. Our user pool required one, and Cognito doesn't let you change that once a pool exists. So we moved every user to a new user pool.
I've worked extensively with Cognito, on a product of my own and on client projects. Most of what I know about it came from moments like that one, where Cognito did exactly what its documentation says and not what I had assumed. These are the gotchas I'd tell anyone starting out. Where I say "we", I mean that product. The rest is general guidance, not the story of any one project.
Required attributes are permanent
When you create a user pool, you choose which standard attributes every user must have, and that choice is final. AWS says it plainly. "After you create a user pool, you can't switch an attribute between required and not required." You can't delete or rename a custom attribute later either.
We had made the first name and the surname required. On a sign-up form, that looked harmless. Once people could sign in with Google, anyone whose Google account had no surname couldn't sign in with it, and the only way out was a new pool.
Our new pools require only an email address. We collect everything else in the app, where we can change our minds later. I'd start every pool that way.
Passwords and ids don't move with your users
Copying users into a new pool is the easy part. We created each one with AdminCreateUser and told it not to send the invitation email, so nobody got a message they weren't expecting. A user created that way starts in "FORCE_CHANGE_PASSWORD". Cognito has no API that gives you the password hashes from the old pool, so the new pool doesn't know anyone's password.
Cognito's own answer is the migrate user trigger. It runs when someone who isn't in the new pool yet signs in with a password. Your function checks the password against the old directory, and if it's right, Cognito creates the user on the spot. It doesn't run for SRP sign-in, because the password never reaches your function in that flow.
We couldn't use the trigger, because we had already copied everyone. But the old pool was still running, and it could still check a password. So we put a small bridge in front of sign-in. When someone's sign-in to the new pool failed, the site sent the same email and password to the bridge. The bridge tried those details against the old pool, and only if they worked did it set the same password on the new pool. Then the site tried again. The person signing in never noticed.
A function that accepts passwords needs care. Ours never logs the request, not even the length of the password. It's throttled, and it only acts on accounts that are still in "FORCE_CHANGE_PASSWORD", so it stops working for a person after their first successful sign-in. We also meant it to run only until the move had settled. If your data doesn't need the new ids before people sign in, I'd use the migrate user trigger instead, so that you don't have an endpoint of your own that takes passwords.
We copied everyone first because of the sub. AWS describes it as "a unique user identifier within each user pool". Cognito assigns it, so a copied user gets a new one. We used the sub as the user id everywhere, so every id in our data had to change at the moment the apps switched pools. Copying everyone first gave us the full list of old and new ids, so we could change them all in one go.
The database was the part we had planned for, but we had used the id in other places too. Every file a person uploads is stored under a path that starts with their user id, so we had to copy those files to the new path, or every upload would have gone missing. Our payment provider keeps the user id on each subscription, and our webhook handlers use it to find the user, so renewals would have failed until we updated them. Our product analytics needed the new ids linked to the old ones, or everyone's history would have started from zero.
Some people also signed up on the old pool after we had copied the users and before the switch. We had written every script so that it was safe to run twice, so we ran them all again after the switch to bring those people across.
If you're starting a new pool, give each user an id of your own and store the sub against it. Moving pools then means updating one mapping, not every table, bucket and webhook.
Google sign-in creates a second user unless you link it
When someone signs in with Google for the first time, Cognito creates a separate user for them, with a username that starts with the provider's name. AWS's Google guide says so directly. "Amazon Cognito doesn't automatically merge a Google user with an existing user that has the same email." If the same person had already signed up with a password, they now have two accounts and two sub values.
We wanted one account per person. So in our setup, every Google sign-in ends up on a regular user, and a pre sign-up trigger links the Google identity to it with AdminLinkProviderForUser. That also means someone who started with Google can add a password later.
AWS's guidance on linking comes with warnings that are worth taking seriously. Linking lets the Google identity sign in as the existing user, so AWS says to use it only with providers and attributes you trust. The Google guide adds that you should link only on a trusted email_verified value. Linking also has to happen before the person's first Google sign-in. Once a separate Google user exists, you have to delete it before you can link the identity.
There are two smaller things to know. Google needs the /oauth2/idpresponse address of your user pool domain as an authorized redirect URI. That domain is also what people see while they sign in, so a custom domain is worth setting up. Ours shows our own address instead of a long amazoncognito.com one.
Triggers get five seconds, and may run twice
Cognito's Lambda triggers run while the person waits. AWS's page on triggers says a function "must respond within 5 seconds". If it doesn't, and the call can be retried, Cognito may call it again. You can't change the five seconds.
So a trigger that calls something slow can run twice for the same person. I've seen a post confirmation trigger call a slow downstream service, miss the five seconds and get called again. The second call created the user's record, and the first one then failed because the record already existed. When that service was down altogether, the person still got into the app, with no record behind them.
Three things follow from that. Make every trigger safe to run twice, the same way you would any event handler. Keep slow work out of the trigger and hand it to a queue instead. And don't make a trigger the only place where a user's record can be created. If your API sees a signed-in user with no record, it should create one.
Cognito isn't a database you can query
Sooner or later, someone needs to find users in bulk. ListUsers returns at most 60 users per call. It pages with a token, so you can't jump to the 121st user. You can filter on one attribute at a time, and only on a short list of standard ones. "Custom attributes aren't searchable." The results are also eventually consistent, so a recent change may not show up straight away.
Then there are the quotas. Listing users is limited to 30 requests a second, and the calls that update users, like AdminUpdateUserAttributes, to 25. You can't have either limit raised, and every user pool in that Region of your account shares them. At 25 a second, changing one attribute for 100,000 users takes over an hour, and anything else that updates users in that time shares the same 25.
Email case is where this causes the most trouble. If the same address was saved as J.Smith@ once and j.smith@ another time, finding every version of it means listing users and comparing them yourself. A user pool can be case insensitive, which covers email too. The console creates new pools that way, but the API and the CLI don't. If you create a pool from either without setting it, the pool is case sensitive, and you can't change it to case insensitive later.
So set it yourself when you create the pool, and lowercase email addresses before they reach Cognito anyway. Keep your own copy of the user list for searching and reporting, and treat Cognito as the place where people sign in.
Check more than the signature
A token with a valid signature isn't necessarily a token meant for you. AWS's guide to verifying a token goes through the checks. These five are the ones you make on the token itself:
- The signature, against your user pool's public keys
- The expiry
- The issuer, which should be your user pool
- The token use, ID or access, depending on which one your API expects
- The audience, which is
audin an ID token andclient_idin an access token, and should be your app client
Access tokens have no aud by default. So code that checks aud rejects them, and code that skips the audience check accepts tokens issued to any other app client on the same pool. Our authorizer accepts only ID tokens from our own pool and our own app clients, and denies everything else. We have to add a new app client to its list before that client goes live.
Signing someone out has a catch too. A revoked token fails on Cognito's own APIs, but AWS says revoked tokens "will still be valid if they are verified using any JWT library that verifies the signature and expiration of the token". So after a sign-out, your API keeps accepting that person's ID and access tokens until they expire. Keep those lifetimes short. Cognito allows anything from 5 minutes to a day. For the actions that matter most, check with Cognito as well. And to sign someone out of one session rather than all of them, revoke that session's refresh token instead of calling global sign-out.
The last one caught us after we added Google sign-in. Our authorizer passed the token's claims on to API Gateway. ID tokens for Google users carry an identities claim, which is a list of objects. API Gateway doesn't accept an object or a list as a value in the authorizer's context, so every request from a Google user failed with a 500. Password users never saw it, because all of their claims are plain values. The fix was to pass on only strings, numbers and true or false values.
What I'd do with a new pool
If you're creating a user pool today, these are the five things I'd do from the start:
- Require only an email address, and collect everything else in the app.
- Set the pool to case insensitive yourself, and lowercase emails before they reach Cognito.
- Give users an id of your own, and store the
subagainst it. - Keep every trigger quick and safe to run twice.
- Check the issuer, token use and audience of every token, and keep token lifetimes short.
All of this is in AWS's documentation, usually in a sentence that's easy to skim the first time. I just read a few of them after the fact.
