Sample code for 30+ languages & platforms
PowerShell Requires Chilkat v11.6.0+

Amazon Cognito: Sign In and Respond to Password or MFA Challenges

See more Amazon Cognito Examples

Enable ALLOW_USER_PASSWORD_AUTH on a public app client without a secret; use a password-based pool with device remembering disabled. Managed login with PKCE is preferable when your application need not handle passwords. This example illustrates the JSON API directly: start with username/password, then respond to each returned challenge with its latest Session. It does not implement SRP, remembered-device authentication, passkeys, custom challenges, or every possible challenge.

Set action=start with a private signin-input.json containing username and password. For respond, supply username plus new_password or code. NEW_PASSWORD_REQUIRED can also require a required_attributes object keyed by the names in ChallengeParameters.requiredAttributes, for example "userAttributes.email". Supply only requested missing attributes; existing required attributes cannot be changed during this challenge. Handles NEW_PASSWORD_REQUIRED, SMS_MFA, SOFTWARE_TOKEN_MFA and EMAIL_OTP. MFA_SETUP is handed to TOTP enrollment. Other challenges stop explicitly.

The latest challenge is saved privately with the canonical username and app/account binding. Only AuthenticationResult constitutes completed sign-in; a Session is not an access token. Confirmation codes remain strings, preserving leading zeroes. On timeout/expired session start again; do not reuse a session across users or parallel flows.

Uses direct Chilkat.Http requests to the regional Cognito User Pools JSON API. Public app-client operations do not use IAM signing. These examples use a public app client without a client secret; do not add administrative AWS credentials. For a confidential app client, implement the operation-specific SecretHash/SECRET_HASH or ClientSecret requirements on a trusted system.

Create qa_data/cognito/app.json with string fields region (for example us-west-2), user_pool_id, client_id, and account_key (your local account identifier). OAuth examples also require domain, the trusted HTTPS base URL of your Cognito domain, without a trailing slash. The region and user pool must match the app client. These examples use commercial AWS endpoints.

Sample cache/input files contain secrets. Use an access-controlled directory outside web content and source control, separate each local user/account, and serialize operations that modify the same cache. In a real application obtain passwords and codes through private UI instead of leaving them in files. Cache writes retain a .bak copy; protect and remove obsolete backups and challenge files after the flow. Production storage should provide atomic replacement and OS-backed secret protection. Never restore an old refresh token automatically after rotation. These examples do not require a hosted web server.

Checks transport completion, HTTP status, and required response fields before using results. Cognito often reports throttling, invalid codes, and authentication failures as HTTP 400. Present generic sign-in/recovery errors to users; keep detailed diagnostics private. Retry throttled reads with bounded backoff, but reconcile uncertain writes and refresh rotations before repeating them.

AWS documentation 1 | AWS documentation 2

Chilkat PowerShell Downloads

PowerShell
Add-Type -Path "C:\chilkat\ChilkatDotNet47-x64\ChilkatDotNet47.dll"

$success = $false

#  Assumes Chilkat is unlocked. See Global Unlock Sample.
$success = $false
#  App settings are trusted configuration. Keep a separate account_key/cache per local user.
$app = New-Object Chilkat.JsonObject
$app.Strict = $true
$success = $app.LoadFile("qa_data/cognito/app.json")
if ($success -ne $true) {
    $("Could not load Cognito app settings.")
    exit
}

if (($app.JsonTypeOf("region") -ne 1) -or ($app.StringOf("region") -eq "")) {
    $("Missing or invalid region.")
    exit
}

if (($app.JsonTypeOf("user_pool_id") -ne 1) -or ($app.StringOf("user_pool_id") -eq "")) {
    $("Missing or invalid user_pool_id.")
    exit
}

if (($app.JsonTypeOf("client_id") -ne 1) -or ($app.StringOf("client_id") -eq "")) {
    $("Missing or invalid client_id.")
    exit
}

if (($app.JsonTypeOf("account_key") -ne 1) -or ($app.StringOf("account_key") -eq "")) {
    $("Missing or invalid account_key.")
    exit
}

$clientId = $app.StringOf("client_id")
$endpoint = New-Object Chilkat.StringBuilder
$endpoint.Append("https://cognito-idp.")
$endpoint.Append($app.StringOf("region"))
$endpoint.Append(".amazonaws.com/")
$http = New-Object Chilkat.Http
$http.RequireSslCertVerify = $true
$http.FollowRedirects = $false
$http.ConnectTimeout = 20
$http.ReadTimeout = 60
$resp = New-Object Chilkat.HttpResponse
$body = New-Object Chilkat.JsonObject
$result = New-Object Chilkat.JsonObject
$result.Strict = $true
#  "start" begins sign-in. "respond" submits input for the most recent saved challenge.
$action = "start"
if (($action -ne "start") -and ($action -ne "respond")) {
    $("Choose start or respond.")
    exit
}

