Asp.net persistent login cookie expires randomly - c#

I'm trying to implement a login form with the remember me functionality in ASP.NET 4.0.
I've set the timeout option in the web.config to 1 year (525600), but after a random amount of time after I logon, I always get logged off.
The cookie is created correctly, I can see it in the browser with the right expire value (september 2014), but it seems that this cookie after some time is not readed by the ASP.NET environment anymore.
I tryed to login with:
FormsAuthentication.RedirectFromLoginPage(username, true);
or:
FormsAuthentication.SetAuthCookie(username, true);
Response.Redirect("/");
or with this custom code:
DateTime expiryDate = DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, userid, DateTime.Now, expiryDate, true, String.Empty);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
authenticationCookie.Expires = ticket.Expiration;
Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
Response.Cookies.Add(authenticationCookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(username, false));
But the result is always the same. The cookie is present, but after some time it's not used anymore.
The Web.config is like so:
<authentication mode="Forms">
<forms loginUrl="/login" defaultUrl="/" name="appName" path="/" timeout="525600" slidingExpiration="true"/>
</authentication>
The odd thing is that in my local test environment (ASP.NET Development server) things works correctly. Only in the production environment it is not working!

#Felipe Garcia: I don't know if I'm using a load balancer, I'm on a public server. But I tryed to config the MachineKey as you said (using the generator here) and now it seems to work correctly!
Thank you!

Related

Asp.Net Form Authentication : Session change to other recently login user session automatically

My asp.net webform application Hosted on IIS8 in intranet with Form authentication. For a single user at a time, this application is working completely fine. But problem is with more than one user. Taking example of two users to explain the problem.
The problem is when UserA login to the application and perform any navigation. At the same time other UserB login to the application and perform any navigation. Now at the same time if userA refresh there browser then UserA realize that his session converted into the UserB session(loggedin recently), which is strange and odd as well. Both user on different machine/system and location. I don't know what should i call this problem.
I think there is some point that i am missing in my configuration/code. My code and configuration given below.
In C#, after validating the user credentials, i am using below piece of code
FormsAuthentication.RedirectFromLoginPage(UserId, false);
In Web.config
<sessionState mode="InProc" timeout="20"></sessionState>
<authentication mode="Forms">
<forms name=".ASPXFORMSAUTH" loginUrl="LogIn.aspx" cookieless="UseCookies" requireSSL="false" path="/" timeout="30" defaultUrl="Welcome.aspx" protection="All"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
I am accessing my Hosted application with the following URL:
http://SERVER_NAME:8020/LogIn.aspx
Please suggest, what i am doing wrong or missing any important step.
Try to log the SessionID after logged on successfully so that verify these sessions are the same.
Besides, there is a possibility that generating same authentication ticket during the redirection logic. It depends on how we control cookie generation.
private void cmdLogin_ServerClick(object sender, System.EventArgs e)
{
if (ValidateUser(txtUserName.Value,txtUserPass.Value) )
{
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (chkPersistCookie.Checked)
ck.Expires=tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);
string strRedirect;
strRedirect = Request["ReturnUrl"];
if (strRedirect==null)
strRedirect = "default.aspx";
Response.Redirect(strRedirect, true);
}
else
Response.Redirect("logon.aspx", true);
}
Check this for more details.
https://support.microsoft.com/en-us/help/301240/how-to-implement-forms-based-authentication-in-your-asp-net-applicatio
Feel free to let me know if the problem still exists.

Increase timeout of an already started session

