コード例 #1
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);
            }
        }
コード例 #2
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);
            }
        }
コード例 #3
0
        /// <summary>
        ///    Change password by current user , with  username  and password
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public bool ChangePassword(ApiChangePasswordRequest request)
        {
            using var userProvider = GetCognitoIdentityProvider();
            CognitoUser user = GetUser(request.UserName, userProvider);

            InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
            {
                Password = request.PreviewPassword
            };

            var authResponse = user.StartWithSrpAuthAsync(authRequest).GetAwaiter().GetResult();

            if (authResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED)
            {
                var result2 = user.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest()
                {
                    SessionID   = authResponse.SessionID,
                    NewPassword = request.NewPassword
                }).ConfigureAwait(false).GetAwaiter().GetResult();
            }

            var task = user.ChangePasswordAsync(request.PreviewPassword, request.NewPassword).GetAwaiter();

            task.GetResult();

            return(true);
        }
コード例 #4
0
        public static CognitoUser ValidateUser(string userName, string password, string newPassword = Constants.NewPassword)
        {
            var provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials());
            var userPool = new CognitoUserPool(PoolId, ClientAppId, provider, ClientSecret);
            var user     = new CognitoUser(userName, ClientAppId, userPool, provider, ClientSecret);

            var authRequest = new InitiateSrpAuthRequest
            {
                Password = password
            };

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

            while (authResponse.AuthenticationResult == null)
            {
                if (authResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED)
                {
                    //string newPassword = "******";

                    authResponse = user.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest
                    {
                        SessionID   = authResponse.SessionID,
                        NewPassword = newPassword
                    }).ConfigureAwait(false).GetAwaiter().GetResult();
                }
                else
                {
                    throw new AuthenticationException($"Unrecognized authentication challenge {authResponse.ChallengeName}.");
                }
            }
            return(authResponse.AuthenticationResult != null ? user : null);
        }
コード例 #5
0
        public async Task <LoginResult> LoginAsync(LoginModel loginModel)
        {
            var result = new LoginResult();

            try
            {
                var user        = new CognitoUser(loginModel.UserID, ClientID, _userPool, _provider);
                var authRequest = new InitiateSrpAuthRequest()
                {
                    Password = loginModel.Password
                };

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

                var token = string.Empty;
                // Force set the current password if the new password is required.
                if (authResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED)
                {
                    authResponse = await user.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest()
                    {
                        SessionID   = authResponse.SessionID,
                        NewPassword = loginModel.Password
                    });

                    // using id token for api auth
                    token = authResponse.AuthenticationResult.IdToken;
                }
                else if (authResponse.AuthenticationResult.IdToken != null)
                {
                    token = authResponse.AuthenticationResult.IdToken;
                }
                else
                {
                    result.IsSuccessful = false;
                    result.Error        = new Exception("Unexpected error");
                    return(result);
                }

                result.IsSuccessful = true;
                result.IDToken      = token;
                await((SPAAuthticateProvider)_authenticationStateProvider).MarkUserAsAuthenticated(loginModel.UserID, result.IDToken);

                return(result);
            }
            catch (NotAuthorizedException e)
            {
                Console.WriteLine("NotAuthorizedException:" + DateTime.Now.ToString());
                result.IsSuccessful = false;
                result.Error        = e;
                return(result);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception:" + DateTime.Now.ToString() + e.ToString());
                result.IsSuccessful = false;
                result.Error        = e;
                return(result);
            }
        }
