Beispiel #1
0
        /// <summary>
        /// Create the role if it's not there already.
        /// Return true if it already existed.
        /// </summary>
        /// <returns></returns>
        private static async Task <bool> ValidateAndSetIamRoleArn(AmazonIdentityManagementServiceClient iamClient)
        {
            var getRoleRequest = new GetRoleRequest
            {
                RoleName = ExecutionRoleName
            };

            try
            {
                ExecutionRoleArn = (await iamClient.GetRoleAsync(getRoleRequest)).Role.Arn;
                return(true);
            }
            catch (NoSuchEntityException)
            {
                // create the role
                var createRoleRequest = new CreateRoleRequest
                {
                    RoleName    = ExecutionRoleName,
                    Description = "Test role for CustomRuntimeTests.",
                    AssumeRolePolicyDocument = LAMBDA_ASSUME_ROLE_POLICY
                };
                ExecutionRoleArn = (await iamClient.CreateRoleAsync(createRoleRequest)).Role.Arn;

                // Wait for role to propagate.
                await Task.Delay(10000);

                return(false);
            }
        }
Beispiel #2
0
        private static async Task SetupVmimportRole(string accessKey, string secretKey)
        {
            var credentials = new BasicAWSCredentials(accessKey, secretKey);

            var iamClient = new AmazonIdentityManagementServiceClient(credentials, RegionEndpoint.EUCentral1);

            Console.WriteLine("Creating role...");

            var createRole = await iamClient.CreateRoleAsync(new CreateRoleRequest
            {
                RoleName = "vmimport",
                AssumeRolePolicyDocument = ReadEmbeddedFile("AwsSetupTool.trust-policy.json")
            });

            Console.WriteLine($"HTTP {createRole.HttpStatusCode}: {createRole}");

            Console.WriteLine("Creating role policy...");

            var putRolePolicy =
                await
                iamClient.PutRolePolicyAsync(new PutRolePolicyRequest
            {
                RoleName       = "vmimport",
                PolicyName     = "vmimport",
                PolicyDocument = ReadEmbeddedFile("AwsSetupTool.role-policy.json")
            });

            Console.WriteLine($"HTTP {putRolePolicy.HttpStatusCode}: {putRolePolicy}");
        }
        public JObject FunctionHandler(JObject input)
        {
            JObject createAccountResponseObject = JObject.FromObject(input.SelectToken("CreateAccountResponse"));
            string  accountId = createAccountResponseObject.SelectToken("CreateAccountStatus.AccountId").ToString();

            var credentials = AssumeIdentity.AssumeRole(accountId).Credentials;

            string accessKey    = credentials.AccessKeyId;
            string secretkey    = credentials.SecretAccessKey;
            string sessionToken = credentials.SessionToken;

            AmazonIdentityManagementServiceClient client = new AmazonIdentityManagementServiceClient(accessKey, secretkey, sessionToken);

            CreateRoleRequest request = new CreateRoleRequest()
            {
                RoleName                 = input.SelectToken("EventData.roleName").ToString(),
                MaxSessionDuration       = 43200,
                AssumeRolePolicyDocument = "{ \"Version\": \"2012-10-17\", \"Statement\": { \"Effect\": \"Allow\", \"Action\": \"sts:AssumeRoleWithSAML\", \"Principal\": {\"Federated\": \"arn:aws:iam::" + accountId + ":saml-provider/ADFS\"}, \"Condition\": {\"StringEquals\": {\"SAML:aud\": \"https://signin.aws.amazon.com/saml\"}} } }"
            };

            CreateRoleResponse response = client.CreateRoleAsync(request).Result;

            JObject outputObject = new JObject();

            outputObject.Add("CreateAccountResponse", createAccountResponseObject);
            outputObject.Add("CreateRoleResponse", JObject.FromObject(response));
            outputObject.Add("EventData", input.SelectToken("EventData"));

            return(outputObject);
        }
