日本語

Testing Cognito Sign-Up and Login with AWS Emulator

​​AWS Emulator​Amazon Cognito,AWS CLI,JWT

When you build sign-up and login for an app with an Amazon Cognito user pool, you may want to check the flow locally without an AWS account. This article creates a user pool on AWS Emulator and runs sign-up, confirmation, login, token signature verification, and sign-out. It shows the commands and output exactly as they were run in the test environment. It also explains how to mark a user as confirmed on an emulator that does not send confirmation code emails.

Note

The test environment was Ubuntu 24.04 (x86_64), AWS Emulator 1.0.556 (released November 21, 2026), AWS CLI 2.42.1, and Node.js 22. No AWS account or credentials were used. I did not test the behavior of real Amazon Cognito: whether confirmation code emails arrive, email sending limits, pricing, what happens when a token expires, or the Hosted UI and managed login pages. Where this article describes real Cognito, it is based on the official documentation. The 12-digit account ID in the output has been replaced.

Diagram of the flow from sign-up to UNCONFIRMED, then CONFIRMED with admin-confirm-sign-up, tokens with initiate-auth, and revocation with global-sign-out, showing the commands used
The user state transitions in this test and the commands used

Start the emulator and point the CLI at it

AWS Emulator is an emulator that accepts AWS API requests locally. According to the official documentation, no AWS account is needed, and requests are not sent to AWS.

For installation, see the separate article "How to Install and Start Using AWS Emulator on Ubuntu." In the test environment, I installed the Debian package from the Linux instructions after verifying its signature with gpg. I worked as root, so I did not use sudo, but the commands below include it for a regular user.

bash
curl -fsSLo aws-emulator_amd64.deb https://downloads.aws.com/aws-emulator/packages/aws-emulator/LTS/latest/aws-emulator_amd64.deb
sudo apt-get install -y ./aws-emulator_amd64.deb
aws-emulator -t off

If you want to review the emulator output later, start it with something like aws-emulator -t off > emulator.out 2>&1 to save the output to a file. -t off turns off telemetry, the usage data that is sent to AWS by default. The emulator keeps running in its terminal, so use the AWS CLI from a different terminal. In that terminal, set the environment variables from the official documentation to direct the CLI to the emulator.

bash
export AWS_ENDPOINT_URL=https://127.0.0.1:9297
export AWS_SHARED_CREDENTIALS_FILE=~/.aws/emulator/9297/emulator_credentials
export AWS_CONFIG_FILE=~/.aws/emulator/9297/config
export AWS_CA_BUNDLE=~/.aws/emulator/9297/ca.pem
export AWS_EC2_METADATA_DISABLED=true
export AWS_DISABLE_HOST_PREFIX_INJECTION=true
export AWS_REGION=us-east-1
export AWS_DEFAULT_REGION=us-east-1
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_PROFILE
Warning

The official documentation warns that if a command runs in a shell where AWS_ENDPOINT_URL is not set, it is sent to real AWS using whatever credentials it finds. On a machine that has real credentials, run commands only in a shell where all the environment variables above are set.

If the ARN ends with user/emulator, the emulator is answering.

text
$ aws sts get-caller-identity --query Arn --output text
arn:aws:iam::<12桁のアカウントID>:user/emulator

Create a user pool and an app client

Create a user pool that signs users in with their email address and treats the email as the attribute to verify. I required passwords of at least 10 characters that include lowercase letters and digits.

text
$ aws cognito-idp create-user-pool --pool-name neko-users \
    --username-attributes email --auto-verified-attributes email \
    --policies 'PasswordPolicy={MinimumLength=10,RequireUppercase=false,RequireLowercase=true,RequireNumbers=true,RequireSymbols=false}' \
    --query 'UserPool.[Id,UsernameAttributes[0],AutoVerifiedAttributes[0],Policies.PasswordPolicy.MinimumLength]' --output text
us-east-1_ab8bfcef9	email	email	10

Next, create the app client that the app will use. It is meant to be called from a browser or a smartphone app, so I did not create a client secret. I allowed login with a password (ALLOW_USER_PASSWORD_AUTH) and getting new tokens with a refresh token (ALLOW_REFRESH_TOKEN_AUTH). Because ClientSecret is null, the requests below do not need a secret hash (SECRET_HASH).

