0

I am trying to set my session object into cookie, so that I might not have login repeatedly. My code is like this :

[HttpPost]
        public ActionResult Login(UserAccount user , [Bind(Include = "ID,NameOfSession")] SessionSave Sessions)
        {
            using (QuestionsDBContext db = new QuestionsDBContext())
            {
                var usr = db.userAccount.Single(u => u.UserName == user.UserName && u.Password == user.Password);
                Session["UserID"] = usr.UserID.ToString();
                Session["Username"] = usr.UserName.ToString();
                if (user != null)
                {
                    bool userAutherised = true;
                    if (userAutherised)
                    {
                        //create the authentication ticket
                        var serializer = new JavaScriptSerializer();
                        string userData = serializer.Serialize(usr.UserName.ToString());

                        var authTicket = new FormsAuthenticationTicket(
                          1,
                          usr.UserName.ToString(),  //user id
                          DateTime.Now,
                          DateTime.Now.AddMinutes(20),  // expiry
                          true,  //true to remember
                          userData, //roles 
                          FormsAuthentication.FormsCookiePath
                        );
                        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
                        Response.Cookies.Add(cookie);
                    }
                    return RedirectToAction("Index");
                }
                else
                {
                    ModelState.AddModelError("", "Username or Password is wrong");
                }
            }
            return View();
        }

And my index action :

    [Authorize]
    public ActionResult Index(string sortOrder, string searchString, string currentFilter, int? page)
  {

     if (Response.Cookies["Username"] != null)
     {
              //code here
     }
  }

Somehow, this code is not working. Every time I go to index page, I have to go through login. Please someone make this clear.

Safayat Zisan
  • 33
  • 1
  • 13
  • You need to read the cookie in each request and replace the `HttpContext.User` (in the `Application_PostAuthenticateRequest()` method in `Global.asax`) - refer [ASP.NET MVC - Set custom IIdentity or IPrincipal](http://stackoverflow.com/questions/1064271/asp-net-mvc-set-custom-iidentity-or-iprincipal) for a typical example. But why are you not just using Identity? And storing passwords in plain text is dreadful practice –  Aug 25 '16 at 22:04
  • New in this, just getting comfortable. Can you show any example of it? – Safayat Zisan Aug 25 '16 at 22:10
  • I gave you a link in my previous comment. –  Aug 25 '16 at 22:11

0 Answers0