public async Task <AuthFlowResponse> StartWithSrpAuthAsync(string userId, string password)
        {
            var             provider = new AmazonCognitoIdentityProviderClient(null, this.RegionEndpoint);
            CognitoUserPool userPool = new CognitoUserPool(
                UserPoolId,
                ClientId,
                provider,
                ClientSecret
                );
            CognitoUser user = new CognitoUser(
                userId,
                ClientId,
                userPool,
                provider,
                ClientSecret
                );

            try
            {
                AuthFlowResponse response = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest()
                {
                    Password = password
                }).ConfigureAwait(false);

                return(response);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Esempio n. 2
0
        public static async void AuthenticateWithSrpAsync(string email, string pass)
        {
            AmazonCognitoIdentityProviderConfig config = new AmazonCognitoIdentityProviderConfig();
            var provider = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), Amazon.RegionEndpoint.EUWest1);
            var userPool = new CognitoUserPool(POOL_NAME, AWS_CLIENT_ID, provider);

            var user = new CognitoUser(email, AWS_CLIENT_ID, userPool, provider);

            AuthFlowResponse authResponse;

            try
            {
                InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
                {
                    Password = pass
                };

                authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);
            }
            catch (Amazon.CognitoIdentityProvider.Model.NotAuthorizedException)
            {
                Console.WriteLine(email + " incorrect");
                return;
            }
            Console.WriteLine(authResponse);
        }
        public async void Test_GivenUserAndLockoutActivated_WhenCheckPasswordSignIn_ThenThrowsNotSupportedException()
        {
            var cognitoUser = new CognitoUser("userId", "clientId", cognitoPoolMock.Object, cognitoClientMock.Object);
            var ex          = await Assert.ThrowsAsync <NotSupportedException>(() => signinManager.CheckPasswordSignInAsync(cognitoUser, "password", lockoutOnFailure: true)).ConfigureAwait(false);

            Assert.Equal("Lockout is not enabled for the CognitoUserManager.", ex.Message);
        }
Esempio n. 4
0
        public async Task <IActionResult> SignUp(SignupModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            CognitoUser user = _pool.GetUser(model.Email);

            if (user.Status != null)
            {
                ModelState.AddModelError("UserExist", "User already exist!");
                return(View(model));
            }

            user.Attributes.Add(CognitoAttribute.Name.AttributeName, model.Email);

            IdentityResult createdUser = await _userManager.CreateAsync(user, model.Password);

            if (createdUser.Succeeded)
            {
                return(RedirectToAction("Confirm"));
            }

            return(View());
        }
Esempio n. 5
0
        public async Task <IActionResult> Signup(SignupModel model)
        {
            if (ModelState.IsValid)
            {
                CognitoUser user = _pool.GetUser(model.Email);
                if (user.Status != null)
                {
                    ModelState.AddModelError("UserExists", "User with this email already exist");
                    return(View(model));
                }
                user.Attributes.Add(CognitoAttributesConstants.Name, model.Email);
                user.Attributes.Add(CognitoAttributesConstants.BirthDate, model.Birthdate);
                var createdUser = await _userManager.CreateAsync(user, model.Password).ConfigureAwait(false);

                if (createdUser.Succeeded)
                {
                    RedirectToAction("Confirm", "Accounts");
                }
                else
                {
                    foreach (var error in createdUser.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }
            return(View());
        }
Esempio n. 6
0
        public virtual async Task <AuthEventEnum> VerifyNewPasswordAsync(string newPassword)
        {
            if (CurrentChallenge != AuthChallengeEnum.NewPassword)
            {
                return(AuthEventEnum.Alert_VerifyCalledButNoChallengeFound);
            }

            if (!CheckNewPasswordFormat(newPassword))
            {
                return(AuthEventEnum.Alert_PasswordFormatRequirementsFailed);
            }

            try
            {
                switch (CurrentAuthProcess)
                {
                case AuthProcessEnum.SigningUp:
                    authFlowResponse = await CognitoUser.RespondToNewPasswordRequiredAsync(
                        new RespondToNewPasswordRequiredRequest()
                    {
                        SessionID   = authFlowResponse.SessionID,
                        NewPassword = newPassword
                    }
                        ).ConfigureAwait(false);

                    this.newPassword = newPassword;
                    AuthChallengeList.Remove(AuthChallengeEnum.NewPassword);
                    return(await NextChallenge());

                case AuthProcessEnum.ResettingPassword:
                    this.newPassword = newPassword;
                    CognitoUser user = new CognitoUser(login, clientId, userPool, providerClient);
                    await user.ForgotPasswordAsync().ConfigureAwait(false);

                    AuthChallengeList.Remove(AuthChallengeEnum.NewPassword);
                    AuthChallengeList.Add(AuthChallengeEnum.Code);
                    return(await NextChallenge());

                case AuthProcessEnum.UpdatingPassword:
                    this.newPassword = newPassword;
                    AuthChallengeList.Remove(AuthChallengeEnum.NewPassword);
                    return(await NextChallenge());

                default:
                    return(AuthEventEnum.Alert_InternalProcessError);
                }
            }
            catch (InvalidPasswordException) { return(AuthEventEnum.Alert_PasswordFormatRequirementsFailed); }
            catch (TooManyRequestsException) { return(AuthEventEnum.Alert_TooManyAttempts); }
            catch (TooManyFailedAttemptsException) { return(AuthEventEnum.Alert_TooManyAttempts); }
            catch (NotAuthorizedException) { return(AuthEventEnum.Alert_NotAuthorized); }
            catch (UserNotFoundException) { return(AuthEventEnum.Alert_UserNotFound); }
            catch (UserNotConfirmedException) { return(AuthEventEnum.Alert_NotConfirmed); }
            catch (Exception e)
            {
                Debug.WriteLine($"VerifyPassword() threw an exception {e}");
                CognitoUser = null;
                return(AuthEventEnum.Alert_Unknown);
            }
        }
        private async Task LoadAsync(CognitoUser user)
        {
            var userName = await _userManager.GetUserNameAsync(user);

            var address     = user.Attributes[CognitoAttribute.Address.AttributeName];
            var birthDate   = user.Attributes[CognitoAttribute.BirthDate.AttributeName];
            var gender      = user.Attributes[CognitoAttribute.Gender.AttributeName];
            var nickName    = user.Attributes[CognitoAttribute.NickName.AttributeName];
            var phoneNumber = user.Attributes[CognitoAttribute.PhoneNumber.AttributeName];
            var familyName  = user.Attributes[CognitoAttribute.FamilyName.AttributeName];
            var givenName   = user.Attributes[CognitoAttribute.GivenName.AttributeName];


            Username = userName;
            Input    = new AccountModel()
            {
                Address     = address,
                BirthDate   = birthDate,
                GivenName   = givenName,
                Gender      = gender,
                NickName    = nickName,
                PhoneNumber = phoneNumber,
                FamilyName  = familyName
            };
        }
    private async Task <string> GetCredsAsync(Config config)
    {
        AmazonCognitoIdentityProviderClient provider =
            new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), RegionEndpoint.USEast2);
        CognitoUserPool        userPool    = new CognitoUserPool(config.userPoolId, config.userPoolClientId, provider);
        CognitoUser            user        = new CognitoUser(config.userId, config.userPoolClientId, userPool, provider);
        InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
        {
            Password = config.userPass
        };

        AuthFlowResponse context = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);

        // TODO: Custom exceptions and handlers
        if (context.AuthenticationResult != null)
        {
            Console.WriteLine("Authentication success");
        }
        else
        {
            Console.WriteLine("Failed PSG authentication!");
        }

        credentials = user.GetCognitoAWSCredentials(config.identityPoolId, RegionEndpoint.USEast2);
        if (credentials != null)
        {
            Console.WriteLine("Acquired user credentials");
        }
        else
        {
            Console.WriteLine("Failed to acquire user credentials!");
        }

        return(context.AuthenticationResult.AccessToken);
    }
        public async Task <string> GetCredsAsync(string userPassword)
        {
            AmazonCognitoIdentityProviderClient provider =
                new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), regionEndpoint);
            CognitoUserPool        userPool    = new CognitoUserPool(poolId, clientId, provider);
            CognitoUser            user        = new CognitoUser(userId, clientId, userPool, provider);
            InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
            {
                Password = userPassword
            };

            try
            {
                authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);

                accessToken  = authResponse.AuthenticationResult.AccessToken;
                refreshToken = authResponse.AuthenticationResult.RefreshToken;
                goodTill     = DateTime.UtcNow.AddSeconds(authResponse.AuthenticationResult.ExpiresIn);

                return(accessToken);
            }
            catch (Exception ex)
            {
                var x = ex.Message;
                throw;
            }
        }
