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

Pet*_*etr 5 c# cookies login asp.net-mvc-3

我在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");
    }
Run Code Online (Sandbox Code Playgroud)

Viv*_*not 17

此代码使用用户名创建加密的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);
Run Code Online (Sandbox Code Playgroud)

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

<authentication mode="Forms">
  <forms loginUrl="~/Logon" timeout="2880" />
</authentication>
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用以下代码检查用户是否已通过身份验证:if(HttpContext.Current.User.Identity.IsAuthenticated) (3认同)