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

标签 c# asp.net-mvc-3 cookies authentication

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

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

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>

关于c# - 在 C# MVC3 中创建并读取 cookie 以确认登录用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9313189/

相关文章:

c# - 取消保存时引发 DocumentBeforeSaveEventHandler 事件

C# 异常用户未处理

c# - 在 WP8.1 项目中找不到 System.Net.Sockets

c# - 从 View 模型映射到域模型的最佳位置在哪里?

jquery - 在查看源代码中不显示隐藏字段

javascript - 我应该用 JavaScript 还是服务器端语言来设置 cookie?

c# - 统计MVC中Child的记录数

asp.net - 更改用户名 ASP.net MVC 3 成员资格

javascript - 如何安全地保存客户端的状态?

.Net Core 2.1 与 IdentityServer4 Cookie 和基于 API JWT 的同一应用程序身份验证