1

我能够验证登录页面的简单方法。如何在 3 层架构中进行身份验证?请有人向我发送 DAL、BAL 和 GUI 层中应该包含什么的代码?这是我的简单代码:

网络配置:

<authentication mode="form">
    <form loginurl="Login.aspx">
         <credential password Format="clear">
          <user name="abcd" password="1234">
        </credential>
      </authentication>
     </form>
   <authorization>
     <deny users="?">
   </authorization>

登录.aspx.cs:

   sqlconnection con=new sqlconnection("server=localhost;database=dbname;uid=;pwd=;Trusted_Connection=true");
sqldataAdapter da=new sqldataAdapter("select * from Login where UserName='"+TextBox1.Text+"' and Password='"+TextBox2.Text+"'",con);
Dataset ds=new Dataset();
da.Fill(ds);

if(ds.Tables[0].rows.Count>0)
{
   if(FormAuthentication.Authenticate("abcd","1234")
   {
        FormAuthentication.RedirectFromLoginPage(TextBox1.Text,false);
        Response.write("Logged in");
    }
    else
    {
        Response.write("Unautherised User");
    }

   Response.Redirect("welcome.aspx");
}
else
{
  Response.write("Sorry Invalid UserName or Password");
}
4

2 回答 2

1

一般来说,您至少应该有以下课程:

  • 在 DAL 中,您应该有一个用于处理数据库连接的类
  • 在 BAl 中,您应该有一个代表每个用户实例的类。这个类应该有一个名为 login() 的方法,所有的身份验证和授权都在其中进行。
  • 表示用户界面的 Web 表单。

此外,为了防止 SQL 注入,永远不要连接查询字符串。改用参数。

以下是一些示例类:

namespace DAL
{
    public class ConnectionManager
    {
        public static SqlConnection GetConnection() {
            SqlConnection cn = new SqlConnection("server=localhost;database=dbname;uid=;pwd=;Trusted_Connection=true");
            cn.Open();
            return cn;
        }
    }
}

namespace BAL
{
    public class User
    {
        public string UserName { get; set; }
        public string Password { private get; set; }

        public bool Login() {
            return Login(this.UserName, this.Password);
        }

        public bool Login(string user, string password) {
            bool success=false;
            using (SqlConnection cn = ConnectionManager.GetConnection())
            {
                string sql = "select count(*) from Login where UserName=@user and Password=@password";
                using (SqlCommand command = new SqlCommand(sql, cn))
                {
                    command.Parameters["@user"].Value = user;
                    command.Parameters["@password"].Value = password;
                    success = (int)command.ExecuteScalar() > 0;
                }
                cn.Close();
            }
            return success;
        }
    }
}
于 2009-01-28T06:50:55.110 回答
0

有点不知所措,为什么要重新发明轮子?ASP.NET Membership 提供程序为您完成这一切,如果您需要大量修改其行为,它的开源、易于阅读、理解和更改。它可以轻松地与您自己的 n 层架构集成——我们一直在这样做。

于 2009-01-28T07:33:08.940 回答