I have the following code setup for forms based authentication with an ms sql backend that accepts a username and password for verification. The problem that I'm running into is when I click the "log in" button after I enter credentials. I get the following
error:
Object reference not set to an instance of an object.
Exception
Details: System.NullReferenceException: Object reference not set to an instance of an object. Source Error:
Line 89:
Line 90:
Line 91: if (ValidateUser(UserName.Value, Password.Value)) Line 92: {
Line 93: FormsAuthenticationTicket tkt;
My login.aspx code is below. Any help would be greatly appreciated.
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Button b = new Button();
b.Click += new System.EventHandler(this.LoginButton_Click);
RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
}
protected 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("server=test\\SQLEXPRESS;Integrated Security=SSPI;database=pubs");
conn.Open();
// Create SqlCommand to select pwd field from users table given supplied userName.
cmd = new SqlCommand("Select Pwd from Users where uname=@userName", conn);
cmd.Parameters.Add("@userName", 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));
}
protected void LoginButton_Click(object sender, EventArgs e)
{
if (ValidateUser(UserName.Value, Password.Value))
{
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, UserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(30), RememberMe.Checked, "your custom data");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (RememberMe.Checked)
ck.Expires = tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);
string strRedirect;
strRedirect = Request["Default.aspx"];
if (strRedirect == null)
strRedirect = "Default.aspx";
Response.Redirect(strRedirect, true);
}
else
Response.Redirect("Login.aspx", true);
}
protected void UserName_TextChanged(object sender, EventArgs e)
{
}
}
Ok. Using the logincontrolID seemed to have corrected that error. But now I'm running into something different. Very odd but I'm getting a 404 error. When I enter username and pass and click "Log-in", I get 404 error saying "resource cannot be found".
Requested URL: /Account/Default.aspx
Default.aspx is not in my "Accounts" folder within my project..it's just located at the root level. Not sure why it can't find default.aspx.
Use ~ infront of the path to go to the root level. ~/Default.aspx. If you just specify the
Default.aspx in the path, it will look up for the Default.aspx page on the current directory, not in the root directory.
jseesharp
0 Points
14 Posts
forms based authentication asp 4.0
Aug 02, 2012 11:14 PM|LINK
Hi all,
I have the following code setup for forms based authentication with an ms sql backend that accepts a username and password for verification. The problem that I'm running into is when I click the "log in" button after I enter credentials. I get the following error:
Object reference not set to an instance of an object.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 89: Line 90: Line 91: if (ValidateUser(UserName.Value, Password.Value)) Line 92: { Line 93: FormsAuthenticationTicket tkt;public partial class Login : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Button b = new Button(); b.Click += new System.EventHandler(this.LoginButton_Click); RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]); } protected 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("server=test\\SQLEXPRESS;Integrated Security=SSPI;database=pubs"); conn.Open(); // Create SqlCommand to select pwd field from users table given supplied userName. cmd = new SqlCommand("Select Pwd from Users where uname=@userName", conn); cmd.Parameters.Add("@userName", 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)); } protected void LoginButton_Click(object sender, EventArgs e) { if (ValidateUser(UserName.Value, Password.Value)) { FormsAuthenticationTicket tkt; string cookiestr; HttpCookie ck; tkt = new FormsAuthenticationTicket(1, UserName.Value, DateTime.Now, DateTime.Now.AddMinutes(30), RememberMe.Checked, "your custom data"); cookiestr = FormsAuthentication.Encrypt(tkt); ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr); if (RememberMe.Checked) ck.Expires = tkt.Expiration; ck.Path = FormsAuthentication.FormsCookiePath; Response.Cookies.Add(ck); string strRedirect; strRedirect = Request["Default.aspx"]; if (strRedirect == null) strRedirect = "Default.aspx"; Response.Redirect(strRedirect, true); } else Response.Redirect("Login.aspx", true); } protected void UserName_TextChanged(object sender, EventArgs e) { } }oned_gk
All-Star
35726 Points
7295 Posts
Re: forms based authentication asp 4.0
Aug 03, 2012 01:09 AM|LINK
Try change UserName.Value, Password.Value
to UserName.Text, Password.Text
Are you using asp:login control, if yes?
change to UserLogin.UserName and UserLogin.Password
Suwandi - Non Graduate Programmer
jseesharp
0 Points
14 Posts
Re: forms based authentication asp 4.0
Aug 03, 2012 02:35 AM|LINK
I am using asp:login control. But it's not recognizing UserLogin.UserName
Ruchira
All-Star
44191 Points
7179 Posts
MVP
Re: forms based authentication asp 4.0
Aug 03, 2012 01:06 PM|LINK
Hello,
Use this
Replace the LoginControlID with the ID of your login control.
My Tech blog | My YouTube ChannelPlease 'Mark as Answer' if this post helps you.jseesharp
0 Points
14 Posts
Re: forms based authentication asp 4.0
Aug 04, 2012 06:07 AM|LINK
Ok. Using the logincontrolID seemed to have corrected that error. But now I'm running into something different. Very odd but I'm getting a 404 error. When I enter username and pass and click "Log-in", I get 404 error saying "resource cannot be found". Requested URL: /Account/Default.aspx
Default.aspx is not in my "Accounts" folder within my project..it's just located at the root level. Not sure why it can't find default.aspx.
Ruchira
All-Star
44191 Points
7179 Posts
MVP
Re: forms based authentication asp 4.0
Aug 04, 2012 07:39 AM|LINK
Use ~ infront of the path to go to the root level. ~/Default.aspx. If you just specify the Default.aspx in the path, it will look up for the Default.aspx page on the current directory, not in the root directory.
My Tech blog | My YouTube ChannelPlease 'Mark as Answer' if this post helps you.jseesharp
0 Points
14 Posts
Re: forms based authentication asp 4.0
Aug 04, 2012 04:18 PM|LINK
Ah ok. Appreciate the help. Looks like it's working now.