Today's topic is as follows:
Validation process telling
Database Preparation
Code writing
Validation process telling
Let's start with a scenario where the user has now opened our home page Default.aspx, but some of the resources can only be seen by the logged-in user, so if the user wants to view those resources, he will be logged in. And this user already has an account number. (Our main topic is authentication, as to how to create a user account, we do not care, many methods, such as a direct database insert on the line!)
We're going to talk about some of our processes right now:
1. User login, enter user name and password information in the input box
2. Click on the Login button to query the database to see if the user exists
3 if present, the server-side code creates an authenticated ticket, saves it in a cookie, and sends it to the client's browser
4. The user already has the authenticated cookie, then the page jumps to the page that the user requested before
Database Preparation
So let's start with a detailed story:
First of all, we must first create a database, we will name the login table, create a user information table, we set up in the table three fields Username,userpassword,userrole (you can create more fields, I'm here just demo, Everyone can expand). As for the data in the table, everyone inserts a few!
Code writing
Because we often have to authenticate the user, we put the code that validates the user in a way in the Helpers.cs class in the App_Code directory
The code is as follows:
Validating code
public static bool ValidateUser(string username, string password)
{
SqlConnection con = new SqlConnection();
con.ConnectionString =
ConfigurationManager.ConnectionStrings[“MyConnectionString”].ConnectionString;
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandText = “Select Count(*) From Users Where Username=@Username and UserPassword=@Password”;
com.Parameters.AddWithValue(“@Username”, username);
com.Parameters.AddWithValue(“@Password”, password);
con.Open();
int cnt = (int)com.ExecuteScalar();
con.Close();
return (cnt > 0);
}