Sample code for 30+ languages & platforms
Lua 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 Lua Downloads

Lua
local chilkat = require("chilkat")

-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local success = false
-- App settings are trusted configuration. Keep a separate account_key/cache per local user.
local app = chilkat.JsonObject.new()
app.strict = true
success = app:load_file("qa_data/cognito/app.json")
if not success then
    print("Could not load Cognito app settings.")
    return
end

if (app:json_type_of("region") ~= 1) or (app:string_of("region") == "") then
    print("Missing or invalid region.")
    return
end

if (app:json_type_of("user_pool_id") ~= 1) or (app:string_of("user_pool_id") == "") then
    print("Missing or invalid user_pool_id.")
    return
end

if (app:json_type_of("client_id") ~= 1) or (app:string_of("client_id") == "") then
    print("Missing or invalid client_id.")
    return
end

if (app:json_type_of("account_key") ~= 1) or (app:string_of("account_key") == "") then
    print("Missing or invalid account_key.")
    return
end

local clientId = app:string_of("client_id")
local endpoint = chilkat.StringBuilder.new()
endpoint:append("https://cognito-idp.")
endpoint:append(app:string_of("region"))
endpoint:append(".amazonaws.com/")
local http = chilkat.Http.new()
http.require_ssl_cert_verify = true
http.follow_redirects = false
http.connect_timeout = 20
http.read_timeout = 60
local resp = chilkat.HttpResponse.new()
local body = chilkat.JsonObject.new()
local result = chilkat.JsonObject.new()
result.strict = true
-- "start" begins sign-in. "respond" submits input for the most recent saved challenge.
local action = "start"
if (action ~= "start") and (action ~= "respond") then
    print("Choose start or respond.")
    return
end

local input = chilkat.JsonObject.new()
input.strict = true
success = input:load_file("qa_data/cognito/signin-input.json")
if not success then
    print("Could not load qa_data/cognito/signin-input.json.")
    return
end

if (input:json_type_of("username") ~= 1) or (input:string_of("username") == "") then
    print("Missing or invalid username.")
    return
end

local username = input:string_of("username")
body:update_string("ClientId", clientId)
if action == "start" then
    if (input:json_type_of("password") ~= 1) or (input:string_of("password") == "") then
        print("Missing or invalid password.")
        return
    end

    body:update_string("AuthFlow", "USER_PASSWORD_AUTH")
    body:update_string("AuthParameters.USERNAME", username)
    body:update_string("AuthParameters.PASSWORD", input:string_of("password"))
    http:set_request_header("X-Amz-Target", "AWSCognitoIdentityProviderService.InitiateAuth")
    success = http:http_json("POST", endpoint:get_as_string(), body, "application/x-amz-json-1.0", resp)
    if resp.status_code ~= 200 then
        print("HTTP status: " .. resp.status_code)
        success = result:load(resp.body_str)
        if success then
            print("Error type: " .. result:string_of("__type"))
            print("OAuth error: " .. result:string_of("error"))
        end

        -- Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
        return
    end

    if not success then
        print("The HTTP exchange did not complete.")
        return
    end

    success = result:load(resp.body_str)
    if not success then
        print("Expected a JSON response.")
        return
    end
