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); AttachRolePolicyRequest request = new AttachRolePolicyRequest() { PolicyArn = "arn:aws:iam::aws:policy/AdministratorAccess", RoleName = input.SelectToken("EventData.roleName").ToString() }; AttachRolePolicyResponse response = client.AttachRolePolicyAsync(request).Result; JObject outputObject = new JObject(); outputObject.Add("AttachRolePolicyResponse", JObject.FromObject(response)); outputObject.Add("CreateAccountResponse", input.SelectToken("CreateAccountResponse")); outputObject.Add("EventData", input.SelectToken("EventData")); return(outputObject); }
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 }
public Task <AttachRolePolicyResponse> AttachRolePolicyAsync( string roleName, string policyArn, CancellationToken cancellationToken = default(CancellationToken)) => _IAMClient.AttachRolePolicyAsync( new AttachRolePolicyRequest() { RoleName = roleName, PolicyArn = policyArn }, cancellationToken).EnsureSuccessAsync();
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 }
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; } }
/// <summary> /// Initializes the IAM client and attaches the IAM Policy to the /// selected IAM Role. /// </summary> public static async Task Main() { var client = new AmazonIdentityManagementServiceClient(); var response = await client.AttachRolePolicyAsync(new AttachRolePolicyRequest { PolicyArn = "arn:aws:iam::aws:policy/AmazonS3FullAccess", RoleName = "S3FullAccessRole", }); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine("AmazonS3FullAccess policy attached to S3FullAccessRole."); } else { Console.WriteLine("Coudln't attach policy."); } }
// snippet-end:[IAM.dotnetv3.CreatePolicyAsync] // snippet-start:[IAM.dotnetv3.AttachPolicy] /// <summary> /// Attach the policy to the role so that the user can assume it. /// </summary> /// <param name="client">The initialized IAM client object.</param> /// <param name="policyArn">The ARN of the policy to attach.</param> /// <param name="roleName">The name of the role to attach the policy to.</param> public static async Task AttachRoleAsync( AmazonIdentityManagementServiceClient client, string policyArn, string roleName) { var request = new AttachRolePolicyRequest { PolicyArn = policyArn, RoleName = roleName, }; var response = await client.AttachRolePolicyAsync(request); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine("Successfully attached the policy to the role."); } else { Console.WriteLine("Could not attach the policy."); } }
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); }
//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); } }