Menu
Amazon Cognito
Developer Guide

Examples: Using User Pools with the iOS SDK

This topic provides details about registering, confirming, and authenticating users, as well as getting user attributes, when using user pools with the AWS Mobile SDK for iOS.

Creating an AWSCognitoIdentityUserPool Object

The following procedure describes how to create an AWSCognitoIdentityUserPool object to interact with.

  1. Set up your service config.

    Note

    The credentialsProvider is set to nil. You do not need a credentials provider or AWS credentials to interact with this service.

    Copy
    //setup service config AWSServiceConfiguration *serviceConfiguration = [[AWSServiceConfiguration alloc] initWithRegion:AWSRegionUSEast1 credentialsProvider:nil];
  2. Create a user pool configuration.

    Copy
    //create a pool AWSCognitoIdentityUserPoolConfiguration *configuration = [[AWSCognitoIdentityUserPoolConfiguration alloc] initWithClientId:@"CLIENT_ID" clientSecret:@"CLIENT_SECRET" poolId:@"USER_POOL_ID"]; [AWSCognitoIdentityUserPool registerCognitoIdentityUserPoolWithConfiguration:serviceConfiguration userPoolConfiguration:configuration forKey:@"UserPool"]; AWSCognitoIdentityUserPool *pool = [AWSCognitoIdentityUserPool CognitoIdentityUserPoolForKey:@"UserPool"];

Example: Sign up a User

Use pool.signUp:password:userAttributes:validationData to sign up a user.

Copy
AWSCognitoIdentityUserAttributeType * phone = [AWSCognitoIdentityUserAttributeType new]; phone.name = @"phone_number"; //phone number must be prefixed by country code phone.value = @"+15555555555"; AWSCognitoIdentityUserAttributeType * email = [AWSCognitoIdentityUserAttributeType new]; email.name = @"email"; email.value = @"email@mydomain.com"; //sign up the user [[pool signUp:@"username" password:@"password" userAttributes:@[email,phone] validationData:nil] continueWithBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserPoolSignUpResponse *> * _Nonnull task) { dispatch_async(dispatch_get_main_queue(), ^{ if(task.error){ [[[UIAlertView alloc] initWithTitle:task.error.userInfo[@"__type"] message:task.error.userInfo[@"message"] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil] show]; }else { AWSCognitoIdentityUserPoolSignUpResponse * response = task.result; if(!response.userConfirmed){ //need to confirm user using user.confirmUser: } }}); return nil; }];

Example: Get a User

You can either get a user by registering or by using one of these methods on the pool.

Copy
//get the last logged in user [pool currentUser]; //get a user without a username [pool getUser]; //get a user with a specific username [pool getUser:@"username"];

Example: Sign in a User

There are two ways to sign in: explicitly or when user credentials are needed via a delegate.

To sign in explicitly, use the following:

