asp.net-mvc - 跟踪登录用户

标签 asp.net-mvc authorization

我正在创建一个 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/

相关文章:

asp.net - 在asp.net mvc2中如何打开新窗口并下载文件

ruby-on-rails - 设计/Rails - 如何只允许管理员为其他人创建帐户?

authentication - 如何跨多个微服务提供用户身份?

graphql - 如何测试 Hasura 授权?

security - firebase 中 protected 内容的正确授权规则

c# - 格式化 HTML 表单布局

mysql - 应用迁移 '..._RenameColumnAlert_Identifier' 。 System.NotImplementedException : The method or operation is not implemented

asp.net-mvc - 限制用户使用 asp.net mvc 中的管理部分

c# - 如何从 ClaimsPrincipal 中删除 ClaimsIdentity

asp.net-mvc - 如何将 RouteValueDictionary 添加到 T4MVC ActionLink