I'm trying to create a persistent cookie (not using the built-in auth) when the user logs in.
The only way I could figure to do this was to create a cookie with an expiry date set to DateTime.Now.AddYears(1)
Since I want to allow the user to log out, I do have a logout button on the layout for every page behind the login form.
This logout button looks like this:
<li>@Html.ActionLink("Log Out", "Logout", "Home")</li>
The confusing thing to me is that this code doesn't get rid of the cookie from the browser. it takes me back to the login form, but I can still easily navigate back to the protected pages and it'll still remember who I am based on my previous login.
Here's my code:
[AllowAnonymous]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Login(User model)
{
try
{
DoLogin(model.EmailAddress, model.Password);
return Json(new
{
Message = "Success",
IsOK = bool.TrueString
});
}
catch (Exception ex)
{
SendError("/", ex);
return ReportError(ex, "USER LOGIN");
}
}
private void DoLogin(string EmailAddress, string Password)
{
var user = db.Users.Include("UserRole").FirstOrDefault(x => x.EmailAddress == EmailAddress);
if (Hashing.ValidatePassword(Password, user.Password))
generateCookie(user);
}
private void generateCookie(Models.User u)
{
HttpCookie userCookie = new HttpCookie("Ortund");
userCookie.Values["userid"] = Convert.ToString(u.Id);
userCookie.Values["fname"] = u.FirstName;
userCookie.Values["lname"] = u.LastName;
userCookie.Values["role"] = u.UserRole.RoleName;
userCookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(userCookie);
}
So why isn't this clearing my cookie?
EDIT
So now I've modified my code (see below) as per suggestions in the answers on the question.
I added in a Logout Action on my controller and it does this:
public ActionResult Logout()
{
Session.Clear();
HttpCookie userCookie = new HttpCookie("Ortund");
userCookie.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(userCookie);
return View("Index");
}
While my login still appears to work okay, the Request Cookie
isn't updating with the new login details. Here's what it looks like after I do the login:
Request.Cookies["Ortund"] {System.Web.HttpCookie} System.Web.HttpCookie
Domain null string
Expires {0001-01-01 12:00:00 AM} System.DateTime
HasKeys true bool
HttpOnly false bool
Name "Ortund" string
Path "/" string
Secure false bool
Shareable false bool