$input = New-Object Chilkat.JsonObject
$input.Strict = $true
$success = $input.LoadFile("qa_data/cognito/signin-input.json")
if ($success -ne $true) {
    $("Could not load qa_data/cognito/signin-input.json.")
    exit
}

if (($input.JsonTypeOf("username") -ne 1) -or ($input.StringOf("username") -eq "")) {
    $("Missing or invalid username.")
    exit
}

$username = $input.StringOf("username")
$body.UpdateString("ClientId",$clientId)
if ($action -eq "start") {
    if (($input.JsonTypeOf("password") -ne 1) -or ($input.StringOf("password") -eq "")) {
        $("Missing or invalid password.")
        exit
    }

    $body.UpdateString("AuthFlow","USER_PASSWORD_AUTH")
    $body.UpdateString("AuthParameters.USERNAME",$username)
    $body.UpdateString("AuthParameters.PASSWORD",$input.StringOf("password"))
    $http.SetRequestHeader("X-Amz-Target","AWSCognitoIdentityProviderService.InitiateAuth")
    $success = $http.HttpJson("POST",$endpoint.GetAsString(),$body,"application/x-amz-json-1.0",$resp)
    if ($resp.StatusCode -ne 200) {
        $("HTTP status: " + $resp.StatusCode)
        $success = $result.Load($resp.BodyStr)
        if ($success -eq $true) {
            $("Error type: " + $result.StringOf("__type"))
            $("OAuth error: " + $result.StringOf("error"))
        }

        #  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
        exit
    }

    if ($success -ne $true) {
        $("The HTTP exchange did not complete.")
        exit
    }

    $success = $result.Load($resp.BodyStr)
    if ($success -ne $true) {
        $("Expected a JSON response.")
        exit
    }

}
else {
    $challenge = New-Object Chilkat.JsonObject
    $challenge.Strict = $true
    $success = $challenge.LoadFile("qa_data/tokens/cognito-challenge.json")
    if ($success -ne $true) {
        $("Could not load qa_data/tokens/cognito-challenge.json.")
        exit
    }

    if (($challenge.JsonTypeOf("client_id") -ne 1) -or ($challenge.StringOf("client_id") -eq "")) {
        $("Missing or invalid client_id.")
        exit
    }

    if ($challenge.StringOf("client_id") -ne $app.StringOf("client_id")) {
        $("Saved data belongs to another client, pool, or local account.")
        exit
    }

    if (($challenge.JsonTypeOf("user_pool_id") -ne 1) -or ($challenge.StringOf("user_pool_id") -eq "")) {
        $("Missing or invalid user_pool_id.")
        exit
    }

    if ($challenge.StringOf("user_pool_id") -ne $app.StringOf("user_pool_id")) {
        $("Saved data belongs to another client, pool, or local account.")
        exit
    }

    if (($challenge.JsonTypeOf("account_key") -ne 1) -or ($challenge.StringOf("account_key") -eq "")) {
        $("Missing or invalid account_key.")
        exit
    }

    if ($challenge.StringOf("account_key") -ne $app.StringOf("account_key")) {
        $("Saved data belongs to another client, pool, or local account.")
        exit
    }

    if (($challenge.JsonTypeOf("Session") -ne 1) -or ($challenge.StringOf("Session") -eq "")) {
        $("Missing or invalid Session.")
        exit
    }

    if (($challenge.JsonTypeOf("ChallengeName") -ne 1) -or ($challenge.StringOf("ChallengeName") -eq "")) {
        $("Missing or invalid ChallengeName.")
        exit
    }

    if (($challenge.JsonTypeOf("username") -ne 1) -or ($challenge.StringOf("username") -eq "")) {
        $("Missing or invalid username.")
        exit
    }

    #  Use the bound canonical username from the previous response, not a new alias.
    $username = $challenge.StringOf("username")
    $challengeName = $challenge.StringOf("ChallengeName")
    $body.UpdateString("Session",$challenge.StringOf("Session"))
    $body.UpdateString("ChallengeName",$challengeName)
    $body.UpdateString("ChallengeResponses.USERNAME",$username)
    if ($challengeName -eq "NEW_PASSWORD_REQUIRED") {
        if (($input.JsonTypeOf("new_password") -ne 1) -or ($input.StringOf("new_password") -eq "")) {
            $("Missing or invalid new_password.")
            exit
        }

        $body.UpdateString("ChallengeResponses.NEW_PASSWORD",$input.StringOf("new_password"))
        #  requiredAttributes is a JSON array encoded inside a JSON string.
        $requiredAttributes = New-Object Chilkat.JsonArray
        $requiredJson = $challenge.StringOf("ChallengeParameters.requiredAttributes")
        if ($challenge.HasMember("ChallengeParameters.requiredAttributes") -ne $true) {
            $requiredJson = "[]"
        }

        $success = $requiredAttributes.Load($requiredJson)
        if ($success -ne $true) {
            $("Invalid required-attributes list.")
            exit
        }

        $answers = New-Object Chilkat.JsonObject
        $success = $body.ObjectOf2("ChallengeResponses",$answers)
        if ($success -ne $true) {
            $("Could not access challenge responses.")
            exit
        }

        $i = 0
        $count = $requiredAttributes.Size

        $supplied = New-Object Chilkat.JsonObject
        if ($count -gt 0) {
            $success = $input.ObjectOf2("required_attributes",$supplied)
            if ($success -ne $true) {
                $("Supply all required attributes in required_attributes.")
                exit
            }

        }

        while ($i -lt $count) {
            $attribute = $requiredAttributes.StringAt($i)
            #  Keys are returned as userAttributes.email, userAttributes.name, etc.
            #  StringOf with a quoted path treats the whole key literally.
            $attributePath = New-Object Chilkat.StringBuilder
            $attributePath.Append("`"")
            $attributePath.Append($attribute)
            $attributePath.Append("`"")
            $attributeValue = $supplied.StringOf($attributePath.GetAsString())
            if (($supplied.JsonTypeOf($attributePath.GetAsString()) -ne 1) -or ($attributeValue -eq "")) {
                $("A required user attribute is missing.")
                exit
            }

            $answers.AppendString($attribute,$attributeValue)
            $i = $i + 1
        }

    }
    else {
        if (($challengeName -ne "SMS_MFA") -and ($challengeName -ne "SOFTWARE_TOKEN_MFA") -and ($challengeName -ne "EMAIL_OTP")) {
            $("This challenge needs a different handler: " + $challengeName)
            #  MFA_SETUP is demonstrated in the TOTP enrollment example. Do not assume sign-in succeeded.
            exit
        }

        if (($input.JsonTypeOf("code") -ne 1) -or ($input.StringOf("code") -eq "")) {
            $("Missing or invalid code.")
            exit
        }

        if ($challengeName -eq "SMS_MFA") {
            $body.UpdateString("ChallengeResponses.SMS_MFA_CODE",$input.StringOf("code"))
        }

        if ($challengeName -eq "SOFTWARE_TOKEN_MFA") {
            $body.UpdateString("ChallengeResponses.SOFTWARE_TOKEN_MFA_CODE",$input.StringOf("code"))
        }

        if ($challengeName -eq "EMAIL_OTP") {
            $body.UpdateString("ChallengeResponses.EMAIL_OTP_CODE",$input.StringOf("code"))
        }

    }

    $http.SetRequestHeader("X-Amz-Target","AWSCognitoIdentityProviderService.RespondToAuthChallenge")
    $success = $http.HttpJson("POST",$endpoint.GetAsString(),$body,"application/x-amz-json-1.0",$resp)
    if ($resp.StatusCode -ne 200) {
        $("HTTP status: " + $resp.StatusCode)
        $success = $result.Load($resp.BodyStr)
        if ($success -eq $true) {
            $("Error type: " + $result.StringOf("__type"))
            $("OAuth error: " + $result.StringOf("error"))
        }

        #  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
        exit
    }

    if ($success -ne $true) {
        $("The HTTP exchange did not complete.")
        exit
    }

    $success = $result.Load($resp.BodyStr)
    if ($success -ne $true) {
        $("Expected a JSON response.")
        exit
    }

}

if ($result.JsonTypeOf("AuthenticationResult") -eq 3) {
    $token = New-Object Chilkat.JsonObject
    $token.UpdateString("access_token",$result.StringOf("AuthenticationResult.AccessToken"))
    $token.UpdateString("id_token",$result.StringOf("AuthenticationResult.IdToken"))
    $token.UpdateString("token_type",$result.StringOf("AuthenticationResult.TokenType"))
    $token.UpdateInt("expires_in",$result.IntOf("AuthenticationResult.ExpiresIn"))
    if ($result.HasMember("AuthenticationResult.RefreshToken") -eq $true) {
        $token.UpdateString("refresh_token",$result.StringOf("AuthenticationResult.RefreshToken"))
    }

    if (($token.JsonTypeOf("access_token") -ne 1) -or ($token.StringOf("access_token") -eq "")) {
        $("Missing or invalid access_token.")
        exit
    }

    if (($token.JsonTypeOf("id_token") -ne 1) -or ($token.StringOf("id_token") -eq "")) {
        $("Missing or invalid id_token.")
        exit
    }

    if (($token.JsonTypeOf("expires_in") -ne 2) -or ($token.IntOf("expires_in") -le 0)) {
        $("Expected a positive token lifetime.")
        exit
    }

    if ($token.StringOf("token_type") -ne "Bearer") {
        $("Expected Bearer tokens.")
        exit
    }

    if (($token.JsonTypeOf("refresh_token") -ne 1) -or ($token.StringOf("refresh_token") -eq "")) {
        $("Missing or invalid refresh_token.")
        exit
    }

    $token.UpdateString("client_id",$app.StringOf("client_id"))
    $token.UpdateString("user_pool_id",$app.StringOf("user_pool_id"))
    $token.UpdateString("account_key",$app.StringOf("account_key"))
    $obtained = New-Object Chilkat.CkDateTime
    $success = $obtained.SetFromCurrentSystemTime()
    if ($success -ne $true) {
        $("Could not get the acquisition time.")
        exit
    }

    $token.UpdateString("obtained_at",$obtained.GetAsTimestamp($false))
    $tokenusertokens = New-Object Chilkat.FileAccess
    $success = $tokenusertokens.DirEnsureExists("qa_data/tokens")
    if ($success -ne $true) {
        $("Could not create the private cache directory.")
        exit
    }

    if ($tokenusertokens.FileExists("qa_data/tokens/cognito-user.json") -eq $true) {
        $success = $tokenusertokens.FileCopy("qa_data/tokens/cognito-user.json","qa_data/tokens/cognito-user.json.bak",$false)
        if ($success -ne $true) {
            $("Could not back up the existing cache.")
            exit
        }

    }

    $success = $token.WriteFile("qa_data/tokens/cognito-user.json")
    if ($success -ne $true) {
        $("Could not save user tokens; preserve any previous backup.")
        exit
    }

    #  A completed flow no longer needs its short-lived challenge session.
    $cleanup = New-Object Chilkat.FileAccess
    if ($cleanup.FileExists("qa_data/tokens/cognito-challenge.json") -eq $true) {
        $cleanup.FileDelete("qa_data/tokens/cognito-challenge.json")
    }

    $("Sign-in completed; private token cache saved.")
    exit
}

if (($result.JsonTypeOf("ChallengeName") -ne 1) -or ($result.StringOf("ChallengeName") -eq "")) {
    $("Missing or invalid ChallengeName.")
    exit
}

if (($result.JsonTypeOf("Session") -ne 1) -or ($result.StringOf("Session") -eq "")) {
    $("Missing or invalid Session.")
    exit
}

#  ChallengeParameters may provide the canonical username after alias-based sign-in.
if (($result.JsonTypeOf("ChallengeParameters.USER_ID_FOR_SRP") -eq 1) -and ($result.StringOf("ChallengeParameters.USER_ID_FOR_SRP") -ne "")) {
    $username = $result.StringOf("ChallengeParameters.USER_ID_FOR_SRP")
}

if (($result.JsonTypeOf("ChallengeParameters.USERNAME") -eq 1) -and ($result.StringOf("ChallengeParameters.USERNAME") -ne "")) {
    $username = $result.StringOf("ChallengeParameters.USERNAME")
}

$result.UpdateString("username",$username)
$result.UpdateString("client_id",$app.StringOf("client_id"))
$result.UpdateString("user_pool_id",$app.StringOf("user_pool_id"))
$result.UpdateString("account_key",$app.StringOf("account_key"))
$resultauthenticationchallenge = New-Object Chilkat.FileAccess
$success = $resultauthenticationchallenge.DirEnsureExists("qa_data/tokens")
if ($success -ne $true) {
    $("Could not create the private cache directory.")
    exit
}

if ($resultauthenticationchallenge.FileExists("qa_data/tokens/cognito-challenge.json") -eq $true) {
    $success = $resultauthenticationchallenge.FileCopy("qa_data/tokens/cognito-challenge.json","qa_data/tokens/cognito-challenge.json.bak",$false)
    if ($success -ne $true) {
        $("Could not back up the existing cache.")
        exit
    }

}

$success = $result.WriteFile("qa_data/tokens/cognito-challenge.json")
if ($success -ne $true) {
    $("Could not save authentication challenge; preserve any previous backup.")
    exit
}

$("Further authentication required: " + $result.StringOf("ChallengeName"))
#  Collect the requested input in your application's UI; never print the Session value.