public async void GetS3BucketsAsync()
        {
            var             provider = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials());
            CognitoUserPool userPool = new CognitoUserPool("poolID", "clientID", provider);
            CognitoUser     user     = new CognitoUser("username", "clientID", userPool, provider);

            string password = "******";

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

            CognitoAWSCredentials credentials =
                user.GetCognitoAWSCredentials("identityPoolID", RegionEndpoint.< YourIdentityPoolRegion >);

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

                foreach (S3Bucket bucket in response.Buckets)
                {
                    Console.WriteLine(bucket.BucketName);
                }
            }
        }
Example #2
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);
        }
Example #3
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);
            }
        }
Example #4
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);
        }
Example #5
0
        public async Task <SignInContext> SignIn(string userName, string password)
        {
            try
            {
                var credentials = new AnonymousAWSCredentials();


                using (var client = new AmazonCognitoIdentityProviderClient(credentials, ClientHttpConfig))
                {
                    CognitoUserPool userPool = new CognitoUserPool(PoolId, ClientId, client);
                    CognitoUser     user     = new CognitoUser(userName, ClientId, userPool, client);

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

                    // TODO handle other challenges
                    if (context.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED)
                    {
                        return new SignInContext(CognitoResult.PasswordChangeRequred)
                               {
                                   //User = user,
                                   SessionId = context.SessionID
                               }
                    }
                    ;
                    else
                    {
                        return(new SignInContext(CognitoResult.Ok)
                        {
                            //User = user,
                            IdToken = context.AuthenticationResult?.IdToken,
                            RefreshToken = context.AuthenticationResult?.RefreshToken,
                            AccessToken = context.AuthenticationResult?.AccessToken,
                            TokenIssued = user.SessionTokens.IssuedTime,
                            Expires = user.SessionTokens.ExpirationTime,
                            SessionId = context.SessionID
                        });
                    }
                }
            }
            catch (NotAuthorizedException)
            {
                return(new SignInContext(CognitoResult.NotAuthorized));
            }
            catch (UserNotFoundException)
            {
                return(new SignInContext(CognitoResult.UserNotFound));
            }
            catch (UserNotConfirmedException)
            {
                return(new SignInContext(CognitoResult.NotConfirmed));
            }
            catch (Exception e)
            {
                Console.WriteLine($"SignIn() threw an exception {e}");
            }
            return(new SignInContext(CognitoResult.Unknown));
        }
    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);
    }
Example #7
0
        public async Task <IActionResult> Post([FromBody] LoginDto loginDto)
        {
            _logger.LogDebug("Login");

            try
            {
                var provider = new AmazonCognitoIdentityProviderClient(
                    new Amazon.Runtime.AnonymousAWSCredentials(),
                    RegionEndpoint.GetBySystemName(_configuration["AWS:Cognito:Region"]));
                var userPool    = new CognitoUserPool(_configuration["AWS:Cognito:PoolId"], _configuration["AWS:Cognito:ClientId"], provider);
                var user        = new CognitoUser(loginDto.Username, _configuration["AWS:Cognito:ClientId"], userPool, provider);
                var authRequest = new InitiateSrpAuthRequest()
                {
                    Password = loginDto.Password
                };
                var authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);

                return(Ok(new {
                    result = "ok",
                    identityToken = authResponse.AuthenticationResult.IdToken,
                    expiresInSeconds = authResponse.AuthenticationResult.ExpiresIn
                }));
            }
            catch (Amazon.CognitoIdentityProvider.Model.NotAuthorizedException ex)
            {
                return(Unauthorized(new {
                    result = "error",
                    type = ex.GetType().ToString(),
                    message = ex.Message
                }));
            }
        }
    //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;
        }
    }
        private async Task <bool> Authorize(string password)
        {
            if (password != null)
            {
                try
                {
                    AuthFlowResponse AuthResponse = await User.StartWithSrpAuthAsync
                                                        (new InitiateSrpAuthRequest()
                    {
                        Password = password
                    }).ConfigureAwait(false);

                    if (AuthResponse != null)
                    {
                        Debug.Log("User successfully authenticated");
                        Client.DefaultRequestHeaders.Accept.Clear();
                        Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(User.SessionTokens.IdToken);
                        Debug.Log(User.SessionTokens.IdToken);
                        return(true);
                    }
                }
                catch (NotAuthorizedException e)
                {
                    Debug.Log("Authentication Error");
                    Debug.Log(e);
                    return(false);
                }
            }
            return(false);
        }
