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;
            }
        }
Ejemplo n.º 2
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
                }));
            }
        }
Ejemplo n.º 3
0
    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);
    }
Ejemplo n.º 4
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);
        }
    }
Ejemplo n.º 5
0
        public async Task <string> LoginAsync(string username, string password)
        {
            CognitoUserPool userPool = new CognitoUserPool(this.POOL_ID, this.CLIENTAPP_ID, provider);

            Amazon.Extensions.CognitoAuthentication.CognitoUser user = new Amazon.Extensions.CognitoAuthentication.CognitoUser(username, this.CLIENTAPP_ID, userPool, provider);

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

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

            if (authResponse.AuthenticationResult != null)
            {
                return(authResponse.AuthenticationResult.RefreshToken);
            }

            //var authReq = new AdminInitiateAuthRequest
            //{
            //    UserPoolId = POOL_ID,
            //    ClientId = CLIENTAPP_ID,
            //    AuthFlow = AuthFlowType.ADMIN_NO_SRP_AUTH
            //};
            //authReq.AuthParameters.Add("USERNAME", userName.ToLower());
            //authReq.AuthParameters.Add("PASSWORD", password);

            //AdminInitiateAuthResponse authResp = await provider.AdminInitiateAuthAsync(authReq);

            return(authResponse.AuthenticationResult.IdToken);
        }
Ejemplo n.º 6
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);
        }
Ejemplo n.º 7
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);
        }
Ejemplo n.º 8
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;
            }
        }
Ejemplo n.º 9
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);
        }
Ejemplo n.º 10
0
    //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;
        }
    }
Ejemplo n.º 11
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);
        }
Ejemplo n.º 12
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);
            }
        }
Ejemplo n.º 13
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);
        }
Ejemplo n.º 14
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);
            }
        }
        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);
            });
        }
Ejemplo n.º 17
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);
        }
Ejemplo n.º 18
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);
        }
Ejemplo n.º 19
0
        // Log in a user using credential provided. Initializes a secure connection to AWS and logs in the user.
        public async Task Login()
        {
            AmazonCognitoIdentityProviderClient provider =
                new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), Amazon.RegionEndpoint.CACentral1);
            CognitoUserPool        userPool    = new CognitoUserPool(Settings.AWS_COGNITO_POOL_ID, Settings.AWS_CLIENT_ID, provider);
            CognitoUser            user        = new CognitoUser(username, Settings.AWS_CLIENT_ID, userPool, provider);
            InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
            {
                Password = password
            };

            AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);
        }
Ejemplo n.º 20
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);
            }
        }
Ejemplo n.º 21
0
        private static async Task <string> GetIdToken(string uid, string pwd)
        {
            Console.WriteLine("Logging in using {0}...", uid);
            var provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), RegionEndpoint.EUWest2);
            var userPool = new CognitoUserPool("eu-west-2_iaOcSeO8H", "60b6uqu956ii0fjmno24ev4rh6", provider);
            var user     = new CognitoUser(uid, "60b6uqu956ii0fjmno24ev4rh6", userPool, provider);
            InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
            {
                Password = pwd
            };

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

            return(authResponse.AuthenticationResult.IdToken);
        }
        public static async void GetCredsAsync()
        {
            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);

            accessToken = authResponse.AuthenticationResult.AccessToken;
        }
Ejemplo n.º 23
0
        public static async Task PwdRedefinedAuthentication(string _username, string _password, int _clientid, string _newPassword)
        {
            //CognitoUser user = new CognitoUser(_username, Constants.CLIENTAPP_ID, Server.cognitoManagerServer.userPool, Server.cognitoManagerServer.provider, Constants.NeokySecret);


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

            //AuthFlowResponse authFlowResponse = null;
            //Console.WriteLine("GetUserAttribute | Pré - isValid : " + user.SessionTokens.IsValid().ToString()); // = Null while SRPAUTH not run
            try
            {
                //Console.WriteLine("SignInClients.cs | Authentication Requested");
                AuthFlowResponse authFlowResponse = await Server.clients[_clientid].myUser.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);
                //Console.WriteLine("SignInClients.cs | Authentication Success");
                //authFlowResponse.AuthenticationResult.RefreshToken
                //Server.clients[_clientid].accessToken = authFlowResponse.AuthenticationResult.AccessToken; // Only Loged In Users have their Access Token Set.

                Console.WriteLine("SignInClients.cs | Authentication Redefine PWD OK");
                if (authFlowResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED)
                {
                    // Updating New Password
                    Console.WriteLine("SignInClients.cs | Updating user with New Password");
                    authFlowResponse = await Server.clients[_clientid].myUser.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest()
                    {
                        SessionID   = authFlowResponse.SessionID,
                        NewPassword = _newPassword
                    });
                    Console.WriteLine("SignInClients.cs | New Password Updated");

                    Console.WriteLine("SignInClients.cs | Authentication With Redefined PWD User");
                    UpdateUserAndSendIntoGame(_clientid, Constants.SCENE_REDEFINE_PWD); // Set the Scene to Unload to Redefine PWD Scene
                }
                else
                {
                    Console.WriteLine("SignInClients.cs | Authentication Without Redefined PWD User");
                    UpdateUserAndSendIntoGame(_clientid, Constants.SCENE_REDEFINE_PWD); // Set the Scene to Unload to Redefine PWD Scene
                }
            }
            catch (Exception e)
            {
                HandleExceptions(e, _clientid, Constants.SCENE_REDEFINE_PWD);
            }
        }
