I have this application that uses custom methods to register and loggin users using FormsAuthentication. The server where this is hosted has a policy of restarting the sessions every 15 minutes and when that happens all my users get logged out. The code to loggin a user is:
var user = this.accountRepo.GetUser(id);
// Create the forms authentication cookie
var cookieValue = user.name;
HttpCookie cookie = FormsAuthentication.GetAuthCookie(cookieValue, true);
// Dercrypt the cookie
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
// Create a new ticket with the desired data
FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket
(
ticket.Version,
ticket.Name,
ticket.IssueDate,
DateTime.Now.AddYears(1),
true,
user.Authentication
);
// Update the cookies value
cookie.Value = FormsAuthentication.Encrypt(newTicket);
Response.Cookies.Set(cookie);
accountRepo.Login(user);
With the Forms cookie created and with my Authentication data, which is basically the users hashed password, I then use the following logic to display the Login button or the username:
@{
var accountRepo = new AccountRepository();
var user = accountRepo.GetCurrentUser();
}
@if(user != null && user.LoggedIn) {
<div>@Html.ActionLink(Context.User.Identity.Name + " - Logout", "LogOff", "Account", null, new { @class = "logout_link" })</div>
}
else
{
@Html.ActionLink("Login", "Login", "Account", new { returnUrl = Request.Url.AbsoluteUri }, new { @class = "login_link" })
}
And that “GetCurrentUser()” method is:
var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
return db.Users.SingleOrDefault(u => u.Authentications.Equals(ticket.UserData, StringComparison.CurrentCultureIgnoreCase));
}
return null;
Am I missing something here? I believe that with this code It should matter if the session restarts, my users should stay logged in.
Thanks in advance.
It’s just as Mystere Man said. The cookie name was getting re-generated every time the session rebooted, so the app was looking for the cookie with a different name than what it had before.
For the peace of mind of all of you that helped me, and for the developer that will support this app in the future, I refactored it so its not that “evil” anymore 😛