else
    local challenge = chilkat.JsonObject.new()
    challenge.strict = true
    success = challenge:load_file("qa_data/tokens/cognito-challenge.json")
    if not success then
        print("Could not load qa_data/tokens/cognito-challenge.json.")
        return
    end

    if (challenge:json_type_of("client_id") ~= 1) or (challenge:string_of("client_id") == "") then
        print("Missing or invalid client_id.")
        return
    end

    if challenge:string_of("client_id") ~= app:string_of("client_id") then
        print("Saved data belongs to another client, pool, or local account.")
        return
    end

    if (challenge:json_type_of("user_pool_id") ~= 1) or (challenge:string_of("user_pool_id") == "") then
        print("Missing or invalid user_pool_id.")
        return
    end

    if challenge:string_of("user_pool_id") ~= app:string_of("user_pool_id") then
        print("Saved data belongs to another client, pool, or local account.")
        return
    end

    if (challenge:json_type_of("account_key") ~= 1) or (challenge:string_of("account_key") == "") then
        print("Missing or invalid account_key.")
        return
    end

    if challenge:string_of("account_key") ~= app:string_of("account_key") then
        print("Saved data belongs to another client, pool, or local account.")
        return
    end

    if (challenge:json_type_of("Session") ~= 1) or (challenge:string_of("Session") == "") then
        print("Missing or invalid Session.")
        return
    end

    if (challenge:json_type_of("ChallengeName") ~= 1) or (challenge:string_of("ChallengeName") == "") then
        print("Missing or invalid ChallengeName.")
        return
    end

    if (challenge:json_type_of("username") ~= 1) or (challenge:string_of("username") == "") then
        print("Missing or invalid username.")
        return
    end

    -- Use the bound canonical username from the previous response, not a new alias.
    username = challenge:string_of("username")
    local challengeName = challenge:string_of("ChallengeName")
    body:update_string("Session", challenge:string_of("Session"))
    body:update_string("ChallengeName", challengeName)
    body:update_string("ChallengeResponses.USERNAME", username)
    if challengeName == "NEW_PASSWORD_REQUIRED" then
        if (input:json_type_of("new_password") ~= 1) or (input:string_of("new_password") == "") then
            print("Missing or invalid new_password.")
            return
        end

        body:update_string("ChallengeResponses.NEW_PASSWORD", input:string_of("new_password"))
        -- requiredAttributes is a JSON array encoded inside a JSON string.
        local requiredAttributes = chilkat.JsonArray.new()
        local requiredJson = challenge:string_of("ChallengeParameters.requiredAttributes")
        if not challenge:has_member("ChallengeParameters.requiredAttributes") then
            requiredJson = "[]"
        end

        success = requiredAttributes:load(requiredJson)
        if not success then
            print("Invalid required-attributes list.")
            return
        end

        local answers = chilkat.JsonObject.new()
        success = body:object_of2("ChallengeResponses", answers)
        if not success then
            print("Could not access challenge responses.")
            return
        end

        local i = 0
        local count = requiredAttributes.size
        local attribute = ""
        local attributeValue = ""
        local supplied = chilkat.JsonObject.new()
        if count > 0 then
            success = input:object_of2("required_attributes", supplied)
            if not success then
                print("Supply all required attributes in required_attributes.")
                return
            end
        end

        while i < count do
            attribute = requiredAttributes:string_at(i)
            -- Keys are returned as userAttributes.email, userAttributes.name, etc.
            -- StringOf with a quoted path treats the whole key literally.
            local attributePath = chilkat.StringBuilder.new()
            attributePath:append("\"")
            attributePath:append(attribute)
            attributePath:append("\"")
            attributeValue = supplied:string_of(attributePath:get_as_string())
            if (supplied:json_type_of(attributePath:get_as_string()) ~= 1) or (attributeValue == "") then
                print("A required user attribute is missing.")
                return
            end

            answers:append_string(attribute, attributeValue)
            i = i + 1
        end
    else
        if (challengeName ~= "SMS_MFA") and ((challengeName ~= "SOFTWARE_TOKEN_MFA") and (challengeName ~= "EMAIL_OTP")) then
            print("This challenge needs a different handler: " .. challengeName)
            -- MFA_SETUP is demonstrated in the TOTP enrollment example. Do not assume sign-in succeeded.
            return
        end

        if (input:json_type_of("code") ~= 1) or (input:string_of("code") == "") then
            print("Missing or invalid code.")
            return
        end

        if challengeName == "SMS_MFA" then
            body:update_string("ChallengeResponses.SMS_MFA_CODE", input:string_of("code"))
        end

        if challengeName == "SOFTWARE_TOKEN_MFA" then
            body:update_string("ChallengeResponses.SOFTWARE_TOKEN_MFA_CODE", input:string_of("code"))
        end

        if challengeName == "EMAIL_OTP" then
            body:update_string("ChallengeResponses.EMAIL_OTP_CODE", input:string_of("code"))
        end
    end

    http:set_request_header("X-Amz-Target", "AWSCognitoIdentityProviderService.RespondToAuthChallenge")
    success = http:http_json("POST", endpoint:get_as_string(), body, "application/x-amz-json-1.0", resp)
    if resp.status_code ~= 200 then
        print("HTTP status: " .. resp.status_code)
        success = result:load(resp.body_str)
        if success then
            print("Error type: " .. result:string_of("__type"))
            print("OAuth error: " .. result:string_of("error"))
        end

        -- Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
        return
    end

    if not success then
        print("The HTTP exchange did not complete.")
        return
    end

    success = result:load(resp.body_str)
    if not success then
        print("Expected a JSON response.")
        return
    end
end

