我正在创建一个 ASP.NET MVC 应用程序。由于复杂的授权,我正在尝试构建自己的登录系统。我没有使用 ASP.NET 成员资格提供程序和相关类)
我可以使用散列密码在数据库中创建新帐户。
如何跟踪用户已登录?
生成一个长随机数并将其与用户 ID 放在数据库和 cookie 中是否足够?
最佳答案
验证用户凭据后,您可以拥有如下代码:
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 应包含登录用户的用户名。
问候!
关于asp.net-mvc - 跟踪登录用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2692144/