4.2 Authenticate Using AWS Cognito Service Wrapper

If you are using AWS Cognito Service for user authentication, AWS Cognito Service Wrapper lets you authenticate with AWS Cognito and Bayun together. You don't need to authenticate with Bayun separately, you can use the Bayun AWS Cognito Service Wrapper APIs to signIn/signUp with AWS Cognito. Bayun AWS Cognito Service Wrapper APIs take care of the authentication with Bayun.

Let us first look at how a typical app is created using user pools with the AWS Mobile SDK for iOS and then look at the components of the S3 app that get affected using Bayun AWSS3 wrapper class SecureAuthentication.

4.2.1 Using user pools with AWS Mobile SDK

Here are the details about registering, confirming, and authenticating users using standard AWS Mobile SDK.

Creating an AWSCognitoIdentityUserPool Object

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

1. Set up your service config

Objective-C
Swift 3.0

AWSServiceConfiguration *serviceConfiguration = [[AWSServiceConfiguration alloc] initWithRegion:AWSRegionUSEast1 credentialsProvider:nil];

 let serviceConfiguration :  AWSServiceConfiguration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: nil)

2. Create a user pool configuration

Objective-C
Swift 3.0

//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"];


let configuration : AWSCognitoIdentityUserPoolConfiguration = AWSCognitoIdentityUserPoolConfiguration(clientId: "CLIENT_ID", clientSecret: "CLIENT_SECRET", poolId: "USER_POOL_ID")
        
AWSCognitoIdentityUserPool.register(with: serviceConfiguration, userPoolConfiguration: configuration, forKey: "UserPool")
        
let pool : AWSCognitoIdentityUserPool = AWSCognitoIdentityUserPool(forKey: "UserPool")

Register a User

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

Objective-C
Swift 3.0

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";   

AWSCognitoIdentityUserPool *pool = [AWSCognitoIdentityUserPool CognitoIdentityUserPoolForKey:@"UserPool"];
//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;
}]; 

let pool : AWSCognitoIdentityUserPool = AWSCognitoIdentityUserPool(forKey: "UserPool")
        
let phone = AWSCognitoIdentityUserAttributeType()
phone?.name = "phone_number"
phone?.value = "+15555555555"
        
let email = AWSCognitoIdentityUserAttributeType()
email?.name = "email"
email?.value = "email@mydomain.com"
        
//sign up the user
pool.signUp("username", password: "password", userAttributes: [phone!,email!], validationData: nil).continueWith  {(task) -> Any? in
    DispatchQueue.main.async(execute: {
        if let error = task.error as? NSError {
            let alertController = UIAlertController(title: error.userInfo["__type"] as? String,
                                                            message: error.userInfo["message"] as? String,
                                                            preferredStyle: .alert)
            let retryAction = UIAlertAction(title: "Retry", style: .default, handler: nil)
            alertController.addAction(retryAction) 
            self?.present(alertController, animated: true, completion:  nil)
         } else if let result = task.result  {
            // handle the case where user has to confirm his identity via email / SMS
            if (result.user.confirmedStatus != AWSCognitoIdentityUserStatus.confirmed) {
                        strongSelf.sentTo = result.codeDeliveryDetails?.destination
                        strongSelf.performSegue(withIdentifier: "confirmSignUpSegue", sender:sender)
            } else {
                        let _ = strongSelf.navigationController?.popToRootViewController(animated: true)
            }
         }
    })
    return nil
}

Confirm Signup

Confirm a users' sign up with the confirmation code using user.confirmSignUp:forceAliasCreation:withBlock: method

Objective-C
Swift 3.0

AWSCognitoIdentityUserPool *pool = [AWSCognitoIdentityUserPool CognitoIdentityUserPoolForKey:@"UserPool"];
AWSCognitoIdentityUser *user = [pool getUser:@"username"];
[user confirmSignUp:"code" forceAliasCreation:YES withBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserConfirmSignUpResponse *> * _Nonnull task) {
       
 if(task.error){
    [[[UIAlertView alloc] initWithTitle:task.error.userInfo[@"__type"]
                                message:task.error.userInfo[@"message"]
                               delegate:nil
                      cancelButtonTitle:@"Ok"
                      otherButtonTitles:nil] show];
 } else {
    //return to signin screen
    [self.navigationController popToRootViewControllerAnimated:YES];
 }
 return nil;
}];

