ASP.NET 登录控制 cookie,它是如何工作的

本文关键字:何工作 工作 登录 NET 控制 cookie ASP | 更新日期: 2023-09-27 18:32:29

我在正在创建的站点上设置了一个登录控件,它工作正常。我可以查询我的数据库,如果详细信息与数据库匹配或失败,它将登录用户。

这是我的代码:

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。

我想知道我对它如何工作的理解是否正确?我对解决方案感到满意,只要它按照我认为的方式工作。

注意:我知道我的代码可能不是最好的,但我是初学者,我每天都在学习!

ASP.NET 登录控制 cookie,它是如何工作的

是的,你的假设是正确的。

触发身份验证事件后,它会查看"已验证"的返回值。

如果为 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线程的当前主体获取用户名。

例如

string username = User.Identity.Name;