Copy
[[user getSession:@"username" password:@"password" validationData:nil scopes:nil] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserSession *> * _Nonnull task) { //success, task.result has user session return nil; }];

To implement the delegate, implement AWSCognitoIdentityInteractiveAuthenticationDelegate and set the delegate on the pool:

Copy
pool.delegate = self;

In your implementation, write code to instantiate your authentication user interfaces if they weren't created and display them.

Copy
//set up password authentication ui to retrieve username and password from the user -(id) startPasswordAuthentication { //write code to instantiate your sign in ui if it wasn't created here dispatch_async(dispatch_get_main_queue(), ^{ //write code to display your ui }); //return your sign in ui which implements the AWSCognitoIdentityPasswordAuthentication protocol return signInViewController; } //set up mfa ui to retrieve mfa code from end user //this is optional and only necessary if you turn on multifactor authentication on your pool -(id) startMultiFactorAuthentication { //write code to instantiate your multifactor authentication ui if it wasn’t created here dispatch_async(dispatch_get_main_queue(), ^{ //write code to display your ui }); //return your sign in ui which implements the AWSCognitoIdentityMultiFactorAuthentication protocol return mfaViewController; } //set up new password required ui to retrieve new password and any required user profile from end user //this is optional and only necessary if you use the AdminCreateUser feature on the pool -(id) startNewPasswordRequired { //write code to instantiate your new password required ui if it wasn’t created here dispatch_async(dispatch_get_main_queue(), ^{ //write code to display your ui }); //return your new password required ui which implements the AWSCognitoIdentityNewPasswordRequired protocol return newPasswordRequiredController; } //set up ui to prompt end user to setup a software MFA //this is optional and only necessary if you have software MFA enabled and MFA is required on your pool -(id<AWSCognitoIdentitySoftwareMfaSetupRequired>) startSoftwareMfaSetupRequired { //write code to instantiate your software token setup required ui if it wasn’t created here dispatch_async(dispatch_get_main_queue(), ^{ //write code to display your ui }); //return your software mfa setup required ui which implements the AWSCognitoIdentitySoftwareMfaSetupRequired protocol return softwareMfaSetupController; } //set up ui to prompt end user to select which MFA they want for this authentication //this is optional and only necessary if you have users can have multiple MFAs setup on the pool -(id<AWSCognitoIdentitySelectMfa>) startSelectMfa { //write code to instantiate your select MFA ui if it wasn’t created here dispatch_async(dispatch_get_main_queue(), ^{ //write code to display your ui }); //return your select MFA ui which implements the AWSCognitoIdentitySelectMfa protocol return selectMfaController; } //set up ui to drive a custom authentication flow //this is optional and only necessary if you have custom authentication lambdas configured on your pool -(id<AWSCognitoIdentityCustomAuthentication>) startCustomAuthentication { //write code to instantiate your custom authentication ui if it wasn’t created here dispatch_async(dispatch_get_main_queue(), ^{ //write code to display your ui }); //return your custom authentication ui which implements the AWSCognitoIdentityCustomAuthentication protocol return customAuthenticationController; }

In your password authentication UI, implement the AWSCognitoIdentityPasswordAuthentication protocol.

Copy
-(void) getPasswordAuthenticationDetails: (AWSCognitoIdentityPasswordAuthenticationInput *) authenticationInput passwordAuthenticationCompletionSource: (AWSTaskCompletionSource<AWSCognitoIdentityPasswordAuthenticationDetails *> *) passwordAuthenticationCompletionSource { //keep a handle to the completion, you'll need it continue once you get the inputs from the end user self.passwordAuthenticationCompletion = passwordAuthenticationCompletionSource; //authenticationInput has details about the last known username if you need to use it } -(void) didCompletePasswordAuthenticationStepWithError:(NSError*) error { dispatch_async(dispatch_get_main_queue(), ^{ //on completion, either display the error or dismiss the ui if(error){ [[[UIAlertView alloc] initWithTitle:error.userInfo[@"__type"] message:error.userInfo[@"message"] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Retry", nil] show]; }else{ [self dismissViewControllerAnimated:YES completion:nil]; } }); }

When the end user has entered his or her username and password, set the result on passwordAuthenticationCompletion.

Copy
self.passwordAuthenticationCompletion.result = [[AWSCognitoIdentityPasswordAuthenticationDetails alloc] initWithUsername:@"username" password:@"password"];

If you support multi-factor authentication (MFA), you can implement the AWSCognitoIdentityMultiFactorAuthentication protocol.

Copy
-(void) getMultiFactorAuthenticationCode: (AWSCognitoIdentityMultifactorAuthenticationInput )authenticationInput mfaCodeCompletionSource: (AWSTaskCompletionSource<NSString > *) mfaCodeCompletionSource { //keep a handle to the completion, you’ll need it continue once you get the inputs from the end user self.mfaCodeCompletion = mfaCodeCompletionSource; //authenticationInput has details about where the mfa code was sent if you need to display them in your ui } -(void) didCompleteMultifactorAuthenticationStepWithError:(NSError*) error { dispatch_async(dispatch_get_main_queue(), ^{ //on completion, either display the error or dismiss the ui if(error){ [[[UIAlertView alloc] initWithTitle:error.userInfo[@"__type"] message:error.userInfo[@"message"] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Retry", nil] show]; }else{ [self dismissViewControllerAnimated:YES completion:nil]; }}); }

When the end user has entered his or her code, set the result on mfaCodeCompletion.

Copy
self.mfaCodeCompletion.result = @"mfaCodeFromUser";

If you support sign-up using AdminCreateUser, you can implement the AWSCognitoIdentityNewPasswordRequired protocol.

Copy
-(void) getNewPasswordDetails: (AWSCognitoIdentityNewPasswordRequiredInput *) newPasswordRequiredInput newPasswordRequiredCompletionSource:(AWSTaskCompletionSource<AWSCognitoIdentityNewPasswordRequiredDetails *> *) newPasswordRequiredCompletionSource { //keep a handle to the completion, you’ll need it continue once you get the inputs from the end user self.newPasswordRequiredCompletionSource = newPasswordRequiredCompletionSource; //newPasswordRequiredInput has details about the existing user attributes and required fields if you need to display them in your ui } -(void) didCompleteNewPasswordStepWithError:(NSError* _Nullable) error { dispatch_async(dispatch_get_main_queue(), ^{ //on completion, either display the error or dismiss the ui if(error){ [[[UIAlertView alloc] initWithTitle:error.userInfo[@"__type"] message:error.userInfo[@"message"] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Retry", nil] show]; }else{ [self dismissViewControllerAnimated:YES completion:nil]; }});

When the end user has entered their proposed password and any required attributes, set the result on newPasswordRequiredCompletionSource.

Copy
NSDictionary<NSString *, NSString *> *userAttributes = @{@"name":@"My new name", @"email":@"mynewemail@myemail.com"}; AWSCognitoIdentityNewPasswordRequiredDetails *details = [[AWSCognitoIdentityNewPasswordRequiredDetails alloc] initWithProposedPassword:@"newPassword" userAttributes:userAttributes]; self.newPasswordRequiredCompletionSource.result = details;

If you support software MFA, you can implement the AWSCognitoIdentitySoftwareMfaSetupRequired protocol.

Copy
-(void) getSoftwareMfaSetupDetails: (AWSCognitoIdentitySoftwareMfaSetupRequiredInput *) softwareMfaSetupInput softwareMfaSetupRequiredDetails: (AWSTaskCompletionSource<AWSCognitoIdentitySoftwareMfaSetupRequiredDetails *> *) softwareMfaSetupRequiredCompletionSource{ //keep a handle to the completion, you’ll need it continue once you get the inputs from the end user self.softwareMfaSetupRequiredCompletionSource = softwareMfaSetupRequiredCompletionSource; // softwareMfaSetupInput has details about the secret code the end user needs to register with their TOTP application. } -(void) didCompleteMfaSetupStepWithError:(NSError* _Nullable) error { dispatch_async(dispatch_get_main_queue(), ^{ //on completion, either display the error or dismiss the ui if(error){ [[[UIAlertView alloc] initWithTitle:error.userInfo[@"__type"] message:error.userInfo[@"message"] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Retry", nil] show]; }else{ [self dismissViewControllerAnimated:YES completion:nil]; } }); }

When the end user has the current code from their software token app, set the result on softwareMfaSetupRequiredCompletionSource.

Copy
AWSCognitoIdentitySoftwareMfaSetupRequiredDetails *details = [[AWSCognitoIdentitySoftwareMfaSetupRequiredDetails alloc] initWithUserCode: @"User Code" friendlyDeviceName:@"Friendly Name" ]; self.newPasswordRequiredCompletionSource.result = details;

If you support multiple MFA types, you can implement the AWSCognitoIdentitySelectMfa protocol.

Copy
-(void) getSelectMfaDetails: (AWSCognitoIdentitySelectMfaInput *) selectMfaInput selectMfaCompletionSource: (AWSTaskCompletionSource<AWSCognitoIdentitySelectMfaDetails *> *) selectMfaCompletionSource { //keep a handle to the completion, you’ll need it continue once you get the inputs from the end user self.selectMfaCompletionSource = selectMfaCompletionSource; // selectMfaInput has details about what MFAS are available to select. } -(void) didCompleteMfaSetupStepWithError:(NSError* _Nullable) error { dispatch_async(dispatch_get_main_queue(), ^{ //on completion, either display the error or dismiss the ui if(error){ [[[UIAlertView alloc] initWithTitle:error.userInfo[@"__type"] message:error.userInfo[@"message"] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Retry", nil] show]; }else{ [self dismissViewControllerAnimated:YES completion:nil]; } }); }

When the end user has selected the MFA, set the result on selectMfaCompletionSource.

Copy
AWSCognitoIdentitySoftwareMfaSetupRequiredDetails *details = [[AWSCognitoIdentitySelectMfaDetails alloc] initWithSelectedMfa: @"Selected MFA" ]; self.selectMfaCompletionSource.result = details;

Example: Forgot Password

Copy
[[user forgotPassword] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserForgotPasswordResponse*> * _Nonnull task) { //success return nil; }]; [[user confirmForgotPassword:@"code" password:@"newPassword"] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserConfirmForgotPasswordResponse *> * _Nonnull task) { //success return nil; }];

Example: Amazon Pinpoint Analytics

The following procedure describes how to integrate Amazon Pinpoint into your iOS Amazon Cognito application.

  1. Sign in to the AWS Management Console and open the Amazon Pinpoint console at https://console.aws.amazon.com/pinpoint/.

  2. Create an Amazon Pinpoint application. Make a note of the Amazon Pinpoint app ID.

  3. In your Amazon Cognito app, when you instantiate your Amazon Cognito user pools instance, provide an AWSCognitoIdentityUserPoolConfiguration and use the Amazon Pinpoint app ID from the previous step to set the pinpointAppId.

    Objective-C:

    Copy
    AWSCognitoIdentityUserPoolConfiguration * poolConfiguration = [[AWSCognitoIdentityUserPoolConfiguration alloc] initWithClientId:@"YOUR_APP_CLIENT_ID" clientSecret:@"YOUR_OPTIONAL_APP_CLIENT_SECRET" poolId:@"YOUR_USER_POOL_ID" shouldProvideCognitoValidationData:YES pinpointAppId:@"YOUR_PINPOINT_APP_ID"];

    Swift:

    Copy
    let poolConfiguration = AWSCognitoIdentityUserPoolConfiguration(clientId: "YOUR_APP_CLIENT_ID", clientSecret: "YOUR_OPTIONAL_APP_CLIENT_SECRET", poolId: "YOUR_USER_POOL_ID", shouldProviderCognitoValidationData: YES, pinpointAppId: "YOUR_PINPOINT_APP_ID")

Authenticated Example: Get User Attributes

Copy
[[user getDetails] continueWithBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserGetDetailsResponse *> * _Nonnull task) { dispatch_async(dispatch_get_main_queue(), ^{ if(task.error){ [[[UIAlertView alloc] initWithTitle:task.error.userInfo[@"__type"] message:task.error.userInfo[@"message"] delegate:self cancelButtonTitle:nil otherButtonTitles:@"Retry", nil] show]; }else{ AWSCognitoIdentityUserGetDetailsResponse *response = task.result; //do something with response.userAttributes } }); return nil; }];

Authenticated Example: Verify User Attributes

Copy
[[user getAttributeVerificationCode:@"phone_number"] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserGetAttributeVerificationCodeResponse *> * _Nonnull task) { //success return nil; }]; [[user verifyAttribute:@"phone_number"code:@"code"] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserVerifyAttributeResponse *> * _Nonnull task) { //success return nil; }];

Authenticated Example: Update User Attributes

Copy
AWSCognitoIdentityUserAttributeType * attribute = [AWSCognitoIdentityUserAttributeType new]; attribute.name = @"name"; attribute.value = @"John User"; [[user updateAttributes:@[attribute]] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserUpdateAttributesResponse *> * _Nonnull task) { //success return nil; }];

Authenticated Example: Change Password

Copy
[[user changePassword:@"currentPassword" proposedPassword:@"proposedPassword"] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserChangePasswordResponse *> * _Nonnull task) { //success return nil; }];

Authenticated Example: Turning on SMS MFA

Copy
AWSCognitoIdentityUserSettings * settings = [AWSCognitoIdentityUserSettings new]; AWSCognitoIdentityUserMFAOption * mfaOptions = [AWSCognitoIdentityUserMFAOption new]; mfaOptions.attributeName = @"phone_number"; mfaOptions.deliveryMedium = AWSCognitoIdentityProviderDeliveryMediumTypeSms; settings.mfaOptions = @[mfaOptions]; [[user setUserSettings:settings] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserSetUserSettingsResponse *> * _Nonnull task) { //success return nil; }];

Authenticated Example: Turning on Software MFA

Copy
//start by calling associateSoftwareToken to get a secret code for end user to register [[self.user associateSoftwareToken] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserAssociateSoftwareTokenResponse *> * _Nonnull t) { dispatch_async(dispatch_get_main_queue(), ^{ UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Associate Software MFA" message:t.result.secretCode preferredStyle:UIAlertControllerStyleAlert]; [alert addAction:[UIAlertAction actionWithTitle:@"Verify" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { //verify the software token by having end user input current code [[self.user verifySoftwareToken:alert.textFields[0].text friendlyDeviceName: @"My Software Token"] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserVerifySoftwareTokenResponse *> * _Nonnull t) { //now the software token is configured, but not enabled, enable it AWSCognitoIdentityUserMfaPreferences * mfaPreferences = [AWSCognitoIdentityUserMfaPreferences new]; mfaPreferences.softwareTokenMfa = [[AWSCognitoIdentityUserMfaType alloc] initWithEnabled:YES preferred:NO]; [[self.user setUserMfaPreference:mfaPreferences] continueWithSuccessBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserSetUserMfaPreferenceResponse *> * _Nonnull t) { return t; }]; return nil; }]; }]]; [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) { textField.placeholder = @"User Code:"; }]; [self presentViewController:alert animated:YES completion:nil]; }); return nil; }];