Forms authentication cookie handling question (C#)



Hi everyone,

I'm creating some Forms authentication for a section of my website. The site
is for musicians, and each band or musician has an "account". All i want to
do is prevent them form accessing the account manager without logging in.

I've got that working with the <location> element of web.config,
<authentication> section and a Login control. I'm using SHA1 to store the
password, and passing the hashed password to check against the database.

I think I've even got cookie storage working, although the site never lets
me be "remembered" even when I tick the box.

I've stored the email address of the user in the UserData element of the
authentication ticket, as I don't need roles. But I'm unsure if this is right
(what should I store here If I dont need roles), and think that might be why
it's not working...

Here's the Login Button code...

protected void loginMyMusos_Authenticate(object sender,
AuthenticateEventArgs e)
{
// Initialize FormsAuthentication (reads the configuration and gets
// the cookie values and encryption keys for the given application)
FormsAuthentication.Initialize();

// Create connection and command objects
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
ConfigurationManager.ConnectionStrings["musoswireDBConnectionString1"].ToString();
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT AccountID FROM Accounts WHERE
Email=@username " +
"AND Password=@password"; // (this should really be a stored
procedure, shown here for simplicity)

// Fill our parameters
cmd.Parameters.Add("@username", SqlDbType.NVarChar, 64).Value =
loginMyMusos.UserName;
cmd.Parameters.Add("@password", SqlDbType.NVarChar, 64).Value =
FormsAuthentication.HashPasswordForStoringInConfigFile(loginMyMusos.Password,
"sha1");

//FormsAuthentication.HashPasswordForStoringInConfigFile(loginMyMusos.Password, "sha1");
// you can use the above method for encrypting passwords to be
stored in the database
//Response.Write(cmd.Parameters["@password"].ToString());
// Execute the command

SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
// Create a new ticket used for authentication
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // Ticket version
loginMyMusos.UserName, // Username to be associated with this
ticket
DateTime.Now, // Date/time issued
DateTime.Now.AddHours(1), // Date/time to expire
loginMyMusos.RememberMeSet, // "true" for a persistent user
cookie (could be a checkbox on form)
reader[0].ToString(), // User-data (the roles from this user
record in our database)
FormsAuthentication.FormsCookiePath); // Path cookie is valid for

// Hash the cookie for transport over the wire
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName, // Name of auth cookie
(it's the name specified in web.config)
hash); // Hashed ticket

// Add the cookie to the list for outbound response
Response.Cookies.Add(cookie);

// Redirect to requested URL, or homepage if no previous page
requested
string returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl == null) returnUrl =
"/mymusos/account/default.aspx";

// Don't call the FormsAuthentication.RedirectFromLoginPage
here, since it could
// replace the custom authentication ticket we just added...
Response.Redirect(returnUrl);
}
else
{
// Username and or password not found in our database...
loginMyMusos.FailureText = "Username / password incorrect.
Please login again.";
}
// (normally you'd put all this db stuff in a try / catch / finally
block)
reader.Close();
conn.Close();
cmd.Dispose();
}

and here is the AuthenticateRequest function from global.asax...

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
// Extract the forms authentication cookie
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];

if (null == authCookie)
{
// There is no authentication cookie.
return;
}

FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch (Exception ex)
{
// Log exception details (omitted for simplicity)
return;
}

if (null == authTicket)
{
// Cookie failed to decrypt.
return;
}

// When the ticket was created, the UserData property was assigned a
// pipe delimited string of role names.
string[] roles = authTicket.UserData.Split(new char[] { '|' });


// Create an Identity object
FormsIdentity id = new FormsIdentity(authTicket);

// This principal will flow throughout the request.
System.Security.Principal.GenericPrincipal principal = new
System.Security.Principal.GenericPrincipal(id, roles);
// Attach the new principal object to the current HttpContext object
Context.User = principal;
}
Can someone take a look and point out what I'm doing wrong?!!? I'm new to
Forms auth!

Thanks,


Dan
.


Loading