I want to add a "keep me logged in" option to my custom login control.
This is how I'm currently using the session:
I'm saving and reading values from HttpContext.Current.Session["key"] manually. Works fine.
Relevant parts of web.config:
<sessionState mode="StateServer" useHostingIdentity="true" cookieless="false" timeout="120" stateConnectionString="tcpip=127.0.0.1:42424" />
<authentication mode="Forms">
<forms loginUrl="/login" name="AuthCookie" timeout="120" slidingExpiration="true" path="/" />
</authentication>
<authorization>
<allow users="*" />
</authorization>
As you can see, the default duration of a session is 120 minutes.
"Logout":
Session.Clear();
Session.Abandon();
Through a custom login control with textboxes, I grant access to a member area. (I don't use System.Web.Security.FormsAuthentication)
After entering valid credentials and a checked checkbox "keep logged in", I want to increase the duration of the already active session to ~30 days.
So far I've found solutions like
FormsAuthenticationTicket fat = new FormsAuthenticationTicket(1, "username", DateTime.Now, DateTime.Now.AddMinutes(1), false, "username");
string encTicket = FormsAuthentication.Encrypt(fat);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket) { Expires = fat.Expiration });
which don't work, because System.Web.Security.FormsAuthentication.Timeout is still at 120 minutes.
The same goes for setting
Session.Timeout = 666;
Any suggestions?
You can't really approach it this way. You can't persist a session over days - it's just not going to scale well.
What most people do is provide a means for automatic login, so that when their session expires, they are seamlessly logged back in on the next action/reload. Most people do this with a cookie that contains a unique hash, which is checked at the server. If you want the person to be logged in for 30 days, you just set the cookie to expire in 30 days time.
I decided to give a short summary how I ended up doing it, because #David Haney asked me to:
I added a column to my usertable, which contains a GUID that is used for "relogging in" / giving credentials again. That GUID is created upon login and stored in the database.
It's also stored as an ecrypted value in a cookie. (My site doesn't use SSL)
Added to Login routine (if a user checked the "remeber me" checkbox):
HttpCookie aCookie = new HttpCookie("Session");
Guid sessionGuid = // Buisiness layer call to generate value
String sessionID = sessionGuid.ToString();
aCookie.Value = Helper.Protect(sessionID, "sessionID");
aCookie.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(aCookie);
where Helper.Protect and Helper.Unprotect are used from here How to use MachineKey.Protect for a cookie? to store an encrypted and MAC signed value in a cookie.
Relogging is done by having every content page inherit from a class, that implements that logic and inherits from System.Web.UI.Page.
public class BasePage : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (Request.Cookies["Session"] != null && !CustomIsLoggedInCheckMethod)
{
String unprotected = Helper.Unprotect(Request.Cookies["Session"].Value, "sessionID");
Guid sessionID = Guid.Parse(unprotected);
// Calls to buisiness layer to get the user, set sessions values et cetera
}
}
}
If a user was banned after the last session or logs out, the cookie value expiration date will be set to a date in the past:
HttpCookie myCookie = new HttpCookie("Session");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
Edit:
Ah I forgot to mention this. I've also added a notification bar, that tells the user that he has been logged back in. It's based on http://blog.grio.com/2012/11/a-copypaste-ble-jquery-notification-bar.html
See Demo

Timeout function for FormsAuthenticationTicket stopped working

I seriously need help. I spent to much time trying to figure out what happened.
I use a FormsAuthenticationTicket to manage the users connection. As here:
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1, userName, System.DateTime.Now, System.DateTime.Now.AddMinutes(timeout),
false, "", FormsAuthentication.FormsCookiePath);
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName,
encryptedTicket);
authCookie.Expires = DateTime.Now.AddMinutes(timeout);
HttpContext.Current.Response.Cookies.Add(authCookie);
So nothing crazy. I did some updates on my live website (but not on the ticket code) and now when I get timed out, the "ReturnUrl" parameter is not in the Url of the login page anymore.
My question is: Do you have any basic recommendation of where to search when a ticket starts to act up?
Thank you all.
I finally found the solution so I put it for the other people that might have a problem.
Another file Web.config was missing on the production server. The only thing that this file has in it is:
<configuration>
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</configuration>
Now the timeout function works again. If someone has any explanation of why this code is helpful, I'd like to know it.

How can I expire the session when the user doesn't work with website?