Beispiel #4
0
        public static async Task SetupFargateRoleAsync()
        {
            #region setup_ecs_frontend_role
            using (var iamClient = new AmazonIdentityManagementServiceClient())
            {
                var createRequest = new CreateRoleRequest
                {
                    RoleName = "ECS-ServerlessTODOList.Frontend",
                    AssumeRolePolicyDocument = @"
{
  ""Version"": ""2012-10-17"",
  ""Statement"": [
    {
      ""Sid"": """",
      ""Effect"": ""Allow"",
      ""Principal"": {
        ""Service"": ""ecs-tasks.amazonaws.com""
      },
      ""Action"": ""sts:AssumeRole""
    }
  ]
}
".Trim()
                };

                try
                {
                    var createResponse = await iamClient.CreateRoleAsync(createRequest);

                    Console.WriteLine($"Role {createResponse.Role.RoleName}");

                    var policies = new string[]
                    {
                        "arn:aws:iam::aws:policy/CloudWatchLogsFullAccess",
                        "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess",
                        "arn:aws:iam::aws:policy/AmazonSSMFullAccess",
                        "arn:aws:iam::aws:policy/AmazonCognitoPowerUser"
                    };
                    foreach (var policy in policies)
                    {
                        await iamClient.AttachRolePolicyAsync(new AttachRolePolicyRequest
                        {
                            RoleName  = createRequest.RoleName,
                            PolicyArn = policy
                        });

                        Console.WriteLine($"Policy {policy} attached to {createRequest.RoleName}");
                    }
                }
                catch (EntityAlreadyExistsException)
                {
                    Console.Error.WriteLine($"Role with the name {createRequest.RoleName} alreaedy exists.");
                }
            }
            #endregion
        }
Beispiel #5
0
        public static async Task SetupStreamProcessorRoleAsync()
        {
            #region setup_streamprocessor_role
            using (var iamClient = new AmazonIdentityManagementServiceClient())
            {
                var createRequest = new CreateRoleRequest
                {
                    RoleName = "ServerlessTODOList.StreamProcessor",
                    AssumeRolePolicyDocument = @"
{
  ""Version"": ""2012-10-17"",
  ""Statement"": [
    {
      ""Sid"": """",
      ""Effect"": ""Allow"",
      ""Principal"": {
        ""Service"": ""lambda.amazonaws.com""
      },
      ""Action"": ""sts:AssumeRole""
    }
  ]
}
".Trim()
                };

                try
                {
                    var createResponse = await iamClient.CreateRoleAsync(createRequest);

                    Console.WriteLine($"Role {createResponse.Role.RoleName}");

                    var policies = new string[]
                    {
                        "arn:aws:iam::aws:policy/service-role/AWSLambdaDynamoDBExecutionRole",
                        "arn:aws:iam::aws:policy/AmazonSESFullAccess"
                    };
                    foreach (var policy in policies)
                    {
                        await iamClient.AttachRolePolicyAsync(new AttachRolePolicyRequest
                        {
                            RoleName  = createRequest.RoleName,
                            PolicyArn = policy
                        });

                        Console.WriteLine($"Policy {policy} attached to {createRequest.RoleName}");
                    }
                }
                catch (EntityAlreadyExistsException)
                {
                    Console.Error.WriteLine($"Role with the name {createRequest.RoleName} alreaedy exists.");
                }
            }
            #endregion
        }
Beispiel #6
0
        private async Task CreateRoleAsync()
        {
            var response = await _iamClient.CreateRoleAsync(new CreateRoleRequest
            {
                RoleName    = _executionRoleName,
                Description = $"Test role for {TestIdentifier}.",
                AssumeRolePolicyDocument = LambdaAssumeRolePolicy
            });

            _executionRoleArn = response.Role.Arn;

            // Wait  5 seconds to let execution role propagate
            await Task.Delay(5000);
        }
Beispiel #7
0
        // snippet-end:[IAM.dotnetv3.AttachPolicy]

        // snippet-start:[IAM.dotnetv3.CreateRoleAsync]

        /// <summary>
        /// Create a new IAM role which we can attach to a user.
        /// </summary>
        /// <param name="client">The initialized IAM client object.</param>
        /// <param name="roleName">The name of the IAM role to create.</param>
        /// <param name="rolePermissions">The permissions which the role will have.</param>
        /// <returns>A Role object representing the newly created role.</returns>
        public static async Task <Role> CreateRoleAsync(
            AmazonIdentityManagementServiceClient client,
            string roleName,
            string rolePermissions)
        {
            var request = new CreateRoleRequest
            {
                RoleName = roleName,
                AssumeRolePolicyDocument = rolePermissions,
            };

            var response = await client.CreateRoleAsync(request);

            return(response.Role);
        }