Example #10
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);
        }
Example #11
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);
        }
    }
Example #12
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);
        }
Example #13
0
        public async Task <bool> loginUser(string email, string password)
        {
            var provider = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), Amazon.RegionEndpoint.EUWest2);
            var userPool = new CognitoUserPool(Statics.poolID, Statics.clientID, provider);
            var user     = new CognitoUser(email, Statics.clientID, userPool, provider);

            try
            {
                Statics.authResponse = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest()
                {
                    Password = password
                }).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.Message);
                }
                return(false);
            }

            if (Statics.authResponse.AuthenticationResult == null)
            {
                return(false);
            }
            Statics.user = user;
            Console.WriteLine(Statics.myidtoken);

            var xxx = await getCredentials();

            return(xxx);
        }
        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;
            }
        }
Example #15
0
        static void Main(string[] args)
        {
            Console.Write("Enter cognito App Id:");
            string cognitoAppId = Console.ReadLine();

            Console.WriteLine("App ID is " + cognitoAppId + ".");
            Console.Write("Enter Cognito User Pool Id:");
            string userPoolId = Console.ReadLine();

            Console.WriteLine("Cognito User Pool Id is " + userPoolId + ".");
            Console.Write("Username:"******"Username is " + username + ".");
            Console.Write("password:"******"pw is " + pw + ".");


            var cognitoClient   = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), RegionEndpoint.USWest2);
            var cognitoUserPool = new CognitoUserPool(userPoolId, cognitoAppId, cognitoClient);
            var currentUser     = new CognitoUser(username, cognitoAppId, cognitoUserPool, cognitoClient);
            var response        = currentUser.StartWithSrpAuthAsync(new InitiateSrpAuthRequest()
            {
                Password = pw
            }).Result;

            string js = JsonConvert.SerializeObject(response);

            Console.WriteLine(js);
            File.WriteAllText("out.txt", js);
            Console.ReadLine();
        }
Example #16
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);
        }
Example #17
0
        static async Task Main(string[] args)
        {
            string clientId = "19efs8tgqe942atbqmot5m36t3";
            string poolId   = "us-east-1_GUFWfhI7g";

            string userId   = "user";     // your mysa login username
            string password = "******"; // your mysa login password

            var provider = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), RegionEndpoint.USEast1);
            var userPool = new CognitoUserPool(poolId, clientId, provider);
            var user     = new CognitoUser(userId, clientId, userPool, provider);

            var authResponse = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest()
            {
                Password = password
            }).ConfigureAwait(false);

            using (var client = new HttpClient())
            {
                var url = "https://app-prod.mysa.cloud/users/readingsForUser";
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + authResponse.AuthenticationResult.IdToken);

                var response = await client.GetStringAsync(url); // response contains the json response, parse and use as needed

                dynamic obj = JsonConvert.DeserializeObject(response);

                Console.WriteLine("JSON: " + obj);
            }
        }
Example #18
0
        public static async Task <string> SignIn(string username, string password)
        {
            try
            {
                CognitoUserPool userPool = new CognitoUserPool(AWS.UserPoolId, AWS.ClientId, App.provider);
                CognitoUser     user     = new CognitoUser(username, AWS.ClientId, userPool, App.provider);

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

                if (context.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED)
                {
                    return("User must change password.");
                }
                else
                {
                    App.user = new AWSUser
                    {
                        IdToken      = context.AuthenticationResult?.IdToken,
                        RefreshToken = context.AuthenticationResult?.RefreshToken,
                        AccessToken  = context.AuthenticationResult?.AccessToken,
                        TokenIssued  = user.SessionTokens.IssuedTime,
                        Expires      = user.SessionTokens.ExpirationTime
                    };
                    return("User logged in.");
                }
            }
            catch (Exception err)
            {
                return("Error: " + err.Message);
            }
        }
Example #19
0
        public static async Task SignIn(string username, string password, bool isShowError)
        {
            AmazonCognitoIdentityProviderClient providerClient = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials()
                                                                                                         , region);

            CognitoUserPool userPool    = new CognitoUserPool(poolId, appClientId, providerClient);
            CognitoUser     cognitoUser = new CognitoUser(username, appClientId, userPool, providerClient);

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

            try
            {
                AuthFlowResponse authFlow = await cognitoUser.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);

                isSignedIn = true;
                Username   = cognitoUser.Username.ToString();
            }
            catch (Exception e)
            {
                if (isShowError)
                {
                    MessageBox.Show(e.Message);
                }
                return;
            }
        }
