user323395
user323395

Reputation:

Keeping track of logged-in users

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?

Upvotes: 7

Views: 6167

Answers (1)

uvita
uvita

Reputation: 4124

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!

Upvotes: 7

Related Questions