let pool : AWSCognitoIdentityUserPool = AWSCognitoIdentityUserPool(forKey: "UserPool")
let user : AWSCognitoIdentityUser = pool.getUser("username")
user.confirmSignUp("code", forceAliasCreation: true).continueWith { (task) -> Any? in
DispatchQueue.main.async(execute: {
    if let error = task.error as? NSError {
        let alertController = UIAlertController(title: error.userInfo["__type"] as? String,
                                              message: error.userInfo["message"] as? String,
                                       preferredStyle: .alert)
        let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
        alertController.addAction(okAction)
            
        self.present(alertController, animated: true, completion:  nil)
    } else {
        let _ = strongSelf.navigationController?.popToRootViewController(animated: true)
    }
})

Sign in a User

Use getSession:password:validationData:scopes: method to get a session username and password.

Objective-C
Swift 3.0

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

user.getSession("username", password: "password", validationData:nil, scopes:nil.continueWith { (task) -> Any? in
   //success, task.result has user session
    return nil;
})

4.2.2 Using user pools with Bayun AWSS3 wrapper 'SecureAuthentication'

User Registration, SignUp Confirmation, SignIn, SignOut needs to be done with SecureAuthentication instance.

Creating an AWSCognitoIdentityUserPool Object

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

1. Set up your service config

There is no change in setting up Service Config and is same as using standard AWS Mobile SDK.

Objective-C
Swift 3.0

AWSServiceConfiguration *serviceConfiguration = [[AWSServiceConfiguration alloc] initWithRegion:AWSRegionUSEast1 credentialsProvider:nil];

 let serviceConfiguration :  AWSServiceConfiguration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: nil)

2. Create a user pool configuration.

There is no change in creating user pool configuration and is same as using standard AWS Mobile SDK.

Objective-C
Swift 3.0

//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"];


let configuration : AWSCognitoIdentityUserPoolConfiguration = AWSCognitoIdentityUserPoolConfiguration(clientId: "CLIENT_ID", clientSecret: "CLIENT_SECRET", poolId: "USER_POOL_ID")
        
AWSCognitoIdentityUserPool.register(with: serviceConfiguration, userPoolConfiguration: configuration, forKey: "UserPool")
        
let pool : AWSCognitoIdentityUserPool = AWSCognitoIdentityUserPool(forKey: "UserPool")

Register a User

Use SecureAuthentication's signUp:username:password:userAttributes:userAttributes:validationData:withBlock: method to register a new user instead of relying on standard AWS Mobile SDK's signUp method.

Objective-C
Swift 3.0

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";   

AWSCognitoIdentityUserPool *pool = [AWSCognitoIdentityUserPool CognitoIdentityUserPoolForKey:@"UserPool"];
//sign up the user    
[[SecureAuthentication sharedInstance] signUp:pool username:@"username" password:@"password" userAttributes:@[email,phone] validationData:nil withBlock:^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){
            // handle the case where user has to confirm his identity
        }
    }});
    return nil;                                                                                    
}];  

let pool : AWSCognitoIdentityUserPool = AWSCognitoIdentityUserPool(forKey: "UserPool")
        
let phone = AWSCognitoIdentityUserAttributeType()
phone?.name = "phone_number"
phone?.value = "+15555555555"
        
let email = AWSCognitoIdentityUserAttributeType()
email?.name = "email"
email?.value = "email@mydomain.com"
        
