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

Objective-C
#import <CkoJsonObject.h>
#import <NSString.h>
#import <CkoStringBuilder.h>
#import <CkoHttp.h>
#import <CkoHttpResponse.h>
#import <CkoJsonArray.h>
#import <CkoDateTime.h>
#import <CkoFileAccess.h>

BOOL success = NO;

//  Assumes Chilkat is unlocked. See Global Unlock Sample.
success = NO;
//  App settings are trusted configuration. Keep a separate account_key/cache per local user.
CkoJsonObject *app = [[CkoJsonObject alloc] init];
app.Strict = YES;
success = [app LoadFile: @"qa_data/cognito/app.json"];
if (success != YES) {
    NSLog(@"%@",@"Could not load Cognito app settings.");
    return;
}

if (([[app JsonTypeOf: @"region"] intValue] != 1) || ([app StringOf: @"region"] == @"")) {
    NSLog(@"%@",@"Missing or invalid region.");
    return;
}

if (([[app JsonTypeOf: @"user_pool_id"] intValue] != 1) || ([app StringOf: @"user_pool_id"] == @"")) {
    NSLog(@"%@",@"Missing or invalid user_pool_id.");
    return;
}

if (([[app JsonTypeOf: @"client_id"] intValue] != 1) || ([app StringOf: @"client_id"] == @"")) {
    NSLog(@"%@",@"Missing or invalid client_id.");
    return;
}

if (([[app JsonTypeOf: @"account_key"] intValue] != 1) || ([app StringOf: @"account_key"] == @"")) {
    NSLog(@"%@",@"Missing or invalid account_key.");
    return;
}

NSString *clientId = [app StringOf: @"client_id"];
CkoStringBuilder *endpoint = [[CkoStringBuilder alloc] init];
[endpoint Append: @"https://cognito-idp."];
[endpoint Append: [app StringOf: @"region"]];
[endpoint Append: @".amazonaws.com/"];
CkoHttp *http = [[CkoHttp alloc] init];
http.RequireSslCertVerify = YES;
http.FollowRedirects = NO;
http.ConnectTimeout = [NSNumber numberWithInt:20];
http.ReadTimeout = [NSNumber numberWithInt:60];
CkoHttpResponse *resp = [[CkoHttpResponse alloc] init];
CkoJsonObject *body = [[CkoJsonObject alloc] init];
CkoJsonObject *result = [[CkoJsonObject alloc] init];
result.Strict = YES;
//  "start" begins sign-in. "respond" submits input for the most recent saved challenge.
NSString *action = @"start";
if ((action != @"start") && (action != @"respond")) {
    NSLog(@"%@",@"Choose start or respond.");
    return;
}

CkoJsonObject *input = [[CkoJsonObject alloc] init];
input.Strict = YES;
success = [input LoadFile: @"qa_data/cognito/signin-input.json"];
if (success != YES) {
    NSLog(@"%@",@"Could not load qa_data/cognito/signin-input.json.");
    return;
}

if (([[input JsonTypeOf: @"username"] intValue] != 1) || ([input StringOf: @"username"] == @"")) {
    NSLog(@"%@",@"Missing or invalid username.");
    return;
}

