Keeping track of logged-in users

雨燕双飞 提交于 2019-11-26 21:05:13

问题


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?


回答1:


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!



来源:https://stackoverflow.com/questions/2692144/keeping-track-of-logged-in-users

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!