Beispiel #8
0
 public Task <CreateRoleResponse> CreateRoleAsync(
     string roleName,
     string description,
     string assumeRolePolicyDocument,
     string path            = null,
     int maxSessionDuration = 12 *3600,
     CancellationToken cancellationToken = default(CancellationToken))
 => _IAMClient.CreateRoleAsync(
     new CreateRoleRequest()
 {
     Description              = description,
     RoleName                 = roleName,
     MaxSessionDuration       = maxSessionDuration,
     AssumeRolePolicyDocument = assumeRolePolicyDocument, Path = path
 },
     cancellationToken).EnsureSuccessAsync();
Beispiel #9
0
        static async Task <string> CreateRole(string roleName, string service, string policy)
        {
            try
            {
                var config = new AmazonIdentityManagementServiceConfig();
                config.RegionEndpoint = region;
                using (var aimsc = new AmazonIdentityManagementServiceClient(config))
                {
                    string assumeRole = @"{""Version"":""2012-10-17"",""Statement"":[{""Effect"":""Allow"",""Principal"":{""Service"": """ + service + @".amazonaws.com""},""Action"":""sts:AssumeRole""}]}";

                    var crres = await aimsc.CreateRoleAsync(new CreateRoleRequest
                    {
                        AssumeRolePolicyDocument = assumeRole,
                        Path     = "/",
                        RoleName = roleName
                    });

                    Role role = crres.Role;

                    bucket = "buildbucket-" + region.SystemName + "-" + GetAWSNum(role.Arn);

                    var cpres = await aimsc.CreatePolicyAsync(new CreatePolicyRequest
                    {
                        PolicyName     = roleName + "Policy",
                        Description    = "This allows " + service + " to access services",
                        PolicyDocument = policy,
                        Path           = "/"
                    });

                    var policyArn = cpres.Policy.Arn;

                    var response = await aimsc.AttachRolePolicyAsync(new AttachRolePolicyRequest
                    {
                        PolicyArn = policyArn,
                        RoleName  = roleName
                    });

                    return(role.Arn);
                }
            }
            catch (AmazonIdentityManagementServiceException imsException)
            {
                Console.WriteLine(imsException.Message, imsException.InnerException);
                throw;
            }
        }
Beispiel #10
0
        /// <summary>
        /// Defines the policy for the IAM role and then creates the role.
        /// </summary>
        static async Task Main()
        {
            // Policy that allows reading and writing to a specific Amazon S3
            // Bucket. This policy will allow managing the bucket as well as
            // working with the objects in that bucket.
            string s3ManagementPolicy = "{" +
                "   \"Version\": \"2012-10-17\"," +
                "	\"Statement\" : [{" +
                    "   \"Sid\": \"ListObjectsInBucket\"," +
                    "	\"Effect\" : \"Allow\"," +
                    "   \"Action\" : [\"s3: ListBucket\"]," +
                    "	\"Resource\" :[\"arn:aws:s3:::doc-example-bucket/*\"]" +
                "}," +
                    "   \"Sid\": \"AllObjectActions\"," +
                    "	\"Effect\" : \"Allow\"," +
                    "   \"Action\" : [\"s3:*Object*\"]," +
                    "	\"Resource\" :[\"arn:aws:s3:::doc-example-bucket/*\"]" +
                "}]" +
            "}";

            string roleName = "S3ManagementRole";

            // Create the IAM client object.
            var client = new AmazonIdentityManagementServiceClient();

            var request = new CreateRoleRequest
            {
                AssumeRolePolicyDocument = s3ManagementPolicy,
                RoleName = roleName,
            };

            var response = await client.CreateRoleAsync(request);

            if (response.Role is not null)
            {
                var r = response.Role;
                Console.WriteLine($"{r.RoleName} created on: {r.CreateDate}");
            }
            else
            {
                Console.WriteLine("Could not create role.");
            }
        }
