public bool Register(string username, string password, string email) { new AnonymousAWSCredentials(); using AmazonCognitoIdentityProviderClient cognito = GetCognitoIdentityProvider(); var response = false; try { var controller = new CognitoSignUpController(cognito); response = controller.SignUpAsync(username, password, email).GetAwaiter().GetResult(); if (response) { var signUpConfirmRequest = new AdminConfirmSignUpRequest(); signUpConfirmRequest.Username = username; signUpConfirmRequest.UserPoolId = CognitoSettings.Values.UserPoolId; var ret = cognito.AdminConfirmSignUpAsync(signUpConfirmRequest, CancellationToken.None).GetAwaiter() .GetResult(); } } catch (Exception ex) { Console.WriteLine(ex.Message); throw; } return(response); }
public override async Task <string> Handle(CognitoSignUpCommand request, CancellationToken cancellationToken) { using (var provider = new AmazonCognitoIdentityProviderClient(AwsId, AwsKey, RegionEndpoint.USEast1)) { var response = await provider.SignUpAsync(new SignUpRequest { Password = request.Password, ClientId = UserGroupClientId, Username = request.Email, UserAttributes = new List <AttributeType> { new AttributeType { Name = "email", Value = request.Email }, new AttributeType { Name = "preferred_username", Value = request.Username } } }, cancellationToken); if (response.HttpStatusCode != HttpStatusCode.OK) { throw new CognitoException("Failed to register user with email " + request.Email + "."); } await provider.AdminConfirmSignUpAsync(new AdminConfirmSignUpRequest { Username = response.UserSub, UserPoolId = UserPoolId }, cancellationToken); await provider.AdminUpdateUserAttributesAsync(new AdminUpdateUserAttributesRequest { UserAttributes = new List <AttributeType> { new AttributeType { Name = "email_verified", Value = "true" } }, Username = response.UserSub, UserPoolId = UserPoolId }, cancellationToken); return(response.UserSub); } }
/// <summary> /// Confirms user registration as an admin without using a confirmation code. Works on any user. /// </summary> /// <param name="username"></param> /// <returns></returns> public async Task <bool> AdminConfirmSignUpAsync(Real.AdminConfirmSignUpRequest request) { AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(RegionEndpoint.GetBySystemName(REGION)); AdminConfirmSignUpRequest userRequest = new AdminConfirmSignUpRequest(); userRequest.Username = request.Username; userRequest.UserPoolId = POOL_ID; try { AdminConfirmSignUpResponse response = await provider.AdminConfirmSignUpAsync(userRequest); } catch (Exception e) { Console.WriteLine(e); return(false); } return(true); }
public async Task <ActionResult <string> > Register(User user) { var cognito = new AmazonCognitoIdentityProviderClient(_region); var request = new SignUpRequest { ClientId = _clientId, Password = user.Password, Username = user.Username }; var emailAttribute = new AttributeType { Name = "email", Value = user.Email }; request.UserAttributes.Add(emailAttribute); var response = await cognito.SignUpAsync(request); var groupResponse = await cognito.AdminAddUserToGroupAsync(new AdminAddUserToGroupRequest { GroupName = "Admin", Username = user.Username, UserPoolId = "us-west-2_TQaxeubl4" }); var confResponse = await cognito.AdminConfirmSignUpAsync(new AdminConfirmSignUpRequest { Username = user.Username, UserPoolId = "us-west-2_TQaxeubl4" }); return(Ok()); }
/// <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); }
public async void SignUpNewUser(string email, string password, string familyName, string firstName, string phoneNumber, string deviceId) { AnonymousAWSCredentials credentials = new AnonymousAWSCredentials(); AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(credentials, Amazon.RegionEndpoint.USEast2); CognitoUserPool pool = new CognitoUserPool(ConfigurationManager.AppSettings["USERPOOL_ID"], ConfigurationManager.AppSettings["CLIENT_ID"], provider, ""); // Based on latest user pool API // https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPool.html // https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_VerificationMessageTemplateType.html // https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cfn-customresource.html Dictionary <string, string> userAttributes = new Dictionary <string, string>(StringComparer.Ordinal) { { "email", email }, { "family_name", familyName }, { "given_name", firstName }, }; Dictionary <string, string> validationData = new Dictionary <string, string>(StringComparer.Ordinal) { { "email", email } }; await pool.SignUpAsync(email, password, userAttributes, validationData).ConfigureAwait(false); //Get the UsersVerificationCode programatically. Task <AdminConfirmSignUpResponse> myresponse = provider.AdminConfirmSignUpAsync(new AdminConfirmSignUpRequest { UserPoolId = ConfigurationManager.AppSettings["USERPOOL_ID"], Username = email }); AdminUpdateUserAttributesRequest i = new AdminUpdateUserAttributesRequest(); i.UserAttributes.Add(new AttributeType { Name = "email_verified", Value = "true" }); i.UserPoolId = ConfigurationManager.AppSettings["USERPOOL_ID"]; i.Username = email; AdminUpdateUserAttributesResponse T = await provider.AdminUpdateUserAttributesAsync(i); Debug.Print(T.ToString()); // client.adminUpdateUserAttributes({ // UserAttributes: // [{ // Name: 'phone_number_verified', // Value: 'true' // }, { // Name: 'email_verified', // Value: 'true' // } // // other user attributes like phone_number or email themselves, etc //], //UserPoolId: 'COGNITO_USER_POOL_ID_HERE', //Username: '******' //myresponse.res. // Debug.Print(myresponse.Result.ToString()); }