Asp.Net Cookie does persists after browser closing - asp.net

What i'm basically doing is creating a cookie and using form auth.
This is what i'm using to create the cookie.
Session.Add("username", userName);
Session.Add("password", passWord);
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, userName, DateTime.Now,
DateTime.Now.AddMinutes(1), false, "your custom data");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);`
Because i'm logging in to something secure, what I want to happen is when the browser closes to delete the cookie that this site creates. However, that doesnt happen, i'm able to log into the secure section of my site.
What am I missing?
basically if I log into /secure/secure.aspx and then close my browser, i can type in www.myaddress.com/secure/secure.aspx and i'll be logged in. I'm 100% positive that it will deny the user if the user has never logged in.

That behavior is controlled by the browser settings. You can control when the author cookie expires but now when its deleted from the client machine.
One strategy is to set the cookie to expire in X minutes on each request. That way if the user is inactive on the site for more than X minutes, they will have to login again.

Related

Something wrong with cookies in asp.net

I am building a web application and when a user signs in, his credentials are first validated against the database. If the credentials are correct, a FormsAuthenticationTicket is created. Then a cookie is created from that ticket. The Expires and Path properties are set. See below.
FormsAuthenticationTicket ticket=new FormsAuthenticationTicket(1, model.User.UserName,
DateTime.Now, DateTime.Now.AddHours(2), RememberMeCheckBox.Checked,
model.User.Id.ToString()+" "+model.User.UserType.ToString());
string cookieStr = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieStr);
cookie.Expires=ticket.Expiration;
cookie.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(cookie);
Response.Redirect("DummyForm.aspx");
And when I redirect the response to a new page, in the Page_Load event the presence of a cookie is checked.
HttpCookie cookie=HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookiePath];
if(cookie!=null)
{
//Do stuff
}
else
{
//Do other stuff
}
When I run the application, it behaves like the cookie variable is null.
Is there something that I have omitted?
Thanks in advance for your help.
cookie.Domain="localhost";
cookie.Name="My auth cookie";
I also set the domain property to localhost in web.config. However, it still doesn't work. I used the developer tools of Google to check the cookie and I can't see it there.

asp.net delete cookie

I'm using a cookie containing an encrypted key to use for authentication. What i need is to delete this cookie on logout. As per msdn a cookie cannot be removed from a client's browser, so I tried to set expiry date HttpContext.Current.Request.Cookies["CAuthCookie"].Expires = DateTime.Now.AddDays(-1);, however the cookie remains. Any other ideas?
Try this:(place this in your logout code)
HttpCookie cookie = new HttpCookie("CAuthCookie", "");
cookie.Expires = DateTime.Now.AddDays(-1);
HttpContext.Current.Response.Cookies.Set(cookie);

How to save session in mvc3 on blocked cookies

In my mvc3 application i save data of each user to session.
HttpContext.Current.Session["UserName"] = "Jon";
The problem is in Safari browser.
The default settings is : "block cookies from third parties and advertisers". So session is not saved. I found solution :
var ticket = new FormsAuthenticationTicket(
1,
"currentUser",
DateTime.Now,
DateTime.Now.AddMinutes(30),
false,
null);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
this.Response.Cookies.Add(cookie);
But this solution work only on localhost, is not work on server...
Is anybody have alternative solution for this problem? Or can explain why is my solution not working on server?
Try to set the Domain property of your cookie to exactly match the name of the domain your work server is in, like this:
var cookie = new HttpCookie(...
cookie.Domain = "Microsoft.com";
Once you do it, your cookie is a first-party cookie (as opposed to being a third-party one).

Asp.Net 4 Response.Cookies.Add does not add cookie to users machine

I am trying to setup a basic Form Authentication using ASP.NET 4.
I know my validation code (code that checks if the username and password is correct) is working because after if the user enters invalid information the ReturnLable tells them so. However if they enter the correct information, they are redirected to the restricted page with a 403 – Forbidden error. When I check the shell:cookie path no cookie has been written even though I added it to the collection “Response.Cookies.Add(cookie);”
protected void Submit_Click(object sender, EventArgs e)
{
Email.Text = Email.Text.Trim();
Password.Text = Password.Text.Trim();
if (IsValid(Email.Text, Password.Text)) //user exists
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
Email.Text,
DateTime.Now,
DateTime.Now.AddMinutes(50),
RememberMe.Checked,
"user",
FormsAuthentication.FormsCookiePath);
string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);
Response.Cookies.Add(cookie);
}
else
{
ReturnLable.Text = "<font color=red> Username/Password Incorrect Please Try Again </font>";
ReturnLable.Visible = true;
}
From this MSDN article:
If you do not set the cookie's expiration, the cookie is created but
it is not stored on the user's hard disk. Instead, the cookie is
maintained as part of the user's session information. When the user
closes the browser or if the session times out, the cookie is
discarded.
Thus, a cookie could be successfully set, alive and well in the browser, but have no corresponding file in the "cookies" folder on the hard drive.
make sure that Enable anonymous access is disabled on IIS and Integrated Windows security is enabled

FormsAuthentication isn't preserving the UserData field after Postback in .NET 3.5

I've created a FormsAuthenticationTicket from scratch, but found that when retrieving it at a later time, the UserData isn't coming back. Here is the code used:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
user.UserId,
DateTime.Now,
DateTime.MaxValue,
false,
user.UserType);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(ticket));
Response.Cookies.Add(cookie);
However, when reading this back on the next Request, I found that the UserData field is now empty:
string encryptedCookie = Request.Cookies[ FormsAuthentication.FormsCookieName ].Value;
FormsAuthenticationticket ticket = FormsAuthentication.Decrypt(encryptedCookie);
Assert.IsTrue( ticket.UserData.Length == 0 ); //TRUE!
Any ideas?
I think I found the problem. If you make up your own cookie name it seems to be fine! So change from:
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(ticket));
to
HttpCookie cookie = new HttpCookie(
"SiteCookie",
FormsAuthentication.Encrypt(ticket));
And then retrieve it as per the question:
string encryptedCookie = Request.Cookies[ "SiteCookie" ].Value;
FormsAuthenticationticket ticket = FormsAuthentication.Decrypt(encryptedCookie);
Assert.IsFalse( ticket.UserData.Length == 0 ); //Hooray! It works
Its possible .NET does some tricky stuff with it, so by putting it in a new one works fine.
UPDATE:
Also, the ticket needs to be refreshed, as otherwise the ticket will expire while the user is using the website:
FormsAuthentication.RenewTicketIfOld(ticket); // Do before saving cookie
I have also encountered this problem.
But I think the real reason is that the server set the same cookie twice and the second override the first which contains your UserData field.
You can capture the cookie writing process by Fiddler, and here is a screenshot that show this problem:
So, how this happened? In my situation, I use the Login control to authenticate. In the Login control's Authenticate event, I set the cookie with my UserData after check the username and password manaully. Then, I set the AuthenticateEventArgs.Authenticated=true, at this time, in the debug window, I see a new cookie is queued to the response which name is also equal to FormsAuthentication.FormsCookieName ! My solution is redirect to the Default page instead of setting the AuthenticateEventArgs.Authenticated=true.
So, you may debug your code to see if the authentication cookie is queued to the response twice.
This works for me:
//Create Form Authentication ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, currentUser.userid.ToString(), DateTime.Now, DateTime.Now.AddMinutes(60), false, currentUser.ToString(), FormsAuthentication.FormsCookiePath);
string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);
cookie.HttpOnly = true;
HttpContext.Current.Response.Cookies.Add(cookie);

Resources