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

Swift

func chilkatTest() {
    var success: Bool = 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.
    let app = CkoJsonObject()!
    app.strict = true
    success = app.loadFile(path: "qa_data/cognito/app.json")
    if success != true {
        print("Could not load Cognito app settings.")
        return
    }

    if (app.jsonType(of: "region").intValue != 1) || (app.string(of: "region") == "") {
        print("Missing or invalid region.")
        return
    }

    if (app.jsonType(of: "user_pool_id").intValue != 1) || (app.string(of: "user_pool_id") == "") {
        print("Missing or invalid user_pool_id.")
        return
    }

    if (app.jsonType(of: "client_id").intValue != 1) || (app.string(of: "client_id") == "") {
        print("Missing or invalid client_id.")
        return
    }

    if (app.jsonType(of: "account_key").intValue != 1) || (app.string(of: "account_key") == "") {
        print("Missing or invalid account_key.")
        return
    }

    var clientId: String? = app.string(of: "client_id")
    let endpoint = CkoStringBuilder()!
    endpoint.append(value: "https://cognito-idp.")
    endpoint.append(value: app.string(of: "region"))
    endpoint.append(value: ".amazonaws.com/")
    let http = CkoHttp()!
    http.requireSslCertVerify = true
    http.followRedirects = false
    http.connectTimeout = 20
    http.readTimeout = 60
    let resp = CkoHttpResponse()!
    let body = CkoJsonObject()!
    let result = CkoJsonObject()!
    result.strict = true
    //  "start" begins sign-in. "respond" submits input for the most recent saved challenge.
    var action: String? = "start"
    if (action != "start") && (action != "respond") {
        print("Choose start or respond.")
        return
    }

    let input = CkoJsonObject()!
    input.strict = true
    success = input.loadFile(path: "qa_data/cognito/signin-input.json")
    if success != true {
        print("Could not load qa_data/cognito/signin-input.json.")
        return
    }

    if (input.jsonType(of: "username").intValue != 1) || (input.string(of: "username") == "") {
        print("Missing or invalid username.")
        return
    }

    var username: String? = input.string(of: "username")
    body.updateString(jsonPath: "ClientId", value: clientId)
    if action == "start" {
        if (input.jsonType(of: "password").intValue != 1) || (input.string(of: "password") == "") {
            print("Missing or invalid password.")
            return
        }

        body.updateString(jsonPath: "AuthFlow", value: "USER_PASSWORD_AUTH")
        body.updateString(jsonPath: "AuthParameters.USERNAME", value: username)
        body.updateString(jsonPath: "AuthParameters.PASSWORD", value: input.string(of: "password"))
        http.setRequestHeader(name: "X-Amz-Target", value: "AWSCognitoIdentityProviderService.InitiateAuth")
        success = http.httpJson(verb: "POST", url: endpoint.getAsString(), json: body, contentType: "application/x-amz-json-1.0", response: resp)
        if resp.statusCode.intValue != 200 {
            print("HTTP status: \(resp.statusCode.intValue)")
            success = result.load(json: resp.bodyStr)
            if success == true {
                print("Error type: \(result.string(of: "__type")!)")
                print("OAuth error: \(result.string(of: "error")!)")
            }

            //  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
            return
        }

        if success != true {
            print("The HTTP exchange did not complete.")
            return
        }

        success = result.load(json: resp.bodyStr)
        if success != true {
            print("Expected a JSON response.")
            return
        }

    }
    else {
        let challenge = CkoJsonObject()!
        challenge.strict = true
        success = challenge.loadFile(path: "qa_data/tokens/cognito-challenge.json")
        if success != true {
            print("Could not load qa_data/tokens/cognito-challenge.json.")
            return
        }

        if (challenge.jsonType(of: "client_id").intValue != 1) || (challenge.string(of: "client_id") == "") {
            print("Missing or invalid client_id.")
            return
        }

        if challenge.string(of: "client_id") != app.string(of: "client_id") {
            print("Saved data belongs to another client, pool, or local account.")
            return
        }

        if (challenge.jsonType(of: "user_pool_id").intValue != 1) || (challenge.string(of: "user_pool_id") == "") {
            print("Missing or invalid user_pool_id.")
            return
        }

        if challenge.string(of: "user_pool_id") != app.string(of: "user_pool_id") {
            print("Saved data belongs to another client, pool, or local account.")
            return
        }

        if (challenge.jsonType(of: "account_key").intValue != 1) || (challenge.string(of: "account_key") == "") {
            print("Missing or invalid account_key.")
            return
        }

        if challenge.string(of: "account_key") != app.string(of: "account_key") {
            print("Saved data belongs to another client, pool, or local account.")
            return
        }

        if (challenge.jsonType(of: "Session").intValue != 1) || (challenge.string(of: "Session") == "") {
            print("Missing or invalid Session.")
            return
        }

        if (challenge.jsonType(of: "ChallengeName").intValue != 1) || (challenge.string(of: "ChallengeName") == "") {
            print("Missing or invalid ChallengeName.")
            return
        }

        if (challenge.jsonType(of: "username").intValue != 1) || (challenge.string(of: "username") == "") {
            print("Missing or invalid username.")
            return
        }

        //  Use the bound canonical username from the previous response, not a new alias.
        username = challenge.string(of: "username")
        var challengeName: String? = challenge.string(of: "ChallengeName")
        body.updateString(jsonPath: "Session", value: challenge.string(of: "Session"))
        body.updateString(jsonPath: "ChallengeName", value: challengeName)
        body.updateString(jsonPath: "ChallengeResponses.USERNAME", value: username)
        if challengeName == "NEW_PASSWORD_REQUIRED" {
            if (input.jsonType(of: "new_password").intValue != 1) || (input.string(of: "new_password") == "") {
                print("Missing or invalid new_password.")
                return
            }

            body.updateString(jsonPath: "ChallengeResponses.NEW_PASSWORD", value: input.string(of: "new_password"))
            //  requiredAttributes is a JSON array encoded inside a JSON string.
            let requiredAttributes = CkoJsonArray()!
            var requiredJson: String? = challenge.string(of: "ChallengeParameters.requiredAttributes")
            if challenge.hasMember(jsonPath: "ChallengeParameters.requiredAttributes") != true {
                requiredJson = "[]"
            }

            success = requiredAttributes.load(jsonArray: requiredJson)
            if success != true {
                print("Invalid required-attributes list.")
                return
            }

            let answers = CkoJsonObject()!
            success = body.objectOf2(jsonPath: "ChallengeResponses", jsonObj: answers)
            if success != true {
                print("Could not access challenge responses.")
                return
            }

            var i: Int = 0
            var count: Int = requiredAttributes.size.intValue
            var attribute: String?
            var attributeValue: String?
            let supplied = CkoJsonObject()!
            if count > 0 {
                success = input.objectOf2(jsonPath: "required_attributes", jsonObj: supplied)
                if success != true {
                    print("Supply all required attributes in required_attributes.")
                    return
                }

            }

            while i < count {
                attribute = requiredAttributes.string(at: i)
                //  Keys are returned as userAttributes.email, userAttributes.name, etc.
                //  StringOf with a quoted path treats the whole key literally.
                let attributePath = CkoStringBuilder()!
                attributePath.append(value: "\"")
                attributePath.append(value: attribute)
                attributePath.append(value: "\"")
                attributeValue = supplied.string(of: attributePath.getAsString())
                if (supplied.jsonType(of: attributePath.getAsString()).intValue != 1) || (attributeValue == "") {
                    print("A required user attribute is missing.")
                    return
                }

                answers.appendString(name: attribute, value: attributeValue)
                i = i + 1
            }

        }
        else {
            if (challengeName != "SMS_MFA") && (challengeName != "SOFTWARE_TOKEN_MFA") && (challengeName != "EMAIL_OTP") {
                print("This challenge needs a different handler: \(challengeName!)")
                //  MFA_SETUP is demonstrated in the TOTP enrollment example. Do not assume sign-in succeeded.
                return
            }

            if (input.jsonType(of: "code").intValue != 1) || (input.string(of: "code") == "") {
                print("Missing or invalid code.")
                return
            }

            if challengeName == "SMS_MFA" {
                body.updateString(jsonPath: "ChallengeResponses.SMS_MFA_CODE", value: input.string(of: "code"))
            }

            if challengeName == "SOFTWARE_TOKEN_MFA" {
                body.updateString(jsonPath: "ChallengeResponses.SOFTWARE_TOKEN_MFA_CODE", value: input.string(of: "code"))
            }

            if challengeName == "EMAIL_OTP" {
                body.updateString(jsonPath: "ChallengeResponses.EMAIL_OTP_CODE", value: input.string(of: "code"))
            }

        }

        http.setRequestHeader(name: "X-Amz-Target", value: "AWSCognitoIdentityProviderService.RespondToAuthChallenge")
        success = http.httpJson(verb: "POST", url: endpoint.getAsString(), json: body, contentType: "application/x-amz-json-1.0", response: resp)
        if resp.statusCode.intValue != 200 {
            print("HTTP status: \(resp.statusCode.intValue)")
            success = result.load(json: resp.bodyStr)
            if success == true {
                print("Error type: \(result.string(of: "__type")!)")
                print("OAuth error: \(result.string(of: "error")!)")
            }

            //  Inspect detailed diagnostics privately. Do not log passwords, sessions, or tokens.
            return
        }

        if success != true {
            print("The HTTP exchange did not complete.")
            return
        }

        success = result.load(json: resp.bodyStr)
        if success != true {
            print("Expected a JSON response.")
            return
        }

    }

    if result.jsonType(of: "AuthenticationResult").intValue == 3 {
        let token = CkoJsonObject()!
        token.updateString(jsonPath: "access_token", value: result.string(of: "AuthenticationResult.AccessToken"))
        token.updateString(jsonPath: "id_token", value: result.string(of: "AuthenticationResult.IdToken"))
        token.updateString(jsonPath: "token_type", value: result.string(of: "AuthenticationResult.TokenType"))
        token.updateInt(jsonPath: "expires_in", value: result.int(of: "AuthenticationResult.ExpiresIn").intValue)
        if result.hasMember(jsonPath: "AuthenticationResult.RefreshToken") == true {
            token.updateString(jsonPath: "refresh_token", value: result.string(of: "AuthenticationResult.RefreshToken"))
        }

        if (token.jsonType(of: "access_token").intValue != 1) || (token.string(of: "access_token") == "") {
            print("Missing or invalid access_token.")
            return
        }

        if (token.jsonType(of: "id_token").intValue != 1) || (token.string(of: "id_token") == "") {
            print("Missing or invalid id_token.")
            return
        }

        if (token.jsonType(of: "expires_in").intValue != 2) || (token.int(of: "expires_in").intValue <= 0) {
            print("Expected a positive token lifetime.")
            return
        }

        if token.string(of: "token_type") != "Bearer" {
            print("Expected Bearer tokens.")
            return
        }

        if (token.jsonType(of: "refresh_token").intValue != 1) || (token.string(of: "refresh_token") == "") {
            print("Missing or invalid refresh_token.")
            return
        }

        token.updateString(jsonPath: "client_id", value: app.string(of: "client_id"))
        token.updateString(jsonPath: "user_pool_id", value: app.string(of: "user_pool_id"))
        token.updateString(jsonPath: "account_key", value: app.string(of: "account_key"))
        let obtained = CkoDateTime()!
        success = obtained.setFromCurrentSystemTime()
        if success != true {
            print("Could not get the acquisition time.")
            return
        }

        token.updateString(jsonPath: "obtained_at", value: obtained.get(asTimestamp: false))
        let tokenusertokens = CkoFileAccess()!
        success = tokenusertokens.dirEnsureExists(dirPath: "qa_data/tokens")
        if success != true {
            print("Could not create the private cache directory.")
            return
        }

        if tokenusertokens.fileExists(path: "qa_data/tokens/cognito-user.json") == true {
            success = tokenusertokens.fileCopy(existingPath: "qa_data/tokens/cognito-user.json", newPath: "qa_data/tokens/cognito-user.json.bak", failIfExists: false)
            if success != true {
                print("Could not back up the existing cache.")
                return
            }

        }

        success = token.writeFile(path: "qa_data/tokens/cognito-user.json")
        if success != true {
            print("Could not save user tokens; preserve any previous backup.")
            return
        }

        //  A completed flow no longer needs its short-lived challenge session.
        let cleanup = CkoFileAccess()!
        if cleanup.fileExists(path: "qa_data/tokens/cognito-challenge.json") == true {
            cleanup.fileDelete(path: "qa_data/tokens/cognito-challenge.json")
        }

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

    if (result.jsonType(of: "ChallengeName").intValue != 1) || (result.string(of: "ChallengeName") == "") {
        print("Missing or invalid ChallengeName.")
        return
    }

    if (result.jsonType(of: "Session").intValue != 1) || (result.string(of: "Session") == "") {
        print("Missing or invalid Session.")
        return
    }

    //  ChallengeParameters may provide the canonical username after alias-based sign-in.
    if (result.jsonType(of: "ChallengeParameters.USER_ID_FOR_SRP").intValue == 1) && (result.string(of: "ChallengeParameters.USER_ID_FOR_SRP") != "") {
        username = result.string(of: "ChallengeParameters.USER_ID_FOR_SRP")
    }

    if (result.jsonType(of: "ChallengeParameters.USERNAME").intValue == 1) && (result.string(of: "ChallengeParameters.USERNAME") != "") {
        username = result.string(of: "ChallengeParameters.USERNAME")
    }

    result.updateString(jsonPath: "username", value: username)
    result.updateString(jsonPath: "client_id", value: app.string(of: "client_id"))
    result.updateString(jsonPath: "user_pool_id", value: app.string(of: "user_pool_id"))
    result.updateString(jsonPath: "account_key", value: app.string(of: "account_key"))
    let resultauthenticationchallenge = CkoFileAccess()!
    success = resultauthenticationchallenge.dirEnsureExists(dirPath: "qa_data/tokens")
    if success != true {
        print("Could not create the private cache directory.")
        return
    }

    if resultauthenticationchallenge.fileExists(path: "qa_data/tokens/cognito-challenge.json") == true {
        success = resultauthenticationchallenge.fileCopy(existingPath: "qa_data/tokens/cognito-challenge.json", newPath: "qa_data/tokens/cognito-challenge.json.bak", failIfExists: false)
        if success != true {
            print("Could not back up the existing cache.")
            return
        }

    }

    success = result.writeFile(path: "qa_data/tokens/cognito-challenge.json")
    if success != true {
        print("Could not save authentication challenge; preserve any previous backup.")
        return
    }

    print("Further authentication required: \(result.string(of: "ChallengeName")!)")
    //  Collect the requested input in your application's UI; never print the Session value.

}