Example #20
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);
        }
        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;
            }
        }
Example #22
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);
            }
        }
Example #23
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);
        }
        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.");
            }
        }
        private void OnSignedUp(string deviceId, string devicePassword, TaskCompletionSource <ICognitoAWSCredentials> promise)
        {
            var userPool = new CognitoUserPool(_userPoolId, _clientId, _cipClient);
            var user     = new CognitoUser(deviceId, userPool.ClientID, userPool, _cipClient);

            var srpRequest = new InitiateSrpAuthRequest();

            srpRequest.Password = devicePassword;

            _logger.Log($"Authenticating for user {deviceId}");
            user.StartWithSrpAuthAsync(srpRequest, srpResult =>
            {
                if (srpResult.Exception != null)
                {
                    if (srpResult.Exception is UserNotFoundException)
                    {
                        var signUpRequest      = new SignUpRequest();
                        signUpRequest.Username = deviceId;
                        signUpRequest.Password = devicePassword;
                        signUpRequest.ClientId = _clientId;

                        _logger.Log($"SignUp with new credentials for user {deviceId}");
                        _cipClient.SignUpAsync(signUpRequest, signUpResult =>
                        {
                            if (signUpResult.Exception != null)
                            {
                                promise.SetException(signUpResult.Exception);
                                return;
                            }

                            _logger.Log("SignUp success!");
                            if (signUpResult.Response != null)
                            {
                                _logger.Log("UserSub:" + signUpResult.Response.UserSub);
                            }

                            _preferences.SetValue(_DeviceIdKey, deviceId);
                            _preferences.SetValue(_DevicePasswordKey, devicePassword);
                            OnSignedUp(deviceId, devicePassword, promise);
                        });
                        return;
                    }

                    promise.SetException(srpResult.Exception);
                    return;
                }

                _logger.Log("Authentication success!");
                ICognitoAWSCredentials credentials = user.GetCognitoAWSCredentials(
                    _identityPoolId,
                    RegionEndpoint.GetBySystemName(_region),
                    _aws);

                promise.SetResult(credentials);
            });
        }
Example #26
0
        public async Task <ResultadoAutenticacaoDTO> Autenticar(AutenticacaoDTO autenticacao)
        {
            ResultadoAutenticacaoDTO resultado = new ResultadoAutenticacaoDTO();

            if (autenticacao == null || string.IsNullOrEmpty(autenticacao.Usuario) || string.IsNullOrEmpty(autenticacao.Senha))
            {
                resultado.Status = EnumResultadoAutenticacao.FALHA_CREDENCIAIS;
            }
            else
            {
                try
                {
                    using (AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(
                               new Amazon.Runtime.AnonymousAWSCredentials(),
                               RegionEndpoint.GetBySystemName(this._awsConfigAdapter.Cognito.PoolRegion)))
                    {
                        CognitoUserPool userPool = new CognitoUserPool(
                            this._awsConfigAdapter.Cognito.PoolID,
                            this._awsConfigAdapter.Cognito.ClientID,
                            provider,
                            this._awsConfigAdapter.Cognito.ClientSecret);

                        CognitoUser user = new CognitoUser(
                            autenticacao.Usuario,
                            this._awsConfigAdapter.Cognito.ClientID,
                            userPool,
                            provider,
                            this._awsConfigAdapter.Cognito.ClientSecret);

                        InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
                        {
                            Password = autenticacao.Senha
                        };

                        AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest);

                        resultado.Status = EnumResultadoAutenticacao.SUCESSO;
                        resultado.Token  = authResponse.AuthenticationResult.IdToken;
                    }
                }
                catch (Amazon.CognitoIdentityProvider.Model.NotAuthorizedException naEx)
                {
                    this._logger.LogError(naEx, "Tentativa de login bloqueada. Usuario: {0} / Senha: {1}", autenticacao.Usuario, autenticacao.Senha);
                    resultado.Status = EnumResultadoAutenticacao.FALHA_CREDENCIAIS;
                }
                catch (Exception ex)
                {
                    this._logger.LogError(ex, "Erro no processo de autenticaĆ§Ć£o");
                    resultado.Status = EnumResultadoAutenticacao.ERRO_NAO_TRATADO;
                }
            }

            return(resultado);
        }