Hello, I created a web site application with asp.net 4.5 and asp.net membership. I want user session to be expire if the user doesn't work with site (like Facebook).
I have set the timeout in web.config for the session but this time gets finished (times out), either if user works or doesn't work. Is there something I'm missing?
<authentication mode="Forms">
<forms loginUrl="~/Pages/Login.aspx" slidingExpiration="true" timeout="1"></forms>
</authentication>
While setting the forms auth cookie you need to set an expiry time for the cookie and create a http module in your application where you check the auth cookie in the request headers and if its not present you logout the user and redirect to the login page. And if the cookie exists just reset the expiry time for the cookie in the response.
Refer to this link. This is an answered that I'm currently help with another user. This should show you how to make the session start once the user logs in.
Edit: Not sure why the downvote, but here is code then.
Change the timeouts on each of the forms authentication and sessionState like below.
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" defaultUrl="~/Dashboard.aspx" timeout="60"/>
</authentication>
<sessionState timeout="60" mode="InProc" cookieless="false" />
Then, put this into your Site.Master.cs under the page load.
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
// Handle the session timeout
string sessionExpiredUrl = Request.Url.GetLeftPart(UriPartial.Authority) + "/DealLog/Account/SessionExpired.aspx";
StringBuilder script = new StringBuilder();
script.Append("function expireSession(){ \n");
script.Append(string.Format(" window.location = '{0}';\n", sessionExpiredUrl));
script.Append("} \n");
script.Append(string.Format("setTimeout('expireSession()', {0}); \n", this.Session.Timeout * 60000)); // Convert minutes to milliseconds
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "expirescript", script.ToString(), true);
}
The session will only expire if the user is authenticated. The user logs in, becomes inactive, and then session times out. Once it times out, goes to an SessionExpired page. On the session expired page, place
FormsAuthentication.SignOut();
in the page load so it signs out the user. Then you can set up a redirect from there. The Authentication and SessionState timeouts are both in minutes. 60 = 1 hour.
Edit 2: It looks like the user of the question that was linked in my answer was deleted by the user. Sorry for that. Hope this helps though.

FormsAuthenticationTicket expiration

I have been searching the web and found many odd answers and i've tried almost all of them.
My problem is this. My login page contains:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(min), persistCookie, userid.ToString());
string encTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
cookie.Expires = ticket.Expiration;
Response.Cookies.Add(cookie);
FormsAuthentication.RedirectFromLoginPage(userName, persistCookie);
Now the min value is per user based and can be set individually, so is persistCookie.
After what i understand this code should result in the possibillity of overriding the default values in web.config. Which should be 30 minutes.
<authentication mode="Forms">
<forms loginUrl="~/Default/default.aspx" defaultUrl="~/User/UserMain.aspx"/>
</authentication>
min is currenlty set to 120, and persistCookie is set too true. When i log in i get timeout at 30 minutes. (Not session, so somewhere expiration date is set, because if it was not set the cookie should be session based, also i do not get 120 minutes which is kind of the deal here)
My question, for simplifying it, is how do i get the value 'min' to be the expiry date of the cookie?
This might turn out too be a simple thing but i am currently totally stuck so any help would be appriciated.
EDIT:
I changed the login logic to this:
FormsAuthenticationTicket fat = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(min), persistCookie, userid.ToString());
string encTicket = FormsAuthentication.Encrypt(fat);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket) { Expires = fat.Expiration });
Response.Redirect(FormsAuthentication.GetRedirectUrl(userName, false));
And now it works. But i cant seem to figure out why this would work, and not the previous one.
Ticket creation is the same, the only difference is that i add Expires property of the HttpCookie when creating the HttpCookie, not after the object is made.
If anybody has a good explanation i am all ears! :)
The problem with your code is that you're calling RedirectFromLoginPage, which will create the forms authentication cookie, overwriting the cookie you've just created:
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
cookie.Expires = ticket.Expiration;
Response.Cookies.Add(cookie);
FormsAuthentication.RedirectFromLoginPage(userName, persistCookie); <-- creates a new cookie
The cookie created by RedirectFromLoginPage will of course have the default timeout taken from configuration.
Your second version is the way to go.
I think you don't understand the difference between cookie expiration and ticket expiration dates - ticket can be considered as expired even if the cookie it is being stored in is still valid. The 4th param of FormsAuthenticationTicket constructor is responsible for the ticket expiration date.
So, to answer your question, you need to manually set expiration date of your cookie or make it long enough to exceed expiration date of your authentication ticket.

Categories