Asp.Net - How to expire Cookie - asp.net

Tried
if (Request.Cookies["IsGuest"] != null)
{
Response.Cookies["IsGuest"].Expires = DateTime.Now.AddDays(-1);
//HttpCookie myCookie = new HttpCookie("IsGuest");
//myCookie.Expires = DateTime.Now.AddDays(-1d);
//Response.Cookies.Add(myCookie);
}
string a = Request.Cookies["IsGuest"].Value;
and also tried by commenting uncommented code and uncommenting commented code but
string a = Request.Cookies["IsGuest"].Value;
Always running and Request.Cookies["IsGuest"] is never null

You got the right concept for deleting a cookie programmatically:
HttpCookie myCookie = new HttpCookie("IsGuest");
cookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(cookie);
However, you missed one point. The above change won't be effective until the postback completes and subsequently user initiates a new request.
MSDN says:
The next time a user makes a request to a page within the domain or path that set the cookie, the browser will determine that the cookie has expired and remove it.
So, the below code illustrates more here::
protected void DeleteCookie_ButtonClick(object sender, EventArgs e)
{
if (Request.Cookies["IsGuest"] != null)
{
HttpCookie myCookie = new HttpCookie("IsGuest");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
// this will always be true here as the Request i.e HttpRequest isn't
// modified actually as the postback isn't complete and we are accessing
// the Cookies collection of same request (not a new request)
if (Request.Cookies["IsGuest"] != null)
{
Label1.Text = "Cookie Collection can't be modified without
making a new request";
}
}
// suppose after postback completes,
// user clicks a button to check the cookie,
// which in turn is a new request/postback/....
protected void CheckCookie_ButtonClick(object sender, EventArgs e)
{
if (Request.Cookies["IsGuest"] != null)
{
Label1.Text = "Cookie is present!";
}
else
{
Label1.Text = "No Cookie is present!";
}
}
One last Note::
Calling the Remove method of the Cookies collection removes the cookie on the server side, so the cookie will not be sent to the client. However, the method does not remove the cookie from the client if it already exists there.

How to Expire a Cookie (on the Client)
I would not reply on ASP.NET Core to remove or expire cookies, as the server-side has very little to do with what happens on the browser. The ASP.NET application & server also has no knowledge of the names of every outdated-cookie, which paths were assigned, if some have already expired, which cookie names are no longer used from an older website, which ones were renamed, which ones are session cookies that need to remain, etc etc.
Cookies are best controlled on the client, which means running JavaScript (unfortunately).
To do that, I recommend you roll your own cookie expiration routine. Below is one I use that removes the top root-path cookies and a sub-path of cookies under the root, starting at the folder from which the script is called from. This generally means most of your cookies are removed. There are some exotic rules as to how browsers remove expired cookies under subpaths that I wont get into. In some cases some subpaths may be missed. But in general, root cookies would all be expired, and any cookies with the same scipts web path and all subpath under it, also expired.
The script below only sets expiration dates on cookies with paths matching the above rules. But the browsers are design to expire cookies under the subpath above as well. Please test in various browser, however, and customize the script as you like. This will NOT delete sessions stored as cookies!
// Get all cookies for this domain but by name-value pairs:
alert('What cookies do I have (name-value)?\r\n ' + document.cookie);
// Get all cookies
var allcookies = document.cookie;
// Splits into multiple cookies
var cookiesArray = allcookies.split(";");
// Loop through each found cookie...
if (cookiesArray && cookiesArray.length >= 0){
for (var i = 0; i < cookiesArray.length; i++) {
var nameString = "";
var pathString = "";
var expiresString = "";
// Strip out all whitespace or formatting from the name-value pair...
var cookieCleaned = cookiesArray[i].replace(/^\s+|\s+$/gm, '').replace(/[\t\n\r]/gm, '')
namePair = cookiesArray[i].split("=");
nameString = namePair[0] + "=; ";// empty the name's value
const earlydate = new Date(0).toUTCString();
expiresString = "expires=" + earlydate;
// DELETE COOKIES using ROOT PATH and SUBPATH
if (namePair[0] !== ""){
// Reset the cookie subpath with new expiration date
// to force the browser cache to delete it.
var pathname = location.pathname.replace(/\/$/,'');
if (pathname !== '') {
pathname = "path=" + pathname + "; ";
document.cookie = nameString + pathname + expiresString;
alert('Final Cookie1:\r\n ' + nameString + pathname + expiresString);
}
// Reset the cookie rootpath, same as above.
document.cookie = nameString + "path=/; " + expiresString;
alert('Final Cookie2:\r\n ' + nameString + "path=/; " + expiresString);
}
}
}

Better you can remove cookie from your list

Related

ASP.NET cookie does not expire

I'm trying cookies for the first time in ASP. The problem is, the cookie doesn't expire no matter how many ways I write the code.
Making a cookie:
HttpCookie cookie = new HttpCookie("test");
cookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(cookie);
Checking if it exists:
if (Request.Cookies["test"] != null)
Response.Write("test");
else
Response.Write("no test");
It always shows "test".
Are you doing this in the same request? In that case the old cookie is still present in the request, but will not be in subsequent requests.
You have destry all cookies in client side..
https://learn.microsoft.com/en-us/dotnet/api/system.net.cookie.expired?view=net-6.0
use this code it works for me.
<script>
$(document).ready(function () {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
});
</script>
Remarks:
Expired cookies, if received, should be destroyed by the client application.

Pass Authenticated Session In Another Request in ASP.NET

I am using ABCPDF.net to render my HTML to PDF pages, but I want to protect these using the current authenticated session. However, the request to get the HTML to render the PDF doesnt carry over the session, but creates a new one. I am using ASP.NET Membership, and passwigin the session ID and creating a cookie on the ASP.NET request.
var sessionId = HttpUtility.ParseQueryString(Url)["sid"];
if(sessionId != null)
{
doc.HtmlOptions.HttpAdditionalHeaders = string.Format("Cookie:
ASP.NET_SessionId={0}", sessionId);
}
I read this in ABCPDF.net documentation and am doing just that, but the request always uses a different session.
httpadditionalheaders
Do I need to pass something else, or can I do something else?
Fixed it by sending the auth cookie in the URL, and updating the cookie.
Url To Call
Url.ActionAbsolute(MVC.Events.Pools(eventId).AddRouteValue(FormsAuthentication.FormsCookieName, Request.Cookies[FormsAuthentication.FormsCookieName].Value)
Global.asax
protected void Application_BeginRequest()
{
try
{
string auth_cookie_name = FormsAuthentication.FormsCookieName;
if (HttpContext.Current.Request.Form[FormsAuthentication.FormsCookieName] != null)
{
UpdateCookie(auth_cookie_name, HttpContext.Current.Request.Form[FormsAuthentication.FormsCookieName]);
}
else if (HttpContext.Current.Request.QueryString[FormsAuthentication.FormsCookieName] != null)
{
UpdateCookie(auth_cookie_name, HttpContext.Current.Request.QueryString[FormsAuthentication.FormsCookieName]);
}
}
catch
{
}
}
void UpdateCookie(string cookieName, string cookieValue)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookieName);
if (cookie == null)
{
cookie = new HttpCookie(cookieName);
HttpContext.Current.Request.Cookies.Add(cookie);
}
cookie.Value = cookieValue;
HttpContext.Current.Request.Cookies.Set(cookie);
}

Persisting Session to DB

My architect is wondering why we need to persist each user's session to the DB instead of just using cookies. I have never seen anyone use just cookies.
Usually I hold the Session Id in a cookie then use it to perform CRUDS on the session record keyed off the ID.
I mean I don't see how you can do session state without in proc. I've always done session state via a custom table holding routine fields like IsLoggedIn, IsClosed, IsNew, IPAddress, Browser, and so on.
Has anyone done session state on an e-commerce site without persisting it in a DB?
UPDATED
So here is kinda how we did things at another place I worked for an e-commerce site that got 500+ page hits a month:
public USession CreateNewSession(int userID)
{
string ipAddress = GetCurrentRequestIPAddress(context.Request);
USession newSession = USession.NewSession();
newSession.IpAddress = ipAddress;
newSession.UserID = customerID;
newSession.Browser = context.Request.UserAgent ?? string.Empty;
if (context.Request.UrlReferrer != null)
newSession.Referer = context.Request.UrlReferrer.ToString();
else
newSession.Referer = string.Empty;
InsertSession(newSession);
return newSession;
}
public USession CreateNewSession(int userID)
{
string ipAddress = GetCurrentRequestIPAddress(context.Request);
USession newSession = USession.NewSession();
newSession.IpAddress = ipAddress;
newSession.UserID = customerID;
newSession.Browser = context.Request.UserAgent ?? string.Empty;
if (context.Request.UrlReferrer != null)
newSession.Referer = context.Request.UrlReferrer.ToString();
else
newSession.Referer = string.Empty;
InsertSession(newSession);
return newSession;
}
public USession GetSession()
{
// existing sessionId this session?
HttpCookie cookie = context.Request.Cookies["usessionId"];
if (cookie == null || string.IsNullOrEmpty(cookie.Value))
session = CreateNewSession(0);
else
{
string sessionID = cookie.Value;
session = GetSession(sessionID);
if (session == null)
session = CreateNewSession(0);
else if (session.IsClosed > 0)
session = CreateNewSession(session.UserID);
}
if (session.LastAccessed < DateTime.Now.AddHours(-1)) session.LoggedIn = false;
if (session.LastDestination.Equals("lesson"))
session.LastDestPageDestinationID = ContextValue(context, "lessonid");
else
session.LastDestPageDestinationID = 0;
if (session.IsNew) session.FirstDestination = session.LastDestination;
SaveSession();
return session;
}
private void SaveSession()
{
session.LastAccess = DateTime.Now;
session.LastDest = string.Empty;
db.UpdateSession(session);
if (!cookieIsSet)
{
// add a session cookie for this current session
HttpCookie cookie = CreateSessionCookie("usessionId", session.SessionID, 365);
if (session.LastDest.Equals("logout", StringComparison.OrdinalIgnoreCase))
cookie.Value = string.Empty;
if (session.LastDest.Equals("lessonOrder")) return;
context.Response.SetCookie(cookie);
}
}
internal void UpdateSession(USession s)
{
using (ourConnection conn = CreateConnection("UpdateSession"))
{
conn.CommandText = #"update csession set
closed = #closed,
userID = #customerID,
lastAccess = #lastAccess,
lastDestination = #lastDest,
orderId = #OrderId,
IsloggedIn = #isLoggedIn;
conn.AddParam("#id", s.Id);
conn.AddParam("#closed", s.Closed);
conn.AddParam("#userID", s.UserID);
conn.AddParam("#lastAccess", s.LastAccess);
conn.AddParam("#firstDestination", s.FirstDestination);
conn.AddParam("#lastDestination", s.LastDestination);
conn.AddParam("#isLoggedIn", s.IsLoggedIn);
conn.AddParam("#orderID", s.OrderID);
try
{
conn.ExecuteNonQuery();
}
catch (Exception ex)
{
LogException(ex);
}
}
}
public HttpCookie CreateSessionCookie(string cookieValue, string uSessionID, double daysTillExpiration)
{
HttpCookie cookie = new HttpCookie("usessionid", uSessionID);
cookie.Expires = DateTime.Now.AddDays(daysTillExpiration);
cookie.Path = "/";
return cookie;
}
So we'd work with the USession custom object in memory throughout our code for checking for loggedIn, to force close their session, and all sorts of stuff based on their current session.
Also in our Application_Error in global.asax we would log the current sessionId for tracking purposes on error.
HttpCookie cookie = Request.Cookies["usessionid"];
if (cookie != null)
{
logger.Variables = "<b>uSessionID:</b> " + cookie.Value;
if (cookie.Value.Length > 0)
logger.USessionID = GetUSessionID(cookie.Value);
}
The ASP.NET session has 3 possible states:
Off (my preferred) - don't use any session at all
InProc - the session is stored in the memory of the web server. Fast, but not convinient if you are running in a web farm because each node of the web farm will have a different copy of the session and you might get conflicts.
Out-of-Proc - the session is stored in memory of a specially dedicated server running the ASP.NET Session state Windows service. Good for webfarms scenarios but not reliable enough as the session is still persisted in the memory of some server which might not survive crashes.
SQL Server - the session is persisted in SQL server. Very reliable and suitable for web farms. Problem is with performance. It will be slower than the previous modes as the session is now persisted in the database.
The 3 modes are covered in depth in the following article.
The mode you choose is configured in web.config and it is completely transparent to your code in which you simply use the Session["someKey"] to work with the session, it's just the underlying storage mechanism that differs.

How can I create persistent cookies in ASP.NET?

I am creating cookies with following lines:
HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Response.Cookies.Add(userid);
Now how can I make it persistent?
If I visit the same page again after closing the browser, I'm unable to get it back.
Here's how you can do that.
Writing the persistent cookie.
//create a cookie
HttpCookie myCookie = new HttpCookie("myCookie");
//Add key-values in the cookie
myCookie.Values.Add("userid", objUser.id.ToString());
//set cookie expiry date-time. Made it to last for next 12 hours.
myCookie.Expires = DateTime.Now.AddHours(12);
//Most important, write the cookie to client.
Response.Cookies.Add(myCookie);
Reading the persistent cookie.
//Assuming user comes back after several hours. several < 12.
//Read the cookie from Request.
HttpCookie myCookie = Request.Cookies["myCookie"];
if (myCookie == null)
{
//No cookie found or cookie expired.
//Handle the situation here, Redirect the user or simply return;
}
//ok - cookie is found.
//Gracefully check if the cookie has the key-value as expected.
if (!string.IsNullOrEmpty(myCookie.Values["userid"]))
{
string userId = myCookie.Values["userid"].ToString();
//Yes userId is found. Mission accomplished.
}
Although the accepted answer is correct, it does not state why the original code failed to work.
Bad code from your question:
HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Response.Cookies.Add(userid);
Take a look at the second line. The basis for expiration is on the Expires property which contains the default of 1/1/0001. The above code is evaluating to 1/1/0002. Furthermore the evaluation is not being saved back to the property. Instead the Expires property should be set with the basis on the current date.
Corrected code:
HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(userid);
FWIW be very careful with storing something like a userid in a cookie unencrypted. Doing this makes your site very prone to cookie poisoning where users can easily impersonate another user. If you are considering something like this I would highly recommend using the forms authentication cookie directly.
bool persist = true;
var cookie = FormsAuthentication.GetAuthCookie(loginUser.ContactId, persist);
cookie.Expires = DateTime.Now.AddMonths(3);
var ticket = FormsAuthentication.Decrypt(cookie.Value);
var userData = "store any string values you want inside the ticket
extra than user id that will be encrypted"
var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name,
ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData);
cookie.Value = FormsAuthentication.Encrypt(newTicket);
Response.Cookies.Add(cookie);
Then you can read this at any time from an ASP.NET page by doing
string userId = null;
if (this.Context.User.Identity.IsAuthenticated)
{
userId = this.Context.User.Identity.Name;
}
As I understand you use ASP.NET authentication and to set cookies persistent you need to set FormsAuthenticationTicket.IsPersistent = true
It is the main idea.
bool isPersisted = true;
var authTicket = new FormsAuthenticationTicket(
1,
user_name,
DateTime.Now,
DateTime.Now.AddYears(1),//Expiration (you can set it to 1 year)
isPersisted,//THIS IS THE MAIN FLAG
addition_data);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, authTicket );
if (isPersisted)
authCookie.Expires = authTicket.Expiration;
HttpContext.Current.Response.Cookies.Add(authCookie);
You need to add this as the last line...
HttpContext.Current.Response.Cookies.Add(userid);
When you need to read the value of the cookie, you'd use a method similar to this:
string cookieUserID= String.Empty;
try
{
if (HttpContext.Current.Request.Cookies["userid"] != null)
{
cookieUserID = HttpContext.Current.Request.Cookies["userid"];
}
}
catch (Exception ex)
{
//handle error
}
return cookieUserID;
//add cookie
var panelIdCookie = new HttpCookie("panelIdCookie");
panelIdCookie.Values.Add("panelId", panelId.ToString(CultureInfo.InvariantCulture));
panelIdCookie.Expires = DateTime.Now.AddMonths(2);
Response.Cookies.Add(panelIdCookie);
//read cookie
var httpCookie = Request.Cookies["panelIdCookie"];
if (httpCookie != null)
{
panelId = Convert.ToInt32(httpCookie["panelId"]);
}