Esempio n. 10
0
        public async Task <IActionResult> Signup(SignupModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    CognitoUser user = _pool.GetUser(model.Email);
                    if (user.Status != null)
                    {
                        ModelState.AddModelError("UserExists", "User with this email already exists");
                        return(View(model));
                    }

                    //user.Attributes.Add(CognitoAttributesConstants.Name, model.Email);
                    user.Attributes.Add(CognitoAttribute.Name.AttributeName, model.Email);
                    user.Attributes.Add(CognitoAttribute.Email.AttributeName, model.Email);
                    IdentityResult createdUser = await _userManager.CreateAsync(user, model.Password).ConfigureAwait(false);

                    if (createdUser.Succeeded)
                    {
                        return(RedirectToAction("Confirm"));
                    }
                    else
                    {
                        ModelState.AddModelError("createdUserError", string.Join <string>(" - ", createdUser.Errors.Select(error => error.Description).ToList()));
                    }
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("Somne kind of error", ex.Message);
            }
            return(View(model));
        }
Esempio n. 11
0
        public async Task <IActionResult> ConfirmPost(ConfirmModel model)
        {
            if (ModelState.IsValid)
            {
                CognitoUser user = await _userManager.FindByEmailAsync(model.Email).ConfigureAwait(false);

                if (user == null)
                {
                    ModelState.AddModelError("NotFound", "A user with the given email address was not found");
                    return(View(model));
                }

                IdentityResult result = await((CognitoUserManager <CognitoUser>)_userManager).ConfirmSignUpAsync(user, model.Code, true).ConfigureAwait(false);
                if (result.Succeeded)
                {
                    return(RedirectToAction("Index", "Home"));
                }
                else //ModelState.AddModelError("ConfirmPost", string.Join<string>(" - ", result.Errors.Select(error => error.Description).ToList()));
                {
                    foreach (var item in result.Errors)
                    {
                        ModelState.AddModelError(item.Code, item.Description);
                    }
                }

                return(View(model));
            }

            return(View(model));
        }
 public ForgotPasswordService(String userEmail)
 {
     email    = userEmail;
     provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), Amazon.RegionEndpoint.CACentral1);
     userPool = new CognitoUserPool(Settings.AWS_COGNITO_POOL_ID, Settings.AWS_CLIENT_ID, provider);
     user     = new CognitoUser(email, Settings.AWS_CLIENT_ID, userPool, provider);
 }
        public AuthenticationCreateUserTests() : base()
        {
            AdminCreateUserRequest createUserRequest = new AdminCreateUserRequest()
            {
                TemporaryPassword = "******",
                Username          = "******",
                UserAttributes    = new List <AttributeType>()
                {
                    new AttributeType()
                    {
                        Name = CognitoConstants.UserAttrEmail, Value = "*****@*****.**"
                    },
                },
                ValidationData = new List <AttributeType>()
                {
                    new AttributeType()
                    {
                        Name = CognitoConstants.UserAttrEmail, Value = "*****@*****.**"
                    }
                },
                UserPoolId = pool.PoolID
            };

            AdminCreateUserResponse createReponse = provider.AdminCreateUserAsync(createUserRequest).Result;

            user = new CognitoUser("User5", pool.ClientID, pool, provider);
        }
