我对 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/