In my asp.net web forms application I am using forms authentication. I am confused on this thing:
My web.config has:
<authentication mode="Forms">
<forms loginUrl="Login.aspx" defaultUrl="Welcome.aspx">
</forms>
</authentication>
and my login button looks like this:
protected void Login_Click(object sender, EventArgs e)
{
if (AuthenticateUser(UserNametxt.Text, Passwordtxt.Text))
{
FormsAuthentication.RedirectFromLoginPage(UserNameTextBox.Text, RememberMeCheckBox.Checked);
}
else
{
MessageLbl.Text = "Wrong UserName and/or Password.";
}
}
<forms> has a property timeout="" that you can set. I understand that by default that property is 30 or 30 minutes. I thought that this timeout property was to set how long users who checked my checkbox to be remembered would be remembered for with FormsAuthentication.RedirectFromLoginPage(UserNameTextBox.Text, RememberMeCheckBox.Checked), but from what I read online it looks like the timeout property is how long you can be idle on a webpage before being signed out.
If this is true, how can I set how long a user is remembered by checking the RememberMeCheckBox with forms authentication?
I understand that by default that property is 30 or 30 minutes. I
thought that this timeout property was to set how long users who
checked my checkbox to be remembered would be remembered for with
FormsAuthentication.RedirectFromLoginPage(UserNameTextBox.Text,
RememberMeCheckBox.Checked)
Yes, you are correct. FormsAuthentication timeout default value is 30 minutes.
what I read online it looks like the timeout property is how long you
can be idle on a webpage before being signed out.
It is called SessionState time out. SessionState time out default value is 20 minutes.
Updated for the Comment (9/12/2014)
So if I set the SessionState timeout to say, 48hrs, does that mean
that users who click my "remember me" checkbox will be remembered and
automatically authenticated with forms authentication on that website
for 48hrs? (given my above code)
If you set SessionState time out to 48 hours, after a user logins, the user can leave the browser idle up to 48 hours without logging-out.
So the Answer for your question is No.
In your question, you just want a user not require to login for 48 hours. If so, you need to set FormAuthentication time out to 48 hours.
The following setting sets the persistent cookie expire in 48 hours.
<authentication mode="Forms">
<forms ... timeout="2880">
</forms>
</authentication>
You need to do this by using Cookies and setting their expiration date-time. If Cookie exists, delete it. Set a new cookie with your preferred expiration date-time.
Related
EDIT 2:
I have a background process running on the server side based on a schedule or an end user's request, and i need to show an image to all the users to keep him notified that this process is running, or take out the image when the process is finished.
EDIT 2 Finished
I am calling an ASMX web service which is located in my website hosted on my IIS from javascript and it is preveting my session from timing out.
Why does a call from the client to the webservice prevent the session on my website to timeout ?
Is there a way to prevent it ?
Please tell me if you need more clarity in my question or more details.
EDIT 1:
Based on the information and the link provided by #Rene147 in the answer below as well as some googling, i tried the following on the side of my webservice :
[WebMethod(EnableSession=false)]
public string GetSummary()
{
HttpContext.Current.Response.Cookies.Remove(System.Web.Security.FormsAuthentication.FormsCookieName);
return "something";
}
But it turns out that HttpContext.Current.Response.Cookies is always empty.
Any hints ?
According to my understanding of your last edit - if you want to read cookie's value, you need to use Context.Request.Cookies instead of Response.
[WebMethod(EnableSession = false)]
public string GetSummary()
{
HttpCookie decryptedCookie =
Context.Request.Cookies[FormsAuthentication.FormsCookieName];
return "something";
}
By default Forms Authentication uses Sliding Expiration. This means that each time you make a request to the server your cookies expiration is reset (with some caveats).
To disable Sliding Expiration set "slidingExpiration" in your web.config to false. Taken from Sliding Expiration
<authentication mode="Forms">
<forms loginUrl="member_login.aspx"
name=".ASPXFORMSAUTH"
cookieless="UseCookies"
requireSSL="true"
slidingExpiration="false" />
</authentication>
In my asp.net web application, I'm using asp.net forms authentication with following configuration.
<authentication mode="Forms">
<forms name=".ASPNETAUTH" loginUrl="Login.aspx" protection="None" timeout="20" />
</authentication>
After form authentication time out, I would like to redirect to a different page. For example to 'SessionTimedOut.aspx' page.
I've found other questions on here, here is one, Forms Authentication Timeout vs Session Timeout
The answer given makes sense but the first line of code has me confused.
var cookie = Retrieve AuthenticationCookie();
if (cookie == null) return;
FormsAuthenticationTicket ticket = null;
try {
ticket = FormsAuthentication.Decrypt(cookie.Value);
} catch (Exceptoin decryptError) {
// Handle properly
}
if (ticket == null) return; // Not authorised
if (ticket.Expiration > DateTime.Now) {
Response.Redirect("SessionExpiredPage.aspx"); // Or do other stuff here
}
Now there is a
FormsAuthentication.GetAuthCookie()
which takes a username and bool to persist the cookie, but this is for creating an auth cookie not getting it. So, what would the var cookie, first line of code look like.
At the moment, I am using " in web config and then when user logins in settings a session and then on every post back in a page init in my base page am checking if that session is null, if so, redirecting to a session timed out page. This is not really what I want.
May have found out how to get cookie,
HttpCookie cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
This doesn't work because when the authentication ticket expires, the cookie goes away and the the cookie var is null. Any other way to get this working? I would still like on post back check if authentication has expired and then take appropriate action. Any thoughts from anyone????
The thing to remember is that even though your session times out on the server end, the client end will not process anything until it's next request. At that time it will discover that it's session has expired and attempt to restart the session. A Response.Redirect or even Server.Redirect call won't help with this.
What you need to do is to synchronize your server timeout with your client timeout, and have some client script in place to redirect the user to a "Timed Out" type page. I've written up an article with some sample code on how to do that here.
Q: So, what would the var cookie, first line of code look like.?
var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]
ASP.NET MVC 2.0, here's my auth code:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Login(string username, string password, string returnUrl) {
if (ModelState.IsValid) {
// Attempt to login
var loginSuccessful = provider.ValidateUser(username, password);
if (loginSuccessful) {
FormsAuthentication.SetAuthCookie(username, true);
if (!String.IsNullOrEmpty(returnUrl))
return Redirect(returnUrl);
return RedirectToAction("Index", "Home");
}
}
return View(Language + "/Login", Vd);
}
Pretty much straight default authentication. Works fine for logging in. However, IE users get auto logged off randomly, even while they're active on the site. Other browsers work fine. Here's the forms auth from web.config:
<authentication mode="Forms">
<forms loginUrl="~/en/Account/Login" timeout="2880"/>
</authentication>
Where do I begin to look in this case? Have I found a bug?
As far as I can see everything seems fine, however, could your issue be something to do with your use of a persistent cookie? I think persistent cookies are not meant to timeout, which is why you might be using them.
Try using a non-persistent one instead, and see if that works:
FormsAuthentication.SetAuthCookie(username, false);
Also, a few others notes of interest:
I think that the timeout attribute in a web.config is specified in minutes. You've specified more than 2000 minutes.
By default, sliding expiration is disabled, so after n minutes it will timeout anyway. If this isn't what you want, then add a slidingExpiration="true" entry onto your <forms/> element in the web.config.
What kind of session mode are you using-in process or out of process? If you are using in process with non-persistent cookie and the application pool recycles, then session is lost.
I want to have functionality on my application that lets a user check off that they wish to stay logged indefinitely (arbitrarily setting the cookie expiration at 3 months from NOW).
The code I have for dealing with this is
private static HttpCookie GetFormsAuthenticationCookie(string userNameResponse,
bool persistCookie)
{
var cookie = FormsAuthentication.GetAuthCookie(userNameResponse, persistCookie);
if (persistCookie)
cookie.Expires = DateTime.Now.AddMonths(3);
return cookie;
}
private void LoginUser(string userNameResponse, bool PersistCookie)
{
Response.Cookies.Add(GetFormsAuthenticationCookie(userNameResponse, PersistCookie));
string navigateAfterUrl = FormsAuthentication.GetRedirectUrl(userNameResponse,
PersistCookie);
Response.Redirect(navigateAfterUrl);
}
However at some point later when I return to the site I need to login again. I have verified that the cookie comes back with my expiration date and that it is not set as a session cookie (also tested with closing/reopening browser and cookie still exists). My one thought is that it has something to do with when ASP.NET expires the session.
I have a specific machine key setup in my web.config so shouldn't the same cookie work if IIS gets restarted etc? Does anyone have any suggestions on what could either be causing this or atleast on how to trace this further since I can't think of anything else to do.
When you call the GetAuthCookie method a FormsAuthenticationTicket is created with a timeout given by the Timeout property in web.config. So be sure to set it properly:
<authentication mode="Forms">
<forms
loginUrl="/someloginUrl"
requireSSL="true"
protection="All"
// This is the setting you are looking for! (it's in seconds)
timeout="120"
domain="example.com"
slidingExpiration="false"
name="cookieName" />
</authentication>
Once the ticket is encrypted it is used as a value for the cookie. When you set the Expires property of your cookie to a given value this indicates that it will be persisted on the client computer for the given period. Then on every request ASP.NET runtime will check the presence of the cookie, will try to decrypt the value and obtain the ticket. Next it will check if the ticket is still valid by using the Timeout property, so if you have a small timeout, no matter that your cookie is still transmitted, the ticket is no longer valid and the authentication will fail.
I have a testproject and the forms timeout specified in web.config overrules the timeout which I set in FormsAuthenticationTicket. According the documentation, the timeout (expire date) in FormsAuthenticationTicket must override the timeout in web.config.
Documentation found on: http://support.microsoft.com/kb/910443
If the ticket is generated manually by using the FormsAuthenticationTicket class, the time-out can be set through the Expiration attribute. This value will override the timeout attribute value specified in configuration files.
Here is my code:
Web.config:
<authentication mode="Forms">
<forms
timeout="1"
loginUrl="login.aspx"
name="sessionTest"
cookieless="UseCookies"
defaultUrl="default.aspx"
/>
</authentication>
Login.aspc.cs:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(Login1.UserName, false, 2);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(cookie);
// redirect user
FormsAuthentication.RedirectFromLoginPage(Login1.UserName, false);
Now, when I login, i get redirected after 1 minute of inactivity. This isn't supposed to happen, right? I have to be redirected after 2 minutes.
Someone can explain this?
I think the call to RedirectFromLoginPage is overwriting your cookie. You can try using this instead.
Response.Redirect( FormsAuthentication.GetRedirectUrl( UserName.Text, chkPersistCookie.Checked );
Additional information that might be useful here: https://web.archive.org/web/20210513002246/https://www.4guysfromrolla.com/webtech/110701-1.3.shtml