2012-02-16 84 views
5

Tôi gặp sự cố với cookie trong MVC3. Tôi muốn tạo một cookie, lưu trữ thông tin cho dù người dùng đã đăng nhập. Tôi chưa bao giờ sử dụng cookie trước đây và không biết cách thích hợp để làm điều đó là gì và tôi mới sử dụng MVC3. Xin vui lòng, ai đó có thể cho tôi biết nếu cách tiếp cận tôi sử dụng để lưu trữ cookie là đúng hoặc nếu có một số nguy cơ bảo mật (mật khẩu được mã hóa)? Nếu các cookie được đặt chính xác, làm cách nào tôi có thể sử dụng chúng trong các chế độ xem khác để kiểm tra xem người dùng có đăng nhập hay không và đặt phiên cho anh ta? Nếu cách tiếp cận tôi sử dụng để đăng nhập người dùng là sai, chỉ cần cho tôi biết.Tạo và đọc cookie để xác nhận người dùng đã đăng nhập trong C# MVC3

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"); 
    } 
+5

có lẽ bạn muốn sử dụng xác thực biểu mẫu? –

Trả lời

17

Mã này tạo ra một cookie được mã hóa với tên người dùng

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

Để kích hoạt các hình thức xác thực thêm dòng sau vào phần system.web của web.config:

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

Cảm ơn ví dụ này, tôi sẽ thử điều này, bạn có thể cho tôi biết làm cách nào để đọc cookie này bằng các phương pháp khác không? – Petr

+0

+1, đây sẽ là cách thích hợp để xử lý xác thực của bạn. – Jesse

+3

Bạn có thể kiểm tra xem người dùng có được xác thực bằng mã này không: if (HttpContext.Current.User.Identity.IsAuthenticated) –

4

Không, Bạn không muốn lưu trữ mật khẩu của người dùng trong cookie tùy chỉnh. Nhìn vào biểu mẫu Authetication. Nó làm tất cả các cookie làm việc cho bạn. Bạn có thể đặt các biểu mẫu cookie xác thực đó tồn tại trên máy tính của người dùng để chúng "duy trì trạng thái đăng nhập".

+0

Nếu tôi sử dụng xác thực biểu mẫu, điều đó có nghĩa là tôi phải thay đổi toàn bộ phương thức đăng nhập? – Petr

+0

Bạn có thể giữ nguyên phương pháp, nhưng phần lớn mã chỉ đơn giản có thể được thay thế theo câu trả lời @Vivien Adnot – Jesse

4

đây là phiên bản simlified của tôi như thế nào bạn có thể làm việc với cookie để ghi nhớ tên người dùng

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

Trong khi bạn đã chứng minh rằng bạn có thể lưu tên người dùng trong cookie, bạn đang lặp lại bánh xe. Biểu mẫu Auth nên được sử dụng trong trường hợp này. – Jesse

+1

@Jesse: đây là minh họa cách sử dụng cookie – cpoDesign

Các vấn đề liên quan