text
$ aws cognito-idp create-user-pool-client --user-pool-id us-east-1_ab8bfcef9 --client-name neko-web \
    --explicit-auth-flows ALLOW_USER_PASSWORD_AUTH ALLOW_REFRESH_TOKEN_AUTH \
    --query 'UserPoolClient.[ClientId,ClientSecret,ExplicitAuthFlows]' --output json
[
    "49fcfe8dca1f4f6bab20ddc5f9",
    null,
    [
        "ALLOW_USER_PASSWORD_AUTH",
        "ALLOW_REFRESH_TOKEN_AUTH"
    ]
]

In the following steps, I put the IDs shown when the resources were created into shell variables, such as POOL=us-east-1_ab8bfcef9 and CLIENT=49fcfe8dca1f4f6bab20ddc5f9. The output shown after each command is the actual output from those values.

Sign up without signing the request

According to the SignUp API reference, sign-up does not use IAM credentials. So I added the AWS CLI option --no-sign-request and sent the request without a signature.

First, I sent a short password that does not meet the password policy.

text
$ aws --no-sign-request cognito-idp sign-up --client-id $CLIENT \
    --username mike@example.com --password short1

aws: [ERROR]: An error occurred (InvalidPasswordException) when calling the SignUp operation: Password did not conform with policy: Password not long enough

When I sent it again with a password that meets the policy, the user was registered.

text
$ aws --no-sign-request cognito-idp sign-up --client-id $CLIENT \
    --username mike@example.com --password nekonote2026 \
    --user-attributes Name=email,Value=mike@example.com
{
    "UserConfirmed": false,
    "CodeDeliveryDetails": {
        "Destination": "m***@e***",
        "DeliveryMedium": "EMAIL",
        "AttributeName": "email"
    },
    "UserSub": "cd8989db-2f40-4e41-bf79-bd38e7a6f38e"
}
$ aws cognito-idp admin-get-user --user-pool-id $POOL --username mike@example.com \
    --query '[UserStatus, Enabled]' --output text
UNCONFIRMED	True

CodeDeliveryDetails shows where the confirmation code was sent, with the address partly masked. The returned format matched the example in the API reference. The user state is UNCONFIRMED. As the official sign-up and confirmation guide explains, a user who signed up by themselves cannot log in until they are confirmed. On the emulator too, login was rejected in this state.

text
$ aws --no-sign-request cognito-idp initiate-auth --client-id $CLIENT --auth-flow USER_PASSWORD_AUTH \
    --auth-parameters USERNAME=mike@example.com,PASSWORD=nekonote2026

aws: [ERROR]: An error occurred (UserNotConfirmedException) when calling the InitiateAuth operation: User is not confirmed.

Confirm the user as an administrator instead of using a confirmation code

With real Cognito, the app receives the confirmation code by email and sends it back with ConfirmSignUp to complete confirmation. The emulator has no mailbox to receive the email. When I sent an arbitrary code, I got CodeMismatchException. In the test, I started the emulator with something like aws-emulator -t off > emulator.out 2>&1 and saved the output (logs) to emulator.out. I searched it too, but it had only four lines, and no confirmation code appeared.

text
$ aws --no-sign-request cognito-idp confirm-sign-up --client-id $CLIENT \
    --username mike@example.com --confirmation-code 123456

aws: [ERROR]: An error occurred (CodeMismatchException) when calling the ConfirmSignUp operation: Invalid verification code provided, please try again.
$ grep -c '' emulator.out
4
$ grep -i -E 'confirm|code|mike|signup|sign_up' emulator.out

So I used AdminConfirmSignUp. This is an administrator operation that marks a user as confirmed without a confirmation code. In exchange, it requires a signature with IAM credentials. On the emulator, sending it unsigned was rejected, and it succeeded when signed with the emulator credentials.

text
$ aws --no-sign-request cognito-idp admin-confirm-sign-up --user-pool-id $POOL --username mike@example.com

aws: [ERROR]: An error occurred (AccessDenied) when calling the AdminConfirmSignUp operation: Sign the request with the emulator credentials
$ aws cognito-idp admin-confirm-sign-up --user-pool-id $POOL --username mike@example.com
$ aws cognito-idp admin-get-user --user-pool-id $POOL --username mike@example.com \
    --query '[UserStatus, UserAttributes[?Name==`email_verified`].Value|[0]]' --output text
CONFIRMED	false

The status became CONFIRMED, but email_verified stayed false. The official documentation also says that a user confirmed by an administrator may not have a verified email address. When the user enters the confirmation code, the email address is verified too. If your app branches on email_verified, keep this difference in mind.

