C# MVC 5 The ticket cookie is cleared when the form authentication signs out

1.1k views Asked by At

I need to access the cookies to get the user and password and then set them in the text boxes of the Login view because in that view is checked "Remember me".

LogOff method

public ActionResult LogOff()
{
    //Session.Abandon();
    // sign out.
    FormsAuthentication.SignOut();
    return RedirectToAction("Index", "Login");
}

Initialization of sessions and cookies after a successful login.

private void InitializeSessionVariables(AgentDTO user)
{
    // SessionModel.AgentId = user.ID;
    Response.Cookies.Clear();
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,user.MobilePhone,DateTime.Now,DateTime.Now.AddDays(30),true,"",FormsAuthentication.FormsCookiePath);
    // Encrypt the ticket.
    string encryptedTicket = FormsAuthentication.Encrypt(ticket);
    // Create the cookie.
    HttpCookie authenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); // Name of auth cookie (it's the name specified in web.config) // Hashed ticket
    authenticationCookie.Expires = DateTime.Now.AddDays(365);
    // Add the cookie to the list for outbound response
    Response.Cookies.Add(authenticationCookie);
}

Action Result of Login View I have problem when I first log out and then try to access the cookie but it returns null because I run "FormsAuthentication.SignOut ();"

public ActionResult Index(LogonDTO model, string message = null, string reason = null)
{
    if (SessionModel.AgentMobilePhone != null) return RedirectToAction("Index", "Home");
    if (reason != null) message = "Su sessión ha expirado. Vuelva a loguearse.";
    ViewBag.Message = message;

    if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
    {
        HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
        FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
        model.Username = authTicket.Name;
        //model.Password = "in progress..."
    }
    return View(model);
}
1

There are 1 answers

3
Vijay Thorat On

You can use javascript to store User information if he click on Remember Me checkbox

use

localStorage.setItem("UserName", "Smith");

to set values

and on Login page on document ready event of Jquery write below code

var UserName = localStorage.getItem("UserName");
if (UserName) $("#username").val(UserName);

Hope this will solve your problem.