I am building an ASP.NET MVC 5 application and, for reasons which are irrelevant at this point, I am attempting to build my own means of authenticating users. I'm still very new to programming, especially to this sort of thing, and I realize that what looks fine to me may be full of problems. Thus, I present my code, simplified for demonstration purposes, for review.
The Contact
model:
public class Contact
{
[Key]
public int ContactID { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string Password { get; set; }
}
The Login
action:
[HttpPost]
public ActionResult Login(Contact contact)
{
bool validEmail = db.Contacts.Any(x => x.Email == contact.Email);
if (!validEmail)
{
return RedirectToAction("Login");
}
string password = db.Contacts.Where(x => x.Email == loginForm.Email)
.Select(x => x.Password)
.Single();
bool passwordMatches = Crypto.VerifyHashedPassword(password, loginForm.Password);
if (!passwordMatches)
{
return RedirectToAction("Login");
}
string authId = Guid.NewGuid().ToString();
Session["AuthID"] = authId;
var cookie = new HttpCookie("AuthID");
cookie.Value = authId;
Response.Cookies.Add(cookie);
return RedirectToAction("Private");
}
Actions that require the user to be logged in will look like this:
public ActionResult Private()
{
try
{
if (Request.Cookies["AuthID"].Value == Session["AuthID"].ToString())
{
return View();
}
else
{
return RedirectToAction("Index");
}
}
catch
{
return RedirectToAction("Index");
}
}
I feel like this is probably really bad. However, every "solution" I find seems overly complex and/or lacking any documentation that would allow me to make sense of it.
All I want is to make sure the user has a valid username and password before they place an order or update their account. Will my code do that securely?
Login
controller is doing too many things: connecting to the database, verifying the password, and creating the session? Can you think about 'S' from the SOLID principle? \$\endgroup\$