if result:json_type_of("AuthenticationResult") == 3 then
    local token = chilkat.JsonObject.new()
    token:update_string("access_token", result:string_of("AuthenticationResult.AccessToken"))
    token:update_string("id_token", result:string_of("AuthenticationResult.IdToken"))
    token:update_string("token_type", result:string_of("AuthenticationResult.TokenType"))
    token:update_int("expires_in", result:int_of("AuthenticationResult.ExpiresIn"))
    if result:has_member("AuthenticationResult.RefreshToken") then
        token:update_string("refresh_token", result:string_of("AuthenticationResult.RefreshToken"))
    end

    if (token:json_type_of("access_token") ~= 1) or (token:string_of("access_token") == "") then
        print("Missing or invalid access_token.")
        return
    end

    if (token:json_type_of("id_token") ~= 1) or (token:string_of("id_token") == "") then
        print("Missing or invalid id_token.")
        return
    end

    if (token:json_type_of("expires_in") ~= 2) or (token:int_of("expires_in") <= 0) then
        print("Expected a positive token lifetime.")
        return
    end

    if token:string_of("token_type") ~= "Bearer" then
        print("Expected Bearer tokens.")
        return
    end

    if (token:json_type_of("refresh_token") ~= 1) or (token:string_of("refresh_token") == "") then
        print("Missing or invalid refresh_token.")
        return
    end

    token:update_string("client_id", app:string_of("client_id"))
    token:update_string("user_pool_id", app:string_of("user_pool_id"))
    token:update_string("account_key", app:string_of("account_key"))
    local obtained = chilkat.DateTime.new()
    success = obtained:set_from_current_system_time()
    if not success then
        print("Could not get the acquisition time.")
        return
    end

    token:update_string("obtained_at", obtained:get_as_timestamp(false))
    local tokenusertokens = chilkat.FileAccess.new()
    success = tokenusertokens:dir_ensure_exists("qa_data/tokens")
    if not success then
        print("Could not create the private cache directory.")
        return
    end

    if tokenusertokens:file_exists("qa_data/tokens/cognito-user.json") then
        success = tokenusertokens:file_copy("qa_data/tokens/cognito-user.json", "qa_data/tokens/cognito-user.json.bak", false)
        if not success then
            print("Could not back up the existing cache.")
            return
        end
    end

    success = token:write_file("qa_data/tokens/cognito-user.json")
    if not success then
        print("Could not save user tokens; preserve any previous backup.")
        return
    end

    -- A completed flow no longer needs its short-lived challenge session.
    local cleanup = chilkat.FileAccess.new()
    if cleanup:file_exists("qa_data/tokens/cognito-challenge.json") then
        cleanup:file_delete("qa_data/tokens/cognito-challenge.json")
    end

    print("Sign-in completed; private token cache saved.")
    return
end

if (result:json_type_of("ChallengeName") ~= 1) or (result:string_of("ChallengeName") == "") then
    print("Missing or invalid ChallengeName.")
    return
end

if (result:json_type_of("Session") ~= 1) or (result:string_of("Session") == "") then
    print("Missing or invalid Session.")
    return
end

-- ChallengeParameters may provide the canonical username after alias-based sign-in.
if (result:json_type_of("ChallengeParameters.USER_ID_FOR_SRP") == 1) and (result:string_of("ChallengeParameters.USER_ID_FOR_SRP") ~= "") then
    username = result:string_of("ChallengeParameters.USER_ID_FOR_SRP")
end

if (result:json_type_of("ChallengeParameters.USERNAME") == 1) and (result:string_of("ChallengeParameters.USERNAME") ~= "") then
    username = result:string_of("ChallengeParameters.USERNAME")
end

result:update_string("username", username)
result:update_string("client_id", app:string_of("client_id"))
result:update_string("user_pool_id", app:string_of("user_pool_id"))
result:update_string("account_key", app:string_of("account_key"))
local resultauthenticationchallenge = chilkat.FileAccess.new()
success = resultauthenticationchallenge:dir_ensure_exists("qa_data/tokens")
if not success then
    print("Could not create the private cache directory.")
    return
end

if resultauthenticationchallenge:file_exists("qa_data/tokens/cognito-challenge.json") then
    success = resultauthenticationchallenge:file_copy("qa_data/tokens/cognito-challenge.json", "qa_data/tokens/cognito-challenge.json.bak", false)
    if not success then
        print("Could not back up the existing cache.")
        return
    end
end

success = result:write_file("qa_data/tokens/cognito-challenge.json")
if not success then
    print("Could not save authentication challenge; preserve any previous backup.")
    return
end

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