Warning

The official documentation warns that when you test email sending with real Cognito, you should not use made-up addresses that have no inbox. If emails keep bouncing (hard bounces), the number of emails you can send from that account is limited. Do not use the example.com addresses from this emulator test as they are in a real environment.

Log in with a password and receive tokens

USER_PASSWORD_AUTH is a login method that sends the password in the request as it is (see the InitiateAuth API reference). This request is also sent without a signature. Tokens are long, so I saved the response to a file and printed only the first 12 characters of each token.

text
$ aws --no-sign-request cognito-idp initiate-auth --client-id $CLIENT --auth-flow USER_PASSWORD_AUTH \
    --auth-parameters USERNAME=mike@example.com,PASSWORD=nekonote2026 > auth.json
$ python3 -c "import json; r=json.load(open('auth.json'))['AuthenticationResult']; print({k: (v[:12]+'...' if isinstance(v,str) and len(v)>40 else v) for k,v in r.items()})"
{'AccessToken': 'eyJhbGciOiJS...', 'ExpiresIn': 3600, 'TokenType': 'Bearer', 'RefreshToken': 'eyJhbGciOiJS...', 'IdToken': 'eyJhbGciOiJS...'}

Three tokens were returned (ID token, access token, and refresh token), and ExpiresIn was 3600 seconds. A wrong password returned NotAuthorizedException (Incorrect username or password.).

For later use, I extracted the access token and refresh token into the shell variables $AT and $RT.

bash
AT=$(python3 -c "import json;print(json.load(open('auth.json'))['AuthenticationResult']['AccessToken'])")
RT=$(python3 -c "import json;print(json.load(open('auth.json'))['AuthenticationResult']['RefreshToken'])")

To display the contents of the ID token (the JWT payload), I used the following show-claims.py. It splits the token at . into three parts and decodes the second part as base64url.

python
import json, base64, sys
r = json.load(open('auth.json'))['AuthenticationResult']
def part(t, i):
    s = t.split('.')[i]; s += '=' * (-len(s) % 4)
    return json.loads(base64.urlsafe_b64decode(s))
name = sys.argv[1]
print(json.dumps(part(r[name], 1), indent=2, ensure_ascii=False))

This is the result when run on the ID token.

text
$ python3 show-claims.py IdToken
{
  "sub": "cd8989db-2f40-4e41-bf79-bd38e7a6f38e",
  "iss": "https://127.0.0.1:9297/us-east-1_ab8bfcef9",
  "aud": "49fcfe8dca1f4f6bab20ddc5f9",
  "cognito:username": "cd8989db-2f40-4e41-bf79-bd38e7a6f38e",
  "token_use": "id",
  "auth_time": 1795281777,
  "iat": 1795281777,
  "exp": 1795285377,
  "jti": "a26b6f80-30db-437a-8ae2-4aacff74d896",
  "origin_jti": "176575c1-b3c3-4b93-bb10-f1e64ad83fa9",
  "email": "mike@example.com",
  "email_verified": false
}

aud contains the client ID, and exp is 3600 seconds after iat. For the access token, token_use was access, scope was aws.cognito.signin.user.admin, and the client ID was in client_id, not aud.

The value that differed from the official description was iss (the issuer). In the official explanation of token verification, the iss of a user pool in us-east-1 is https://cognito-idp.us-east-1.amazonaws.com/<ユーザープールID>. On the emulator, it was the emulator's own address. Code that hard-codes an expected iss value will need different settings for the emulator and for real Cognito.

You can use the access token to get your own user information.

text
$ aws --no-sign-request cognito-idp get-user --access-token "$AT"
{
    "Username": "cd8989db-2f40-4e41-bf79-bd38e7a6f38e",
    "UserAttributes": [
        {
            "Name": "email",
            "Value": "mike@example.com"
        },
        {
            "Name": "email_verified",
            "Value": "false"
        },
        {
            "Name": "sub",
            "Value": "cd8989db-2f40-4e41-bf79-bd38e7a6f38e"
        }
    ]
}

Verify the token signature with the public key

When a server receives a token, it should verify the signature before trusting the contents. According to the official documentation, the public key set (JWKS) is at https://cognito-idp.<リージョン>.amazonaws.com/<ユーザープールID>/.well-known/jwks.json. On the emulator, appending the same path to the emulator's address returned two keys. The official documentation also says each user pool has two key pairs, one for access tokens and one for ID tokens.

