保持登录用户的轨道 [英] Keeping track of logged-in users

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

问题描述

我创建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在数据库和饼干足够?

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

推荐答案

验证用户凭据后,你可以有一个code,如:

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

所以你的code可以是这样的:

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天全站免登陆