创建并读取cookie以确认C#MVC3中的登录用户

创建并读取cookie以确认C#MVC3中的登录用户,c#,asp.net-mvc-3,cookies,login,C#,Asp.net Mvc 3,Cookies,Login,我对MVC3中的cookies有问题。我想创建一个cookie,它存储用户是否登录的信息。我以前从未使用过cookies,也不知道什么是正确的方法,而且我对MVC3还是新手。 请问,有人能告诉我,我用来存储cookie的方法是否正确,或者是否存在安全风险(密码是加密的)? 如果cookie设置正确,我如何在其他视图中使用它们来检查用户是否已登录并为其设置会话? 如果我使用的登录用户的方法是错误的,请告诉我 public ActionResult Login(string name, string

我对MVC3中的cookies有问题。我想创建一个cookie,它存储用户是否登录的信息。我以前从未使用过cookies,也不知道什么是正确的方法,而且我对MVC3还是新手。 请问,有人能告诉我,我用来存储cookie的方法是否正确,或者是否存在安全风险(密码是加密的)? 如果cookie设置正确,我如何在其他视图中使用它们来检查用户是否已登录并为其设置会话? 如果我使用的登录用户的方法是错误的,请告诉我

public ActionResult Login(string name, string hash, string keepLogged)
    {
        if (string.IsNullOrWhiteSpace(hash))
        {
            Random random = new Random();
            byte[] randomData = new byte[sizeof(long)];
            random.NextBytes(randomData);
            string newNonce = BitConverter.ToUInt64(randomData, 0).ToString("X16");
            Session["Nonce"] = newNonce;
            return View(model: newNonce);
        }

        User user = model.Users.Where(x => x.Name == name).FirstOrDefault();
        string nonce = Session["Nonce"] as string;
        if (user == null || string.IsNullOrWhiteSpace(nonce))
        {
            return RedirectToAction("Login", "Users");
        }

        string computedHash;
        using (SHA256 sha256 = SHA256.Create())
        {
            byte[] hashInput = Encoding.ASCII.GetBytes(user.Password + nonce);
            byte[] hashData = sha256.ComputeHash(hashInput);
            StringBuilder stringBuilder = new StringBuilder();
            foreach (byte value in hashData)
            {
                stringBuilder.AppendFormat("{0:X2}", value);
            }
            computedHash = stringBuilder.ToString();
        }

        if (computedHash.ToLower() == hash.ToLower())
        {                
            Session["IsAdmin"] = user.IsAdmin == 1;
            Session["IDUser"] = user.IDUser;

            ViewBag.IdUser = IDUser;
            ViewBag.IsAdmin = IsAdmin;
            ViewBag.UserName = model.Users.Where(x => x.IDUser == IDUser).First().Name;

            if (keepLogged == "keepLogged")
            {
                //Set user's cookies - is this correct?
                Response.Cookies.Add(new HttpCookie("UserCookie", user.IDUser.ToString()));
                Response.Cookies.Add(new HttpCookie("PassCookie", user.Password.ToString()));
            }
        }
        return RedirectToAction("Index", "Posts");
    }

不,您不想将用户密码存储在自定义cookie中。研究授权的形式。它为你做了所有的甜点。您可以将表单验证cookie设置为在用户的计算机上保持,以便他们“保持登录状态”。

此代码使用用户名创建加密cookie

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
    1,
    user.UserName,
    DateTime.Now,
    DateTime.Now.AddMinutes(10),
    false,
    null);

string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

this.Response.Cookies.Add(cookie);
要启用表单身份验证,请将以下内容添加到web.config的
system.web
部分:

<authentication mode="Forms">
  <forms loginUrl="~/Logon" timeout="2880" />
</authentication>

这是我的简化版本,您可以使用cookies 请记住用户名

   /// <summary>
   /// Account controller.
   /// </summary>

      public ActionResult LogOn()
      {
         LogOnModel logOnModel = new LogOnModel();

         HttpCookie existingCookie = Request.Cookies["userName"];
         if (existingCookie != null)
         {
            logOnModel.UserName = existingCookie.Value;
         }

         return View(logOnModel);
      }


      public ActionResult LogOn(LogOnModel model, string returnUrl)
      {
         if (model.RememberMe)
         {
            // check if cookie exists and if yes update
            HttpCookie existingCookie = Request.Cookies["userName"];
            if (existingCookie != null)
            {
               // force to expire it
               existingCookie.Value = model.UserName;
               existingCookie.Expires = DateTime.Now.AddHours(-20);
            }

            // create a cookie
            HttpCookie newCookie = new HttpCookie("userName", model.UserName);
            newCookie.Expires = DateTime.Today.AddMonths(12);
            Response.Cookies.Add(newCookie);
         }


         // If we got this far, something failed, redisplay form
         return View(model);
      }
//
///账户控制员。
/// 
公共操作结果登录()
{
LogOnModel LogOnModel=新LogOnModel();
HttpCookie existingCookie=Request.Cookies[“用户名”];
if(existingCookie!=null)
{
logOnModel.UserName=existingCookie.Value;
}
返回视图(logOnModel);
}
公共操作结果登录(LogOnModel模型,字符串返回URL)
{
if(型号记忆)
{
//检查cookie是否存在,如果存在,则更新
HttpCookie existingCookie=Request.Cookies[“用户名”];
if(existingCookie!=null)
{
//强迫它过期
existingCookie.Value=model.UserName;
existingCookie.Expires=DateTime.Now.AddHours(-20);
}
//创建一个cookie
HttpCookie newCookie=新的HttpCookie(“用户名”,model.userName);
newCookie.Expires=DateTime.Today.AddMonths(12);
Response.Cookies.Add(newCookie);
}
//如果我们走到这一步,有些东西失败了,重新显示形式
返回视图(模型);
}

也许您想使用表单身份验证?如果我使用表单身份验证,这意味着我必须更改整个登录方法?您可以保留该方法,但大多数代码可以按照@Vivien Adnot answer进行替换谢谢这个示例,我将尝试此方法,您能告诉我如何用其他方法读取此cookie吗?+1,这将是处理您的身份验证的正确方法。您可以检查用户是否使用以下代码进行了身份验证:if(HttpContext.Current.user.Identity.IsAuthenticated)我必须使用您的代码,而不是创建会话和ViewBags,然后在视图中,而不是使用ViewBags,我将检查是否已验证?我为我愚蠢的问题感到抱歉,但是MVC对我来说真的是新东西,我不清楚每件事到底是如何工作的……所以我让它工作了,但是当我重新启动浏览器时,我必须再次登录。知道我做错了什么吗?虽然你已经证明你可以把用户名保存在cookie中,但你在重复这个过程。表单验证应该在这个场景中使用。@Jesse:这是为了演示如何使用cookie