text
$ curl -s --cacert ~/.aws/emulator/9297/ca.pem https://127.0.0.1:9297/$POOL/.well-known/jwks.json -o jwks.json
$ python3 -c "import json; print([(k['kid'], k['kty'], k['alg'], k['use']) for k in json.load(open('jwks.json'))['keys']])"
[('Ss5p5lcfQTHTrq4dt_d01BLM7SoJq8xhvS9jP0sjIwY', 'RSA', 'RS256', 'sig'), ('mFadnjcW7_RaE_Zi-_uZ5UYIvaIY3dL36EkRoFhAHVQ', 'RSA', 'RS256', 'sig')]

I selected the key whose kid matches the one in the ID token header, and checked the RS256 signature with Node.js crypto. For comparison, I also checked a token whose payload had only its email changed.

js
// verify-jwt.mjs: Verify the signature of IdToken with the user pool's JWKS public key
import { createPublicKey, createVerify } from 'node:crypto';
import { readFileSync } from 'node:fs';
const token = JSON.parse(readFileSync('auth.json', 'utf8')).AuthenticationResult.IdToken;
const jwks = JSON.parse(readFileSync('jwks.json', 'utf8'));
const [h, p, s] = token.split('.');
const header = JSON.parse(Buffer.from(h, 'base64url'));
const jwk = jwks.keys.find((k) => k.kid === header.kid);
const key = createPublicKey({ key: jwk, format: 'jwk' });
const ok = createVerify('RSA-SHA256').update(`${h}.${p}`).verify(key, Buffer.from(s, 'base64url'));
console.log('kid が一致する鍵:', jwk ? 'あり' : 'なし');
console.log('署名の検証:', ok ? 'OK' : 'NG');
const forged = Buffer.from(JSON.stringify({ ...JSON.parse(Buffer.from(p, 'base64url')), email: 'other@example.com' })).toString('base64url');
const ok2 = createVerify('RSA-SHA256').update(`${h}.${forged}`).verify(key, Buffer.from(s, 'base64url'));
console.log('中身を書き換えたトークンの検証:', ok2 ? 'OK' : 'NG');
text
$ node verify-jwt.mjs
kid が一致する鍵: あり
署名の検証: OK
中身を書き換えたトークンの検証: NG

This code only checks the signature. The official documentation also asks you to check exp, aud (client_id for access tokens), iss, and token_use. For Node.js apps, AWS recommends aws-jwt-verify.

Refresh and sign out

When I sent the refresh token with REFRESH_TOKEN_AUTH, I got a new ID token and access token. The response did not include a refresh token.

text
$ aws --no-sign-request cognito-idp initiate-auth --client-id $CLIENT --auth-flow REFRESH_TOKEN_AUTH \
    --auth-parameters REFRESH_TOKEN="$RT" --query 'keys(AuthenticationResult)' --output text
AccessToken	ExpiresIn	TokenType	IdToken

Finally, I signed out with GlobalSignOut. The API reference says that calling an API with a revoked access token returns Access Token has been revoked, and that the refresh token is no longer accepted. The emulator returned the same errors.

text
$ aws --no-sign-request cognito-idp global-sign-out --access-token "$AT"
$ aws --no-sign-request cognito-idp get-user --access-token "$AT"

aws: [ERROR]: An error occurred (NotAuthorizedException) when calling the GetUser operation: Access Token has been revoked
$ aws --no-sign-request cognito-idp initiate-auth --client-id $CLIENT --auth-flow REFRESH_TOKEN_AUTH \
    --auth-parameters REFRESH_TOKEN="$RT" --query 'keys(AuthenticationResult)' --output text

aws: [ERROR]: An error occurred (NotAuthorizedException) when calling the InitiateAuth operation: Refresh Token has been revoked

However, a signature check alone cannot tell you whether a token has been revoked. In a separate test, after signing out and getting Access Token has been revoked from get-user, verify-jwt.mjs above still reported the ID token's signature as "OK." The official documentation also says that if you need revocation to take effect before expiration, you should either check with Cognito or shorten the access token's lifetime.

After I confirmed a user and signed them out, signing up again with the same email address returned UsernameExistsException (User already exists).

You can delete a user pool you no longer need with aws cognito-idp delete-user-pool --user-pool-id $POOL. In the test environment, the count from list-user-pools was 0 after deletion.

​Posted by 86