使用会话验证用户名和密码

本文关键字:密码 用户 验证 会话 | 更新日期: 2023-09-27 18:26:07

我在stackoverflow和谷歌上到处找了找,但没能找到与我的问题有关的答案,所以我把它发布在这里。

我有一个登录页面,引导用户输入他们的用户名和密码,这两个都存储在MySQL数据库中。用户名以纯文本形式存储,密码经过哈希处理(使用CrackStation-https://crackstation.net/hashing-security.htm#aspsourcecode)并且该散列被存储在数据库中。我可以使用用户名和密码成功地让用户登录一次,但我想使用SESSION,这样用户就可以在网站上导航,而不必每次访问不同的页面时都登录。我很容易在测试环境中使用SESSION,因为密码是以纯文本形式存储的,但现在密码被散列了,我无法在代码中使用SESSION。所以我想知道我该怎么做才能在SESSION中验证密码。

我在登录页面上使用的代码如下:

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        admin = Convert.ToInt16(Request.QueryString["Admin"]);               
        Instructor = Convert.ToInt16(Request.QueryString["Inst"]);               
        if (Session["username"] == null || (string)(Session["username"]) == "")
        {                   
            token = Request.QueryString["tokenNumber"];
            lblUsername.Visible = true;
            txtUsername.Visible = true;
            lblPassword.Visible = true;
            txtPassword.Visible = true;
            btnlogin.Visible = true;
        }
        else if (Session["username"] != null || (string)(Session["username"]) != "")
        {                   
            username = (string)Session["username"];
            userType = (string)Session["userType"];
            pass = (string)Session["password"];                   
            if (userType == "Participant")
            {                       
                Response.Redirect("/srls/StudentUser");
            }
            else if (userType == "Coordinator")
            {
                Response.Redirect("/srls/CoordinatorUser");                       
            }
            else if (userType == "Instructor")
            {
                Response.Redirect("/srls/InstructorUser");
            }
        }

    }
    catch (Exception exc) //Module failed to load
    {
        Exceptions.ProcessModuleLoadException(this, exc);
    }
}
protected void btnlogin_Click(object sender, System.EventArgs e)
{
    char activation;
    if (Request.QueryString["tokenNum"] != null)
    {
        using (OdbcConnection dbConnection = new OdbcConnection(srlsConnStr))
        {
            dbConnection.Open();
            {
                OdbcCommand dbCommand = new OdbcCommand();
                dbCommand.Connection = dbConnection;
                dbCommand.CommandText = @"SELECT tokenNum FROM srlslogin WHERE user_email_pk = ?";
                dbCommand.Parameters.AddWithValue("@user_email_pk", txtUsername.Text);
                dbCommand.ExecuteNonQuery();
                OdbcDataReader dataReader = dbCommand.ExecuteReader();
                while (dataReader.Read())
                {
                    if (token == dataReader["tokenNum"].ToString())
                    {
                        updateActivationStatus(txtUsername.Text);
                        LoginWithPasswordHashFunction();
                    }
                    else
                    {
                        test.Text = "You are not authorized to login! Please activate your account following the activation link sent to your email " + txtUsername.Text + " !";
                    }
                }
            }
            dbConnection.Close();
        }
    }
    else if (Request.QueryString["tokenNum"] == null)
    {
        using (OdbcConnection dbConnection = new OdbcConnection(srlsConnStr))
        {
            dbConnection.Open();
            {
                OdbcCommand dbCommand1 = new OdbcCommand();
                dbCommand1.Connection = dbConnection;
                dbCommand1.CommandText = @"SELECT * FROM srlslogin WHERE user_email_pk = ?;";
                dbCommand1.Parameters.AddWithValue("@user_email_pk", txtUsername.Text);
                dbCommand1.ExecuteNonQuery();
                OdbcDataReader dataReader1 = dbCommand1.ExecuteReader();
                if (dataReader1.Read())
                {
                    activation = Convert.ToChar(dataReader1["activation_status"]);
                    if (activation == 'Y')
                    {
                        activation status, activation == Y";
                        LoginWithPasswordHashFunction();
                    }
                    else
                    {
                        lblMessage.Text = "Please activate your account following the Activation link emailed to you at <i>" + txtUsername.Text + "</i> to Continue!";
                    }
                }
                else
                {
                    lblMessage.Text = "Invalid Username or Password";
                }
                dataReader1.Close();
            }
            dbConnection.Close();
        }
    }
}
private void LoginWithPasswordHashFunction()
{
    List<string> salthashList = null;
    List<string> usernameList = null;
    try
    {
        using (OdbcConnection dbConnection = new OdbcConnection(srlsConnStr))
        {
            dbConnection.Open();
            {
                OdbcCommand dbCommand = new OdbcCommand();
                dbCommand.Connection = dbConnection;
                dbCommand.CommandText = @"SELECT slowhashsalt, user_email_pk FROM srlslogin WHERE user_email_pk = ?;";
                dbCommand.Parameters.AddWithValue(@"user_email_pk", txtUsername.Text);
                OdbcDataReader dataReader = dbCommand.ExecuteReader();
                while (dataReader.HasRows && dataReader.Read())
                {
                    if (salthashList == null)
                    {
                        salthashList = new List<string>();
                        usernameList = new List<string>();
                    }
                    string saltHashes = dataReader.GetString(dataReader.GetOrdinal("slowhashsalt"));
                    salthashList.Add(saltHashes);
                    string userInfo = dataReader.GetString(dataReader.GetOrdinal("user_email_pk"));
                    usernameList.Add(userInfo);
                }
                dataReader.Close();
                if (salthashList != null)
                {
                    for (int i = 0; i < salthashList.Count; i++)
                    {
                        bool validUser = PasswordHash.ValidatePassword(txtPassword.Text, salthashList[i]);
                        if (validUser == true)
                        {                                    
                            Session["user_email_pk"] = usernameList[i];
                            OdbcCommand dbCommand1 = new OdbcCommand();
                            dbCommand1.Connection = dbConnection;
                            dbCommand1.CommandText = @"SELECT user_status FROM srlslogin WHERE user_email_pk = ?;";
                            dbCommand1.Parameters.AddWithValue("@user_email_pk", txtUsername.Text);
                            dbCommand1.ExecuteNonQuery();
                            OdbcDataReader dataReader1 = dbCommand1.ExecuteReader();
                            while (dataReader1.Read())
                            {
                                user_status = dataReader1["user_status"].ToString();
                                Session["userType"] = user_status;
                            }
                            Response.BufferOutput = true;
                            if (user_status == "Participant")
                            {
                                Response.Redirect("/srls/StudentUser", false);
                            }
                            else if (user_status == "Coordinator")
                            {
                                Response.Redirect("/srls/CoordinatorUser", false);
                            }
                            else if (user_status == "Instructor")
                            {
                                Response.Redirect("/srls/InstructorUser", false);
                            }
                            dataReader1.Close();
                Response.Redirect(/srls/StudentUser) - Goes to Login Page";
                        }
                        else
                        {
                            lblMessage.Text = "Invalid Username or Password! Please Try Again!";
                        }
                    }
                }
            }
            dbConnection.Close();
        }
    }
    catch (Exception ex)
    {
    }

使用会话验证用户名和密码

您应该不要将用户名和密码存储在会话中。你应该存储用户已经成功登录的"事实"。但实际上你甚至不应该自己这样做。ASP.NET提供了各种身份验证方法。请看一下http://www.asp.net/identity开始。

这不是一个很好的解决方案。不要将用户名的登录名、密码、类型等存储在会话中。一旦用户登录到您的系统,只需存储他的ID。我下一步使用:我有登录页面,我有MasterPage,我所有的web表单都继承自MasterPage。在Page_Init上的MasterPage中,我做了一些类似的事情:

string users_role = MyClass.GetUsersRoleById(Session["id"].ToString());

我在数据库中有用户的角色,所以通过ID我可以排除用户的角色。例如,每个角色都有一个文件夹。你可以做一些类似的事情:

if (String.IsNullOrEmpty(users_role)) //if null it means that user have no any role or you didn't checked for authorization first
    Response.Redirect(users_role); //redirect to role's page: e.g. Admin, User, Student, Teacher, so on.