跟踪登录用户 [英] Keeping track of logged-in users

查看:30
本文介绍了跟踪登录用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

生成一个长随机数并将其与用户 ID 一起放入数据库和 cookie 是否足够?

Is generating a long random number and putting this with the userID in the database and cookie enough?

推荐答案

在验证用户凭据后,您可以得到如下代码:

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

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

In subsequent requests from the logged in user, HttpContext.User.Identity.Name should contain the user name of the logged in user.

问候!

这篇关于跟踪登录用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