Is it possible to persist cookies between visual studio debug sessions - c#

I have an authentication cookie that gets set after I hit a login screen in my local environment. That cookie has been set to be persistent and has been given a timeout period of 7 days in the future.
When I end my debug session and start debugging after another build the cookie is not present. This happens for every browser. Is there a way to get Visual Studio to remember the persistent cookie after a debug session completes?

The solution I found was to make it so that new instances of .NET Core MVC would not open up in a brand new window, but an existing one. I changed one setting
1)Tools menu
2)Options...
3)Debugging > General
4)Uncheck "Enable JavaScript debugging for ASP.NET"
And when I run the app with F5 an instance fires up in an existing instance of chrome and I can reuse the cookies that are already in existence. With that box checked it always opens into a new instance of chrome and cookies are not present.

Assuming you are using VS and ASPNet 4.5 or core 1.0/2.0 under IIS, check your debug output on start up and you might see :
“Neither user profile nor HKLM registry available. Using an ephemeral key repository. Protected data will be unavailable when application exits.”
This is caused by the DataProtection keys used by IIS. Follow this short blog post to resolve

Let’s have a quick look how to make cookies as persistent
//Creting a Cookie Object
HttpCookie _userInfoCookies = new HttpCookie("UserInfo");
//Setting values inside it
_userInfoCookies["UserName"] = "Abhijit";
_userInfoCookies["UserColor"] = "Red";
_userInfoCookies["Expire"] = "5 Days";
//Adding Expire Time of cookies
_userInfoCookies.Expires = DateTime.Now.AddDays(5);
//Adding cookies to current web response
Response.Cookies.Add(_userInfoCookies);
Now once you have set with the Cookies expires time , it will be stored in hard drive until expires or user manually delete or clear all the cookies. If you want your cookies need to be expires before the expiration time that you have mentioned earlier, you just need to override the cookies information.
HttpCookie _userInfoCookies = new HttpCookie("UserInfo");
//Adding Expire Time of cookies before existing cookies time
_userInfoCookies.Expires = DateTime.Now.AddDays(-1);
//Adding cookies to current web response
Response.Cookies.Add(_userInfoCookies);
So Just Work on Expiration.
and take a look at This

Related

.net core 2.2 Session logout

So I have a problem with my session logout. After 20 minutes I get redirected to the home page of my website.
I've looked at Session Services but they all show ways to use the session timeout to make it so a label name or id just goes away after the set time. How do I change the Session timeout from default to any other time. I've added
services.AddSession(opts =>
{
opts.IdleTimeout = TimeSpan.FromSeconds(10);
});
to my Startup.cs folder and added app.UseSession() to the Configure but the timeout doesn't time me out in 10 seconds.
I know inside asp.net there is a web.config file that you can set the timeout time in my .net core doesn't have a web.config.
GDPR (no, seriously).
Core 2.1 introduced some tooling that assists with GDPR compliance by not storing non-essential cookies until a user consents to cookie storage. Unfortunately session state uses cookies, and since session state is used for all sorts of things, MS defaulted session state cookies to non-essential.
The easiest way to fix this is to implement the cookie consent form and accept it, but there are other workarounds that can be found here.

invalidate aspx authentication cookie

I have an asp.net web form. when a user authenticate, it create a Secured cookie called .aspxauth
uppon logout, I call these 2 methods
FormsAuthentication.SignOut();
Session.Abandon()
Problem is that we had penetration test and if I steal the cookie, logout and manually reinsert the cookie, I become loggued in again. So the .aspauth isn't invalidated server side.
I've googled it and I can't find the answer to that security breach.
Microsoft has acknowledged this issue here: https://support.microsoft.com/en-us/kb/900111
They offer several ideas for mitigating this vulnerability:
protect the application by using SSL
Enforce TTL and absolute expiration
Use HttpOnly cookies and forms authentication in ASP.NET 2.0
Use the Membership class in ASP.NET 2.0
Regarding the last one, I'll paste the contents from the site for convenience/preservation:
When you implement forms authentication in ASP.NET 2.0, you have the option of storing user information in a Membership provider. This option is a new feature that is introduced in ASP.NET 2.0. The MembershipUser object contains specific users.
If the user is logged in, you can store this information in the Comment property of the MembershipUser object. If you use this property, you can develop a mechanism to reduce cookie replay issues in ASP.NET 2.0. This mechanism would follow these steps:
You create an HttpModule that hooks the PostAuthenticateRequest event.
If a FormsIdentity object is in the HttpContext.User property, the FormsAuthenticationModule class recognizes the forms authentication ticket as valid.
Then, the custom HttpModule class obtains a reference to the MembershipUser instance that is associated with the authenticated user.
You examine the Comment property to determine whether the user is currently logged in.
Important: You must store information in the Comment property that indicates when the user explicitly signed out. Also, you must clear the information that is in the Comment property when the customer eventually signs in again.
If the user is not currently logged in as indicated by the Comment property, you must take the following actions:
Clear the cookie.
Set the Response.Status property to 401.
Make a call to the Response.End method that will implicitly redirect the request to the logon page.
By using this method, the forms authentication cookie will only be accepted if the user has not been explicitly signed out and the forms authentication ticket has not yet expired.
Read this article about Session fixation and how to get rid of it once and for all:
http://www.dotnetfunda.com/articles/show/1395/how-to-avoid-the-session-fixation-vulnerability-in-aspnet
This remains an issue in .NET Framework. Everyone seems to think Session.Abandon() is the answer, but the sad truth is that command does not invalidate the session on the server's side. Anyone with the right token value can still resurrect a dead session, until the session expires based on the Web.config settings (default = 20minutes).
A similar questioner posed this question a long time ago here:
Session Fixation in ASP.NET
Most of those links are dead, and Microsoft has no new news on the topic.
https://forums.asp.net/t/2154458.aspx?Preventing+Cookie+Replay+Attacks+MS+support+article+is+now+a+dead+link
Worse still, you're still vulnerable to this cookie replay attack even if you're implementing a completely stateless MVC application and don't use the Session object to store data between views. You can even turn off session state in the web.config settings and still replay cookies to gain access to a logged-out session.
The true solution is hack-y and described here, and you need to have session data enabled InProc to use it.
When the user logs in, set a boolean value in the session data, like Session["LoggedIn"] = true;, which is stored on the server side.
When the user logs out, set that value to false.
Check the session value on every request--an attacker trying to replay a session isn't going to be nice to you and come in through the Login page only. It's probably easiest to do this using a custom filter and registering it globally in the global.asax file (so you don't have to duplicate the code everywhere, or attribute every controller/method).
Even if the attacker has all the cookie values, they won't be able to re-use that same session ID, and the server will automatically delete it once it reaches the specified timeout.
if you are using the FormsAuthentication, you can use this code. By using this code you can destroy the created cookies by setting the Expire property of HttpCookie. It will help you:
FormsAuthentication.SignOut();
Session.Clear();
Session.Abandon();
Session.RemoveAll();
// clear authentication cookie
HttpCookie httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, "");
httpCookie.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(httpCookie);

Intermittent cookie issues - Chrome / C# ASP.NET MVC / Umbraco

I'm having some really weird cookie issues on a website. It's an ASP.NET website, uses Umbraco 6.1.6 as its CMS but is mainly custom code and uses Forms Authentication for user login. It runs on IIS Server 2012 R2.
On successful registration, the user credentials are passed to the login method, which sets a cookie like this:
var authTicket = new FormsAuthenticationTicket(realUsername, false, 60);
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
{
HttpOnly = true,
Secure = FormsAuthentication.RequireSSL,
Path = FormsAuthentication.FormsCookiePath,
Domain = FormsAuthentication.CookieDomain,
Expires = authTicket.Expiration
};
HttpContext.Current.Response.Cookies.Set(cookie);
It then does a redirect, trying to go to wherever the user was previously on the site before registering.
return Redirect(redirectUrl);
From the redirected page, it checks the request cookie to see whether the user was logged in:
HttpCookie authCookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
Sometimes the authCookie contains the session data, and works for long periods of time..... and other times it is null - for equally long periods of time - so it only intermittently works.
This led me to believe that perhaps IIS is having trouble checking the request cookie on redirect - because the cookie has not yet reached the user's browser. But various docs and other SO posts tell me this should work when I am using a ResponseRedirect type redirect.
The bit where it gets weird is that when I've just registered but the server thinks I'm not logged in, I can look at the cookies for this "not logged in" page in Chrome dev tools, and it's true - there's no cookie set - however, when you click on the site's "Login" button from the "not logged in" page... which forces it to check whether the user is logged in again, this time "authCookie" contains cookie data. Right after Chrome told me this data was not present when I submitted the page! The cookie then reappears in dev tools when the "logged in" page is returned.
At this point, I don't know whether it's that I can't trust Chrome dev tools, or it's that there's some odd browser caching / IIS caching going on, or what. I tried looking up cookie / redirection issues and they only seem to come up with newer versions of IE.
I've tried closing the browser, closing visual studio, and that doesn't seem to have a direct impact.
One last bit of information - I read in one post here that there are sometimes issues when the registration / login is performed on one thread but the code after registration is performed on another thread. I checked the thread debugger and found that indeed the registration / login were being performed on different threads... but this was observed when it was working.
The most frustrating part is when it suddenly starts working for a few hours - and there's seemingly nothing I can do to break it again to try out different things. (Which is where I am now! I wanted to at least try it in different browsers...)

session never destroy for application in any browser

