Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

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");
    }
like image 320
Petr Avatar asked Feb 16 '12 14:02

Petr


1 Answers

This code creates an encrypted cookie with the username

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.web section of the web.config:

<authentication mode="Forms">
  <forms loginUrl="~/Logon" timeout="2880" />
</authentication>
like image 175
Vivien Adnot Avatar answered Oct 05 '22 12:10

Vivien Adnot