コード例 #6
0
        public LoginUserQueryParam ChangePassword(ResetPasswordQueryParams changePasswordParams)
        {
            var userPool    = new CognitoUserPool(_connectionInfo.UserPoolId, _connectionInfo.ClientId, _provider);
            var cognitoUser = new CognitoUser(changePasswordParams.Email, _connectionInfo.ClientId, userPool, _provider);

            try
            {
                AuthFlowResponse authResponse = null;

                authResponse = cognitoUser.StartWithSrpAuthAsync(new InitiateSrpAuthRequest()
                {
                    Password = changePasswordParams.Password
                }).Result;

                while (authResponse.AuthenticationResult == null)
                {
                    if (authResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED)
                    {
                        authResponse =
                            cognitoUser.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest()
                        {
                            SessionID   = authResponse.SessionID,
                            NewPassword = changePasswordParams.NewPassword,
                        }).Result;
                    }
                }
                if (authResponse.AuthenticationResult != null)
                {
                    LoggingHandler.LogInfo("User successfully authenticated.");
                    var loginParams = new LoginUserQueryParam();
                    loginParams.Email    = changePasswordParams.Email;
                    loginParams.Password = changePasswordParams.NewPassword;
                    return(loginParams);
                }
                else
                {
                    LoggingHandler.LogError("Error in authentication process.");
                }
            }
            catch (AggregateException e)
            {
                e.Handle((x) =>
                {
                    if (x is NotAuthorizedException)  // This we know how to handle.
                    {
                        LoggingHandler.LogInfo("Authentication Gateway:  Invalid credentials provided.");
                        return(true);
                    }
                    if (x is UserNotFoundException)  // This we know how to handle.
                    {
                        LoggingHandler.LogInfo("Authentication Gateway:  User not found.");
                        return(true);
                    }
                    return(false); // Let anything else stop the application.
                });
            }
            return(null);
        }
コード例 #7
0
        public static async void GetCredsChallengesAsync()
        {
            AmazonCognitoIdentityProviderClient provider =
                new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials());
            CognitoUserPool        userPool    = new CognitoUserPool("poolID", "clientID", provider);
            CognitoUser            user        = new CognitoUser("username", "clientID", userPool, provider);
            InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
            {
                Password = "******"
            };

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

            while (authResponse.AuthenticationResult == null)
            {
                if (authResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED)
                {
                    Console.WriteLine("Enter your desired new password:"******"Enter the MFA Code sent to your device:");
                    string mfaCode = Console.ReadLine();

                    AuthFlowResponse mfaResponse = await user.RespondToSmsMfaAuthAsync(new RespondToSmsMfaRequest()
                    {
                        SessionID = authResponse.SessionID,
                        MfaCode   = mfaCode
                    }).ConfigureAwait(false);

                    accessToken = authResponse.AuthenticationResult.AccessToken;
                }
                else
                {
                    Console.WriteLine("Unrecognized authentication challenge.");
                    accessToken = "";
                    break;
                }
            }

            if (authResponse.AuthenticationResult != null)
            {
                Console.WriteLine("User successfully authenticated.");
            }
            else
            {
                Console.WriteLine("Error in authentication process.");
            }
        }
コード例 #8
0
        private AuthenticationResultType Authentication(string userName, string password)
        {
            AmazonCognitoIdentityProviderClient userProvider = GetCognitoIdentityProvider();
            {
                AuthenticationResultType status = null;

                _user = GetUser(userName, userProvider);

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

                try
                {
                    var authResponse = _user.StartWithSrpAuthAsync(authRequest).GetAwaiter().GetResult();

                    if (authResponse != null)
                    {
                        status = authResponse.AuthenticationResult;


                        if (authResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED)
                        {
                            var result2 = _user.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest()
                            {
                                SessionID   = authResponse.SessionID,
                                NewPassword = password
                            }).ConfigureAwait(false).GetAwaiter().GetResult();

                            status = result2.AuthenticationResult;
                        }
                    }
                }
                catch (Exception ex)
                {
                    status = null;
                }

                if (status == null)
                {
                    _user = null;
                }
                else
                {
                    token = status.IdToken;
                }

                return(status);
            }
        }