Beispiel #11
0
        /// <summary>
        /// Create the instance profile that will give permission for the EC2 instance to make request to Amazon S3.
        /// </summary>
        /// <returns></returns>
        string CreateInstanceProfile()
        {
            var roleName = "magicec2" + RESOURCDE_POSTFIX;
            // AmazonIdentityManagementServiceClient
            var client = new AmazonIdentityManagementServiceClient(accessKeyId, secretAccessKey, region);

            client.CreateRoleAsync(new CreateRoleRequest
            {
                RoleName = roleName,
                AssumeRolePolicyDocument = @"{""Statement"":[{""Principal"":{""Service"":[""ec2.amazonaws.com""]},""Effect"":""Allow"",""Action"":[""sts:AssumeRole""]}]}"
            });

            var statement = new Amazon.Auth.AccessControlPolicy.Statement(Amazon.Auth.AccessControlPolicy.Statement.StatementEffect.Allow);

            statement.Actions.Add(S3ActionIdentifiers.AllS3Actions);
            statement.Resources.Add(new Resource("*"));

            var policy = new Policy();

            policy.Statements.Add(statement);

            client.PutRolePolicyAsync(new PutRolePolicyRequest
            {
                RoleName       = roleName,
                PolicyName     = "S3Access",
                PolicyDocument = policy.ToJson()
            });

            var response = client.CreateInstanceProfileAsync(new CreateInstanceProfileRequest
            {
                InstanceProfileName = roleName
            });

            client.AddRoleToInstanceProfileAsync(new AddRoleToInstanceProfileRequest
            {
                InstanceProfileName = roleName,
                RoleName            = roleName
            });

            return(response.Result.InstanceProfile.Arn);
        }
Beispiel #12
0
        private async Task CreateRoleAsync()
        {
            var response = await _iamClient.CreateRoleAsync(new CreateRoleRequest
            {
                RoleName    = _executionRoleName,
                Description = $"Test role for {TestIdentifier}.",
                AssumeRolePolicyDocument = LambdaAssumeRolePolicy
            });

            _executionRoleArn = response.Role.Arn;

            // Wait  10 seconds to let execution role propagate
            await Task.Delay(10000);

            await _iamClient.AttachRolePolicyAsync(new AttachRolePolicyRequest
            {
                RoleName  = _executionRoleName,
                PolicyArn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
            });

            // Wait  10 seconds to let execution role propagate
            await Task.Delay(10000);
        }
Beispiel #13
0
        //Tests GetCognitoAWSCredentials
        public async void TestGetCognitoAWSCredentials()
        {
            string password     = "******";
            string poolRegion   = user.UserPool.PoolID.Substring(0, user.UserPool.PoolID.IndexOf("_"));
            string providerName = "cognito-idp." + poolRegion + ".amazonaws.com/" + user.UserPool.PoolID;

            AuthFlowResponse context =
                await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest()
            {
                Password = password
            }).ConfigureAwait(false);

            //Create identity pool
            identityClient = new AmazonCognitoIdentityClient(clientCredentials, clientRegion);
            CreateIdentityPoolResponse poolResponse =
                await identityClient.CreateIdentityPoolAsync(new CreateIdentityPoolRequest()
            {
                AllowUnauthenticatedIdentities = false,
                CognitoIdentityProviders       = new List <CognitoIdentityProviderInfo>()
                {
                    new CognitoIdentityProviderInfo()
                    {
                        ProviderName = providerName, ClientId = user.ClientID
                    }
                },
                IdentityPoolName = "TestIdentityPool" + DateTime.Now.ToString("yyyyMMdd_HHmmss"),
            }).ConfigureAwait(false);

            identityPoolId = poolResponse.IdentityPoolId;

            //Create role for identity pool
            managementClient = new AmazonIdentityManagementServiceClient(clientCredentials, clientRegion);
            CreateRoleResponse roleResponse = managementClient.CreateRoleAsync(new CreateRoleRequest()
            {
                RoleName = "_TestRole_" + DateTime.Now.ToString("yyyyMMdd_HHmmss"),
                AssumeRolePolicyDocument = "{\"Version\": \"2012-10-17\",\"Statement\": [{\"Effect" +
                                           "\": \"Allow\",\"Principal\": {\"Federated\": \"cognito-identity.amazonaws.com\"}," +
                                           "\"Action\": \"sts:AssumeRoleWithWebIdentity\"}]}"
            }).Result;

            roleName = roleResponse.Role.RoleName;

            //Create and attach policy for role
            CreatePolicyResponse policyResponse = managementClient.CreatePolicyAsync(new CreatePolicyRequest()
            {
                PolicyDocument = "{\"Version\": \"2012-10-17\",\"Statement\": " +
                                 "[{\"Effect\": \"Allow\",\"Action\": [\"mobileanalytics:PutEvents\",\"cog" +
                                 "nito-sync:*\",\"cognito-identity:*\",\"s3:*\"],\"Resource\": [\"*\"]}]}",
                PolicyName = "_Cognito_" + DateTime.Now.ToString("yyyyMMdd_HHmmss"),
            }).Result;

            policyArn = policyResponse.Policy.Arn;

            AttachRolePolicyRequest attachRequest = new AttachRolePolicyRequest()
            {
                PolicyArn = policyArn,
                RoleName  = roleName
            };
            AttachRolePolicyResponse attachRolePolicyResponse = managementClient.AttachRolePolicyAsync(attachRequest).Result;

            //Set the role for the identity pool
            await identityClient.SetIdentityPoolRolesAsync(new SetIdentityPoolRolesRequest()
            {
                IdentityPoolId = identityPoolId,
                Roles          = new Dictionary <string, string>()
                {
                    { "authenticated", roleResponse.Role.Arn },
                    { "unauthenticated", roleResponse.Role.Arn }
                },
            }).ConfigureAwait(false);

            //Create and test credentials
            CognitoAWSCredentials credentials = user.GetCognitoAWSCredentials(identityPoolId, clientRegion);

            using (var client = new AmazonS3Client(credentials, Amazon.RegionEndpoint.USEast1))
            {
                int tries = 0;
                ListBucketsResponse bucketsResponse = null;
                var       retryLimit    = 5;
                Exception lastException = null;

                for (; tries < retryLimit; tries++)
                {
                    try
                    {
                        bucketsResponse = await client.ListBucketsAsync(new ListBucketsRequest()).ConfigureAwait(false);

                        Assert.Equal(bucketsResponse.HttpStatusCode, System.Net.HttpStatusCode.OK);
                        break;
                    }
                    catch (Exception ex)
                    {
                        lastException = ex;
                        System.Threading.Thread.Sleep(3000);
                    }
                }

                if (tries == retryLimit && lastException != null)
                {
                    throw lastException;
                }
            }
        }