Esempio n. 14
0
        internal async Task <CognitoUser> ValidateUser(string username, string password)
        {
            AmazonCognitoIdentityProviderClient providerClient = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), REGION);
            CognitoUserPool userPool = new CognitoUserPool(USERPOOL_ID, CLIENT_ID, providerClient);
            CognitoUser     user     = new CognitoUser(username, CLIENT_ID, userPool, providerClient);

            InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
            {
                Password = password
            };

            AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(true);

            while (authResponse.AuthenticationResult == null)
            {
                if (authResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED)
                {
                    authResponse = await user.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest()
                    {
                        NewPassword = password,
                        SessionID   = authResponse.SessionID
                    }).ConfigureAwait(true);
                }
            }

            if (authResponse.AuthenticationResult != null)
            {
                return(user);
            }
            else
            {
                return(null);
            }
        }
    //Method that signs in Cognito user
    private async Task SignInUser()
    {
        string userName = UsernameField.text;
        string password = PasswordField.text;
        string email    = EmailField.text;

        AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), Region);

        CognitoUserPool userPool = new CognitoUserPool(PoolID, AppClientID, provider);

        CognitoUser user = new CognitoUser(userName, AppClientID, userPool, provider);

        InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
        {
            Password = password
        };

        AuthFlowResponse authResponse = null;

        try
        {
            authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);

            GetUserRequest getUserRequest = new GetUserRequest();
            getUserRequest.AccessToken = authResponse.AuthenticationResult.AccessToken;

            Debug.Log("User Access Token: " + getUserRequest.AccessToken);
            signInSuccessful = true;
        }
        catch (Exception e)
        {
            Debug.Log("EXCEPTION" + e);
            return;
        }
    }
        public async Task <string> RefreshCredsAsync()
        {
            AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient
                                                               (new AnonymousAWSCredentials(), regionEndpoint);
            CognitoUserPool userPool = new CognitoUserPool(poolId, clientId, provider);

            CognitoUser user = new CognitoUser(userId, clientId, userPool, provider);

            user.SessionTokens = new CognitoUserSession(null, null, authResponse.AuthenticationResult.RefreshToken, DateTime.Now, DateTime.Now.AddHours(1));

            InitiateRefreshTokenAuthRequest refreshRequest = new InitiateRefreshTokenAuthRequest()
            {
                AuthFlowType = AuthFlowType.REFRESH_TOKEN_AUTH
            };

            try
            {
                authResponse = await user.StartWithRefreshTokenAuthAsync(refreshRequest).ConfigureAwait(false);

                accessToken  = authResponse.AuthenticationResult.AccessToken;
                refreshToken = authResponse.AuthenticationResult.RefreshToken;
                goodTill     = DateTime.UtcNow.AddSeconds(authResponse.AuthenticationResult.ExpiresIn);
                return(accessToken);
            }
            catch (Exception ex)
            {
                var x = ex.Message;
                throw;
            }
        }
