ASP.NET authenticated users signout frequently even after applying all attributes - asp.net

I had implemented custom asp.net authentication and added all the required attributes even then the user are signout frequently.
I had hosted this website on shared godaddy server.
Here is my code:
var ticket = new FormsAuthenticationTicket(2, auth.Message.ToString(), DateTime.Now, DateTime.Now.AddDays(3), true,
string.Empty, FormsAuthentication.FormsCookiePath);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket))
{
Domain = FormsAuthentication.CookieDomain,
Expires = DateTime.Now.AddYears(50),
HttpOnly = true,
Secure = FormsAuthentication.RequireSSL,
Path = FormsAuthentication.FormsCookiePath
};
Response.Cookies.Add(cookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(auth.Message.ToString(), true));
My Web.config has these values:
<authentication mode="Forms">
<forms requireSSL="false" timeout="120" loginUrl="~/CRM/Logon.aspx" defaultUrl="~/CRM/OTP.aspx" />
</authentication>
My users are complaining that they are logged off around 10-20 minutes
Any help is appreciated.
EDIT
I had removed requireSSL="false" timeout="120" and even then no effect.
I am not using session as well

The problem is we need to specify Application Pool Idle timeout also to make the above conditions works.

Related

problem automatic logout user after refreshing the page or changing the page or after a few minutes

i use this code for login user in my api:
var ticket = new FormsAuthenticationTicket(
1,
CurrentCustommer.PhoneNumber,
DateTime.Now,
DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
false,
"user,user1",
FormsAuthentication.FormsCookiePath
);
var encryptedTicket = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
{
HttpOnly = true,
Secure = FormsAuthentication.RequireSSL,
Path = FormsAuthentication.FormsCookiePath,
Domain = FormsAuthentication.CookieDomain
};
HttpContext.Current.Response.AppendCookie(cookie);
my webconfig code is:
<authentication mode="Forms">
<forms loginUrl="Login.aspx" protection="All" timeout="10080" slidingExpiration="true">
</forms>
</authentication>
<compilation debug="true" targetFramework="4.6.2" />
<httpRuntime targetFramework="4.6.2" />
<pages enableSessionState="true" validateRequest="false"></pages>
<sessionState mode="InProc" cookieless="false" timeout="10080" />
now. user after login and after a few minutes and refresh page or change page in site, Automatically Log outed; I see cookies stored through the "document.cookie" in chrome console. this problem does not exist in local host but when used server this problem showed :/
Also, I add that I use my customized database and don't use sql membership provider asp.net.
Should I apply certain settings when I call the method API for user login? Or I need to apply other configurations?
Really I do not know how to fix this problem.
thanks all.
UPDATE: i check authenticate user by this code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.User.Identity.IsAuthenticated)
{
//Page.Response.Redirect("/");
MainContainer.Visible = false;
Page.ClientScript.RegisterStartupScript(this.GetType(),
"CallMyFunction", "LoginForm()", true);
}
}
for more info And i now see Page.User.ExpireDate in watch in Page_Load, this time 30 minutes after login user.
cookieless="false" can you just try using cookieless property as default or true

How to read cookie's domain name from web.config?

If I want to set up a multidomain authentication (or for whatever other reason I want to specify the authentication domain) I have to do it in two places:
In the web.config:
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" enableCrossAppRedirects="true" domain="mydomain.com" />
On the login page, when I am creating my authentication cookie:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user, DateTime.Now, DateTime.Now.AddHours(3), false, role, FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
cookie.Expires = ticket.Expiration;
cookie.Domain = "mydomain.com"; // <-----
Response.Cookies.Add(cookie);
That is fine... but whenever I want to change the domain I have to do it in two places. Is there a way to read the domain straight from the < authentication > tag in web.config? I know I could put it in the < appSettings > section and read it easily from wherever in the program, but then I would have to change it twice in the web.config file.
you can set it in authentication/forms and read it as FormAuthentication.CookieDomain

Forms authentication - sliding expiration

I think my sliding expiration is not happening and the people keep getting logged out after just a few minutes. Here is my setup, slidingExpiration is set to "true" and timeout i updated to "60" instead of 20 for testing purposes.
<authentication mode="Forms">
<forms name="Lab.ASPXFORMSAUTH" loginUrl="~/Login" enableCrossAppRedirects="true" cookieless="AutoDetect" domain="lab.org" slidingExpiration="true" protection="All" path="/" timeout="60" />
</authentication>
and here is the login code. If remember me is selected then the ticket expiration time will be one year from nw other wise it will be 20 mins from now.
private static void LoginUser(User user, bool isRememberMe)
{
//Forms Authentication
var expiryDateTime = isRememberMe ? DateTime.Now.AddYears(1) : DateTime.Now.AddMinutes(20);
var ticket = new FormsAuthenticationTicket(
1, // Ticket version
user.UserId, // Username associated with ticket
DateTime.Now, // Date/time issued
expiryDateTime, // Date/time to expire DateTime.Now.AddYears(1)
isRememberMe, // "true" for a persistent user cookie
JsonConvert.SerializeObject(user.Roles), // User-data, in this case the roles
FormsAuthentication.FormsCookiePath); // Path cookie valid for
// Encrypt the cookie using the machine key for secure transport
var hash = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(
FormsAuthentication.FormsCookieName, // Name of auth cookie
hash); // Hashed ticket
// Set the cookie's expiration time to the tickets expiration time
if (ticket.IsPersistent)
{
cookie.Expires = ticket.Expiration;
}
// Add the cookie to the list for outgoing response
HttpContext.Current.Response.Cookies.Add(cookie);
}
Looks like i have some disconnect going on between the web.config and the ticket expiry time. Do you see what i am doing wrong here? Thanks
Update #1:
Tested the dev site, logged in (FF and chrome) then refreshed the page after 5 mins and it kept me logged in. Then refreshed the page after 14mins and it redirected me to login page.
Tested the prod site (2 servers - load balanced), followed the dev site refresh interval, kept me logged in.
Scott Hanselman has detailed it here.
http://www.hanselman.com/blog/WeirdTimeoutsWithCustomASPNETFormsAuthentication.aspx
You may need to look into iisidle time out
https://technet.microsoft.com/en-us/library/cc771956%28v=ws.10%29.aspx
Got help at asp.net forums to fix the issue.

