Chris James
Chris James

Reputation: 11701

ASP-MVC Forms authentication - cookie not persisting

I have my own linq to sql database with a nice login method which gives me back a user.

I have followed the 101 examples there on the web as to how to add the cookie to the client.

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                1,
                _u.id.ToString(), 
                DateTime.Now, 
                DateTime.Now.AddDays(14), 
                true, 
                "hi", 
                FormsAuthentication.FormsCookiePath);

        string hash = FormsAuthentication.Encrypt(ticket);

        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);   

        if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;

        //Response.Cookies.Add(cookie);

        //FormsAuthentication.RedirectFromLoginPage(_u.name, _remember);
        FormsAuthentication.SetAuthCookie(_u.name, _remember);

And sure enough it does get added. But when I inspect it, its expiration says end of session, not two weeks as specified. So when a user tries to come back to the site after closing the browser, they have to log in.

Any ideas?

Upvotes: 1

Views: 3503

Answers (2)

Chris James
Chris James

Reputation: 11701

This particular error was caused because I had the browser set to erase cookies when it was closed.

Upvotes: 3

Aldo
Aldo

Reputation: 1

I have the same problem and I solve on login Page_Load
First validate User.Identity is correct
if true we have a valid user!!!.
if false remove old cookie (See this link http://forums.asp.net/t/1227365.aspx/1)
this last part is to prevent new cookie can't save correctly.

Upvotes: -1

Related Questions