views:

169

answers:

1

I'm creating a ASP MVC application. And because of the complex authorization i'm trying to build my own login system. (So i'm not using asp membership providers, and related classes).

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

But 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?

Sorry for my rather bad english! Ty in advance :)

+3  A: 

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
Wow thanks alot man! Very usefull!!!
wh0emPah