Forms Authentication cookie seems to stop working - c#

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.

Related

Set how long a user is remembered with forms authentication

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.

I am calling an ASMX web service from javascript and it is preveting my session from timing out

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>

Redirect to page after Forms Authentication Timeout

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]

Why isn't .ASPAUX cookie being validated by FormsAuthentication?

I have a site that uses FormsAuthentication and yes, the name of the cookie is .ASPAUX :)
I can log in perfectly. The server creates a forms authentication ticket, packs it in a cookie, properly determines the expiration time (1 year ahead) and sends it to the client.
For some reason, after some time, even though the cookie is there yet (I can see it with FireCookies) HttpContext.Current.Request.IsAuthenticated becomes false at the server. It's as if the cookie couldn't be validated.
The problem is: Why would that happen? How can I debug why the cookie suddenly becomes invalid without expiring?
EDIT
Here's the login method:
public static bool Login(int id)
{
try
{
string securityToken = UserHelper.AuthenticateUser(id);
DateTime expiryDate = DateTime.Now.AddYears(1);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, id.ToString(), DateTime.Now, expiryDate, true,
securityToken, FormsAuthentication.FormsCookiePath);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
cookie.Expires = expiryDate;
HttpContext.Current.Response.Cookies.Add(cookie);
return true;
}
catch
{
return false;
}
}
And the web.config:
<authentication mode="Forms">
<forms loginUrl="~/Login.aspx" timeout="2880" slidingExpiration="true"/>
</authentication>
Set static machine keys in your web.config to make sure that the encryption key used in generating your ticket survives an application pool being recycled (or your website being restarted in the ASP.NET web server)?
Also see the Forms Authentication Tickets section of this MSDN library article
A few things I can think of to check:
Do you have multiple domains (including www.domain.com vs domain.com)?
If so, either set the domain in the cookie as domain.com or ensure you always use the same domain
Are you using HTTPS?
If so, make sure you're always accessing the cookie via HTTPS or making sure that Secure is set to false on the HttpCookie (otherwise it's only accessible on HTTPS requests)
Are you writing the cookie from a virtual directory?
If so, the "path" on the cookie might be set and it won't be accessible from outside the path.
Do you have multiple web servers?
If so, make sure your machine key is set to the same value (though that should be throwing an exception)

authCookie not secure in global.asax

I have a login problem.
First i am using SSL while logging.
When i log in, i am creating a cookie like this. when i check if it is secure the answer is yes.
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, // version
UserName.Text, // user name
DateTime.Now, // creation
DateTime.Now.AddMinutes(60),// Expiration
false, // Persistent
role); // User data
// Now encrypt the ticket.
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
// Create a cookie and add the encrypted ticket to the
// cookie as data.
HttpCookie authCookie =
new HttpCookie(FormsAuthentication.FormsCookieName,
encryptedTicket);
if (authCookie.Secure)
{
new GUIUtility().LogMessageToFile("The cookie is secure with SSL.");
// Add other required code here.
}
authCookie.Secure = FormsAuthentication.RequireSSL;
// Add the cookie to the outgoing cookies collection.
HttpContext.Current.Response.Cookies.Add(authCookie);
// Redirect the user to the originally requested page
Response.Redirect(FormsAuthentication.GetRedirectUrl(UserName.Text,false));
then this is redirected to the global.asax page which has this code:
string cookieName = FormsAuthentication.FormsCookieName.ToString();
HttpCookie authCookie = Context.Request.Cookies[cookieName];
try
{
new GUIUtility().LogMessageToFile(cookieName + authCookie.Secure);
}
catch (Exception)
{
//
}
here i get the cookieName as ".ASPXAUTH" and authCookie.Secure value as False.
Why is this happening i want the authCookie.Secure value to be true here.
Any suggestions?? thanks
my web config has this:
<authentication mode="Forms">
<forms loginUrl="Login.aspx" defaultUrl="~/Default.aspx" slidingExpiration="true" timeout="120" path="/" requireSSL="true" protection="All">
</forms>
</authentication>
<httpCookies requireSSL="true"/>
<authorization>
<deny users="?"/>
<!--<allow users="*"/>-->
</authorization>
Restrict the Authentication Cookie-to-HTTPS Connections
Cookies support a "secure" property that determines whether or not browsers should send the cookie back to the server. With the secure property set, the cookie is sent by the browser only to a secure page that is requested using an HTTPS URL.
If you are using .NET Framework version 1.1, set the secure property by using requireSSL="true" on the element as follows:
<forms loginUrl="Secure\Login.aspx"
requireSSL="true" . . . />
If you are using .NET Framework version 1.0, set the secure property manually in the Application_EndRequest event handler in Global.asax using the following code:
protected void Application_EndRequest(Object sender, EventArgs e)
{
string authCookie = FormsAuthentication.FormsCookieName;
foreach (string sCookie in Response.Cookies)
{
if (sCookie.Equals(authCookie))
{
// Set the cookie to be secure. Browsers will send the cookie
// only to pages requested with https
Response.Cookies[sCookie].Secure = true;
}
}
}
so according to me the first option is not working in web config so im doing it manually
which is the second option in the code..
Please suggest.
Are you redirecting on log-in to a non-SSL resource? If this is the case, then the cookie you created in the first piece of code shouldn't be used, because it's a secure cookie and hence only applicable to SSL connections (i.e. you explicitly said it shouldn't be sent to non-SSL requests, that's what .Secure does), and hence a new cookie would be created. I would expect it to also not include the ticket value.
In this case, you're going to want to either:
Keep with SSL from the point of being logged in.
Live with the risk of session stealing (there are further means of mitigating this risk).
Use an authentication protocol like Digest or NTLM that allows for challenge-response and for you to more rapidly expire the log-in without the user being pestered (because the browser does the second log-in for you).

Categories

Resources