Beispiel #14
0
        /// <summary>
        /// Internal constructor to initialize a provider, user pool, and user for testing
        /// Created user info: Username = User 5, Password = PassWord1!, Email = [email protected]
        /// </summary>
        public MfaAuthenticationTests()
        {
            //Delete pool created by BaseAuthenticationTestClass
            if (pool != null)
            {
                provider.DeleteUserPoolAsync(new DeleteUserPoolRequest()
                {
                    UserPoolId = pool.PoolID
                }).Wait();
            }

            UserPoolPolicyType         passwordPolicy     = new UserPoolPolicyType();
            List <SchemaAttributeType> requiredAttributes = new List <SchemaAttributeType>();
            List <string> verifiedAttributes = new List <string>();

            var creds  = FallbackCredentialsFactory.GetCredentials();
            var region = FallbackRegionFactory.GetRegionEndpoint();

            provider = new AmazonCognitoIdentityProviderClient(creds, region);

            AdminCreateUserConfigType adminCreateUser = new AdminCreateUserConfigType()
            {
                UnusedAccountValidityDays = 8,
                AllowAdminCreateUserOnly  = false
            };

            passwordPolicy.PasswordPolicy = new PasswordPolicyType()
            {
                MinimumLength    = 8,
                RequireNumbers   = true,
                RequireSymbols   = true,
                RequireUppercase = true,
                RequireLowercase = true
            };

            SchemaAttributeType emailSchema = new SchemaAttributeType()
            {
                Required          = true,
                Name              = CognitoConstants.UserAttrEmail,
                AttributeDataType = AttributeDataType.String
            };
            SchemaAttributeType phoneSchema = new SchemaAttributeType()
            {
                Required          = true,
                Name              = CognitoConstants.UserAttrPhoneNumber,
                AttributeDataType = AttributeDataType.String
            };

            requiredAttributes.Add(emailSchema);
            requiredAttributes.Add(phoneSchema);
            verifiedAttributes.Add(CognitoConstants.UserAttrEmail);
            verifiedAttributes.Add(CognitoConstants.UserAttrPhoneNumber);

            //Create Role for MFA
            using (var managementClient = new AmazonIdentityManagementServiceClient())
            {
                CreateRoleResponse roleResponse = managementClient.CreateRoleAsync(new CreateRoleRequest()
                {
                    RoleName = "TestRole_" + DateTime.Now.ToString("yyyyMMdd_HHmmss"),
                    AssumeRolePolicyDocument = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"\",\"Effect\":\"Allow" +
                                               "\",\"Principal\":{\"Service\":\"cognito-idp.amazonaws.com\"},\"Action\":\"sts:AssumeRole\",\"Condition" +
                                               "\":{\"StringEquals\":{\"sts:ExternalId\":\"8327d096-57c0-4fb7-ad24-62ea8fc692c0\"}}}]}"
                }).Result;

                roleName = roleResponse.Role.RoleName;
                roleArn  = roleResponse.Role.Arn;

                //Create and attach policy for role
                CreatePolicyResponse createPolicyResponse = managementClient.CreatePolicyAsync(new CreatePolicyRequest()
                {
                    PolicyDocument = "{\"Version\": \"2012-10-17\",\"Statement\": [{\"Effect\": \"Allow\",\"Action" +
                                     "\": [\"sns:publish\"],\"Resource\": [\"*\"]}]}",
                    PolicyName = "Cognito_" + DateTime.Now.ToString("yyyyMMdd_HHmmss"),
                }).Result;

                policyName = createPolicyResponse.Policy.PolicyName;
                policyArn  = createPolicyResponse.Policy.Arn;

                managementClient.AttachRolePolicyAsync(new AttachRolePolicyRequest()
                {
                    PolicyArn = policyArn,
                    RoleName  = roleName
                }).Wait();
            }

            //Create user pool and client
            CreateUserPoolRequest createPoolRequest = new CreateUserPoolRequest
            {
                PoolName = "mfaTestPool_" + DateTime.Now.ToString("yyyyMMdd_HHmmss"),
                Policies = passwordPolicy,
                Schema   = requiredAttributes,
                AdminCreateUserConfig  = adminCreateUser,
                MfaConfiguration       = "ON",
                AutoVerifiedAttributes = verifiedAttributes,
                SmsConfiguration       = new SmsConfigurationType
                {
                    SnsCallerArn = roleArn,
                    ExternalId   = "8327d096-57c0-4fb7-ad24-62ea8fc692c0"
                }
            };

            //Build in buffer time for role/policy to be created
            CreateUserPoolResponse createPoolResponse = null;
            string bufferExMsg = "Role does not have a trust relationship allowing Cognito to assume the role";

            while (true)
            {
                try
                {
                    createPoolResponse = provider.CreateUserPoolAsync(createPoolRequest).Result;
                    break;
                }
                catch (Exception ex)
                {
                    if (string.Equals(bufferExMsg, ex.InnerException.Message))
                    {
                        System.Threading.Thread.Sleep(3000);
                    }
                    else
                    {
                        throw ex;
                    }
                }
            }

            UserPoolType poolCreated = createPoolResponse.UserPool;

            CreateUserPoolClientResponse clientResponse =
                provider.CreateUserPoolClientAsync(new CreateUserPoolClientRequest()
            {
                ClientName     = "App1",
                UserPoolId     = poolCreated.Id,
                GenerateSecret = false,
            }).Result;

            UserPoolClientType clientCreated = clientResponse.UserPoolClient;

            this.pool = new CognitoUserPool(poolCreated.Id, clientCreated.ClientId, provider, "");

            SignUpRequest signUpRequest = new SignUpRequest()
            {
                ClientId       = clientCreated.ClientId,
                Password       = "******",
                Username       = "******",
                UserAttributes = new List <AttributeType>()
                {
                    new AttributeType()
                    {
                        Name = CognitoConstants.UserAttrEmail, Value = "*****@*****.**"
                    },
                    new AttributeType()
                    {
                        Name = CognitoConstants.UserAttrPhoneNumber, Value = "+15555555555"
                    }
                },
                ValidationData = new List <AttributeType>()
                {
                    new AttributeType()
                    {
                        Name = CognitoConstants.UserAttrEmail, Value = "*****@*****.**"
                    },
                    new AttributeType()
                    {
                        Name = CognitoConstants.UserAttrPhoneNumber, Value = "+15555555555"
                    }
                }
            };

            SignUpResponse signUpResponse = provider.SignUpAsync(signUpRequest).Result;

            AdminConfirmSignUpRequest confirmRequest = new AdminConfirmSignUpRequest()
            {
                Username   = "******",
                UserPoolId = poolCreated.Id
            };
            AdminConfirmSignUpResponse confirmResponse = provider.AdminConfirmSignUpAsync(confirmRequest).Result;

            this.user = new CognitoUser("User5", clientCreated.ClientId, pool, provider);
        }
        //Tests GetCognitoAWSCredentials
        public async void TestGetCognitoAWSCredentials()
        {
            var password     = "******";
            var poolRegion   = user.UserPool.PoolID.Substring(0, user.UserPool.PoolID.IndexOf("_", StringComparison.Ordinal));
            var providerName = "cognito-idp." + poolRegion + ".amazonaws.com/" + user.UserPool.PoolID;

            var context =
                await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest()
            {
                Password = password
            }).ConfigureAwait(false);

            //Create identity pool
            identityClient = new AmazonCognitoIdentityClient(clientCredentials, clientRegion);
            var poolResponse =
                await identityClient.CreateIdentityPoolAsync(new CreateIdentityPoolRequest()
            {
                AllowUnauthenticatedIdentities = false,
                CognitoIdentityProviders       = new List <CognitoIdentityProviderInfo>()
                {
                    new CognitoIdentityProviderInfo()
                    {
                        ProviderName = providerName, ClientId = user.ClientID
                    }
                },
                IdentityPoolName = "TestIdentityPool" + DateTime.Now.ToString("yyyyMMdd_HHmmss"),
            }).ConfigureAwait(false);

            identityPoolId = poolResponse.IdentityPoolId;

            //Create role for identity pool
            managementClient = new AmazonIdentityManagementServiceClient(clientCredentials, clientRegion);
            var roleResponse = managementClient.CreateRoleAsync(new CreateRoleRequest()
            {
                RoleName = "_TestRole_" + DateTime.Now.ToString("yyyyMMdd_HHmmss"),
                AssumeRolePolicyDocument = "{\"Version\": \"2012-10-17\",\"Statement\": [{\"Effect" +
                                           "\": \"Allow\",\"Principal\": {\"Federated\": \"cognito-identity.amazonaws.com\"}," +
                                           "\"Action\": \"sts:AssumeRoleWithWebIdentity\"}]}"
            }).Result;

            roleName = roleResponse.Role.RoleName;

            //Create and attach policy for role
            var policyResponse = managementClient.CreatePolicyAsync(new CreatePolicyRequest()
            {
                PolicyDocument = "{\"Version\": \"2012-10-17\",\"Statement\": " +
                                 "[{\"Effect\": \"Allow\",\"Action\": [\"mobileanalytics:PutEvents\",\"cog" +
                                 "nito-sync:*\",\"cognito-identity:*\",\"s3:*\"],\"Resource\": [\"*\"]}]}",
                PolicyName = "_Cognito_" + DateTime.Now.ToString("yyyyMMdd_HHmmss"),
            }).Result;

            policyArn = policyResponse.Policy.Arn;

            var attachRequest = new AttachRolePolicyRequest()
            {
                PolicyArn = policyArn,
                RoleName  = roleName
            };
            var attachRolePolicyResponse = managementClient.AttachRolePolicyAsync(attachRequest).Result;

            //Set the role for the identity pool
            await identityClient.SetIdentityPoolRolesAsync(new SetIdentityPoolRolesRequest()
            {
                IdentityPoolId = identityPoolId,
                Roles          = new Dictionary <string, string>()
                {
                    { "authenticated", roleResponse.Role.Arn },
                    { "unauthenticated", roleResponse.Role.Arn }
                },
            }).ConfigureAwait(false);

            //Create and test credentials
            var credentials = user.GetCognitoAWSCredentials(identityPoolId, clientRegion);

            using (var client = new AmazonS3Client(credentials, Amazon.RegionEndpoint.USEast1))
            {
                var tries       = 0;
                var bufferExMsg = "Invalid identity pool configuration. Check assigned IAM roles for this pool.";
                ListBucketsResponse bucketsResponse = null;

                for (; tries < 5; tries++)
                {
                    try
                    {
                        bucketsResponse = await client.ListBucketsAsync(new ListBucketsRequest()).ConfigureAwait(false);

                        break;
                    }
                    catch (NullReferenceException)
                    {
                        System.Threading.Thread.Sleep(3000);
                    }
                    catch (Exception ex)
                    {
                        if (string.Equals(bufferExMsg, ex.Message))
                        {
                            System.Threading.Thread.Sleep(3000);
                        }
                        else
                        {
                            throw ex;
                        }
                    }
                }

                Assert.True(tries < 5, "Failed to list buckets after 5 tries");
                Assert.Equal(bucketsResponse.HttpStatusCode, System.Net.HttpStatusCode.OK);
            }
        }