I am writing a "Remember My Username" Cookie that expires in a custom duration of time e.g. one month. I noticed that when I add HttpOnly = true, the expiration changes to session. Why is this? I can't seem to find any documentation on why this would happen.
Thanks.
Here is the documentation.
true if the cookie has the HttpOnly attribute and cannot be accessed
through a client-side script; otherwise, false. The default is false.
Basically, it becomes a session variable because it will only be stored on the server due to your setting
I'm adding the following code: Also, now I'm getting a different behaviors than the Title. I'm running this locally against the VS2010 built-in server. It seems to show inconsistent behaviors. I would move the HttpOnly = true before the Expires and after it and it seemed to change behavior until I refreshed the browser page. So, I am assuming everything was fine and never had an issue. In addition, I am moving HttpOnly and Secure flags to the web.config because not all my environments have SSL.
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket
(strUserID, //name
false, //IsPersistent
24 * 60); // 24 hours
// Encrypt the ticket.
string encryTicket = FormsAuthentication.Encrypt(ticket);
// Create the cookie.
HttpCookie userCookie = new HttpCookie("Authentication", encryTicket);
userCookie.HttpOnly = true;
Response.Cookies.Add(userCookie);
e.Authenticated = true;
if (LoginPannelMain.RememberMeSet)
{
HttpCookie aCookie = new HttpCookie("email", strUserLogin);
aCookie.HttpOnly = true;
aCookie.Expires = DateTime.Now.AddYears(1);
Response.AppendCookie(aCookie);
}
else
{
HttpCookie aCookie = new HttpCookie("email", "");
aCookie.HttpOnly = true;
Response.AppendCookie(aCookie);
}
Related
I have getting issue with delete FormsAuthentication ticket cookie with remember me option.. it always showing expired date 01/01/0001, I am setting FormsAuthentication ticket with expired time at the time of login controller.
When the application URL open that time again check the expired time & Auth Cookie.
everytime it Authentication cookies expired time showing the same..
How to manage FormsAuth ticket with remember me option?
I have search a lots in different forums but not get the exact solutions..
Below screenshot when i have not selected Remember me.
When I selected remember me it showing time in Expire age. but not handling with C# code.
// Here u is view model object that set the username,password and remember me options.
// LOGIN FUNCTION CODE
if (u.RememberMe)
{
int timeout = u.RememberMe ? 525600 : (int)sessionSection.Timeout.TotalMinutes; // Timeout in minutes, 525600 = 365 days.
var ticket = new FormsAuthenticationTicket(1, u.Email, DateTime.UtcNow, DateTime.UtcNow.AddMinutes(timeout), u.RememberMe, logmodel.UserType);
string encrypted = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Path = FormsAuthentication.FormsCookiePath;
//cookie.Expires = System.DateTime.UtcNow.AddMinutes(timeout);// Not my line
//if (ticket.IsPersistent)
// cookie.Expires = ticket.Expiration;
cookie.Expires = ticket.Expiration;
/// cookie.HttpOnly = true; // cookie not available in javascript.
Response.Cookies.Add(cookie);
}
else
{
FormsAuthentication.SetAuthCookie(u.Email, false);
}
When I log I create the following cookie:
HttpCookie cookie = new HttpCookie("Ortund");
// insert cookie values
cookie.Expires = DateTime.Now.AddMonths(1);
Response.Cookies.Add(cookie);
When I request data from this cookie, I use Request.Cookies:
string username = Convert.ToString(Request.Cookies["Ortund"]["Username"]);
When i log out, I do this:
HttpCookie cookie = new HttpCookie("Ortund");
cookie.Expires = DateTime.Now.AddMonths(-1);
Response.Cookies.Add(cookie);
For some reason, now I'm sitting with a cookie that has an expiry date of 0001-01-01 12:00:00 AM in Request.Cookies["Ortund"] and the expiry date of the cookie doesn't change no matter how many times I log in.
Have I done something wrong here? Is this even close to how it should be done?
In your logout you are creating a new instance of the cookie. Also you are using Response.Cookies.Add which may allow multiple cookies of the same name to be appended to the Response.
I would suggest you to check the Request for the cookie key and if it doesn't exist add the cookie.
For updating the cookie, first get the existing cookie object and use Response.SetCookie to update the value.
Code
set
if(!Request.Cookies.AllKeys.Contains("Ortund"))
{
HttpCookie cookie = new HttpCookie("Ortund");
// insert cookie values
cookie.Expires = DateTime.Now.AddMonths(1);
Response.Cookies.Add(cookie);
}
update
if (Request.Cookies.AllKeys.Contains("Ortund"))
{
HttpCookie cookie = Request.Cookies["Ortund"];
cookie.Expires = DateTime.Now.AddMonths(-1);
Response.SetCookie(cookie);
}
I've been trying to figure out how to set the secure flag on all the server cookies for our website. We're running .NET 4.5. I tried adding <httpCookies requireSSL="true" /> to the web.config file. I tried adding <authentication><forms requireSSL="true" /></authentication>. I tried setting the secure flag in code. Nothing had any effect. Adding the following c# function to Global.asax.cs was supposed to work, but didn't:
protected void Application_EndRequest()
{
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
var httpCookie = Response.Cookies[sCookie];
if (httpCookie != null) httpCookie.Secure = true;
}
}
It finally started working after I got rid of the "if (sCookie.Equals(authCookie))..." statement. So this is the working version:
protected void Application_EndRequest()
{
string authCookie = FormsAuthentication.FormsCookieName;
foreach (string sCookie in Response.Cookies)
{
// Set the cookie to be secure. Browsers will send the cookie
// only to pages requested with https
var httpCookie = Response.Cookies[sCookie];
if (httpCookie != null) httpCookie.Secure = true;
}
}
I have several questions. First, what is the logic behind putting this in the Application_EndRequest method? Second, why did I have to get rid of the sCookie.Equals(authCookie)) part? Finally, has anyone found a more elegant solution? Thanks.
If you are executing the request over HTTP and not HTTPS then I do not think you can set Secure = true. Can you verify that you are running over a secure connection? You can do some google / bing searches on how to generate a local certificate if you are testing on your dev box. Also do not forget to encrypt your cookie so its not readable on the client side.
Here is some sample code.
var userName = "userName";
var expiration = DateTime.Now.AddHours(3);
var rememberMe = true;
var ticketValueAsString = generateAdditionalTicketInfo(); // get additional data to include in the ticket
var ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, expiration, rememberMe, ticketValueAsString);
var encryptedTicket = FormsAuthentication.Encrypt(ticket); // encrypt the ticket
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
{
HttpOnly = true,
Secure = true,
};
EDIT - Added link
Also take a look at this previous answer and how you can configure your web.config to ensure that cookies are always marked as secure.
I'm writing an ASP.net MVC 5 application using FormsAuthentication. I had everything up and working properly using FormsAuthentication.SetAuthCookie(user.Email, model.RememberMe).
However, I wanted to create a custom ticket so I could store some extra information in the UserData field of the ticket. This is how I'm creating my ticket and storing it in a cookie:
var ticket = new FormsAuthenticationTicket(1, user.Email, DateTime.Now, DateTime.Now.AddMinutes(FormsAuthentication.Timeout.Minutes), model.RememberMe, user.AuthToken);
var encryptedTicket = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) { Domain = FormsAuthentication.CookieDomain, Path = FormsAuthentication.FormsCookiePath, HttpOnly = true, Secure = FormsAuthentication.RequireSSL };
HttpContext.Response.Cookies.Add(cookie);
This creates an encrypted ticket and sends it to the browser. I've verified with developer tools and Fiddler that the ticket is present in the browser and that it is sent back to the server on the subsequent requests.
But authentication is now broken. Also, the cookie is not available in Application_AuthenticateRequest or Application_PostAuthenticateRequest events. When I use the debugger to explore Context.Request.Cookies it is not present in the list.
Oddly enough the cookie does exist if I step back in the pipeline and check it in Application_BeginRequest:
void Application_BeginRequest(object sender, EventArgs e)
{
// Auth cookie exists in the collection here! Ticket decrypts successfully
HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null)
return;
var encTicket = authCookie.Value;
var ticket = FormsAuthentication.Decrypt(encTicket);
}
void Application_AuthenticateRequest(object sender, EventArgs e)
{
// Auth cookie missing from the cookies collection here!
HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null)
return;
var encTicket = authCookie.Value;
var ticket = FormsAuthentication.Decrypt(encTicket);
using (var db = new BadgerContext())
{
var user = db.Users.OfType<RegisteredUser>().FirstOrDefault(x => x.UserName == ticket.Name);
if (ticket.UserData != user.AuthToken)
{
FormsAuthentication.SignOut();
Response.Redirect(FormsAuthentication.DefaultUrl);
}
}
}
So it appears that something is stripping my custom FormsAuthenticationTicket out of the cookies after BeginRequest but before AuthenticateRequest. Unfortunately, this breaks authentication altogether on the site.
Any ideas what is causing this behavior when I create a custom ticket? Am I doing something wrong with my cookie creation?
Check in the .config file the inside the system.web node, the httpRuntime tag.
<httpRuntime targetFramework="4.5" />
as same as main web site
Rowan suggested I look at the value for FormsAuthentication.Timeout.Minutes. After investigation, this value always came back as 0. This led to an immediate expiration of the ticket. I had to use FormsAuthentication.Timeout.TotalMinutes instead and everything started working properly
I am creating the cookie using the code below, How to read the txtusername value in another page and how to delete the cookie when I click sign out(code for sign out). I am new to programming please help.
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);
You should never store password as a cookie. That's a very big security threat. To delete a cookie, you really just need to modify and expire it. You can't really delete it, i.e. remove it from the user's disk. Check out this documentation.
Here is a sample:
HttpCookie aCookie;
string cookieName;
int limit = Request.Cookies.Count;
for (int i=0; i<limit; i++)
{
cookieName = Request.Cookies[i].Name;
aCookie = new HttpCookie(cookieName);
aCookie.Expires = DateTime.Now.AddDays(-1); // make it expire yesterday
Response.Cookies.Add(aCookie); // overwrite it
}
You cannot directly delete a cookie, you have to set it to expire before the current date:
if (Request.Cookies["clienDetails"] != null)
{
HttpCookie myCookie = new HttpCookie("clienDetails");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
You can read more about it here.
Furthermore I really encourage you to not write your own security but to read up on asp.net membership. More secure and easier to use. As I can see many flaws in your security model. Storing the password in plain text in a cookie is really really bad.
EDIT:
As you now changed your code, you have to do this to remove the cookie:
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
HttpCookie myCookie = new HttpCookie(FormsAuthentication.FormsCookieName);
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
FYI this did not work for me using Chrome 69 with the Continue where you left off feature enabled. Similar issue with Firefox. Disabling this feature worked for me.
See
Chrome doesn't delete session cookies
How to delete or expire a cookie in Chrome using Asp.Net
In my case this code worked:
Response.Cookies.Delete("access_token");
return Ok();