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

时间:2014-11-30 21:55:38

标签: c# asp.net cookies

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

这是我的代码:

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。

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

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

1 个答案:

答案 0 :(得分:4)

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

在触发身份验证事件后,它会查看经过身份验证的的返回值。

如果是,则创建表单身份验证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.Name 线程的当前主体获取用户名。

例如,

string username = User.Identity.Name;