/// <summary> /// Initializes an IAM Client object and then calls CreatePolicyAsync /// to create the policy. /// </summary> public static async Task Main() { // Represents JSON code for AWS managed full access policy for // Amazon Simple Storage Service (Amazon S3). string s3FullAccessPolicy = "{" + " \"Statement\" : [{"+ " \"Action\" : [\"s3:*\"],"+ " \"Effect\" : \"Allow\","+ " \"Resource\" : \"*\""+ "}]" + "}"; string policyName = "S3FullAccess"; var client = new AmazonIdentityManagementServiceClient(); var response = await client.CreatePolicyAsync(new CreatePolicyRequest { PolicyDocument = s3FullAccessPolicy, PolicyName = policyName, }); if (response is not null) { var policy = response.Policy; Console.WriteLine($"{policy.PolicyName} created with ID: {policy.PolicyId}."); } else { Console.WriteLine("Coultn't create policy."); } }
public Task <CreatePolicyResponse> CreatePolicyAsync(string name, string description, string json, string path = null, CancellationToken cancellationToken = default(CancellationToken)) => _IAMClient.CreatePolicyAsync( new CreatePolicyRequest() { Description = description, PolicyName = name, PolicyDocument = json, Path = path }, cancellationToken).EnsureSuccessAsync();
// snippet-end:[IAM.dotnetv3.CreateAccessKey] // snippet-start:[IAM.dotnetv3.CreatePolicyAsync] /// <summary> /// Create a policy to allow a user to list the buckets in an account. /// </summary> /// <param name="client">The initialized IAM client object.</param> /// <param name="policyName">The name of the poicy to create.</param> /// <param name="policyDocument">The permissions policy document.</param> /// <returns>The newly created ManagedPolicy object.</returns> public static async Task <ManagedPolicy> CreatePolicyAsync( AmazonIdentityManagementServiceClient client, string policyName, string policyDocument) { var request = new CreatePolicyRequest { PolicyName = policyName, PolicyDocument = policyDocument, }; var response = await client.CreatePolicyAsync(request); return(response.Policy); }
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; } }
//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; } } }
/// <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); } }