Here is the story of me creating a web application using ASP.NET 4.5 with EntityFramework. I use ASP.NET control for login and logout functionalities. Now, my issue is that I want to create such application in which I need user to be always logged in to the application after closing the browser or system as a Gmail account.
I tried searching on net but didn't get any proper results. How I can implement this by using session for any browser?
Session is the term derived one instance of the browser, means till the browser gets closed.
To have user session even if browser gets closed, create a cookie.
HttpCookie myCookie = new HttpCookie("cookieUser");
DateTime now = DateTime.Now;
// Set the cookie value.
myCookie.Value = now.ToString();
// Set the cookie expiration date.
myCookie.Expires = now.AddMinutes(10);
// Add the cookie.
Response.Cookies.Add(myCookie);
Gmail also works in the same way.
Remember me at this computer explicitly saves the cookie
Hope this helps.

Browser occasionally losing HttpCookie for authentication after postback and redirect

This has been a nagging issue for some time, but very sporadic and difficult to isolate.
From time to time, browsers that have authenticated on a web application, have been open for a while, have logged in and out of the same web application multiple times, have multiple tabs, are pretty much any browser (Chrome, IE, Firefox, Safari), and seemingly at random, lose their ability to retain an AuthCookie after being set and followed by a redirect. Closing the browser and starting a new session resolves the issue, as does opening up a different browser and attempting to authenticate.
Our team uses forms authentication for all of our websites and web application. This is a pretty typical setup where a login form is displayed, the user enters credentials and a cookie is set on the click event of the postback, then a redirect occurs to the same page where the cookie is then referenced and used to complete authentication.
In this situation
FormsAuthentication.FormsCookieName = ".WebAuth"
Within Event:
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, Username, DateTime.Now, DateTime.Now.AddMinutes(SessionTimeout), false, Username);
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(faCookie);
Response.Redirect(Request.RawUrl, true);
After the redirect, on PreInit:
HttpCookie authCookie = Request.Cookies[cookieName];
At this point, the authCookie variable is typically not null, but in these isolated circumstances that I've outlined above, the cookie comes back null after the redirect.
This happens very randomly, sometimes weeks before affecting one of our developers. As I said, restarting the browser resolves the issue.
Today I had it happen on our dev server while using Chrome. I had logged into the application, allowed the application to session timeout, and then attempted to login again. The attempted login then failed to set the cookie. I remotely attached Visual Studio to the process on the server to begin debugging. The entire time I could step through my code, even deploy new code versions to the server with updates, restart the app, restart IIS on the server, attach and reattach to the project, and the issue persisted in Chrome. In Firefox, I was able to authenticate without issue.
From Chrome, the login would validate, attempt to set a Response Cookie as outlined above. Prior to redirect, I could see the properly set Response Cookie, as well as its counterpart in the Request Cookies. However, on each redirect after a seemingly successful login, the Response and Request Cookie are gone.
I enabled Trace on the application to view the cookie collection:
There is a .WebAuth in the Request Cookies Collection, as well as ASP.NET_SessionId and several ASPSESSIONIDxxxxxxxx, but when the page loads, only the ASP.NET_SessionId and ASPSESSIONIDxxxxxxxx cookies are available in the Request.Cookies scope, no sign of the .WebAuth. However, in the page's Trace information after render, there multiple .WebAuth cookies listed, it is just that the page seems to have no access to them.
Primarily, on a working version after authentication there is both a .WebAuth Response and Request Cookie in the page's Trace info. But on a non functioning browser window, the Response Cookie is absent.
Has anyone else had any experience with this? It is such a nagging issue, and so sporadic, but I would love to be able to resolve it. My concern is that it may be affecting users and we would have no knowledge since the description of the issue is so convoluted.
Based on your scenario you may be running into browser's restrictions on number of cookies per domain/total. The limits are relatively high, but exist (spec: http://www.ietf.org/rfc/rfc2109.txt, section 6.3 , some recent information - http://www.nczonline.net/blog/2008/05/17/browser-cookie-restrictions/)
If you get it happening again try to look at actual server responses (i.e. using Fiddler) to see if cookies are send to the browser. Check what cookies are set for the domain and current page (depending on browser there are different ways of doing it, in all browsers you can see some cookies by running following in address bar javascript:alert(document.cookie) )
This is a non-persistent cookie issue. Session simply times out.
Try changing false to true in this line:
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, Username, DateTime.Now, DateTime.Now.AddMinutes(SessionTimeout), true, Username);
Also add
faCookie.Expires = DateTime.Now.AddMinutes(SessionTimeout);
I have fall in similar situation, things was certain as you described. But, later the reason have been found.
ASP.NET and IIS understood MyApplication and myapplication as one equal, but browsers undertood them as different. So, when we set auth cookies for /MyApplication, they were not sent to the server, when we go to /myapplication.
The fix is next:
protected void Application_BeginRequest(object sender, EventArgs e)
{
string url = HttpContext.Current.Request.Url.PathAndQuery;
string application = HttpContext.Current.Request.ApplicationPath;
if (!url.StartsWith(application))
{
HttpContext.Current.Response.Redirect(application + url.Substring(application.Length));
Response.End();
return;
}
}

Categories