繁体   English   中英

ASP.NET登录控件cookie,它如何工作?

[英]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); 

登录控件的AttemptLogin方法

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.NameThread的Current Principal中获取用户名。

例如,

string username = User.Identity.Name;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM