how stop session (tracking) in google analytic - javascript

I use code from google analytic home page with remote ga.js. All works cool beside one thing: Avg. Time on Page. I close page in browser but my session leaves active.
I want to stop session from JS handy. I try search but nothing.
How can i do it ?
UPDATE
You miss me. I know that moment when say to GA that session is closed. My app plays in UIWebView on iOs. So I want to send termination when app is exited.
It's so simple. Isn't ?
Thanks

JavaScript does not know the difference between a page close and a page refresh and a page navigation away. Plus there is no reliable way with JavaScript to send the information to the server when the unload event is called.

Use javascript to delete the _utmb cookie:
Cookies Set By Google Analytics
function del_cookie(name) {
document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
}
del_cookie("_utmb");

You are looking for the true time on site/page
Have a look to the strategy proposed by Savio

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 reload a page without deleting the cookie

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);

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.

Cant read my cookie from the root of my site

I successfully set a cookie with javascript on one page like this:
..
I went to this article and took the code from it:
UPDATE :
**http://techpatterns.com/downloads/javascript_cookies.php**
The code works.. but I can set and read my cookie from one page only, when I go to the document root , the cookie isnt available there anymore..
I set my cookie when i am in a subfolder of my directory
I am also trying to set it this way:
document.cookie =
"landing_page_ref=" + encodeURIComponent("FBLND1") +
"; path=/; " ;
but i dont know where i am wrong
Session cookies (which are deleted when the browser is closed) are created by not specifying an explicit expiration time.
function setSessionCookie(c_name,value,exdays) {
document.cookie=c_name + "=" + escape(value);
}
That said, I'd use a robust cookie library to handle cookies rather than trying to roll-my-own.
There's no way to set a cookie to expire based on closing the browser and have an expiration time. That functionality is determined by the user's browser. If they have it set up to clear their cookies upon closing, then it will delete your cookie regardless of expiration time.
Your best bet would be setting the cookie to a relatively short lifetime (say 30 minutes or so) and refreshing that cookie on each page view. That would allow you to expire the cookie after 30 minutes of inactivity on your site. It's not quite the same thing, but as there's no way to enforce what you're looking for, it's a close second.
There are two type of cookies. persistent and session. Use session cookie for it. These cookies expire whenever you close your browser. To convert a persistent cookie to a session cookie just skip expire time.

Categories