示例#1
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;
                }
            }
        }
        //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);
            }
        }