I searched for a lot of posts here about user user authentication, but no one touched on all my problems.
I am new to ASP.NET MVC and used traditional ASP.NET (WebForms) but don’t know how to create a login / authentication mechanism for a user using ASP.NET MVC.
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
string userName = Login1.UserName;
string password = Login1.Password;
bool rememberUserName = Login1.RememberMeSet;
if (validateuser(userName, password))
{
Database db = DatabaseFactory.CreateDatabase();
System.Data.Common.DbCommand cmd = db.GetStoredProcCommand("sp_RolesForUser");
db.AddInParameter(cmd, "@Uid", System.Data.DbType.String, 15);
db.SetParameterValue(cmd, "@Uid", Login1.UserName);
System.Data.IDataReader reader = db.ExecuteReader(cmd);
System.Collections.ArrayList roleList = new System.Collections.ArrayList();
if (reader.Read())
{
roleList.Add(reader[0]);
string myRoles = (string)roleList[0];
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now,
DateTime.Now.AddMinutes(20), rememberUserName, myRoles, FormsAuthentication.FormsCookiePath);
string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);
Response.Cookies.Add(cookie);
if (HttpContext.Current.User.IsInRole("Administrators"))
{
Response.Redirect("~/Admin/Default.aspx");
}
else
{
string returnURL = "~/Default.aspx";
Response.Redirect(returnURL);
}
}
}
}
protected bool validateuser(string UserName, string Password)
{
Boolean boolReturnValue = false;
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetStoredProcCommand("sp_ValidateUser");
db.AddInParameter(cmd, "@userid", DbType.String, 15);
db.SetParameterValue(cmd, "@userid", Login1.UserName);
db.AddInParameter(cmd, "@password", DbType.String, 15);
db.SetParameterValue(cmd, "@password", Login1.Password);
db.AddOutParameter(cmd, "@retval", DbType.Int16, 2);
db.ExecuteNonQuery(cmd);
int theStatus = (System.Int16)db.GetParameterValue(cmd, "@retval");
if (theStatus > 0)
boolReturnValue = true;
else
boolReturnValue = false;
return boolReturnValue;
}
I really don't know how to translate this ASP.NET code into MVC-esque architecture; and I still don't understand how to implement authentication in ASP.NET MVC.
What do I need to do? How to implement the above code in ASP.NET MVC? What am I missing in this code?