NSString *username = [input StringOf: @"username"];
[body UpdateString: @"ClientId" value: clientId];
if (action == @"start") {
    if (([[input JsonTypeOf: @"password"] intValue] != 1) || ([input StringOf: @"password"] == @"")) {
        NSLog(@"%@",@"Missing or invalid password.");
        return;
    }

    [body UpdateString: @"AuthFlow" value: @"USER_PASSWORD_AUTH"];
    [body UpdateString: @"AuthParameters.USERNAME" value: username];
    [body UpdateString: @"AuthParameters.PASSWORD" value: [input StringOf: @"password"]];
    [http SetRequestHeader: @"X-Amz-Target" value: @"AWSCognitoIdentityProviderService.InitiateAuth"];
    success = [http HttpJson: @"POST" url: [endpoint GetAsString] json: body contentType: @"application/x-amz-json-1.0" response: resp];
    if ([resp.StatusCode intValue] != 200) {
        NSLog(@"%@%d",@"HTTP status: ",[resp.StatusCode intValue]);
        success = [result Load: resp.BodyStr];
        if (success == YES) {
            NSLog(@"%@%@",@"Error type: ",[result StringOf: @"__type"]);
            NSLog(@"%@%@",@"OAuth error: ",[result StringOf: @"error"]);
        }

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

    if (success != YES) {
        NSLog(@"%@",@"The HTTP exchange did not complete.");
        return;
    }

    success = [result Load: resp.BodyStr];
    if (success != YES) {
        NSLog(@"%@",@"Expected a JSON response.");
        return;
    }

}
else {
    CkoJsonObject *challenge = [[CkoJsonObject alloc] init];
    challenge.Strict = YES;
    success = [challenge LoadFile: @"qa_data/tokens/cognito-challenge.json"];
    if (success != YES) {
        NSLog(@"%@",@"Could not load qa_data/tokens/cognito-challenge.json.");
        return;
    }

    if (([[challenge JsonTypeOf: @"client_id"] intValue] != 1) || ([challenge StringOf: @"client_id"] == @"")) {
        NSLog(@"%@",@"Missing or invalid client_id.");
        return;
    }

    if ([challenge StringOf: @"client_id"] != [app StringOf: @"client_id"]) {
        NSLog(@"%@",@"Saved data belongs to another client, pool, or local account.");
        return;
    }

    if (([[challenge JsonTypeOf: @"user_pool_id"] intValue] != 1) || ([challenge StringOf: @"user_pool_id"] == @"")) {
        NSLog(@"%@",@"Missing or invalid user_pool_id.");
        return;
    }

    if ([challenge StringOf: @"user_pool_id"] != [app StringOf: @"user_pool_id"]) {
        NSLog(@"%@",@"Saved data belongs to another client, pool, or local account.");
        return;
    }

    if (([[challenge JsonTypeOf: @"account_key"] intValue] != 1) || ([challenge StringOf: @"account_key"] == @"")) {
        NSLog(@"%@",@"Missing or invalid account_key.");
        return;
    }

    if ([challenge StringOf: @"account_key"] != [app StringOf: @"account_key"]) {
        NSLog(@"%@",@"Saved data belongs to another client, pool, or local account.");
        return;
    }

    if (([[challenge JsonTypeOf: @"Session"] intValue] != 1) || ([challenge StringOf: @"Session"] == @"")) {
        NSLog(@"%@",@"Missing or invalid Session.");
        return;
    }

    if (([[challenge JsonTypeOf: @"ChallengeName"] intValue] != 1) || ([challenge StringOf: @"ChallengeName"] == @"")) {
        NSLog(@"%@",@"Missing or invalid ChallengeName.");
        return;
    }

    if (([[challenge JsonTypeOf: @"username"] intValue] != 1) || ([challenge StringOf: @"username"] == @"")) {
        NSLog(@"%@",@"Missing or invalid username.");
        return;
    }

    //  Use the bound canonical username from the previous response, not a new alias.
    username = [challenge StringOf: @"username"];
    NSString *challengeName = [challenge StringOf: @"ChallengeName"];
    [body UpdateString: @"Session" value: [challenge StringOf: @"Session"]];
    [body UpdateString: @"ChallengeName" value: challengeName];
    [body UpdateString: @"ChallengeResponses.USERNAME" value: username];
    if (challengeName == @"NEW_PASSWORD_REQUIRED") {
        if (([[input JsonTypeOf: @"new_password"] intValue] != 1) || ([input StringOf: @"new_password"] == @"")) {
            NSLog(@"%@",@"Missing or invalid new_password.");
            return;
        }

        [body UpdateString: @"ChallengeResponses.NEW_PASSWORD" value: [input StringOf: @"new_password"]];
        //  requiredAttributes is a JSON array encoded inside a JSON string.
        CkoJsonArray *requiredAttributes = [[CkoJsonArray alloc] init];
        NSString *requiredJson = [challenge StringOf: @"ChallengeParameters.requiredAttributes"];
        if ([challenge HasMember: @"ChallengeParameters.requiredAttributes"] != YES) {
            requiredJson = @"[]";
        }

        success = [requiredAttributes Load: requiredJson];
        if (success != YES) {
            NSLog(@"%@",@"Invalid required-attributes list.");
            return;
        }

        CkoJsonObject *answers = [[CkoJsonObject alloc] init];
        success = [body ObjectOf2: @"ChallengeResponses" jsonObj: answers];
        if (success != YES) {
            NSLog(@"%@",@"Could not access challenge responses.");
            return;
        }

        int i = 0;
        int count = [requiredAttributes.Size intValue];
        NSString *attribute = 0;
        NSString *attributeValue = 0;
        CkoJsonObject *supplied = [[CkoJsonObject alloc] init];
        if (count > 0) {
            success = [input ObjectOf2: @"required_attributes" jsonObj: supplied];
            if (success != YES) {
                NSLog(@"%@",@"Supply all required attributes in required_attributes.");
                return;
            }

        }

        while (i < count) {
            attribute = [requiredAttributes StringAt: [NSNumber numberWithInt: i]];
            //  Keys are returned as userAttributes.email, userAttributes.name, etc.
            //  StringOf with a quoted path treats the whole key literally.
            CkoStringBuilder *attributePath = [[CkoStringBuilder alloc] init];
            [attributePath Append: @"\""];
            [attributePath Append: attribute];
            [attributePath Append: @"\""];
            attributeValue = [supplied StringOf: [attributePath GetAsString]];
            if (([[supplied JsonTypeOf: [attributePath GetAsString]] intValue] != 1) || (attributeValue == @"")) {
                NSLog(@"%@",@"A required user attribute is missing.");
                return;
            }

            [answers AppendString: attribute value: attributeValue];
            i = i + 1;
        }

    }
    else {
        if ((challengeName != @"SMS_MFA") && (challengeName != @"SOFTWARE_TOKEN_MFA") && (challengeName != @"EMAIL_OTP")) {
            NSLog(@"%@%@",@"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 JsonTypeOf: @"code"] intValue] != 1) || ([input StringOf: @"code"] == @"")) {
            NSLog(@"%@",@"Missing or invalid code.");
            return;
        }

        if (challengeName == @"SMS_MFA") {
            [body UpdateString: @"ChallengeResponses.SMS_MFA_CODE" value: [input StringOf: @"code"]];
        }

        if (challengeName == @"SOFTWARE_TOKEN_MFA") {
            [body UpdateString: @"ChallengeResponses.SOFTWARE_TOKEN_MFA_CODE" value: [input StringOf: @"code"]];
        }

        if (challengeName == @"EMAIL_OTP") {
            [body UpdateString: @"ChallengeResponses.EMAIL_OTP_CODE" value: [input StringOf: @"code"]];
        }

    }

    [http SetRequestHeader: @"X-Amz-Target" value: @"AWSCognitoIdentityProviderService.RespondToAuthChallenge"];
    success = [http HttpJson: @"POST" url: [endpoint GetAsString] json: body contentType: @"application/x-amz-json-1.0" response: resp];
    if ([resp.StatusCode intValue] != 200) {
        NSLog(@"%@%d",@"HTTP status: ",[resp.StatusCode intValue]);
        success = [result Load: resp.BodyStr];
        if (success == YES) {
            NSLog(@"%@%@",@"Error type: ",[result StringOf: @"__type"]);
            NSLog(@"%@%@",@"OAuth error: ",[result StringOf: @"error"]);
        }

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

    if (success != YES) {
        NSLog(@"%@",@"The HTTP exchange did not complete.");
        return;
    }

    success = [result Load: resp.BodyStr];
    if (success != YES) {
        NSLog(@"%@",@"Expected a JSON response.");
        return;
    }

}

if ([[result JsonTypeOf: @"AuthenticationResult"] intValue] == 3) {
    CkoJsonObject *token = [[CkoJsonObject alloc] init];
    [token UpdateString: @"access_token" value: [result StringOf: @"AuthenticationResult.AccessToken"]];
    [token UpdateString: @"id_token" value: [result StringOf: @"AuthenticationResult.IdToken"]];
    [token UpdateString: @"token_type" value: [result StringOf: @"AuthenticationResult.TokenType"]];
    [token UpdateInt: @"expires_in" value: [result IntOf: @"AuthenticationResult.ExpiresIn"]];
    if ([result HasMember: @"AuthenticationResult.RefreshToken"] == YES) {
        [token UpdateString: @"refresh_token" value: [result StringOf: @"AuthenticationResult.RefreshToken"]];
    }

    if (([[token JsonTypeOf: @"access_token"] intValue] != 1) || ([token StringOf: @"access_token"] == @"")) {
        NSLog(@"%@",@"Missing or invalid access_token.");
        return;
    }

    if (([[token JsonTypeOf: @"id_token"] intValue] != 1) || ([token StringOf: @"id_token"] == @"")) {
        NSLog(@"%@",@"Missing or invalid id_token.");
        return;
    }

    if (([[token JsonTypeOf: @"expires_in"] intValue] != 2) || ([[token IntOf: @"expires_in"] intValue] <= 0)) {
        NSLog(@"%@",@"Expected a positive token lifetime.");
        return;
    }

    if ([token StringOf: @"token_type"] != @"Bearer") {
        NSLog(@"%@",@"Expected Bearer tokens.");
        return;
    }

    if (([[token JsonTypeOf: @"refresh_token"] intValue] != 1) || ([token StringOf: @"refresh_token"] == @"")) {
        NSLog(@"%@",@"Missing or invalid refresh_token.");
        return;
    }

    [token UpdateString: @"client_id" value: [app StringOf: @"client_id"]];
    [token UpdateString: @"user_pool_id" value: [app StringOf: @"user_pool_id"]];
    [token UpdateString: @"account_key" value: [app StringOf: @"account_key"]];
    CkoDateTime *obtained = [[CkoDateTime alloc] init];
    success = [obtained SetFromCurrentSystemTime];
    if (success != YES) {
        NSLog(@"%@",@"Could not get the acquisition time.");
        return;
    }

    [token UpdateString: @"obtained_at" value: [obtained GetAsTimestamp: NO]];
    CkoFileAccess *tokenusertokens = [[CkoFileAccess alloc] init];
    success = [tokenusertokens DirEnsureExists: @"qa_data/tokens"];
    if (success != YES) {
        NSLog(@"%@",@"Could not create the private cache directory.");
        return;
    }

    if ([tokenusertokens FileExists: @"qa_data/tokens/cognito-user.json"] == YES) {
        success = [tokenusertokens FileCopy: @"qa_data/tokens/cognito-user.json" newPath: @"qa_data/tokens/cognito-user.json.bak" failIfExists: NO];
        if (success != YES) {
            NSLog(@"%@",@"Could not back up the existing cache.");
            return;
        }

    }

    success = [token WriteFile: @"qa_data/tokens/cognito-user.json"];
    if (success != YES) {
        NSLog(@"%@",@"Could not save user tokens; preserve any previous backup.");
        return;
    }

    //  A completed flow no longer needs its short-lived challenge session.
    CkoFileAccess *cleanup = [[CkoFileAccess alloc] init];
    if ([cleanup FileExists: @"qa_data/tokens/cognito-challenge.json"] == YES) {
        [cleanup FileDelete: @"qa_data/tokens/cognito-challenge.json"];
    }

    NSLog(@"%@",@"Sign-in completed; private token cache saved.");
    return;
}

if (([[result JsonTypeOf: @"ChallengeName"] intValue] != 1) || ([result StringOf: @"ChallengeName"] == @"")) {
    NSLog(@"%@",@"Missing or invalid ChallengeName.");
    return;
}

if (([[result JsonTypeOf: @"Session"] intValue] != 1) || ([result StringOf: @"Session"] == @"")) {
    NSLog(@"%@",@"Missing or invalid Session.");
    return;
}

//  ChallengeParameters may provide the canonical username after alias-based sign-in.
if (([[result JsonTypeOf: @"ChallengeParameters.USER_ID_FOR_SRP"] intValue] == 1) && ([result StringOf: @"ChallengeParameters.USER_ID_FOR_SRP"] != @"")) {
    username = [result StringOf: @"ChallengeParameters.USER_ID_FOR_SRP"];
}

if (([[result JsonTypeOf: @"ChallengeParameters.USERNAME"] intValue] == 1) && ([result StringOf: @"ChallengeParameters.USERNAME"] != @"")) {
    username = [result StringOf: @"ChallengeParameters.USERNAME"];
}

[result UpdateString: @"username" value: username];
[result UpdateString: @"client_id" value: [app StringOf: @"client_id"]];
[result UpdateString: @"user_pool_id" value: [app StringOf: @"user_pool_id"]];
[result UpdateString: @"account_key" value: [app StringOf: @"account_key"]];
CkoFileAccess *resultauthenticationchallenge = [[CkoFileAccess alloc] init];
success = [resultauthenticationchallenge DirEnsureExists: @"qa_data/tokens"];
if (success != YES) {
    NSLog(@"%@",@"Could not create the private cache directory.");
    return;
}

if ([resultauthenticationchallenge FileExists: @"qa_data/tokens/cognito-challenge.json"] == YES) {
    success = [resultauthenticationchallenge FileCopy: @"qa_data/tokens/cognito-challenge.json" newPath: @"qa_data/tokens/cognito-challenge.json.bak" failIfExists: NO];
    if (success != YES) {
        NSLog(@"%@",@"Could not back up the existing cache.");
        return;
    }

}

success = [result WriteFile: @"qa_data/tokens/cognito-challenge.json"];
if (success != YES) {
    NSLog(@"%@",@"Could not save authentication challenge; preserve any previous backup.");
    return;
}

NSLog(@"%@%@",@"Further authentication required: ",[result StringOf: @"ChallengeName"]);
//  Collect the requested input in your application's UI; never print the Session value.