Esempio n. 17
0
        public virtual async Task <AuthEventEnum> RefreshUserDetailsAsync()
        {
            if (CognitoUser == null)
            {
                return(AuthEventEnum.Alert_NeedToBeSignedIn);
            }

            try
            {
                // Get the current user attributes from the server
                // and set UserEmail and IsUserEmailVerified
                GetUserResponse getUserResponse = await CognitoUser.GetUserDetailsAsync().ConfigureAwait(false);

                foreach (AttributeType item in getUserResponse.UserAttributes)
                {
                    if (item.Name.Equals("email"))
                    {
                        email = item.Value;
                    }

                    if (item.Name.Equals("email_verified"))
                    {
                        IsEmailVerified = item.Value.Equals("true");
                    }
                }
                return(AuthEventEnum.Alert_RefreshUserDetailsDone);
            }
            catch (Exception e)
            {
                Debug.WriteLine($"RefreshUserDetails threw an exception {e}");
                return(AuthEventEnum.Alert_Unknown);
            }
        }
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            CognitoUserManager _signInManager = CognitoUserManager.CognitoManager;
            CognitoUser        cognitoUser    = new CognitoUser()
            {
                UserName = model.Email
            };                                                                                  // "*****@*****.**" };
            var isvalid = await _signInManager.CheckPasswordAsync(cognitoUser, model.Password); // "crig7wee*uy7TANT");

            if (isvalid)
            {
                Session["IdToken"] = cognitoUser.IdToken;
                SignInAsync(cognitoUser, true);
                return(RedirectToLocal(returnUrl));
            }
            else
            {
                ModelState.AddModelError("", "Invalid login attempt.");
                return(View(model));
            }
        }
Esempio n. 19
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new CognitoUser()
                {
                    UserName = model.Email, Email = model.Email, Password = model.Password
                };
                var result = await UserManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    // Uncomment this if you just want to let the user login. Commented out, means they'll need to login and confirm the code in their email.
                    //await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                    // TODO: Redirect them to a page saying sign-up succeeded and they need to get a code from their email.

                    return(RedirectToAction("Registered"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Esempio n. 20
0
        public async Task <string> GetS3BucketsAsync(CognitoUser user)
        {
            CognitoAWSCredentials credentials =
                user.GetCognitoAWSCredentials(FED_POOL_ID, new AppConfigAWSRegion().Region);
            StringBuilder bucketlist = new StringBuilder();

            bucketlist.Append("================Cognito Credentails==================\n");
            bucketlist.Append("Access Key - " + credentials.GetCredentials().AccessKey);
            bucketlist.Append("\nSecret - " + credentials.GetCredentials().SecretKey);
            bucketlist.Append("\nSession Token - " + credentials.GetCredentials().Token);

            bucketlist.Append("\n================User Buckets==================\n");

            using (var client = new AmazonS3Client(credentials))
            {
                ListBucketsResponse response =
                    await client.ListBucketsAsync(new ListBucketsRequest()).ConfigureAwait(false);

                foreach (S3Bucket bucket in response.Buckets)
                {
                    bucketlist.Append(bucket.BucketName);

                    bucketlist.Append("\n");
                }
            }
            Console.WriteLine(bucketlist.ToString());
            return(bucketlist.ToString());
        }
Esempio n. 21
0
        public async Task <string> SignIn(string username, string password)
        {
            var provider =
                new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials( ));

            var userPool    = new CognitoUserPool(UserPool, ClientId, provider);
            var user        = new CognitoUser(username, ClientId, userPool, provider);
            var authRequest = new InitiateSrpAuthRequest( )
            {
                Password = password
            };

            var authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);

            // if the user has mfa enabled, this response will have a challenge attribute set accordingly. We would then need to branch based on the MFA type. The return type should probably be some type of object that has some field that says "tokenPresent"
            string retVal;

            if (string.IsNullOrWhiteSpace(authResponse.ChallengeName))
            {
                retVal = authResponse.AuthenticationResult.AccessToken;
            }
            else
            {
                retVal = authResponse.ChallengeName;
            }

            return(retVal);
        }
Esempio n. 22
0
        protected async Task <string> GetAccessToken(AuthenticationModel model)
        {
            string responseToken = String.Empty;

            try
            {
                AmazonCognitoIdentityProviderClient IdentityClientProvider = new AmazonCognitoIdentityProviderClient(
                    new AnonymousAWSCredentials(), RegionEndpoint.GetBySystemName(model.RegionEndpoint));
                CognitoUserPool UserPool = new CognitoUserPool(model.PoolId, model.ClientId, IdentityClientProvider);
                CognitoUser     user     = new CognitoUser(model.Username, model.ClientId, UserPool, IdentityClientProvider);
                var             response = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest { Password = model.Password }).ConfigureAwait(false);

                if (response.AuthenticationResult != null)
                {
                    responseToken = response.AuthenticationResult.AccessToken;
                    ExpiresIn     = response.AuthenticationResult.ExpiresIn - 300;
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }

            return(responseToken);
        }