コード例 #9
0
        public async Task <CognitoContext> UpdatePassword(string userName, string newPassword, string sessionId)
        {
            try
            {
                CognitoUser user = new CognitoUser(userName, Keys.AWS_UsersPool_ClientID, UserPool, awsProvider);
                var         res  = await user.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest
                {
                    SessionID   = sessionId,
                    NewPassword = newPassword
                });

                return(new CognitoContext(CognitoResult.Ok));
            }
            catch (Exception e)
            {
                Console.WriteLine($"UpdatePassword() threw an exception {e}");
            }
            return(new CognitoContext(CognitoResult.Unknown));
        }
コード例 #10
0
        public async Task <CognitoContext> UpdatePassword(string userName, string newPassword, string sessionId)
        {
            try
            {
                CognitoUserPool userPool = new CognitoUserPool(Constants.COGNITO_USER_POOL_ID, Constants.COGNITO_CLIENT_ID, CognitoIdentityProviderClient);
                CognitoUser     user     = new CognitoUser(userName, Constants.COGNITO_CLIENT_ID, CognitoUserPool, CognitoIdentityProviderClient);

                var res = await user.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest
                {
                    SessionID   = sessionId,
                    NewPassword = newPassword
                });

                return(new CognitoContext(CognitoResult.Ok));
            }
            catch (Exception e)
            {
                Console.WriteLine($"UpdatePassword() threw an exception {e}");
            }
            return(new CognitoContext(CognitoResult.Unknown));
        }
コード例 #11
0
        /// <summary>
        /// Try to login to aws using cognito
        /// If user  has not changed the password then he will be redirected to password change
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="newPassword"></param>
        /// <returns></returns>
        private async Task <string> LoginUserAsync(string username, string password, string newPassword = null)
        {
            var a = FallbackRegionFactory.GetRegionEndpoint();

            CognitoInit awsInit = new CognitoInit();

            CognitoUserPool        userPool    = new CognitoUserPool(awsInit.PoolId, awsInit.ClientId, awsInit.Client);
            CognitoUser            user        = new CognitoUser(username, awsInit.ClientId, userPool, awsInit.Client);
            InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
            {
                Password = password
            };

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

                if (authResponse.ChallengeName != null && authResponse.ChallengeName.ToString().Equals(ChallengeNameType.NEW_PASSWORD_REQUIRED, StringComparison.OrdinalIgnoreCase))
                {
                    //This case is when a user is created by admin form portal
                    if (String.IsNullOrWhiteSpace(newPassword))
                    {
                        authResponse = await user.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest { SessionID = authResponse.SessionID, NewPassword = "******" });
                    }
                    return(ChallengeNameType.NEW_PASSWORD_REQUIRED);
                }
                if (String.IsNullOrWhiteSpace(authResponse.ChallengeName))
                {
                    // GetCredentials(authResponse.AuthenticationResult);
                    return(authResponse.AuthenticationResult.IdToken);
                }
            }
            catch (Exception e)
            {
                return(e.Message);
            }
            return("Login didn't succeded!");
        }
コード例 #12
0
ファイル: ApiCognito.cs プロジェクト: RidhwanDev/CognitoForms
        public async Task <CognitoContext> UpdatePassword(string userName, string newPassword, string sessionId)
        {
            try
            {
                var provider = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), RegionEndpoint.USWest2);

                CognitoUserPool userPool = new CognitoUserPool(PoolId, ClientId, provider);
                CognitoUser     user     = new CognitoUser(userName, ClientId, userPool, provider);

                var res = await user.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest
                {
                    SessionID   = sessionId,
                    NewPassword = newPassword
                });

                return(new CognitoContext(CognitoResult.Ok));
            }
            catch (Exception e)
            {
                Console.WriteLine($"SignIn() threw an exception {e}");
            }
            return(new CognitoContext(CognitoResult.Unknown));
        }
