How to reload a page without deleting the cookie - javascript

Im doiing a web app and Im already in the part where theuser has an option to change the language of the app, ex. from en-US to ja, I'm using i18next. What I did was write the user's preferred language to cookie, reload the page, and read the cookie I created with the user's preferred lang. however it doest work because it seems that everytime you reload the page, the cookie that I created is deleted, so it reverts back to the default lang.
The question is there a way to reload the page without deleting the cookie that I made?

Try setting an expiry date on the cookie. Code below sets it one year in the future.
a = new Date(new Date().getTime() +1000*60*60*24*365);
document.cookie = 'mycookie=somevalue; expires='+a.toGMTString()+';';
Please give it a shot and check the resources tab again to see if it's changed.
Here is some info regarding cookie syntax and options.

This might happen while development time, once you deploy the app it may not occur.
please deploy the app into local IIS and test it weather you facing same problem.
also hope you added expiry time for cookie. its some thing like below
HttpCookie aCookie = new HttpCookie("SiteLanguage");
aCookie.Value = "en-US";
aCookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(aCookie);

Related

How can I clear browser cache (memory / disk cache) after logout?

I use asp net core mvc + js. One type of my pages have cache.
[ResponseCache(Location = ResponseCacheLocation.Client, Duration = 60)]
public async Task<IActionResult> StaticContent(string path)
{
// code
}
I have a problem when user logout on this page. User sees his account after logout because page was cache. If refresh page cache clear and user does not see account.
I try location.reload(); on js when logout click but reload work earlier than logout work on server. I try change Vary header but I change Vary only page which I redirect after logout
How can I clear cache after logout? Any ideas?
As the King King says, if you enable the client cache , there is no way to tell the client side in the server-side. The only way is just tell the CX to clear the cache. Since once the browser obeys the cache rules you send here, the only opportunity you will have to retract your cache rules is the next time the browser requests the page.
Normally, the dynamic pages should not attempt to set client-side caching if you want them to stay dynamic.
I find answer on microsoft site https://learn.microsoft.com/en-us/aspnet/core/performance/caching/response?view=aspnetcore-5.0#responsecache-attribute
They say don`t cache content which using user info.
I cache individual parts of page without account info.
I use
<cache expires-after="" />
Thanks all
In your logout post, you can clear a session that may solve your problem.
HttpContext.Session.Clear(); //this will clear all session
HttpContext.Session.Remove("sessionName"); //this will clear a specific session

How can I safely implement idle timeout when using identityserver4 and aspnet identity?

I'm working on an identityserver4 login site (server UI) with .NET Identity in .NET Core 2.2 Razor Pages, I have a javascript modal alert that warns users of a pending idle timeout, and then when reaching timeout it redirects the user to the logout screen by setting window.location
The trouble I have is that the OnGet in the quick start sample shows a user prompt to log out as at this point logoutId is null. I want to log out without prompting the user.
For the time being I have worked around this by passing an "autoLogout" parameter to my Logout page which bypasses the check for logoutId and sets ShowLogoutPrompt = false. I'm aware that this somewhat defeats the purpose of checking for logoutId to ensure that it is safe to sign-out without prompt.
Is there a better way to do what I'm trying to do?
Edit 16 Jul 2019:
It seems as though the "right" way to handle idle timeout is to set the application cookie's token expiry (to say 20 minutes) and enable SlidingExpiration so that the token is renewed when the user refreshes. For good info on this see this blog post, this github issue thread (including comments from Brock Allen), and this info in the MS docs.
My trouble is that this solution has two huge drawbacks.
SlidingExpiration only refreshes the cookie if the user is >50% through the token's TimeSpan (see SlidingExpiration info in MS docs here). So if they refresh 9m59s into a 20 minute token they will timeout after just 10 minutes instead of 20. One workaround would be to set the token lifetime to 40 minutes, which would give the user at least 20 minutes of idle time, but they could have up to 40 minutes of idle time which is not acceptable.
One of my requirements is a modal to warn the user of an impending timeout and give them the option to continue/log out. To do this using this cookie approach I would need to read the token expiry time from the cookie in my Javascript (or at least in my Razor Page in C#) to enable me to time when to show the warning. Even without the modal requirement I'd need to know when the token has expired so that I could cause a page refresh to send the user to the login screen. I'm attempting to read the expiry time using the following code but it fails to read the correct expiry time after a token refresh until the page is refreshed a second time, I don't know why.
#(DateTime.Parse(((await Context.AuthenticateAsync()).Properties.Items)[".expires"]))
Another less significant drawback to the cookies approach is that if I manage to implement a modal popup and the user opts to continue, then the page will need a refresh to get a new token, at which point any unsaved data would be lost. I guess if they time out then unsaved data would be lost anyway though so this is a relatively minor point compared with the above.
I'm thinking of going back to my original solution which has the desired functionality but would be open to abuse by an attacker who noticed my autoLogout parameter in the idle timeout javascript and could then use it to provide a hotlink to the logout page. At the moment taking that risk feels like my best option.
I feel like I've been down a rabbit hole on this one and still have no good solution. It amazes me that what I imagine to be a common use case (idle timeout with a warning allowing the user to continue/log out) is so poorly catered for with this authentication technology. Am I missing something? Do I have the wrong end of the stick?
I'm posting my final solution here. It works but I don't like it much. For references, details on why I think it's a bit hacky, and of what I think the main drawbacks are see the 16th Jul edit to my original question above.
In ConfigureServices after adding identityserver I set the cookie's SlidingExpiration = true; ExpireTimeSpan = AppSettings.IdleTimeoutMins (see this blog for how I set up AppSettings):
// Rename the .AspNetCore.Identity.Application cookie and set up for idle timeout
services.ConfigureApplicationCookie(options =>
{
options.Cookie.Name = "xxxx.Application";
options.SlidingExpiration = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(_config.GetValue<int>("AppSettings:" + nameof(AppSettings.IdleTimeoutMins)));
});
I have a Partial Razor Page in which I have javascript code to display a modal alert to the user with a count down timer. I get the timeoutSeconds from AppSettings.IdleTimeoutMins and also have a setting to determine when to show the warning. For more detail on this bit (and its pros and cons) see my other question and answer here: How to get ASP.NET Identity authentication ticket expiry in Razor Page? The warning message gives the user the option to "Continue" which refreshes the page (and therefore the authentication ticket) or "Log Out", which sends them to the Log Out confirmation page. If the clock runs down then the page is refreshed, which causes them to be returned to the Log In screen.
At the top of the Partial:
#inject RussellLogin.Services.IAppSettings AppSettings;
#using Microsoft.AspNetCore.Authentication;
Getting the (assumed) number of seconds remaining on the ticket:
secondsRemaining = "#(DateTime.Parse(((await AuthenticationHttpContextExtensions
.AuthenticateAsync(Context))
.Properties
.Items)[".expires"])
.Subtract(DateTime.Now)
.TotalSeconds)";
// If secondsRemaining is less than half the expiry timespan then assume it will be re-issued
if (secondsRemaining < timeoutSeconds / 2) {
secondsRemaining = timeoutSeconds;
}

How to store cookies instantly and permanently?

I'm developing a website in MVC and I'm setting/updating cookies like this on my action method:
HttpCookie cookie = new HttpCookie("cookie_name");
cookie.Expires = DateTime.Now.AddDays(30);
cookie.Value = cookieValue;
Response.SetCookie(cookie);
Now, this works just fine. But, if I kill Chrome right after this, the next time I access the website, the cookie is not there (or it has an older value and not the last one).
I've checked the 'Cookies' file stored in 'C:\Users\my_user\AppData\Local\Google\Chrome\User Data\Default' and it seems it is only updated approximately once every minute or so. It looks like new cookies are all stored in RAM for a while and then saved as a batch to the hard drive.
I've also tried to set the cookie directly with javascript (using js-cookie library) but the outcome was the same:
Cookies.set('cookie_name', 'cookie_value', { expires: 30 });
Is there a way to store cookies instantly and permanently?

IE9 cookies not working once browser is close and open?

i Have done application using Extjs 4.1. Have login page with remember me option. Here we are storing the remembered user information in cookie using java script, Once the use login the application with remember me option, his information will be storing in cookie till 7 days from date of login. This feature is working very fine in all browser except IE9. In IE9, if i login with remember me option, it will remember till i close the application. once i closed and open the browser next run the application. It is not remembered me. but when i visited developer tools-> view cookie information, it contains my login information. next again i reloaded the application remember me is working. Again i have closed browser and opened remember is not working without opening developer tools. if i open developer tools option and reload application remember me working. Why should i need to open developer tools each time whenever i close the browser. Can any body tell me how to resolve this issue? any IE9 browser setting problem? Great appreciated. Thank you.
Here is my code:
var check = Ext.getCmp('chkBoxId').getValue();
var username = Ext.getCmp('userId1').getValue();
var Password = Ext.getCmp('paswordId').getValue();
if(check==true)
{
var now = new Date();
var time = now.getTime();
var expireTime = time + 604800000//1000*36000;
now.setTime(expireTime);
var tempExp = 'Wed, 31 Oct 2012 08:50:17 GMT';
document.cookie = 'AddedCookie='+username+'/'+Password+'/'+check+';expires='+now.toGMTString()+';path=/';
}
else{
document.cookie = 'AddedCookie='+username+'/'+Password+'/'+check+';expires='+new Date()+';path=/';
}
You shouldn't be using javascript with your login cookie.
Use SSL, and useSSL-only cookies.
Create the cookie on the server, with the HTTP-only flag.
Store an authentication ticket in the cookie, not the password.
Don't store the user's password in your database, store a salted hash.
Otherwise, for cookies, you can try http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.util.Cookies to make it easier.
Issue is resolved, actually i have written in code console.log(something);. In IE9 it wont recognize this is causing the problem. Now it is working very nicely. so it means dont have to keep console.log() in code.

CodeIgniter destroying my session without

So, my current task involves a site where people can sign in, and view a series of training videos on a particular topic. I developed this within CodeIgniter. The only trouble is that once I have them log in, and I create a session, that session seems to mysteriously disappear after a few minutes, and they're mysteriously bounced back to the login page (which is what happens if someone is on the training video page without being signed in. This is the block of code in my config.php page:
$config['sess_cookie_name'] = 'cc_session';
$config['sess_expiration'] = 0;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'cc_sessions';
$config['sess_match_ip'] = TRUE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 3000000;
Why is sess_time_to_update set so high? At first, I thought that was the culprit, updating the session after 5 minutes. I have set the session to record to a database, and all that good stuff. Please, ask me questions, and help me get to the bottom of this!
I should point out that I have an iFrame that is on the course page that is sending a "ping" back to a server this way...
<iframe id="timerAddEnd" style="display:none;" src="http://www.example.com/course/finish/<?=$course->intKey?>/ping" >
</iframe>
<script type="text/javascript">
var auto_refresh = setInterval( function ()
{
var iframe = document.getElementById('timerAddEnd');
iframe.src = iframe.src;
}, 60000);
// refresh every minute
</script>
Could THIS be the culprit? I was hoping this would be a quick and dirty fix to the initial problem.
Are you using Firefox and Firebug with extensions (like FirePHP) installed? Because if you are having such a setup, when you open/close the Firebug console, the user-agent string changes, and your session is no longer recognized by CI.
My workaround was to disable FirePHP. Try checking your user-agent string and see if you have something extra besides the default browser user-agent. You should be able to identify it easily. if there is one.
Well, this may not be a full "answer" per se, but I did come up with a workaround of sorts.
I knew that the problem involved CodeIgniter handling sessions with... how do I put it... stuff running in the background. Originally I was using a CI page within the iFrame. Those "pings" back to the system were what was causing the lockout. So, I now use a regular, flat ol' PHP page within the iFrame. It connects to the database, but doesn't go through CI to do it. I get my "pings" to the table in question, but I don't break the session.
I had the same problem with session data getting "randomly" destroyed in CodeIgniter and I spent alot of time finding out what was wrong. Now I think i found MY problem, and it seemed as the $this->session->set_flashdata was the culprit.
I noticed that I got logged out on pages where this were used. I also noticed that if you do:
$this->session->set_flashdata('thisItem', 'value');
and later on the same page have the same variable again:
$this->session->set_flashdata('thisItem', 'new value');
then it will destroy the session data every time. Now I removed all the set_flashdata from my site, I havent been logged out since.. hoping this was my problem. When I have the time I will try to rewrite my flashing system to maybe something like if (!isset('thisItem)) { set it; } and stuff like this to prevent it from happening again, because I really want the flash messages.

Categories