web api, how to do this login correctly?

Asked

Viewed 102 times

0

I am developing an application that is a short version of a web system, this system was developed in PHP. For the application, I am developing in Xamarin Forms, however via web api I am trying to make the login screen, but when entering any login or password it is logging in, and this could not happen, should log in only when entering the saved user data in the database. Down with my code:

Loginpage.xaml.Cs

public partial class LoginPage : TabbedPage
    {

        public LoginPage()
        {
            InitializeComponent();
            NavigationPage.SetHasNavigationBar(this, false);

        }

        protected async void BtnLogin_Clicked(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(emailEntry.Text))
            {
                await DisplayAlert("Erro", "Digite um nome de usuário válido", "Aceitar");
                emailEntry.Focus();
                return;
            }
            if (string.IsNullOrEmpty(senhaEntry.Text))
            {
                await DisplayAlert("Erro", "Digite uma senha", "Aceitar");
                emailEntry.Focus();
                return;
            }
            this.logar();


            App.Current.MainPage = new MainPageRoot();
        }

        private async void logar()
        {
            waitActivityIndicator.IsRunning = true;
            var loginRequest = new LoginRequest
            {
                Usuario = emailEntry.Text,
                Senha = senhaEntry.Text,
            };
            var JsonRequest = JsonConvert.SerializeObject(loginRequest);
            var httpContent = new StringContent(JsonRequest);
            var resp = string.Empty;

            try
            {
                var client = new HttpClient();
                client.BaseAddress = new Uri("http://ativoproject.ebasesistemas.com.br");
                var url = "http://ativoproject.ebasesistemas.com.br/login.php";
                var result = await client.PostAsync(url, httpContent);

                if (!result.IsSuccessStatusCode)
                {
                    await DisplayAlert("Erro", "Usuario ou senha incorretos", "Aceitar");
                    waitActivityIndicator.IsRunning = false;
                    return;
                }

                resp = await result.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                await DisplayAlert("Erro", ex.Message, "Aceitar");
                waitActivityIndicator.IsRunning = false;
                return;

            }

            var user = JsonConvert.DeserializeObject<Colaborador>(resp);
            waitActivityIndicator.IsRunning = false;
            await DisplayAlert("Bem vindo","vc esta logado", "Aceitar");
        }
    }

Collaborator.Cs

 public class Colaborador
    {
        public int ColaboradorID { get; set; }

        public string Nome { get; set; }

        public string UserName { get; set; }

        public string Password { get; set; }

        public bool Inativo { get; set; }
    }

Loginrequest.Cs

class LoginRequest
    {
        public string Usuario { get; set; }
        public string Senha { get; set; }
    }

And this here is the system link on the web: http://ativoproject.ebasesistemas.com.br

1 answer

1


Usually the property tested on result.IsSuccessStatusCode actually concerns the communication itself, whether or not there was success in sending the request.

If it fails, fine, you need to inform the user that you were unable to communicate with the server. But if you were able to communicate with the server (as seems to be the case), you need to do a second check step, analyzing the content of the reply, which would be flagged for authentication or not ( via message or a code) according to your business rules (and the API contract you are consuming) stating whether or not authentication was made.

This information must be available at the property result.Content.Result.

In your case, you are deserializing for an object of the type Colaborador in var user = JsonConvert.DeserializeObject<Colaborador>(resp);. It’s probably a strategy where you consider success if a Colaborador valid and, if not, means not authenticated (but also you do not know the reason, could be the wrong password, could be that the user is blocked, could be that the user does not exist...).

I suggest you consult your api contract or debug the result of this return property for some scenarios to know how to treat.

I hope this helps.

  • I sort of understood, because I’m still a beginner in this language, you could show me an example of what you’re saying applied in my context?

  • @Wpfan To show in your scenario, I would need to know the structure of the response you get from the webservice to treat what we would be expecting, but I’ll try to include an example in the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.