コード例 #13
0
        public AuthenticationResultType GetAuthentication(string userName, string password)
        {
            using AmazonCognitoIdentityProviderClient userProvider = GetCognitoIdentityProvider();
            if (String.IsNullOrEmpty(userName))
            {
                throw new ArgumentNullException("userName");
            }

            if (String.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException("password");
            }

            AuthenticationResultType status = null;

            _user = GetUser(userName, userProvider);

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

            try
            {
                var authResponse = _user.StartWithSrpAuthAsync(authRequest).GetAwaiter().GetResult();

                if (authResponse != null)
                {
                    status = authResponse.AuthenticationResult;


                    if (authResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED)
                    {
                        var result2 = _user.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest()
                        {
                            SessionID   = authResponse.SessionID,
                            NewPassword = password
                        }).ConfigureAwait(false).GetAwaiter().GetResult();

                        status = result2.AuthenticationResult;
                    }


                    String idToken = status.IdToken, accessToken = status.AccessToken, refreshToken = status.RefreshToken;


                    var user2 = GetUser(userName, userProvider);

                    user2.SessionTokens = new CognitoUserSession(idToken, accessToken, refreshToken, DateTime.Now,
                                                                 DateTime.Now.AddDays(10));



                    var result = user2.StartWithRefreshTokenAuthAsync(
                        new InitiateRefreshTokenAuthRequest()
                    {
                        AuthFlowType = AuthFlowType.REFRESH_TOKEN
                    }
                        ).ConfigureAwait(false).GetAwaiter().GetResult();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                status = null;
            }

            if (status == null)
            {
                _user = null;
            }
            else
            {
                if (status != null)
                {
                    token = status.IdToken;
                }
            }

            return(status);
        }
コード例 #14
0
        private async void button1_Click(object sender, EventArgs e)
        {
            AmazonCognitoIdentityProviderClient provider =
                new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), Amazon.RegionEndpoint.USEast2);
            String AccessToken = "";

            CognitoUserPool        userPool    = new CognitoUserPool("us-east-2_5823vgrxD", "7dpaqpkf9b5pjp9gg94k3gndld", provider);
            CognitoUser            user        = new CognitoUser("AppUser2", "7dpaqpkf9b5pjp9gg94k3gndld", userPool, provider);
            InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
            {
                Password = "******"
            };

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

            if (authResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED)
            {
                String NewPassword;
                frmEnterNewPassword f = new frmEnterNewPassword();
                if (f.ShowDialog() == DialogResult.OK)
                {
                    NewPassword  = f.Controls["txtPassword"].Text;
                    authResponse = await user.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest()
                    {
                        SessionID   = authResponse.SessionID,
                        NewPassword = NewPassword
                    });

                    AccessToken = authResponse.AuthenticationResult.AccessToken;
                }
            }
            else
            {
                AccessToken = authResponse.AuthenticationResult.AccessToken;
            }


            CognitoAWSCredentials credentials =
                user.GetCognitoAWSCredentials("us-east-2:bd9037c3-26d6-432a-a6a9-9d66281f49ba", Amazon.RegionEndpoint.USEast2);


            //            CognitoAWSCredentials credentials = new CognitoAWSCredentials("us-east-2:bd9037c3-26d6-432a-a6a9-9d66281f49ba", Amazon.RegionEndpoint.USEast2);

            //   credentials.AddLogin("www.amazon.com", AccessToken);
            //credentials.

            //Cognitocr


            using (var client = new AmazonS3Client(credentials, Amazon.RegionEndpoint.USEast2))
            {
                //var response1 =
                //    await client.ListBucketsAsync(new ListBucketsRequest()).ConfigureAwait(false);
                //client.DeleteBucketAsync("Kalle");
                //client.ListVersionsAsync("ssdfsdf");
                ListBucketsResponse response =
                    await client.ListBucketsAsync(new ListBucketsRequest()).ConfigureAwait(false);

                foreach (S3Bucket bucket in response.Buckets)
                {
                    Console.WriteLine(bucket.BucketName);
                }
            }
        }