public static void AttachRolePolicy() { var client = new AmazonIdentityManagementServiceClient(); string policy = GenerateRolePolicyDocument(); CreateRoleRequest roleRequest = new CreateRoleRequest() { RoleName = "tester", AssumeRolePolicyDocument = policy }; var request = new AttachRolePolicyRequest() { PolicyArn = "arn:aws:iam::123456789:policy/DemoEC2Permissions", RoleName = "tester" }; try { var response = client.AttachRolePolicy(request); Console.WriteLine("Policy DemoEC2Permissions attached to Role TestUser"); } catch (NoSuchEntityException) { Console.WriteLine ("Policy 'DemoEC2Permissions' does not exist"); } catch (InvalidInputException) { Console.WriteLine ("One of the parameters is incorrect"); } }
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); }
/// <summary> /// 本接口(AttachRolePolicy)用于绑定策略到角色。 /// </summary> /// <param name="req">参考<see cref="AttachRolePolicyRequest"/></param> /// <returns>参考<see cref="AttachRolePolicyResponse"/>实例</returns> public async Task <AttachRolePolicyResponse> AttachRolePolicy(AttachRolePolicyRequest req) { JsonResponseModel <AttachRolePolicyResponse> rsp = null; try { var strResp = await this.InternalRequest(req, "AttachRolePolicy"); rsp = JsonConvert.DeserializeObject <JsonResponseModel <AttachRolePolicyResponse> >(strResp); } catch (JsonSerializationException e) { throw new TencentCloudSDKException(e.Message); } return(rsp.Response); }
// 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."); } }
//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; } } }
public Task <AttachRolePolicyResponse> AttachRolePolicyAsync(AttachRolePolicyRequest request, CancellationToken cancellationToken = new CancellationToken()) { throw new System.NotImplementedException(); }
public static string CreateRole(IAmazonIdentityManagementService iamClient, string roleName, string assuleRolePolicy, params string[] managedPolicies) { if (managedPolicies != null && managedPolicies.Length > 0) { for (int i = 0; i < managedPolicies.Length; i++) { managedPolicies[i] = ExpandManagedPolicyName(iamClient, managedPolicies[i]); } } string roleArn; try { CreateRoleRequest request = new CreateRoleRequest { RoleName = roleName, AssumeRolePolicyDocument = assuleRolePolicy }; var response = iamClient.CreateRoleAsync(request).Result; roleArn = response.Role.Arn; } catch (Exception e) { throw new ToolsException($"Error creating IAM Role: {e.Message}", ToolsException.CommonErrorCode.IAMCreateRole, e); } if (managedPolicies != null && managedPolicies.Length > 0) { try { foreach (var managedPolicy in managedPolicies) { var request = new AttachRolePolicyRequest { RoleName = roleName, PolicyArn = managedPolicy }; iamClient.AttachRolePolicyAsync(request).Wait(); } } catch (Exception e) { throw new ToolsException($"Error assigning managed IAM Policy: {e.Message}", ToolsException.CommonErrorCode.IAMAttachRole, e); } } bool found = false; do { // There is no way check if the role has propagated yet so to // avoid error during deployment creation do a generous sleep. Console.WriteLine("Waiting for new IAM Role to propagate to AWS regions"); long start = DateTime.Now.Ticks; while (TimeSpan.FromTicks(DateTime.Now.Ticks - start).TotalSeconds < SLEEP_TIME_FOR_ROLE_PROPOGATION.TotalSeconds) { Thread.Sleep(TimeSpan.FromSeconds(1)); Console.Write("."); Console.Out.Flush(); } Console.WriteLine("\t Done"); try { var getResponse = iamClient.GetRoleAsync(new GetRoleRequest { RoleName = roleName }).Result; if (getResponse.Role != null) { found = true; } } catch (NoSuchEntityException) { } catch (Exception e) { throw new ToolsException("Error confirming new role was created: " + e.Message, ToolsException.CommonErrorCode.IAMGetRole, e); } } while (!found); return(roleArn); }
public string CreateDefaultRole(string roleName, string managedRole) { string roleArn; try { CreateRoleRequest request = new CreateRoleRequest { RoleName = roleName, AssumeRolePolicyDocument = Constants.LAMBDA_ASSUME_ROLE_POLICY }; var response = this.IAMClient.CreateRoleAsync(request).Result; roleArn = response.Role.Arn; } catch (Exception e) { throw new LambdaToolsException($"Error creating IAM Role: {e.Message}", LambdaToolsException.ErrorCode.IAMCreateRole, e); } if (!string.IsNullOrEmpty(managedRole)) { try { var request = new AttachRolePolicyRequest { RoleName = roleName, PolicyArn = managedRole }; this.IAMClient.AttachRolePolicyAsync(request).Wait(); } catch (Exception e) { throw new LambdaToolsException($"Error assigning managed IAM Policy: {e.Message}", LambdaToolsException.ErrorCode.IAMAttachRole, e); } } bool found = false; do { // There is no way check if the role has propagted yet so to // avoid error during function creation do a generous sleep. Console.WriteLine("Waiting for new IAM Role to propagate to AWS regions"); long start = DateTime.Now.Ticks; while (TimeSpan.FromTicks(DateTime.Now.Ticks - start).TotalSeconds < SLEEP_TIME_FOR_ROLE_PROPOGATION.TotalSeconds) { Thread.Sleep(TimeSpan.FromSeconds(1)); Console.Write("."); Console.Out.Flush(); } Console.WriteLine("\t Done"); try { var getResponse = this.IAMClient.GetRoleAsync(new GetRoleRequest { RoleName = roleName }).Result; if (getResponse.Role != null) { found = true; } } catch (NoSuchEntityException) { } catch (Exception e) { throw new LambdaToolsException("Error confirming new role was created: " + e.Message, LambdaToolsException.ErrorCode.IAMGetRole, e); } } while (!found); return(roleArn); }
//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); } }