在asp.net Web应用程序中validation时遇到问题

我正在尝试validation从登录页面登录我的Web应用程序的用户。 我使用本教程作为指南,几乎完全解释了我希望做的事情,但是当我输入用户名和密码时,validation无效。 请允许我解释一下。

这是我的HTML的相关部分。 没有什么不寻常的:

该页面包含用户名和登录按钮(以及用于记住cookie的复选框,但我认为这与我的问题无关)。

这是后面的代码:

 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Web.Security; namespace MRAApplication { public partial class _1__0__0__0_LoginScreen : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { this.cmdLogin.ServerClick += new System.EventHandler(this.cmdLogin_ServerClick); } private bool ValidateUser(string userName, string passWord) { SqlConnection conn; SqlCommand cmd; string lookupPassword = null; // Check for invalid userName. // userName must not be null and must be between 1 and 15 characters. if ((null == userName) || (0 == userName.Length) || (userName.Length > 15)) { System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of userName failed."); return false; } // Check for invalid passWord. // passWord must not be null and must be between 1 and 25 characters. if ((null == passWord) || (0 == passWord.Length) || (passWord.Length > 25)) { System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of passWord failed."); return false; } try { // Consult with your SQL Server administrator for an appropriate connection // string to use to connect to your local SQL Server. conn = new SqlConnection("databaseConnect"); conn.Open(); // Create SqlCommand to select pwd field from users table given supplied userName. cmd = new SqlCommand("Select Password from Users where User=@userName", conn); cmd.Parameters.Add("@userName", System.Data.SqlDbType.VarChar, 25); cmd.Parameters["@userName"].Value = userName; // Execute command and fetch pwd field into lookupPassword string. lookupPassword = (string)cmd.ExecuteScalar(); // Cleanup command and connection objects. cmd.Dispose(); conn.Dispose(); } catch (Exception ex) { // Add error handling here for debugging. // This error message should not be sent back to the caller. System.Diagnostics.Trace.WriteLine("[ValidateUser] Exception " + ex.Message); } // If no password found, return false. if (null == lookupPassword) { // You could write failed login attempts here to event log for additional security. return false; } // Compare lookupPassword and input passWord, using a case-sensitive comparison. return (0 == string.Compare(lookupPassword, passWord, false)); } private void cmdLogin_ServerClick(object sender, System.EventArgs e) { if (ValidateUser(txtUserName.Value, txtUserPass.Value)) { FormsAuthenticationTicket tkt; string cookiestr; HttpCookie ck; tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now, DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data"); cookiestr = FormsAuthentication.Encrypt(tkt); ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr); if (chkPersistCookie.Checked) ck.Expires = tkt.Expiration; ck.Path = FormsAuthentication.FormsCookiePath; Response.Cookies.Add(ck); string strRedirect; strRedirect = Request["ReturnUrl"]; if (strRedirect == null) strRedirect = "default.aspx"; Response.Redirect(strRedirect, true); } else Response.Redirect("1.0.0.0_LoginScreen.aspx", true); } } } 

现在,我已经测试了我的连接字符串,它可以工作。 它连接到SQL Server数据库中的表,该数据库包含3列User,Password和UserRole。 现在我在表格中只有一个测试条目, 如下所示 。

但是,当我运行应用程序并将“test”输入“txtUserName”并将“password”输入“txtUserPass”并单击“submit”时,它将重定向回登录页面,这意味着它返回false为“if(ValidateUser( txtUserName.Value,txtUserPass.Value))“。

如果有人能帮助我解决这个错误,我将不胜感激。 谢谢您的帮助。 🙂

这是我第一次尝试进行身份validation,所以我不完全确定如何通过使用断点来获取返回值。

您希望在连接到SQL Server之前使用硬编码的用户名和密码进行测试。

 protected void cmdLogin_ServerClick(object sender, System.EventArgs e) { if (String.Equals(txtUserName.Value, "johndoe", StringComparison.InvariantCultureIgnoreCase) && String.Equals(txtUserPass.Value, "123456", StringComparison.InvariantCultureIgnoreCase)) { var roles = new[] {"Administrators"}; var ticket = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now, DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, string.Join(",", roles), FormsAuthentication.FormsCookiePath); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)); if (chkPersistCookie.Checked) cookie.Expires = ticket.Expiration; Response.Cookies.Add(cookie); string returnUrl = Request["ReturnUrl"]; if (returnUrl == null) returnUrl = "default.aspx"; Response.Redirect(returnUrl, true); } else Response.Redirect("1.0.0.0_LoginScreen.aspx", true); } 

如何创建主体对象

当为经过身份validation的用户请求页面时,您需要从cookie检索身份validation票证,并创建Principal对象。

 // Global.asax.cs public class Global : HttpApplication { void Application_AuthenticateRequest(object sender, EventArgs e) { HttpCookie decryptedCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (decryptedCookie != null) { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(decryptedCookie.Value); string[] roles = ticket.UserData.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries); var identity = new GenericIdentity(ticket.Name); var principal = new GenericPrincipal(identity, roles); HttpContext.Current.User = principal; Thread.CurrentPrincipal = HttpContext.Current.User; } } } 

用法

 public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { if (User.Identity.IsAuthenticated) { string username = User.Identity.Name; bool isAdministrator = User.IsInRole("Administrators"); } } }