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.
Related
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
It appears that I am able to read the SessionID at any time, even if no cookie currently exists!
Dim SessionID As String = Request.Cookies("ASP.NET_SessionId").Value
This code will always return a value, presumably the ID held by IIS server side.
The cookie appears to be generated only when a request to store session information is made.
Why is this?
and ...
If I am using session state server will the SessionID ever differ from the cookie SessionID and which take priority if one of the ID's is lost or reset?
EDIT
If the app_pool is reset. A new session ID must be created will this cause the session cookie to be updated also? As this could create potential conflicts for users already logged in.
When a user accesses a website powered by ASP.NET IIS generates a SessionID to uniquely idetinfy the users session.
If the website is using cookies:
<sessionState mode="StateServer" cookieless="UseCookies"/>
A cookie named ASP.NET_SessionId will be generated only when a request to store session information is made by the webpage. If no session information is stored a cookie will not be created but the user will still have an active SessionID.
The SessionID is read from IIS when no cookie is present.
The SessionID on the server always takes precedence and will update the session cookie when a new request to store information in the cookie is made.
Every time that an user access the website and a session is opened ASP.Net by default creates a SessionID unless you specify the cookieless option:
If you are using a session state server the SessionID should be the same across all web servers otherwise you wouldn't be able to find the same user.
If the ID is lost or reset the state server will simply create a new one and write a new cookie with the new SessionID and the old one will be deleted after the expiration time.
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);
I'm using facebook to authenticate users at my website. I need to delete facebook cookie on logout from serverside with C#. could you please show me how to do it? tested and working example
Assuming you know the name of the cookie, you can set it's expiry date to some time in the past. When the browser receives the cookie, it will see that it's expired and delete it.
If you're using a System.Web.HttpCookieCollection, this MSDN article has example code which demonstrates this (example adapted from that on MSDN):
if (Request.Cookies["NameOfFacebookCookie"] != null) {
HttpCookie myCookie = new HttpCookie("NameOfFacebookCookie");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
Since you're authenticating users through Facebook, I'm assuming you're using OAuth. In this case, you don't know the name of the cookie, and in any case it isn't your cookie, it's set by facebook.com during the login process. To log off a user who's signed in via Facebook, see this answer.
I don't understand why I can't "comment" when, but whatever; to add to the discussion between Alexei and Cameron above, the assumption there is that the cookie is controlled by Facebook. If you used the Javascript SDK, then yes, Cameron's comment is true. However, if instead you created a manual login flow (no SDK) so that you could server-side handle the login, then you likely created your own cookie to save the retrieved access_token, and of course, you could delete that.
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;
}
}