I have a login control set up on the site I'm creating and it works okay. I can query my database and it will login a user if the details match the database or fail otherwise.
Here's my code:
private bool UserLoginConnection(string user, string password)
{
SqlConnection sqlConnection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("Select userEmail from Users where userEmail = @user and userPassword = @password", sqlConnection);
cmd.Parameters.AddWithValue("@user", user);
cmd.Parameters.AddWithValue("@password", password);
sqlConnection.Open();
string result = Convert.ToString(cmd.ExecuteScalar());
sqlConnection.Close();
if (String.IsNullOrEmpty(result))
{
return false;
}
return true;
}
protected void UserLogin_Authenticate(object sender, AuthenticateEventArgs e)
{
string user = UserLogin.UserName;
string password = UserLogin.Password;
bool result = UserLoginConnection(user, password);
if (result)
{
e.Authenticated = true;
Session["username"] = user;
}
else
{
e.Authenticated = false;
}
}
My question is to do with cookies. My understanding is that if I check the remember me box (provided by the login control) the form authentication module creates a persistent cookie.
I'd like to know if my understanding of how it works is correct? I'm happy enough with the solution as it is, provided it works the way I think it does.
Note: I know my code might not be the best but I'm a beginner and I'm learning every day!
Yes, your assumption is correct.
After Authenticate event is fired, it looks at the returns value of Authenticated .
If it is true, it creates Form Authentication Cookie -
FormsAuthentication.SetAuthCookie(UserNameInternal, RememberMeSet);
private void AttemptLogin() {
// ... removed for brevity...
AuthenticateEventArgs authenticateEventArgs = new AuthenticateEventArgs();
OnAuthenticate(authenticateEventArgs);
if (authenticateEventArgs.Authenticated) {
FormsAuthentication.SetAuthCookie(UserNameInternal, RememberMeSet);
OnLoggedIn(EventArgs.Empty);
Page.Response.Redirect(GetRedirectUrl(), false);
}
else {
// ... removed for brevity...
}
}
You do not need Session["username"] = user;
. If you use Form Authentication , you can use User.Identity.Name to get username from Thread's Current Principal .
For example,
string username = User.Identity.Name;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.