Проблема входа в AWS Cognito с помощью Xamarin C # - PullRequest
0 голосов
/ 17 марта 2019

Я реализовал этот код для регистрации пользователя в моем AWS Cognito Pool Код регистрации , и он работает нормально.

        public SignUp2ViewModel()
    {
        SendInfoAWSCommand = new Command(async ()=> await SendInfoAWS());

    }

    public Command SendInfoAWSCommand { get; }

    const string AppClientID = "sum stuff";
    const string PoolID = " sum place";
    static Amazon.RegionEndpoint Region = Amazon.RegionEndpoint.USWest2;




    async Task SendInfoAWS()
    {
        IsBusy = true;
        await Task.Delay(500);
        AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), Region);
        SignUpRequest signUpRequest = new SignUpRequest()
        {
            ClientId = AppClientID,
            Username = usuario,
            Password = senha
        };
        List<AttributeType> attributes = new List<AttributeType>()
        {
            new AttributeType(){Name = "email", Value = email }
        };
        signUpRequest.UserAttributes = attributes;
        try
        {
            SignUpResponse result = await provider.SignUpAsync(signUpRequest);
        }
        catch (Exception e)
        {
            IsBusy = false;
            await Application.Current.MainPage.DisplayAlert("Error", ("Contact has NOT been saved" + e.Message + " "), "OK");
            return;
        }

        IsBusy = false;

        await Application.Current.MainPage.DisplayAlert("Save", "Contact has been saved", "OK");
    }


    string email;
    string usuario;
    string senha;
    bool isBusy = false;



    public string Email
    {
        get
        {
            return email;
        }
        set
        {
            email = value;
            OnPropertyChanged();
        }
    }
    public string Usuario
    {
        get
        {
            return usuario;
        }
        set
        {
            usuario = value;
            OnPropertyChanged();
        }
    }
    public string Senha
    {
        get
        {
            return senha;
        }
        set
        {
            senha = value;
            OnPropertyChanged();
        }
    }

    public bool IsBusy
    {
        get { return isBusy; }
        set
        {
            isBusy = value;

            OnPropertyChanged();
            SendInfoAWSCommand.ChangeCanExecute();
        }
    }


    public event PropertyChangedEventHandler PropertyChanged;
    void OnPropertyChanged([CallerMemberName] string name = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }





    }


}

Но при попытке войти в систему с помощью пользователя Код входа Код вызывает сбой моего приложения при использовании правильной комбинации пользователя (usuario) / пароля (senha). Если я оставлю поле пароля пустым, оно вернет мне ошибку с try / catch ~ thing ~.

    public SignInViewModel()
    {
        SendInfoAWSCommand = new Command(async () => await SendInfoAWS());

    }

    public  Command SendInfoAWSCommand { get; }

     static string usuario;
     static string senha;
     static bool isBusy = false;

    public  string Usuario
    {
        get
        {
            return usuario;
        }
        set
        {
            usuario = value;
            OnPropertyChanged();
        }
    }
    public  string Senha
    {
        get
        {
            return senha;
        }
        set
        {
            senha = value;
            OnPropertyChanged();
        }
    }
    public  bool IsBusy
    {
        get { return isBusy; }
        set
        {
            isBusy = value;

            OnPropertyChanged();
            SendInfoAWSCommand.ChangeCanExecute();
        }
    }

    const string AppClientID = "same place";
    const string PoolID = " other suff";
    static Amazon.RegionEndpoint Region = Amazon.RegionEndpoint.USWest2;

    public event PropertyChangedEventHandler PropertyChanged;
     void OnPropertyChanged([CallerMemberName] string name = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }

    public   async Task SendInfoAWS()
    {
       IsBusy = true;

        await Task.Delay(500);

        AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials(), Region);
        CognitoUserPool userPool = new CognitoUserPool(PoolID, AppClientID, provider);
        CognitoUser user = new CognitoUser(usuario, AppClientID, userPool, provider);
        InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
        {
            Password = senha
        };
        AuthFlowResponse authFlowResponse = null;

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

        }
        catch (Exception e)
        {
            isBusy = false;
            await Application.Current.MainPage.DisplayAlert("Login Failed", (" " + e.Message + " "), "OK");
            return;
        }

        IsBusy = false;
        GetUserRequest getUserRequest = new GetUserRequest();
        getUserRequest.AccessToken = authFlowResponse.AuthenticationResult.AccessToken;
        await Application.Current.MainPage.DisplayAlert("Login Successful", "Welcome!", "OK");
    }




}

Есть что-нибудь, что я здесь упускаю?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...