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 Swift Downloads
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
var action: String? = "begin"
var mode: String? = "signed_in"
if (action != "begin") && (action != "verify") {
print("Choose begin or verify.")
return
}
if (mode != "signed_in") && (mode != "challenge") {
print("Choose signed_in or challenge.")
return
}
var username: String? = ""
let credential = CkoJsonObject()!
if mode == "signed_in" {
success = credential.loadFile(path: "qa_data/tokens/cognito-user.json")
if success != true {
print("Could not load user tokens.")
return
}
if (credential.jsonType(of: "client_id").intValue != 1) || (credential.string(of: "client_id") == "") {
print("Missing or invalid client_id.")
return
}
if credential.string(of: "client_id") != app.string(of: "client_id") {
print("Saved data belongs to another client, pool, or local account.")
return
}
if (credential.jsonType(of: "user_pool_id").intValue != 1) || (credential.string(of: "user_pool_id") == "") {
print("Missing or invalid user_pool_id.")
return
}
if credential.string(of: "user_pool_id") != app.string(of: "user_pool_id") {
print("Saved data belongs to another client, pool, or local account.")
return
}
if (credential.jsonType(of: "account_key").intValue != 1) || (credential.string(of: "account_key") == "") {
print("Missing or invalid account_key.")
return
}
if credential.string(of: "account_key") != app.string(of: "account_key") {
print("Saved data belongs to another client, pool, or local account.")
return
}
if (credential.jsonType(of: "access_token").intValue != 1) || (credential.string(of: "access_token") == "") {
print("Missing or invalid access_token.")
return
}
}
else {
success = credential.loadFile(path: "qa_data/tokens/cognito-challenge.json")
if success != true {
print("Could not load the MFA_SETUP challenge.")
return
}
if (credential.jsonType(of: "client_id").intValue != 1) || (credential.string(of: "client_id") == "") {
print("Missing or invalid client_id.")
return
}
if credential.string(of: "client_id") != app.string(of: "client_id") {
print("Saved data belongs to another client, pool, or local account.")
return
}
if (credential.jsonType(of: "user_pool_id").intValue != 1) || (credential.string(of: "user_pool_id") == "") {
print("Missing or invalid user_pool_id.")
return
}
if credential.string(of: "user_pool_id") != app.string(of: "user_pool_id") {
print("Saved data belongs to another client, pool, or local account.")
return
}
if (credential.jsonType(of: "account_key").intValue != 1) || (credential.string(of: "account_key") == "") {
print("Missing or invalid account_key.")
return
}
if credential.string(of: "account_key") != app.string(of: "account_key") {
print("Saved data belongs to another client, pool, or local account.")
return
}
if (credential.jsonType(of: "Session").intValue != 1) || (credential.string(of: "Session") == "") {
print("Missing or invalid Session.")
return
}
if (credential.jsonType(of: "username").intValue != 1) || (credential.string(of: "username") == "") {
print("Missing or invalid username.")
return
}
if credential.string(of: "ChallengeName") != "MFA_SETUP" {
print("Expected an MFA_SETUP challenge.")
return
}
username = credential.string(of: "username")
}
if action == "begin" {
if mode == "signed_in" {
body.updateString(jsonPath: "AccessToken", value: credential.string(of: "access_token"))
}
else {
body.updateString(jsonPath: "Session", value: credential.string(of: "Session"))
}
http.setRequestHeader(name: "X-Amz-Target", value: "AWSCognitoIdentityProviderService.AssociateSoftwareToken")
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: "SecretCode").intValue != 1) || (result.string(of: "SecretCode") == "") {
print("Missing or invalid SecretCode.")
return
}
let newEnrollment = CkoJsonObject()!
newEnrollment.updateString(jsonPath: "secret_code", value: result.string(of: "SecretCode"))
newEnrollment.updateString(jsonPath: "mode", value: mode)
newEnrollment.updateString(jsonPath: "username", value: username)
if mode == "challenge" {
if (result.jsonType(of: "Session").intValue != 1) || (result.string(of: "Session") == "") {
print("Missing or invalid Session.")
return
}
newEnrollment.updateString(jsonPath: "session", value: result.string(of: "Session"))
// Bind enrollment to this precise challenge, not just the account.
newEnrollment.updateString(jsonPath: "original_session", value: credential.string(of: "Session"))
}
newEnrollment.updateString(jsonPath: "client_id", value: app.string(of: "client_id"))
newEnrollment.updateString(jsonPath: "user_pool_id", value: app.string(of: "user_pool_id"))
newEnrollment.updateString(jsonPath: "account_key", value: app.string(of: "account_key"))
let newEnrollmentTOTPenrollment = CkoFileAccess()!
success = newEnrollmentTOTPenrollment.dirEnsureExists(dirPath: "qa_data/tokens")
if success != true {
print("Could not create the private cache directory.")
return
}
if newEnrollmentTOTPenrollment.fileExists(path: "qa_data/tokens/cognito-totp.json") == true {
success = newEnrollmentTOTPenrollment.fileCopy(existingPath: "qa_data/tokens/cognito-totp.json", newPath: "qa_data/tokens/cognito-totp.json.bak", failIfExists: false)
if success != true {
print("Could not back up the existing cache.")
return
}
}
success = newEnrollment.writeFile(path: "qa_data/tokens/cognito-totp.json")
if success != true {
print("Could not save TOTP enrollment; preserve any previous backup.")
return
}
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
}
let enrollment = CkoJsonObject()!
enrollment.strict = true
success = enrollment.loadFile(path: "qa_data/tokens/cognito-totp.json")
if success != true {
print("Could not load qa_data/tokens/cognito-totp.json.")
return
}
if (enrollment.jsonType(of: "client_id").intValue != 1) || (enrollment.string(of: "client_id") == "") {
print("Missing or invalid client_id.")
return
}
if enrollment.string(of: "client_id") != app.string(of: "client_id") {
print("Saved data belongs to another client, pool, or local account.")
return
}
if (enrollment.jsonType(of: "user_pool_id").intValue != 1) || (enrollment.string(of: "user_pool_id") == "") {
print("Missing or invalid user_pool_id.")
return
}
if enrollment.string(of: "user_pool_id") != app.string(of: "user_pool_id") {
print("Saved data belongs to another client, pool, or local account.")
return
}
if (enrollment.jsonType(of: "account_key").intValue != 1) || (enrollment.string(of: "account_key") == "") {
print("Missing or invalid account_key.")
return
}
if enrollment.string(of: "account_key") != app.string(of: "account_key") {
print("Saved data belongs to another client, pool, or local account.")
return
}
if enrollment.string(of: "mode") != mode {
print("Enrollment mode mismatch.")
return
}
let input = CkoJsonObject()!
input.strict = true
success = input.loadFile(path: "qa_data/cognito/totp-input.json")
if success != true {
print("Could not load qa_data/cognito/totp-input.json.")
return
}
if (input.jsonType(of: "code").intValue != 1) || (input.string(of: "code") == "") {
print("Missing or invalid code.")
return
}
// Enter a fresh six-digit code from the authenticator; preserve leading zeroes.
body.updateString(jsonPath: "UserCode", value: input.string(of: "code"))
body.updateString(jsonPath: "FriendlyDeviceName", value: "Authenticator")
if mode == "signed_in" {
body.updateString(jsonPath: "AccessToken", value: credential.string(of: "access_token"))
}
else {
if (enrollment.jsonType(of: "session").intValue != 1) || (enrollment.string(of: "session") == "") {
print("Missing or invalid session.")
return
}
if enrollment.string(of: "original_session") != credential.string(of: "Session") {
print("Enrollment belongs to another sign-in challenge.")
return
}
body.updateString(jsonPath: "Session", value: enrollment.string(of: "session"))
}
http.setRequestHeader(name: "X-Amz-Target", value: "AWSCognitoIdentityProviderService.VerifySoftwareToken")
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.string(of: "Status") != "SUCCESS" {
print("Authenticator verification did not succeed; do not enable it.")
return
}
// Verification succeeded. Discard the enrollment secret and its backup.
let removeEnrollment = CkoFileAccess()!
removeEnrollment.fileDelete(path: "qa_data/tokens/cognito-totp.json")
if removeEnrollment.fileExists(path: "qa_data/tokens/cognito-totp.json.bak") == true {
removeEnrollment.fileDelete(path: "qa_data/tokens/cognito-totp.json.bak")
}
success = body.load(json: "{}")
if success != true {
print("Could not reset the request body.")
return
}
if mode == "signed_in" {
body.updateString(jsonPath: "AccessToken", value: credential.string(of: "access_token"))
body.updateBool(jsonPath: "SoftwareTokenMfaSettings.Enabled", value: true)
body.updateBool(jsonPath: "SoftwareTokenMfaSettings.PreferredMfa", value: true)
http.setRequestHeader(name: "X-Amz-Target", value: "AWSCognitoIdentityProviderService.SetUserMFAPreference")
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
}
print("Authenticator verified and set as the preferred MFA method.")
return
}
if (result.jsonType(of: "Session").intValue != 1) || (result.string(of: "Session") == "") {
print("Missing or invalid Session.")
return
}
// Submit the NEW Session returned by VerifySoftwareToken, not the earlier one.
body.updateString(jsonPath: "ClientId", value: clientId)
body.updateString(jsonPath: "ChallengeName", value: "MFA_SETUP")
body.updateString(jsonPath: "Session", value: result.string(of: "Session"))
body.updateString(jsonPath: "ChallengeResponses.USERNAME", value: username)
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.
}