private static async Task AttachAdminPolicyToAdminGroup(IAmazonIdentityManagementService client, CancellationToken token) { const string policyDocument = @" { ""Version"": ""2012-10-17"", ""Statement"": [ { ""Effect"": ""Allow"", ""Action"": ""*"", ""Resource"": ""*"" } ] }"; CreatePolicyRequest request = new CreatePolicyRequest() { Description = "Policy for Administrators", PolicyDocument = policyDocument, PolicyName = "AllAccess" }; CreatePolicyResponse response = await client.CreatePolicyAsync(request, token); //throw new NotImplementedException(); }
private static void UnmarshallResult(XmlUnmarshallerContext context, CreatePolicyResponse response) { int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) { targetDepth += 2; } while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("Policy", targetDepth)) { var unmarshaller = ManagedPolicyUnmarshaller.Instance; response.Policy = unmarshaller.Unmarshall(context); continue; } } } return; }
public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { CreatePolicyResponse response = new CreatePolicyResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.IsStartElement) { if (context.TestExpression("CreatePolicyResult", 2)) { UnmarshallResult(context, response); continue; } if (context.TestExpression("ResponseMetadata", 2)) { response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context); } } } return(response); }
public CreatePolicyResponse CreatePolicy(CreatePolicyRequest inputParameters, Broker broker) { Client client = Mapper.Map <Client>(inputParameters.RegisteredKeeper); if (inputParameters.RegisteredKeeper.IsLegalPerson) { client.LegalPerson = Mapper.Map <LegalPerson>(inputParameters.RegisteredKeeper); client.LegalPerson.Address = Mapper.Map <AddressDto>(inputParameters.RegisteredKeeper); client.LegalPerson.MailingAddress = Mapper.Map <MailingAddressDto>(inputParameters.RegisteredKeeper); } else { client.Person = Mapper.Map <Person>(inputParameters.RegisteredKeeper); client.Person.Address = Mapper.Map <AddressDto>(inputParameters.RegisteredKeeper); client.Person.MailingAddress = Mapper.Map <MailingAddressDto>(inputParameters.RegisteredKeeper); } Vehicle vehicle = Mapper.Map <Vehicle>(inputParameters.Vehicle); Policy savedPolicy = DataAccess.SavePolicy(inputParameters.QuoteGuid, client, vehicle, broker); CreatePolicyResponse result = new CreatePolicyResponse() { PolicyNumber = savedPolicy.PolicyNumber }; return(result); }
public async Task <string> CreateIamPolicy(IAmazonIdentityManagementService iamClient, string policyName) { try { Console.WriteLine("Creating IAM Policy"); CreatePolicyResponse response = await iamClient.CreatePolicyAsync(new CreatePolicyRequest() { PolicyName = policyName, PolicyDocument = AwsResourceConstant.PolicyDocument, Description = "Created via AWS Timestream sample" }); Console.WriteLine($"The ARN of the policy is : {response.Policy.Arn}"); // Wait for the policy to be available Thread.Sleep(2000); return(response.Policy.Arn); } catch (EntityAlreadyExistsException) { string accountId = new AmazonSecurityTokenServiceClient().GetCallerIdentityAsync(new GetCallerIdentityRequest()).Result.Account; return(String.Format("arn:aws:iam::{0}:policy/{1}", accountId, policyName)); } catch (Exception e) { Console.WriteLine($"IAM policy creation failed: {e}"); throw; } }
public static CreatePolicyResponse Unmarshall(UnmarshallerContext context) { CreatePolicyResponse createPolicyResponse = new CreatePolicyResponse(); createPolicyResponse.HttpResponse = context.HttpResponse; createPolicyResponse.RequestId = context.StringValue("CreatePolicy.RequestId"); CreatePolicyResponse.CreatePolicy_Policy policy = new CreatePolicyResponse.CreatePolicy_Policy(); policy.PolicyName = context.StringValue("CreatePolicy.Policy.PolicyName"); policy.PolicyType = context.StringValue("CreatePolicy.Policy.PolicyType"); policy.Description = context.StringValue("CreatePolicy.Policy.Description"); policy.DefaultVersion = context.StringValue("CreatePolicy.Policy.DefaultVersion"); policy.CreateDate = context.StringValue("CreatePolicy.Policy.CreateDate"); createPolicyResponse.Policy = policy; return(createPolicyResponse); }
/// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { CreatePolicyResponse response = new CreatePolicyResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("Policy", targetDepth)) { var unmarshaller = PolicyUnmarshaller.Instance; response.Policy = unmarshaller.Unmarshall(context); continue; } } return(response); }
/// <summary> /// Creates the policy. /// </summary> /// <param name="inputParameters">The input parameters.</param> /// <returns></returns> /// <exception cref="FaultException{ExceptionFaultContract}">new ExceptionFaultContract(CreatePolicy, not implemented, )</exception> /// <exception cref="ExceptionFaultContract">CreatePolicy;not implemented</exception> public CreatePolicyResponse CreatePolicy(CreatePolicyRequest inputParameters) { try { //to do AUTH IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest; WebHeaderCollection headers = request.Headers; //var url = HttpContext.Current.Request.Url.AbsoluteUri; Broker broker = new Broker() { ID = 1, Name = "Test" }; CreatePolicyResponse result = Wservice.CreatePolicy(inputParameters, broker); return(result); } catch (Exception ex) { //throw new FaultException("CreatePolicy error description"); throw new FaultException <ExceptionFaultContract>(new ExceptionFaultContract("CreatePolicy", "Error during creating the policy", ex.Message), ""); } }
/// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { CreatePolicyResponse response = new CreatePolicyResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("policyArn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.PolicyArn = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("policyDocument", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.PolicyDocument = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("policyName", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.PolicyName = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("policyVersionId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.PolicyVersionId = unmarshaller.Unmarshall(context); continue; } } return(response); }
//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); }