跟踪登录用户

时间:2010-04-22 15:26:03

标签: asp.net-mvc authorization

我正在创建一个ASP.NET MVC应用程序。由于复杂的授权,我正在尝试构建自己的登录系统。我没有使用ASP.NET成员资格提供程序和相关的类)

我可以使用散列密码在数据库中创建新帐户。

如何跟踪用户是否已登录?

生成一个长的随机数并将其与userID放在数据库和cookie中吗?

1 个答案:

答案 0 :(得分:7)

验证用户凭据后,您可以使用以下代码:

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);
}

所以你的代码可以是这样的:

[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");
}

在登录用户的后续请求中,HttpContext.User.Identity.Name应包含登录用户的用户名。

问候!