Menu
Amazon Cognito
Developer Guide (Version Last Updated: 07/28/2016)

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.

    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: Register a User

Use pool.signUp:password:userAttributes:validationData to register 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"; //register 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 credentials are needed via a delegate.

To sign in explicitly, use the following:

Copy
[user getSession:@"username" password:@"password" validationData:nil scopes: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; }

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; //AWSCognitoIdentityNewPasswordRequiredDetails 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;

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; }];

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 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; }];