Ejemplo n.º 24
0
        public async Task <RequestResult> AuthnicateUser(string username, string password)
        {
            RequestResult result = new RequestResult();

            try
            {
                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
                };


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

                if (authResponse.AuthenticationResult != null)
                {
                    cognitoUserSession = new CognitoUserSession(authResponse.AuthenticationResult.IdToken, authResponse.AuthenticationResult.AccessToken, authResponse.AuthenticationResult.RefreshToken, DateTime.Now, DateTime.Now.AddHours(1));
                    //JwtSecurityTokenHandler jt = new JwtSecurityTokenHandler();
                    //if (!jt.CanReadToken(authResponse.AuthenticationResult.AccessToken))
                    //{
                    //}

                    //JwtSecurityToken tokenS = jt.ReadToken(authResponse.AuthenticationResult.AccessToken) as JwtSecurityToken;
                    //result.Id = tokenS.Id;
                    //IEnumerable<Claim> cc = tokenS.Claims;

                    //result.cc = cc;
                    result.Status = true;
                    result.Data   = user;
                }
                else
                {
                    result.Status = false;
                }
            }
            catch (Exception ex)
            {
                result.Status  = false;
                result.Message = ex.Message;
            }

            return(result);
        }
Ejemplo n.º 25
0
    public async Task <bool> Login(string email, string password)
    {
        // Debug.Log("Login: "******", " + password);

        CognitoUserPool userPool = new CognitoUserPool(userPoolId, AppClientID, _provider);
        CognitoUser     user     = new CognitoUser(email, AppClientID, userPool, _provider);

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

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

            _userid = await GetUserIdFromProvider(authFlowResponse.AuthenticationResult.AccessToken);

            // Debug.Log("Users unique ID from cognito: " + _userid);

            UserSessionCache userSessionCache = new UserSessionCache(
                authFlowResponse.AuthenticationResult.IdToken,
                authFlowResponse.AuthenticationResult.AccessToken,
                authFlowResponse.AuthenticationResult.RefreshToken,
                _userid);

            SaveDataManager.SaveJsonData(userSessionCache);

            // This how you get credentials to use for accessing other services.
            // This IdentityPool is your Authorization, so if you tried to access using an
            // IdentityPool that didn't have the policy to access your target AWS service, it would fail.
            _cognitoAWSCredentials = user.GetCognitoAWSCredentials(IdentityPool, Region);

            _user = user;

            return(true);
        }
        catch (Exception e)
        {
            Debug.Log("Login failed, exception: " + e);
            return(false);
        }
    }
