I have a ASP.NET Core 1.1.2 project in which I am using cookie authentication. I am having a problem where users are being prompted to log back in after being idle for an hour or less, and losing work. The code below is what I'm using in the Configure function in Startup.cs to set this up and from what I can tell, it should expire after at least 8 hours. BTW, ProjectProcessFlow is just the name of the project.
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "ProjectProcessFlow",
LoginPath = new PathString("/Account/Login/"),
ExpireTimeSpan = new TimeSpan(8, 0, 0),
SlidingExpiration = true,
AutomaticAuthenticate = true,
AutomaticChallenge = true
});
I am including Microsoft.AspNetCore.Authentication.Cookies v1.1.2 in NuGet. What do I need to do to get the login expiration to happen at the expected time?
Additional Information:
I found that when the timeout happened and the user was asked to login again, a warning was recorded in the Event Viewer on the server that it couldn't find the logs folder under the project. So I created that folder, and waited for the timeout to happen again. When that happened, a log file was created in that folder that contained this:
Hosting environment: Production
Content root path: C:\inetpub\wwwroot\Sprout
Now listening on: http://localhost:13423
Application started. Press Ctrl+C to shut down.
When I repeated this process, the same thing happened, except that a different number appeared after "localhost:". I should mention that the project name is ProjectProcessFlow, but the URL ends in Sprout.
I know that is too late for answering this question, but for whom facing this.
The IIS reset pool every 20 minutes and every 20 mins ASP.NET generate new key for protect cookie values (Authentication and Session). to prevent this, add following code to ConfigureServices in Startup class
services.AddDataProtection()
.PersistKeysToFileSystem(new System.IO.DirectoryInfo("SOME WHERE IN STORAGE"))
//.ProtectKeysWithCertificate(new X509Certificate2());
.SetDefaultKeyLifetime(TimeSpan.FromDays(90));
A complete guide is here. It is all about DataProtection
users are being prompted to log back in after being idle for an hour
or less, and loosing work.
I have similar configuration, but it works fine for me.
One thing I can think of is you cannot let web server idle for 20 minutes. IIS's app pool default idle time-out is 20 minutes (I could not say for other Linux web server).
So you could either set longer app pool time-out (0 for infinity), or ping every 5 minutes from external service like Monitis.
Do you have services.AddIdentity set up in your ConfigureServices method?
services.AddIdentity<ApplicationUser, IdentityRole>(config =>
{
// Require a confirmed email in order to log in
config.SignIn.RequireConfirmedEmail = true;
// Cookie settings
config.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromHours(10);
config.Cookies.ApplicationCookie.LoginPath = "/Account/LogIn";
config.Cookies.ApplicationCookie.LogoutPath = "/Account/LogOut";
}).AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();
I had a similar issue and resolved it here
ASP.NET MVC Core Identity & Cookies
Related
I have an ASP .Net Core application (Razor Pages). Set IdleTimeout to 30 minutes :
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(60);
}
);
It works fine except that when the user exceeds 30 minutes he will be redirected to the login page (session expires).
How can I extend the duration automatically while the user is working?
The answer is, you shouldn't. This would be a security risk in my opinion.
It would be better to get the user to save their changes frequently which in turn will keep the session alive.
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.
In my startup class, I am enabling session storage with this line:
services.AddDistributedMemoryCache()
.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(20);
options.Cookie.HttpOnly = true;
})
However, if I understand this correctly, setting the IdleTimeout property simply states that the session will begin anew if the user does not complete any actions for > 20 minutes. My app has polling which uses user information in the session storage every 5-10 seconds, so I don't think this would ever be of use here. User permissions and roles can change from actions made outside of the current user's browser, so I would like to limit the session storage to 1 minute. I can't seem to find any exact verbiage on what the default expiration is or how to properly set that.
The CookieBuilder class has Expiration and MaxAge options, but I don't know which one is necessary. I've also read that Expiration is ignored, so that adds even more to my confusion in this subject.
Update: I receive this message when I try to set the expiration: "Expiration cannot be set for the cookie defined by SessionOption", so I've set MaxAge to 1 minute, yet I can see that the session still has old user data in it after more than 1 minute has passed.
Session does not have an 'expiration' like cookies do, but the default Idle Timeout is 20 minutes, and can be adjusted using the IdleTimeout option.
Session only expires after the idle timeout period has elapsed. Additionally, the idle timeout starts after the last request is received.
For your case, the session will not expire because you poll every 5 - 10 seconds (checking the session data). This polling is seen as a 'request' to the .net core, and resets the timeout.
You can verify this by disabling the polling, and creating a page with a button that checks the session data. Wait for a period of time (ex: 20 seconds), and click the button.
Make sure that you set the Idle Timeout to a low value:
options.IdleTimeout = TimeSpan.FromSeconds(10);
Here is a link to the Documentation on Session.
This code below runs on the development environment, but when deployed on Windows Server 2012 R2 the DsCookie cookie could not get the values created from the cookie creation.
It uses MVC 4 with Entity Framework v4 and jQuery.
HttpCookie ds_id = new HttpCookie("ds");
ds_id.Value = reqCookie.ToString();
ds_id.Expires = DateTime.Now.AddHours(1);
Response.SetCookie(ds_id);
Response.Flush();
private HttpCookie DsCookie
{
get
{
return Request.Cookies["ds"];
}
}
Does anyone know why my solution only works in a development environment and not live?
May be there is a difference between the server time and your local time.
The code
DateTime.Now.AddHours(1);
takes the server time.
And if the server time is 1 hour earlier than your local pc time, the cooke will be created and deleted immediately.
Check the server time, if this is the case, change the expiration time like
ds_id.Expires = DateTime.Now.AddHours(10); //Or more.
Or you can precise time difference and :
ds_id.Expires = DateTime.Now.AddHours(1 + time difference between the server and your local time);
You haven't provided a great variety of information so here's my guesses based on what I can think of.
Check your IIS settings
Under your IIS settings, head to your website deployment then under the features panel, navigate to IIS > Authentication > Check you have the correct authentication methods in place. You could also verify that you are allowing all users to authenticate via cookie authentication
Web.config must allow IIS to send cookies to you
If your web.config file is not set up correctly, it may be preventing your deployment from sending cookies. Read through and check that it allows IIS to send them out.
Try adding a single day like so
If you don't receive a cookie, it could be that the cookie is instantly deleted? It's rare, but it happens. Try doing this instead:
ds_id.Expires = DateTime.Now.AddDays(1d);
This should make the cookie persist
Check the server's datetime is correct
If it isn't this could very well be the root of the issue. It sounds silly, but it has been a legitimate problem in the past for some.
Make sure your browser accepts the cookie
If you have any options in your browser to reject cookies, this will prevent you from accepting the login and therefore it will be almost as if you can't log in.
If you still have problems after these fixes, please let us know and provide a bit more detail and we might be able to help narrow down the issue for you.
As an additional note, this is a much better (and cleaner) way of doing this:
var dsCookie = new HttpCookie("dsCookie")
{
Value = reqCookie.ToString(),
Expires = DateTime.Now.AddHours(1)
};
Response.Cookies.Add(dsCookie);
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