SecureAuthentication.sharedInstance().signUp(pool, username: "username", password: "password", userAttributes: [phone!,email!], validationData: nil){ (task) -> Any? in
    DispatchQueue.main.async(execute: {
        if let error = task.error as? NSError {
            let alertController = UIAlertController(title: error.userInfo["__type"] as? String,
                                                            message: error.userInfo["message"] as? String,
                                                            preferredStyle: .alert)
            let retryAction = UIAlertAction(title: "Retry", style: .default, handler: nil)
            alertController.addAction(retryAction)
            self?.present(alertController, animated: true, completion:  nil)
        } else if let result = task.result  {
            if (result.user.confirmedStatus != AWSCognitoIdentityUserStatus.confirmed) {
                // handle the case where user has to confirm his identity
            }
        }
    })
}

Confirm Signup

Confirm a users' sign up with the confirmation code using SecureAuthentication's confirmSignUpForUser:confirmationCode:forceAliasCreation:withBlock: method.

Objective-C
Swift 3.0

AWSCognitoIdentityUserPool *pool = [AWSCognitoIdentityUserPool CognitoIdentityUserPoolForKey:@"UserPool"];
AWSCognitoIdentityUser *user = [pool getUser:@"username"];
[[SecureAuthentication sharedInstance] confirmSignUpForUser:user confirmationCode:"code" forceAliasCreation:YES withBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserConfirmSignUpResponse *> * _Nonnull task) {
       
 if(task.error){
    [[[UIAlertView alloc] initWithTitle:task.error.userInfo[@"__type"]
                                message:task.error.userInfo[@"message"]
                               delegate:nil
                      cancelButtonTitle:@"Ok"
                      otherButtonTitles:nil] show];
 } else {
    //return to signin screen
    [self.navigationController popToRootViewControllerAnimated:YES];
 }
 return nil;
}];

let pool : AWSCognitoIdentityUserPool = AWSCognitoIdentityUserPool(forKey: "UserPool")
let user : AWSCognitoIdentityUser = pool.getUser("username")
SecureAuthentication.sharedInstance().confirmSignUp(for: user, confirmationCode: "code", forceAliasCreation: true) { (task) -> Any? in
DispatchQueue.main.async(execute: {
    if let error = task.error as? NSError {
        let alertController = UIAlertController(title: error.userInfo["__type"] as? String,
                                              message: error.userInfo["message"] as? String,
                                       preferredStyle: .alert)
        let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
        alertController.addAction(okAction)
            
        self.present(alertController, animated: true, completion:  nil)
    } else {
        let _ = strongSelf.navigationController?.popToRootViewController(animated: true)
    }
})

Sign in a User

Use SecureAuthentication's signInPool:username:password:withBlock: method to get a session username and password.

Objective-C
Swift 3.0

AWSCognitoIdentityUserPool *pool = [AWSCognitoIdentityUserPool CognitoIdentityUserPoolForKey:@"UserPool"];
   
[[SecureAuthentication sharedInstance] signInPool:pool username:@"username" password:@"password" withBlock:^id _Nullable(AWSTask<AWSCognitoIdentityUserSession*> * _Nonnull task) {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSError *error = task.error;
        if(error){
            [[[UIAlertView alloc] initWithTitle:error.userInfo[@"__type"]
                                        message:error.userInfo[@"message"]
                                       delegate:nil
                              cancelButtonTitle:nil
                              otherButtonTitles:@"Retry", nil] show];
        } else {
           //signIn successful
        }
    });
    return nil;
}];

SecureAuthentication.sharedInstance().sign(in: pool, username: "username", password: "password", with: { (task) -> Any? in
    DispatchQueue.main.async(execute: {
        if let error = task.error as? NSError {
            let alertController = UIAlertController(title: error.userInfo["__type"] as? String,
                                                  message: error.userInfo["message"] as? String,
                                           preferredStyle: .alert)
            let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
            alertController.addAction(okAction)
            self.present(alertController, animated: true, completion: nil)
        } else {
            //signIn successful
        }
    })
})

Signout a user

Use SecureAuthentication's signout method to clear all tokens.

Objective-C
Swift 3.0

[[SecureAuthentication sharedInstance] signout:user];

SecureAuthentication.sharedInstance().signout(user)

results matching ""

    No results matching ""