Best way to determine if cookies are enabled in ASP.NET?

What is the best method for determining if a users browser has cookies enabled in ASP.NET
Set a cookie, force a redirect to some checking page and check the cookie.
Or set a cookie on every pageload, if it's not already set. For instance, I assume this is to check if cookies are supported to display a message when they try to login that they need to enable cookies. Set your login cookie to some default value for guest users if they don't have the cookie set yet. Then on your login page, check for the user cookie, and if it's not set, then display your message.
#Mattew is right the only way to find out is to set a cookie, redirect, then check it.
Here is a C# function to preform that check you can put this in your page load event:
private bool cookiesAreEnabled()
{
bool cookieEnabled = false;
if(Request.Browser.Cookies)
{
//Your Browser supports cookies
if (Request.QueryString["TestingCookie"] == null)
{
//not testing the cookie so create it
HttpCookie cookie = new HttpCookie("CookieTest","");
Response.Cookies.Add(cookie);
//redirect to same page because the cookie will be written to the client computer,
//only upon sending the response back from the server
Response.Redirect("Default.aspx?TestingCookie=1")
}
else
{
//let's check if Cookies are enabled
if(Request.Cookies["CookieTest"] == null)
{
//Cookies are disabled
}
else
{
//Cookies are enabled
cookieEnabled = true;
}
}
}
else
{
// Your Browser does not support cookies
}
return cookieEnabled;
}
You can do it in javascript also, this way :
function cookiesAreEnabled()
{
var cookieEnabled = (navigator.cookieEnabled) ? 1 : 0;
if (typeof navigator.cookieEnabled == "undefined" && cookieEnabled == 0){
document.cookie="testcookie";
cookieEnabled = (document.cookie.indexOf("test­cookie") != -1) ? 1 : 0;
}
return cookieEnabled == 1;
}
Write a cookie, redirect, see if you can read the cookie.
Well I think if we can save cookie in Global.ASAX session start and read that on page.. isnt that best way?
Essentially the same solution as meda, but in VB.NET:
Private Function IsCookieDisabled() As Boolean
Dim currentUrl As String = Request.RawUrl
If Request.Browser.Cookies Then
'Your Browser supports cookies
If Request.QueryString("cc") Is Nothing Then
'not testing the cookie so create it
Dim c As HttpCookie = New HttpCookie("SupportCookies", "true")
Response.Cookies.Add(c)
If currentUrl.IndexOf("?") > 0 Then
currentUrl = currentUrl + "&cc=true"
Else
currentUrl = currentUrl + "?cc=true"
End If
Response.Redirect(currentUrl)
Else
'let's check if Cookies are enabled
If Request.Cookies("SupportCookies") Is Nothing Then
'Cookies are disabled
Return True
Else
'Cookies are enabled
Return False
End If
End If
Else
Return True
End If
End Function
meda's c# function works though you have to change the line:
HttpCookie cookie = new HttpCookie("","");
to
HttpCookie cookie = new HttpCookie("CookieTest","CookieTest");
You can also check the value of Request.Browser.Cookies. If true, the browser supports cookies.
this is the best way
taken from
http://www.eggheadcafe.com/community/aspnet/7/42769/cookies-enabled-or-not-.aspx
function cc()
{
/* check for a cookie */
if (document.cookie == "")
{
/* if a cookie is not found - alert user -
change cookieexists field value to false */
alert("COOKIES need to be enabled!");
/* If the user has Cookies disabled an alert will let him know
that cookies need to be enabled to log on.*/
document.Form1.cookieexists.value ="false"
} else {
/* this sets the value to true and nothing else will happen,
the user will be able to log on*/
document.Form1.cookieexists.value ="true"
}
}
thanks to Venkat K

Resources