Example #27
0
        public async Task <AuthFlowResponse> SignIn(Guid userId, string password)
        {
            var userPool = new CognitoUserPool(cognitoPoolId, clientId, cognitoIpClient);
            var user     = new CognitoUser(userId.ToString(), clientId, userPool, cognitoIpClient);

            return(await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest()
            {
                Password = password
            })
                   .ConfigureAwait(false));
        }
Example #28
0
        static private async Task <UserCognitoCredentials> getCognitoCredentials(String userEmail, String userPassword)
        {
            String cognitoUserPoolId     = "us-east-1_n8TiZp7tu";
            String cognitoClientId       = "6clvd0v40jggbaa5qid2h6hkqf";
            String cognitoIdentityPoolId = "us-east-1:bff024bb-06d0-4b04-9e5d-eb34ed07f884";

            Amazon.RegionEndpoint cognitoRegion = Amazon.RegionEndpoint.USEast1;

            AmazonCognitoIdentityProviderClient provider =
                new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), Amazon.RegionEndpoint.USEast1);
            CognitoUserPool userPool = new CognitoUserPool(cognitoUserPoolId, cognitoClientId, provider);
            CognitoUser     user     = new CognitoUser(userEmail, cognitoClientId, userPool, provider);

            AuthFlowResponse context = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest()
            {
                Password = userPassword
            }).ConfigureAwait(false);

            String accessToken = context.AuthenticationResult.AccessToken;
            String idToken     = context.AuthenticationResult.IdToken;

            CognitoAWSCredentials credentials =
                user.GetCognitoAWSCredentials(cognitoIdentityPoolId, cognitoRegion);

            var identityClient = new AmazonCognitoIdentityClient(credentials, cognitoRegion);
            var idRequest      = new Amazon.CognitoIdentity.Model.GetIdRequest();

            idRequest.IdentityPoolId = cognitoIdentityPoolId;
            idRequest.Logins         = new Dictionary <string, string> {
                { "cognito-idp.us-east-1.amazonaws.com/" + cognitoUserPoolId, idToken }
            };
            var idResponseId = await identityClient.GetIdAsync(idRequest).ConfigureAwait(false);

            if (idResponseId.HttpStatusCode != System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine(String.Format("Failed to get credentials for identity. Status code: {0} ", idResponseId.HttpStatusCode));
                System.Environment.Exit(1);
            }

            var idResponseCredential = await identityClient.GetCredentialsForIdentityAsync(idResponseId.IdentityId, new Dictionary <string, string> {
                { "cognito-idp.us-east-1.amazonaws.com/" + cognitoUserPoolId, idToken }
            }).ConfigureAwait(false);

            if (idResponseCredential.HttpStatusCode != System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine(String.Format("Failed to get credentials for identity. Status code: {0} ", idResponseCredential.HttpStatusCode));
                System.Environment.Exit(1);
            }

            var cognitoCredentials = new UserCognitoCredentials(idResponseCredential.Credentials);

            return(cognitoCredentials);
        }
Example #29
0
        public async Task <string> LogIn(User user)
        {
            CognitoUserPool        userPool    = new CognitoUserPool(cognitoPoolId, cognitoAppClientId, _clientCognito);
            CognitoUser            userlog     = new CognitoUser(user.Email, cognitoAppClientId, userPool, _clientCognito);
            InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
            {
                Password = user.Password
            };
            AuthFlowResponse auth = await userlog.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);

            return(auth.AuthenticationResult.IdToken);
        }
Example #30
0
        public async Task <IActionResult> Login()
        {
            AmazonCognitoIdentityProviderClient _client = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), RegionEndpoint.USEast1);
            CognitoUserPool  userPool = new CognitoUserPool("us-east-1_EttBoTOfx", "4s8cbl7ptf75hp2tbqc14coib7", _client);
            CognitoUser      user     = new CognitoUser("*****@*****.**", "4s8cbl7ptf75hp2tbqc14coib7", userPool, _client);
            AuthFlowResponse context  = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest
            {
                Password = "******"
            }).ConfigureAwait(false);


            return(Ok(context.AuthenticationResult.AccessToken));
        }