0

I'm trying to make an authentication system inside my website. I'm sending a simple POST request with the email and password inside, to my ASP.NET server and for some reason the data (email and password) inside the server is empty. I don't know what I'm doing wrong and I'm a beginner on ASP.NET and Angular.

Angular code: (I tried to show the text from the text boxes inside some elements and it shows the correct text)

  isUserLoggedIn: boolean;
  emailAddress: string;
  password: string;

  constructor(private http: HttpClient, @Inject('BASE_URL') private baseUrl: string) {}

  login() {

    const headers = {'Content-Type': 'application/json', };
    const body = { emailAddress: this.emailAddress.toString, password: this.password.toString };
    this.http.post<any>(this.baseUrl + "login", body, { headers }).subscribe(result => {
      this.isUserLoggedIn = result;
      if (this.isUserLoggedIn) console.log("Logged in")
      else console.log("Not logged in")
    }, error => console.error(error));

  }

My ASP.NET controller:

[HttpPost]
[Route("login")]
public bool LoginUser(string emailAddress, string password)
{
    // DOES NOT PRINT ANY VALUE OF EMAIL OR PASSWORD
    Console.WriteLine("1: " + emailAddress);
    Console.WriteLine("2: " + password);
            
    SakilaContext context = HttpContext.RequestServices.GetService(typeof(SakilaContext)) as SakilaContext;
    return context.LoginUser(emailAddress, password);
}

My code for database inside ASP.NET server:

public bool LoginUser(string emailAddress, string password)
{
    bool isUserLoggedIn = false;
    List<UserModel> list = new List<UserModel>();
    using (MySqlConnection conn = GetConnection())
    {
        string query = $"SELECT * FROM users WHERE email = '{emailAddress}'";
        conn.Open();
        MySqlCommand cmd = new MySqlCommand(query, conn);
        using (MySqlDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                if (reader.HasRows)
                {
                    string db_password = reader.GetString("password");
                    if (db_password == password)
                    {
                        isUserLoggedIn = true;
                    }
                }
            }
        }
    }
    return isUserLoggedIn;
}

1 Answer 1

1

Create a LoginModel class.

public class LoginModel
{
    public string EmailAddress { get; set; }
    public string Password { get; set; }
}

Change the Login method signature to read the object value from the request body via [FromBody].

[HttpPost]
[Route("login")]
public bool LoginUser([FromBody] LoginModel model)
{
    Console.WriteLine(model.EmailAddress);
    Console.WriteLine(model.Password);

    ...
}

For Angular, I don't think the below part is correct:

const body = { emailAddress: this.emailAddress.toString, password: this.password.toString };

Change to

const body = { emailAddress: this.emailAddress.toString(), password: this.password.toString() };

Or

const body = { emailAddress: this.emailAddress, password: this.password };

Side note:

Don't concatenate the value in SQL command, use a parameterized query with .AddWithValue("@parameter", value). Check out Why do we always prefer using parameters in SQL statements?.

string query = $"SELECT * FROM users WHERE email = @emailAddress";
conn.Open();
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@emailAddress", emailAddress);

Reference

[FromBody] attribute

Sign up to request clarification or add additional context in comments.

4 Comments

Still not working :((
Hi, did you check the browser DevTools Netwotk tab, did you post the request with value? And in Angular side, I think this is wrong this.emailAddress.toString, use this.emailAddress.toString(). Same goes for password.
ichecked it and it doesn't send any data for some reason, the data inside the payload is empty
i fixed the problem by converting .toString to .toString()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.