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

Amazon Cognito: Enroll an Authenticator for TOTP MFA

See more Amazon Cognito Examples

Enable software-token MFA in the pool first. Choose mode=signed_in to enroll with a user access token containing aws.cognito.signin.user.admin, or mode=challenge to continue the MFA_SETUP saved by the sign-in example. Begin obtains a secret and saves it in private cognito-totp.json. Present secret_code securely to the user for manual entry or an otpauth QR code; never place it in ordinary logs. Then set action=verify with the authenticator's code in private totp-input.json.

Checks VerifySoftwareToken.Status=SUCCESS before activating the preference or finishing sign-in. A signed-in enrollment sets SoftwareTokenMfaSettings.Enabled and PreferredMfa. Challenge enrollment uses the successive Session values from AssociateSoftwareToken and VerifySoftwareToken, then RespondToAuthChallenge(MFA_SETUP). Verifying a replacement authenticator can disassociate the old one. If a later step fails after successful verification, inspect the user's MFA/sign-in state rather than repeatedly beginning enrollment.

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 | AWS documentation 3

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
local action = "begin"
local mode = "signed_in"
if (action ~= "begin") and (action ~= "verify") then
    print("Choose begin or verify.")
    return
end

if (mode ~= "signed_in") and (mode ~= "challenge") then
    print("Choose signed_in or challenge.")
    return
end

local username = ""
local credential = chilkat.JsonObject.new()
if mode == "signed_in" then
    success = credential:load_file("qa_data/tokens/cognito-user.json")
    if not success then
        print("Could not load user tokens.")
        return
    end

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

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

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

    if credential: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 (credential:json_type_of("account_key") ~= 1) or (credential:string_of("account_key") == "") then
        print("Missing or invalid account_key.")
        return
    end

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

    if (credential:json_type_of("access_token") ~= 1) or (credential:string_of("access_token") == "") then
        print("Missing or invalid access_token.")
        return
    end
else
    success = credential:load_file("qa_data/tokens/cognito-challenge.json")
    if not success then
        print("Could not load the MFA_SETUP challenge.")
        return
    end

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

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

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

    if credential: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 (credential:json_type_of("account_key") ~= 1) or (credential:string_of("account_key") == "") then
        print("Missing or invalid account_key.")
        return
    end

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

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

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

    if credential:string_of("ChallengeName") ~= "MFA_SETUP" then
        print("Expected an MFA_SETUP challenge.")
        return
    end

    username = credential:string_of("username")
end

if action == "begin" then
    if mode == "signed_in" then
        body:update_string("AccessToken", credential:string_of("access_token"))
    else
        body:update_string("Session", credential:string_of("Session"))
    end

    http:set_request_header("X-Amz-Target", "AWSCognitoIdentityProviderService.AssociateSoftwareToken")
    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

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

    local newEnrollment = chilkat.JsonObject.new()
    newEnrollment:update_string("secret_code", result:string_of("SecretCode"))
    newEnrollment:update_string("mode", mode)
    newEnrollment:update_string("username", username)
    if mode == "challenge" then
        if (result:json_type_of("Session") ~= 1) or (result:string_of("Session") == "") then
            print("Missing or invalid Session.")
            return
        end

        newEnrollment:update_string("session", result:string_of("Session"))
        -- Bind enrollment to this precise challenge, not just the account.
        newEnrollment:update_string("original_session", credential:string_of("Session"))
    end

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

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

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

    print("Enrollment saved. Present secret_code privately in your authenticator setup UI.")
    -- This secret can generate future OTPs. Never log it or email it.
    return
end

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

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

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

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

if enrollment: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 (enrollment:json_type_of("account_key") ~= 1) or (enrollment:string_of("account_key") == "") then
    print("Missing or invalid account_key.")
    return
end

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

if enrollment:string_of("mode") ~= mode then
    print("Enrollment mode mismatch.")
    return
end

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

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

-- Enter a fresh six-digit code from the authenticator; preserve leading zeroes.
body:update_string("UserCode", input:string_of("code"))
body:update_string("FriendlyDeviceName", "Authenticator")
if mode == "signed_in" then
    body:update_string("AccessToken", credential:string_of("access_token"))
else
    if (enrollment:json_type_of("session") ~= 1) or (enrollment:string_of("session") == "") then
        print("Missing or invalid session.")
        return
    end

    if enrollment:string_of("original_session") ~= credential:string_of("Session") then
        print("Enrollment belongs to another sign-in challenge.")
        return
    end

    body:update_string("Session", enrollment:string_of("session"))
end

http:set_request_header("X-Amz-Target", "AWSCognitoIdentityProviderService.VerifySoftwareToken")
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

if result:string_of("Status") ~= "SUCCESS" then
    print("Authenticator verification did not succeed; do not enable it.")
    return
end

-- Verification succeeded. Discard the enrollment secret and its backup.
local removeEnrollment = chilkat.FileAccess.new()
removeEnrollment:file_delete("qa_data/tokens/cognito-totp.json")
if removeEnrollment:file_exists("qa_data/tokens/cognito-totp.json.bak") then
    removeEnrollment:file_delete("qa_data/tokens/cognito-totp.json.bak")
end

success = body:load("{}")
if not success then
    print("Could not reset the request body.")
    return
end

if mode == "signed_in" then
    body:update_string("AccessToken", credential:string_of("access_token"))
    body:update_bool("SoftwareTokenMfaSettings.Enabled", true)
    body:update_bool("SoftwareTokenMfaSettings.PreferredMfa", true)
    http:set_request_header("X-Amz-Target", "AWSCognitoIdentityProviderService.SetUserMFAPreference")
    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

    print("Authenticator verified and set as the preferred MFA method.")
    return
end

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

-- Submit the NEW Session returned by VerifySoftwareToken, not the earlier one.
body:update_string("ClientId", clientId)
body:update_string("ChallengeName", "MFA_SETUP")
body:update_string("Session", result:string_of("Session"))
body:update_string("ChallengeResponses.USERNAME", username)
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

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.