7

I'm creating an ASP.NET MVC application. Due to the complex authorization, I'm trying to build my own login system. I'm not using ASP.NET membership providers, and related classes)

I'm able to create new accounts in the database with hashed passwords.

How do I keep track that a user is logged in?

Is generating a long random number and putting this with the userID in the database and cookie enough?

p.campbell
  • 98,673
  • 67
  • 256
  • 322
  • 2
    If you want to customize ASP.NET authentication, then you *should* use a membership provider, even if you have to write it all yourself. http://blogs.teamb.com/craigstuntz/2009/09/09/38390/ – Craig Stuntz Apr 22 '10 at 15:38

1 Answers1

7

After validating the user credentials you can have a code like:

public void SignIn(string userName, bool createPersistentCookie)
{
    int timeout = createPersistentCookie ? 43200 : 30; //43200 = 1 month
    var ticket = new FormsAuthenticationTicket(userName, createPersistentCookie, timeout);
    string encrypted = FormsAuthentication.Encrypt(ticket);
    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
    cookie.Expires = System.DateTime.Now.AddMinutes(timeout);
    HttpContext.Current.Response.Cookies.Add(cookie);
}

So your code can be like this:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LogOn(string userName, string passwd, bool rememberMe)
{
    //ValidateLogOn is your code for validating user credentials
    if (!ValidateLogOn(userName, passwd))
    {
        //Show error message, invalid login, etc.
        //return View(someViewModelHere);
    }

    SignIn(userName, rememberMe);

    return RedirectToAction("Home", "Index");
}

In subsequent requests from the logged in user, HttpContext.User.Identity.Name should contain the user name of the logged in user.

Regards!

uvita
  • 4,124
  • 1
  • 27
  • 23
  • @HelpASisterOut FormsAuthentication.SignOut();FormsAuthentication.RedirectToLoginPage() – uvita Jul 04 '14 at 14:08