Esempio n. 23
0
    internal async Task <CognitoUser> ValidateUser(string username, string password)
    {
        AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials());

        CognitoUserPool userPool = new CognitoUserPool(this.POOL_ID, this.CLIENTAPP_ID, provider);

        CognitoUser            user        = new CognitoUser(username, this.CLIENTAPP_ID, userPool, provider);
        InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
        {
            Password = password
        };
        var adsadas = new InitiateAuthRequest();



        AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);

        if (authResponse.AuthenticationResult != null)
        {
            return(user);
        }
        else
        {
            return(null);
        }
    }
Esempio n. 24
0
        public async void Test_GivenAUserWithStatus_WhenIsPasswordResetRequired_ThenResponseIsValid(string status, bool isPasswordResetRequired)
        {
            var user   = new CognitoUser("userID", "clientID", _cognitoPoolMock.Object, _cognitoClientMock.Object, null, status, null, null);
            var output = await _store.IsPasswordResetRequiredAsync(user, CancellationToken.None).ConfigureAwait(false);

            Assert.Equal(isPasswordResetRequired, output);
        }
Esempio n. 25
0
        public AuthenticationConfirmUserTests() : base()
        {
            SignUpRequest signUpRequest = new SignUpRequest()
            {
                ClientId       = pool.ClientID,
                Password       = "******",
                Username       = "******",
                UserAttributes = new List <AttributeType>()
                {
                    new AttributeType()
                    {
                        Name = CognitoConstants.UserAttrEmail, Value = "*****@*****.**"
                    },
                },
                ValidationData = new List <AttributeType>()
                {
                    new AttributeType()
                    {
                        Name = CognitoConstants.UserAttrEmail, Value = "*****@*****.**"
                    }
                }
            };

            SignUpResponse signUpResponse = provider.SignUpAsync(signUpRequest).Result;

            AdminConfirmSignUpRequest confirmRequest = new AdminConfirmSignUpRequest()
            {
                Username   = "******",
                UserPoolId = pool.PoolID
            };
            AdminConfirmSignUpResponse confirmResponse = provider.AdminConfirmSignUpAsync(confirmRequest).Result;

            user = new CognitoUser("User5", pool.ClientID, pool, provider);
        }
Esempio n. 26
0
        /// <summary>
        ///     Get refreshed token from Cognito using for the current user
        /// </summary>
        /// <param name="userRequest"></param>
        /// <returns>AuthFlowResponse</returns>
        public AuthFlowResponse ProcessRefreshToken(UserRequest userRequest)
        {
            AuthFlowResponse authResponse;

            try
            {
                AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), RegionEndpoint.USWest2);
                CognitoUserPool userPool = new CognitoUserPool("XXX_XXX", userRequest.CognitoClientId, provider);
                CognitoUser     user     = new CognitoUser(userRequest.UserName, userRequest.CognitoClientId, userPool, provider, userRequest.ClientSecret)
                {
                    SessionTokens = new CognitoUserSession(null, null, userRequest.Payload.RefreshToken, DateTime.Now, DateTime.Now.AddDays(10))
                };

                InitiateRefreshTokenAuthRequest authRequest = new InitiateRefreshTokenAuthRequest()
                {
                    AuthFlowType = AuthFlowType.REFRESH_TOKEN
                };
                authResponse = user.StartWithRefreshTokenAuthAsync(authRequest).Result;
                return(authResponse);
            }
            catch (Exception processRefreshTokenException)
            {
                LambdaLogger.Log(processRefreshTokenException.ToString());
                return(null);
            }
        }