Proper creation of a cross-domain forms authentication cookie

I'm just creating a simple test between two server. Basically if a user has already authenticated I want to be able to pass them between applications. I changed the keys to hide them
I have three questions:
What is the proper way to validate the cookie across domain application. For example, when the user lands at successpage.aspx what should I be checking for?
Is the below code valid for creating a cross domain authentication cookie?
Do I have my web.config setup properly?
My code:
if (authenticated == true)
{
//FormsAuthentication.SetAuthCookie(userName, false);
bool IsPersistent = true;
DateTime expirationDate = new DateTime();
if (IsPersistent)
expirationDate = DateTime.Now.AddYears(1);
else
expirationDate = DateTime.Now.AddMinutes(300);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
userAuthName,
DateTime.Now,
expirationDate,
IsPersistent,
userAuthName,
FormsAuthentication.FormsCookiePath);
string eth = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, eth);
if (IsPersistent)
cookie.Expires = ticket.Expiration;
cookie.Domain = ".myDomain.com";
Response.SetCookie(cookie);
Response.Cookies.Add(cookie);
Response.Redirect("successpage.aspx");
}
My config:
<authentication mode="Forms">
<forms loginUrl="~/Default.aspx" timeout="2880" name=".AUTHCOOKIE" domain="myDomain.com" cookieless="UseCookies" enableCrossAppRedirects="true"/>
</authentication>
<customErrors mode="Off" defaultRedirect="failure.aspx" />
<machineKey decryptionKey="#" validationKey="*" validation="SHA1" decryption="AES"/>
What is the proper way to validate the cookie across domain application.
For example, when the user lands at successpage.aspx what should I be checking for ?
There shouldn't be anything to check. Forms authentication mechanism will retrieve the ticket from the cookie, check if it is valid. If not present, or invalid, user will redirected to ~/Default.aspx .
This will work provided your cookie matches the configuration of your web.config
Is the below code valid for creating a cross domain authentication cookie ?
I think you shouldn't try to override the settings of your web.config by manually handling the cookie. I think there are better ways for handling cookie persistence (see below for web.config) and you are just implementing a part of the Forms authentication API (loosing web.config for SSL for example )
here, your manual cookie is not HttpOnly : you could for example be subject to cookie theft through XSS
FormsAuthentication has its own way of handling the cookie (see the TimeOut attribute description in http://msdn.microsoft.com/en-us/library/1d3t3c61%28v=vs.80%29.aspx) Your cookie persistence mechanism will be overwritten by this automatic behavior
Your code should just be :
if (authenticated)
{
bool isPersistent = whateverIwant;
FormsAuthentication.SetAuthCookie(userName, isPersistent );
Response.Redirect("successpage.aspx");
}
Do I have my web.config setup properly?
It should be ok for the domain attribute, as long as you want to share authentication among direct subdomains of mydomain.com (it won't work for x.y.mydomain.com), and mydomain.com is not in the public suffix list ( http://publicsuffix.org/list/ )
I would change the timeout and slidingExpiration attributes to :
<forms loginUrl="~/Default.aspx" timeout="525600" slidingExpiration="false" name=".AUTHCOOKIE" domain="myDomain.com" cookieless="UseCookies" enableCrossAppRedirects="true"/>
I guess it is a good way to handle the choice between one year persistent cookies and session cookies. See https://stackoverflow.com/a/3748723/1236044 for more info

How to implement cookies less form authentication when we create our own cookie

I am implementing the forms authentication like (I need to create the ticket based some some conditions not from active directory or from database)
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
"userName",
DateTime.Now,
DateTime.Now.AddMinutes(30), // value of time out property
false, // Value of IsPersistent property
String.Empty,
FormsAuthentication.FormsCookiePath);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authCookie = new HttpCookie(
FormsAuthentication.FormsCookieName,
encryptedTicket);
authCookie.Secure = true;
Response.Cookies.Add(authCookie);
and my web.config
<system.web>
<authentication mode="Forms">
<forms loginUrl="Login.aspx"
protection="All"
timeout="30"
name="test"
path="/"
requireSSL="false"
slidingExpiration="true"
cookieless="UseDeviceProfile"
enableCrossAppRedirects="false" />
</authentication>
</system.web>
This implementation is working fine if the browser cookies are enabled . while it is not working when cookies are disabled( I tried Cookieless="useuri" but it doesnt help)
Can you please guys tell me how should i implement cookiless forms authentication in this scenario
I want to use uri for auth cookie or any other better solution?.
For cookieless browsers asp.net provides session id to embed in URL;
See the below question :
What will happen to asp.net membership if the client browser is not accepting cookies

Resources