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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9313189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:51:01  来源:igfitidea点击:

Create and read cookie to confirm logged in user in C# MVC3

c#asp.net-mvc-3cookieslogin

提问by Petr

I have a problem with cookies in MVC3. I want to create a cookie, that stores informations whether the user is logged in. I have never used cookies before and don't know what is the proper way to do it and I am new to MVC3. Please, can somebody tell me if the approach I used to store cookie is proper or if there is some security risk (the password is encrypted)? If the cookies are set correctly, how can I use them in other views to check if the user is logged in and set the session for him? If the approach I use to log in user is wrong, just tell me.

我在 MVC3 中遇到了 cookie 问题。我想创建一个 cookie,存储用户是否登录的信息。我以前从未使用过 cookie,不知道正确的做法是什么,我是 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");
    }

采纳答案by Vivien Adnot

This code creates an encrypted cookie with the username

此代码使用用户名创建一个加密的 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);

To enable forms authentication add the following to the system.websection of the web.config:

要启用表单身份验证,请将以下内容添加到system.webweb.config 部分:

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

回答by Ryand.Johnson

No,You do not want to store the user's password in a custom cookie. Look into Forms Authetication. It does all the cookie work for you. You can set that forms authetication cookie to persist on the user's computer so that they "stay logged in".

不,您不想将用户的密码存储在自定义 cookie 中。查看表单身份验证。它为您完成所有 cookie 工作。您可以将表单身份验证 cookie 设置为保留在用户的计算机上,以便他们“保持登录状态”。

回答by cpoDesign

here is my simlified version how you can work with cookies for remember user name

这是我的简化版本如何使用 cookie 来记住用户名

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