Esempio n. 27
0
        //Login
        private async Task <AuthFlowResponse> AuthenticateWithSrpAsync(string userName, string password)
        {
            AuthFlowResponse authResponse = null;
            var provider = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), FallbackRegionFactory.GetRegionEndpoint());
            var userPool = new CognitoUserPool(ConfigData.UserPoolId, ConfigData.ClientId, provider);

            this.User = new CognitoUser(userName, ConfigData.ClientId, userPool, provider);

            try
            {
                authResponse = await this.User.StartWithSrpAuthAsync(new InitiateSrpAuthRequest()
                {
                    Password = password
                }).ConfigureAwait(false);

                if (authResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED)
                {
                    authResponse = await this.User.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest()
                    {
                        SessionID   = authResponse.SessionID,
                        NewPassword = ""
                    });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(authResponse);
        }
Esempio n. 28
0
        public async Task <String> AuthorizeUser()
        {
            try
            {
                AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials());
                CognitoUserPool userPool = new CognitoUserPool(ConfigurationManager.AppSettings["USERPOOL_ID"],
                                                               ConfigurationManager.AppSettings["CLIENT_ID"], provider);

                CognitoUser cognitoUser = new CognitoUser(inputEmail.Value, ConfigurationManager.AppSettings["CLIENT_ID"], userPool, provider);

                InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
                {
                    Password = inputPassword.Value
                };

                AuthFlowResponse authFlowResponse = await cognitoUser.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);

                if (authFlowResponse.AuthenticationResult != null)
                {
                    return(authFlowResponse.AuthenticationResult.AccessToken);
                }
            }
            catch (Exception ex)
            {
                var message = new JavaScriptSerializer().Serialize(ex.Message.ToString());
                var script  = string.Format("alert({0});", message);
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ex", "alert('" + ex.Message + "');", true);
            }
            return(null);
        }
Esempio n. 29
0
        public static async Task <AuthenticationResultType> RefreshTokenDaihuyen(AuthenticationResultType request)
        {
            try
            {
                var    accesstoken = new JwtSecurityToken(request.AccessToken);
                var    idtoken     = new JwtSecurityToken(request.IdToken);
                string userName    = idtoken.Claims.FirstOrDefault(m => m.Type.Equals("cognito:username"))?.Value;
                // get new token
                AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(_region);
                CognitoUserPool userPool = new CognitoUserPool(UserPoolId, _clientId, provider);
                CognitoUser     user     = new CognitoUser(userName, _clientId, userPool, provider, _clientSecret)
                {
                    SessionTokens = new CognitoUserSession(request.IdToken, request.AccessToken, request.RefreshToken, DateTime.Now, DateTime.Now.AddHours(1))
                };
                InitiateRefreshTokenAuthRequest refreshRequest = new InitiateRefreshTokenAuthRequest()
                {
                    AuthFlowType = AuthFlowType.REFRESH_TOKEN_AUTH
                };

                AuthFlowResponse authResponse = await user.StartWithRefreshTokenAuthAsync(refreshRequest);

                return(authResponse.AuthenticationResult);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Esempio n. 30
0
        public async Task <IActionResult> ResetPasswordPost(ResetPasswordModel resetPasswordModel)
        {
            if (ModelState.IsValid)
            {
                CognitoUser user = await _userManager.FindByEmailAsync(resetPasswordModel.Email).ConfigureAwait(false);

                if (user == null)
                {
                    ModelState.AddModelError("NotFound", "A user with the given email address was not found");
                    return(View(resetPasswordModel));
                }

                var result = await _userManager.ResetPasswordAsync(user, resetPasswordModel.Code, resetPasswordModel.Password).ConfigureAwait(false);

                if (result != null)
                {
                    if (result.Succeeded)
                    {
                        return(RedirectToAction("Login", "Accounts"));
                    }
                    else
                    {
                        ModelState.AddModelError("ResetError", "Information Specified is incorrect");
                    }
                }
            }
            return(View("Login", resetPasswordModel));
        }