简体   繁体   中英

Form based login and FormAuthenticationTicket still ask for credential

Am using ASP.NET MVC3 with Form based login. The login process works great. But when i closed the browser and return to the page, it goes to the login page and i need to input the credential again. How can i avoid this.

This is my code for login:

[HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.Username, model.Password))
                {
                    var userprofile = svc.GetUserByUsername(model.Username);

                    var serializeModel = new CustomPrincipalSerializeModel();
                    serializeModel.Username = userprofile.Username;
                    serializeModel.Name = userprofile.Name;
                    serializeModel.DisplayAs = userprofile.DisplayAs;
                    serializeModel.MarketId = userprofile.MarketId;

                    var serializer = new JavaScriptSerializer();
                    var userData = serializer.Serialize(serializeModel);

                    //FormsAuthentication.SetAuthCookie(model.Username, model.RememberMe);
                    var authTicket = new FormsAuthenticationTicket(
                        1,
                        model.Username,
                        DateTime.Now,
                        DateTime.Now.AddDays(30),
                        true,
                        userData);

                    var encTicket = FormsAuthentication.Encrypt(authTicket);
                    var faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                    Response.Cookies.Add(faCookie);

                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Användarnamnet eller lösenordet är felaktigt.");
                }
            }

            return View(model);
        }

You would need to use a persistent cookie (set faCookie.Expires in your case, as you're creating the cookie manually).

See this KB article for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM