itmanir
itmanir

Reputation: 177

Cookie is not delete in mvc(c#)

I want to make login and logOut functions in mvc4. In login func, if login cookie exist and not empty, user is in signIn mode, else redirect to login page. In logOut func, all cookies and sessions clear and redirect to login func, but in login func login cookie exist!

Login:

public ActionResult Login()
        {
            if (Request.Cookies["login"] != null)
            {
                string login = Request.Cookies["login"].Value.ToString();                

                if (login != string.Empty)
                {
                    //Get from service
                    Service srv = new Service();
                    UserItem userItem = srv.getUserItem(login);                    
                    srv.Close();

                    Session.Timeout = 30;
                    Session["login "] = login;
                    Session["userId"] = userItem.No;
                    Session["firstName"] = userItem.FirstName;
                    Session["lastName"] = userItem.LastName;
                    string loginName = userItem.LoginName;                    

                    FormsAuthentication.SetAuthCookie(loginName, false);

                    return Redirect(“Index”);
                }
                else 
                {
                    Return redirect("http://mySite/SignIn.aspx");
                }
            }
            else
            {
                Return redirect("http://mySite/SignIn.aspx");                    
            }
        }

LogOut:

public ActionResult LogOut()
        {
            string login = Session["login"].ToString();

            Request.Cookies["login"].Value = "";
            Response.Cookies["login"].Value = "";

            FormsAuthentication.SignOut();
            HttpCookie c = Request.Cookies[FormsAuthentication.FormsCookieName];
            c.Expires = DateTime.Now.AddDays(-1);

            Session.Clear();
            Request.Cookies.Clear();
            Response.Cookies.Clear();

            //FormsAuthentication.Initialize();
            //string strRole = String.Empty;
            //FormsAuthenticationTicket fat = new FormsAuthenticationTicket(1, "", DateTime.Now, DateTime.Now.AddMinutes(-30), false, strRole, FormsAuthentication.FormsCookiePath);
            //Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(fat)));

            //Session.Abandon();

            //// clear authentication cookie
            //HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
            //cookie1.Expires = DateTime.Now.AddYears(-1);
            //Response.Cookies.Add(cookie1);

            //// clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
            //HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
            //cookie2.Expires = DateTime.Now.AddYears(-1);
            //Response.Cookies.Add(cookie2);

            //FormsAuthentication.RedirectToLoginPage();               

            return RedirectToAction("Login", "Usr");
        }

Web.config:

<authentication mode="Forms">
      <forms loginUrl="~/Usr/Login" timeout="30" />
    </authentication>

I am trying comment codes, even comment this line:

FormsAuthentication.SignOut();

Even I set the cookie value to "", but in login page this cookie have old value! And trying several ways to clear cookie like set expire to one day later. But…

Thanks

Upvotes: 2

Views: 16105

Answers (3)

itmanir
itmanir

Reputation: 177

Thank you AndreyMaybe, Ant P

This code work:

Response.Cookies.Clear();

FormsAuthentication.SignOut();     

HttpCookie c = new HttpCookie("login");
c.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(c);

Session.Clear();

Upvotes: 0

David Colwell
David Colwell

Reputation: 2590

There is a much easier way to determine if the user is authenticated, as per this post How to check if user is authorized inside Action

After you have called the FormsAuthentication.SetAuthCookie(), you can call User.Identity.IsAuthenticated. No need to set your own cookies.

If you do it like this, the FormsAuthentication.SignOut() will destroy the correct cookie

Upvotes: 1

Ant P
Ant P

Reputation: 25221

You're changing the value of the cookie, but you're not adding it to the response again!

FormsAuthentication.SignOut();
HttpCookie c = Request.Cookies[FormsAuthentication.FormsCookieName];
c.Expires = DateTime.Now.AddDays(-1);

// Update the amended cookie!
Response.Cookies.Set(c)

Session.Clear();
/* Get rid of this, it will break the above by clearing
 * the cookie collection that you've just updated. */
// Request.Cookies.Clear();
// Response.Cookies.Clear();

Upvotes: 6

Related Questions