If you want to authenticate a user against your own custom database then you can use the Authenticate event of the Login control. Here is a small example that shows how to achieve it.
| // Use Authenticate event if you want to do custom authentication protected void Login1_Authenticate(object sender, AuthenticateEventArgs e) { string userName = Login1.UserName; string password = Login1.Password; bool result = UserLogin(userName, password); if (result) e.Authenticated = true; else e.Authenticated = false; } private bool UserLogin(string userName, string password) { string query = @"SELECT UserName FROM Users WHERE UserName = @UserName AND Password = @Password"; string connectionString = (string)ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; SqlConnection myConnection = new SqlConnection(connectionString); SqlCommand myCommand = new SqlCommand(query, myConnection); myCommand.Parameters.AddWithValue("@UserName", userName); myCommand.Parameters.AddWithValue("@Password", password); myConnection.Open(); string userId = (string) myCommand.ExecuteScalar(); myConnection.Close(); if (userId != null && userId.Length > 0) return true; else return false; } |
As you can see that I am simply sending the values from the Login control to UserLogin method and returns true or false based on the authentication status.
| When using custom authentication always remember to set the Authenticated property of the Login control to true or false based on the result of authentication. Also when authenticating a user against a custom database you don't need to provide the membership settings in the web.config file. |
No comments:
Post a Comment