Ejemplo n.º 26
0
        private async void BtnSignIn_ClickAsync(object sender, EventArgs e)
        {
            try
            {
                AmazonCognitoIdentityProviderClient provider =
                    new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), wwRegion);
                CognitoUserPool        userPool    = new CognitoUserPool(wwUserPoolID, wwAppClientID, provider);
                CognitoUser            user        = new CognitoUser(txtID.Text, wwAppClientID, userPool, provider);
                InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
                {
                    Password = txtPass.Text
                };

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

                string accessToken = authResponse.AuthenticationResult.AccessToken;
                string idToken     = authResponse.AuthenticationResult.IdToken;

                // Amazon Cognito 認証情報プロバイダーを初期化します
                CognitoAWSCredentials credentials = new CognitoAWSCredentials(
                    wwIdPoolID, // ID プールの ID
                    wwRegion    // リージョン
                    );

                credentials.AddLogin("cognito-idp.us-east-1.amazonaws.com/" + wwUserPoolID, idToken); // the raw token
                //↓おまじない
                string hoge = await credentials.GetIdentityIdAsync();

                using (var client = new AmazonS3Client(credentials, wwRegion))
                {
                    var listObjectRequest = new ListObjectsRequest();
                    listObjectRequest.BucketName = wwS3BucketName;
                    var response = await client.ListObjectsAsync(listObjectRequest);

                    //ここでオブジェクトがとれる
                    ;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 27
0
        //internal async Task<CognitoUser> ResetPassword(string username)
        //{
        //    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);
        //    await user.ForgotPasswordAsync();
        //    return user;
        //}

        //internal async Task<CognitoUser> UpdatePassword(string username, string code, string newpassword)
        //{
        //    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);
        //    await user.ConfirmForgotPasswordAsync(code, newpassword);
        //    return user;
        //}

        public async Task ValidateUser(string username, string password)
        {
            try
            {
                AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), RegionEndpoint.EUCentral1);
                CognitoUserPool userPool = new CognitoUserPool(this.USERPOOL_ID, this.CLIENTAPP_ID, provider);
                CognitoUser     user     = new CognitoUser(username, this.CLIENTAPP_ID, userPool, provider);

                InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest();
                authRequest.Password = password;

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

                if (authFlowResponse.AuthenticationResult == null)
                {
                    throw new Exception("Cognito authentication error");
                }

                GetUserResponse userDetails = await user.GetUserDetailsAsync();

                string idtoken = authFlowResponse.AuthenticationResult.IdToken;

                //CognitoAWSCredentials creds = user.GetCognitoAWSCredentials(this.IDENTITYPOOL_ID, RegionEndpoint.EUCentral1);
                CognitoAWSCredentials creds = new CognitoAWSCredentials(this.IDENTITYPOOL_ID, RegionEndpoint.EUCentral1);
                creds.Clear();
                //creds.CurrentLoginProviders.SetValue(idtoken, 0);
                //creds.CurrentLoginProviders.SetValue(idtoken, 1);
                creds.AddLogin("cognito-idp." + RegionEndpoint.EUCentral1.SystemName + ".amazonaws.com/" + this.USERPOOL_ID, idtoken);

                UserInfo.Clear();
                UserInfo.Credentials = creds;
                UserInfo.UserId      = userDetails.UserAttributes.Find(x => x.Name.ToLower() == "sub").Value;
                UserInfo.UserName    = user.Username;
                UserInfo.Email       = userDetails.UserAttributes.Find(x => x.Name.ToLower() == "email").Value;
                UserInfo.Picture     = "userphoto";
            }
            catch (Exception ex)
            {
                Console.WriteLine("ValidateUser ERROR: " + ex.Message);
                throw ex;
            }
        }
        /// <summary>
        /// Authenticates user
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="userPassword"></param>
        /// <returns></returns>
        public async Task <AuthResultDto> AuthenticateAsync(string userName, string userPassword)
        {
            CognitoUser user = new CognitoUser(userName, _appConfigInfo.AWSAppClientId, _userPool, _provider);

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

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

                if (!string.IsNullOrEmpty(authResponse.ChallengeName))
                {
                    return(new AuthResultDto
                    {
                        ChallengeRequired = true,
                        ChallengeName = authResponse.ChallengeName
                    });
                }

                var idToken      = authResponse.AuthenticationResult.IdToken;
                var accessToken  = authResponse.AuthenticationResult.AccessToken;
                var refreshToken = authResponse.AuthenticationResult.RefreshToken;

                return(new AuthResultDto
                {
                    IdToken = idToken,
                    AccessToken = accessToken,
                    RefreshToken = refreshToken
                });
            }
            catch (NotAuthorizedException)
            {
                throw new UnauthorizedAccessException();
            }
            catch (PasswordResetRequiredException)
            {
                throw new CcsSsoException("PASSWORD_RESET_REQUIRED");
            }
        }
Ejemplo n.º 29
0
        public async Task <ActionResult> GetToken(GetTokenRequest input)
        {
            try
            {
                var user        = new CognitoUser(input.username, AppConfig.ClientId, _userPool, _identityProvider, AppConfig.ClientSecret);
                var authRequest = new InitiateSrpAuthRequest()
                {
                    Password = input.password
                };

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

                var authenticationResultSerialized = JsonConvert.SerializeObject(authResponse.AuthenticationResult);
                return(new JsonResult(authenticationResultSerialized));
            }
            catch (Exception e)
            {
                return(StatusCode((int)HttpStatusCode.BadRequest, e.Message));
            }
        }
Ejemplo n.º 30
0
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////


        private async Task <bool> _Login()
        {
            try
            {
                // Already authenticated?
                if (m_idToken != null &&
                    m_accessToken != null &&
                    m_refreshToken != null)
                {
                    return(true);
                }

                // Autheticate to Amazon to get access token
                AWSCredentials credentials = new Amazon.Runtime.AnonymousAWSCredentials();
                string         systemName  = COGNITO_USER_POOL_ID.Split('_')[0];
                RegionEndpoint region      = RegionEndpoint.GetBySystemName(systemName);
                using (IAmazonCognitoIdentityProvider provider = new AmazonCognitoIdentityProviderClient(credentials, region))
                {
                    CognitoUserPool userPool = new CognitoUserPool(COGNITO_USER_POOL_ID, COGNITO_CLIENT_ID, provider);
                    CognitoUser     user     = new CognitoUser(m_evnexUsername, COGNITO_CLIENT_ID, userPool, provider);

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

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

                    m_idToken      = response.AuthenticationResult.IdToken;
                    m_accessToken  = response.AuthenticationResult.AccessToken;
                    m_refreshToken = response.AuthenticationResult.RefreshToken;
                }
                logger.Info("EvnexV2 Login succeeded");
                return(true);
            }
            catch (Exception ex)
            {
                logger.Error(ex, "EvnexV2 Login failed. " + ex.Message);
            }
            return(false);
        }