I have setup my first login system and have followed:
https://stackoverflow.com/a/10524305
To store some additional data without having to make multiple trips to the database.
The issue I am having is that when the cookie/ticket expires, the user is still seen to be authenticated?
For example:
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
authCookie is null, but
HttpContext.Current.User.Identity.IsAuthenticated
Continues to return true.
Is there a way to force a log out if the cookie has expired?
Thanks!
You could try to replace
HttpContext.Current.User.Identity.IsAuthenticated
with
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if(authTicket.Expired) (...)
But this does not explain why HttpContext.Current.User.Identity.IsAuthenticated is still set to true.
I would firstly make sure that my forms authentication and session expiration is set to the same value in the configuration file:
<authentication mode="Forms">
<forms cookieless="UseCookies"
//some configuration +
timeout="20">
</forms>
</authentication>
<sessionState mode="InProc" cookieless="false" timeout="20" />
Related
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
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
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.
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
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