Timeout function for FormsAuthenticationTicket stopped working - c#

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.

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.

Stop session from expiring when browser closes in MVC

I am facing a session issue After I close my browser my session expires, and after re-open browser, I have to log in again.
I don't want to expire my session on browser close.
I am using this in my web.config file:
<authentication>
<forms loginUrl="~/account/login" name="astroswamig" slidingExpiration="true" timeout="1000"></forms>
</authentication>
<sessionState mode="StateServer" cookieless="false" timeout="1000" />
and this in my controller:
string str = JsonConvert.SerializeObject(user);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.CustEmail, DateTime.Now, DateTime.Now.AddDays(120), true, str);
string enctryptTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authCustCookie = new HttpCookie(FormsAuthentication.FormsCookieName, enctryptTicket);
authCustCookie.Domain = "xyz.com";
Response.Cookies.Add(authCustCookie);
The web.config sample in the question is using StateServer mode, so the out-of-process ASP.NET State Service is storing state information. You will need to configure the State Service; see an example of how to do that in the "STATESERVER MODE(OUTPROC MODE)" section here:
https://www.c-sharpcorner.com/UploadFile/484ad3/session-state-in-Asp-Net/
Also be sure to read the disadvantages section of the above linked article to make sure this approach is acceptable for your needs.
Another way to manage user session is using the InProc mode to manage sessions via a worker process. You can then get and set HttpSessionState properties as shown here:
https://www.c-sharpcorner.com/UploadFile/3d39b4/inproc-session-state-mode-in-Asp-Net/
and also here:
https://learn.microsoft.com/en-us/dotnet/api/system.web.sessionstate.httpsessionstate?view=netframework-4.8#examples
Again be sure to note the pros and cons of InProc mode in the above linked article to determine what approach best fits your needs.

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

Asp.net persistent login cookie expires randomly

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!

User not logged in when WWW. is on URL

If I visit my site with out the www. prefix, login and then add the www., my user is not logged in any more, but if I remove the www., the user is logged in. It acts the same way if I do the Opposite. go to the web site with the www., login, and then remove the www. the user will not be logged in.
Here is the Login method and the authentication at the web.config.
public static void LogIn(userId)
{
Item user = Framework.Business.Item.Load(userId);
var _ticket = new FormsAuthenticationTicket(1, _usrItm.ID, DateTime.Now, DateTime.Now.AddDays(30), true, _usrItm.ID);
string encTicket = FormsAuthentication.Encrypt(_ticket);
HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
}
<authentication mode="Forms">
<forms name="k_Authentication" protection="All" timeout="120" cookieless="UseCookies" loginUrl="default.aspx" path="/" defaultUrl="/myweb.aspx"/>
</authentication>
I'll bet you a shilling to a guinea that the two answers about the domain setting of the cookies are correct +1s all around from me.
However. Most often the two sites are the same or they are not. If they're not, then you usually want the user to no longer be logged in, so don't change anything. If they are the same, then set one to permanently redirect to the other. As well as making this problem go away, you also gain some SEO benefits, benefits for people's history records being more consistent, and reduced pressure on shared caches. So I'd suggest that approach. I'd only deal with the matter of the domain set on the cookie if the two are separate-but-related, and sharing the log-in between them is appropriate.
There is probably a problem with the domain of your cookie. www.example.com and example.com are not the same domain.
You'll have to set the Domain property to www.yourdomain.com manually to share the cookies.

Categories