[英]ASP.NET Login Control cookies, how does it work?
我在要創建的網站上設置了登錄控件,並且可以正常運行。 我可以查詢數據庫,如果詳細信息與數據庫匹配,它將登錄用戶,否則將失敗。
這是我的代碼:
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;
}
}
我的問題是與cookie有關。 我的理解是,如果我選中“記住我”框(由登錄控件提供),則表單身份驗證模塊將創建一個持久性cookie。
我想知道我對它如何工作的理解是正確的嗎? 我對解決方案足夠滿意,只要它能按我認為的方式工作即可。
注意:我知道我的代碼可能不是最好的,但是我是一個初學者,每天都在學習!
是的,您的假設是正確的。
觸發Authenticate事件后,它將查看Authenticated的返回值。
如果為true,則會創建表單身份驗證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...
}
}
您不需要Session["username"] = user;
。 如果使用表單身份驗證 ,則可以使用User.Identity.Name從Thread的Current Principal中獲取用戶名。
例如,
string username = User.Identity.Name;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.