Failing to delete a cookie using JavaScript - what am I doing wrong? - cookies

I'm trying to delete a cookie in Android Chrome (latest version).
DevTools (phone connected to PC via USB) shows the following cookies when I navigate my phone to www.domain.com/admin/clearcookies:
Name Value Domain Path Expires
data-cookie-name foo www.domain.com / 2020-09-16T07:57:01.000Z
data-cookie-name bar .domain.com / 2021-03-24T09:03:04.000Z
On page load I run the following javascript:
function deleteOldWwwScopedCookiesThatWereConflictingWithNewNonWwwCookiesThatISwitchedToBecauseOfLanguageSubdomains()
{
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
var tmp = name + "=;domain=www.domain.com;expires=Thu, 01 Jan 1970 00:00:00 GMT";
console.log(tmp);
document.cookie = tmp;
}
}
deleteOldWwwScopedCookiesThatWereConflictingWithNewNonWwwCookiesThatISwitchedToBecauseOfLanguageSubdomains();
I reload the page nummerous times, and see the console correctly output
data-cookie-name=;domain=www.domain.com;expires=Thu, 01 Jan 1970 00:00:00 GMT
There's no errors in the console.
But if I view the page request in the network tab I get the same cookies listed as above.
I've tried a couple of variations as well:
dropping the domain: data-cookie-name=;expires=Thu, 01 Jan 1970 00:00:00 GMT
adding a path: data-cookie-name=;domain=www.domain.com;path=/;expires=Thu, 01 Jan 1970 00:00:00 GMT
No dice.
Nothing I seem to try will get rid of this unwanted cookie that is overriding the .domain.com one.
What am I doing wrong? Please!

I think what I needed was a combination of the two alternatives that I'd tried.
Adding a path AND dropping the domain:
data-cookie-name=;path=/;expires=Thu, 01 Jan 1970 00:00:00 GMT
I've no idea why it's important to NOT specify the domain. Can anyone explain?

Related

How to completely clean up Google Analytics cookies (including dynamically set ones like _gali)

Since GDPR we all have cookie preferences and obliged to remove cookies if user withdraw their consent. However, if you have Google Analytics (www.googletagmanager.com/gtag) and clean cookies on a button press event, you can find out after page reload that you still have some GA cookies like _gali and _ga_XXXXXX. So, the question is how to kill these?
Apparently GA sets some cookies on document unload (or beforeunload) event. So if you clean up on unload event it works then:
function removeAllCookies() {
document.cookie.split( ";" ).forEach( cookie => {
const [ name ] = cookie.split( "=" );
document.cookie = name + `=; path=/; domain=.YOUR-DOMAIN.com;expires=Thu, 01 Jan 1970 00:00:00 GMT`;
document.cookie = name + "=; path=/;expires=Thu, 01 Jan 1970 00:00:00 GMT";
});
}
window.addEventListener("unload", () => removeAllCookies() );

query a webpage for variable entity using a consistent URL structure

Would someone please help me to understand how I might inject into my program a query to this webpage?
There are two parameters that need to be set, i.e.
"Site:", is where you enter the language and site code.
&
"Page:", you must put in the exact title of the page as it appears on the connected site.
The URL's always look like this:
https://www.wikidata.org/wiki/Special:ItemByTitle?site=en&page=Mikhail+Bakunin&submit=Search
https://www.wikidata.org/wiki/Special:ItemByTitle?site=en&page=Thomas+Edward+Lawrence&submit=Search
and the language is always English, so you see, it's just:
https://www.wikidata.org/wiki/Special:ItemByTitle?site=en&page=Blah+Blah&submit=Search
The objective of querying that page is to retrieve the ID value associated with the page, so for Mikhail Bakunin it's Q27645 and for T. E. Lawrence it's Q170596
It becomes part of the URL once the page is reached:
https://www.wikidata.org/w/index.php?title=Q170596&site=en&page=Thomas+Edward+Lawrence&submit=Search
But also maybe I could strip it from the page, using beautifulSoup or soemthng?(that's a guess)
The program needs to be generalizable, which is to say, that the name of the entity we're searching for is variable, it will change in the program, so that needs to be taken in account.
I guess using python or php or something would not be a crime against humanity if it's easier, though I prefer java.
update:
import java.net.*;
import java.io.*;
public class URLConnectionReader
{
public static void main(String[] args) throws Exception
{
URL site = new URL("https://www.wikidata.org/wiki/Special:ItemByTitle?site=en&page=Mikhail+Bakunin&submit=Search");
URLConnection yc = site.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
this works sort of, but the result is quite messy.
I guess I could grab it out of this thing:
<!-- wikibase-toolbar --><span class="wikibase-toolbar-container"><span class="wikibase-toolbar-item wikibase-toolbar ">[<span class="wikibase-toolbar-item wikibase-toolbar-button wikibase-toolbar-button-edit">edit</span>]</span></span>
but how?
When you request this URL the response is:
HTTP/1.1 302 forced.302
Server: Apache
X-Powered-By: HHVM/3.3.1
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Vary: Accept-Encoding,X-Forwarded-Proto,Cookie
X-Content-Type-Options: nosniff
Location: http://www.wikidata.org/w/index.php?title=Q27645&site=en&page=Mikhail+Bakunin&submit=Search
Content-Type: text/html; charset=utf-8
X-Varnish: 1641959068, 1690824779, 1606045625
Via: 1.1 varnish, 1.1 varnish, 1.1 varnish
Transfer-Encoding: chunked
Date: Fri, 17 Apr 2015 11:49:55 GMT
Age: 0
Connection: keep-alive
X-Cache: cp1054 miss (0), cp3003 miss (0), cp3013 frontend miss (0)
Cache-Control: private, s-maxage=0, max-age=0, must-revalidate
Set-Cookie: GeoIP=NL:XXX:51.4400:5.6194:v4; Path=/; Domain=.wikidata.org
So there's a 302 redirect in the HTTP response headers. That's where you'll want to grab your Q-number. Simlpy regex it out of the Location header with a regex like:
^Location:.*?title=(Q[0-9]+)
...and use matchgroup 1 (should be Q27645).
To grab the HTTP headers, have a look at this page; it basically goes like:
URL obj = new URL("https://www.wikidata.org/wiki/Special:ItemByTitle?site=en&page=Mikhail%20Bakunin&submit=Search");
URLConnection conn = obj.openConnection();
//get header by 'key'
String location = conn.getHeaderField("Location");
//TODO: Regex here

PCL HttpClient response ignoring cookies without a domain

I am working on a REST-based app that connects to Office365. The app will be available on multiple platforms, so I have created a portable class library to handle all the logic, including authentication. The PCL targets Windows Phone 7.1 and onwards, and includes the Microsoft HTTP Client Libraries (NuGet), which is required for Windows Phone 7.1 apps.
The last step of the authentication for Office365 is to get a FedAuth cookie from the site, and that is where I am having a problem.
The code I use to get the cookie is:
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = false;
var newClient = new HttpClient(handler);
var newResponse = await newClient.PostAsync(host + "/_forms/default.aspx?wa=wsignin1.0", new StringContent(binarySecurityToken));
The 'host' variable is just the URL of the Office365 site, and the binarySecurityToken I got from previous requests. These things work equally well in all the apps: Whether I run the PCL code from the context of a Windows Phone 7.1 app, Windows Phone 8 app, Windows 8 app, or even a Console application, I am getting exactly the same response (see below), which contains the FedAuth cookie. This I have verified using Fiddler.
Then I try to get the cookie to reuse it on subsequent requests.
var cookieCollection = handler.CookieContainer.GetCookies(new Uri(host));
foreach (var cookie in cookieCollection)
{
if (cookie.Name.StartsWith("FedAuth"))
{
//TODO: Store the cookie.
return true;
}
}
This leads to the following result: On Windows Phone 7.1 the 'cookieCollection' variable only contains the cookie rtFa'. On the other platforms it contains all three cookies 'RpsContextCookie', 'rtFa', 'FedAuth'.
Windows Phone 7.1 differs from the other apps in that this is the only platform that actually uses the HttpClient from the NuGet package. The other platforms have a native HttpClient that is swapped in by the magic of PCL.
It seems likely that the problem is caused by the FedAuth cookie not having a domain. I have tried using .GetCookies(null), and different variations of .GetCookies(new Uri("something", UriKind.Relative)), which all result in an exception. I have also tried changing most of the properties of the HttpClientHandler without luck.
Has anyone encountered this problem, and perhaps solved it? Or just a suggestion on what I could try?
The response I get on the .PostAsync above is the same on all platforms, and according to Fiddler the raw response is:
HTTP/1.1 302 Found
Cache-Control: no-cache, no-store
Pragma: no-cache
Content-Type: text/html; charset=utf-8
Expires: -1
Location: /
Server: Microsoft-IIS/7.5
X-SharePointHealthScore: 0
X-AspNet-Version: 4.0.30319
Set-Cookie: RpsContextCookie=; path=/
Set-Cookie: rtFa=+13jGMMp0A0V+driESaO30ixYclFCRjEvS2jMSwXPfQcrefiJvLEExxYu7V+1JZHM6X5JWeuL70jb3/N/Q/hUTwoAiC/XLJZ1QfERi4aUt8AAVF4ekcNyMdWnj65foDwPkhaV5z8whNSZQigBFD/2Vc1xMTH0ukHbS4cbtJO5U28/4g66vgIZg7dGpNOZg2jDt+HF3GSQ4/W+T1oS9/F5e+Pbwd0p8mqPhkGjL+M7IptmkeHoIqVcS4Ps25dM6q1AniLiv/3NujYmrQjseaEYZ2aaCfc7ZHX7LygBZm8KsoGNyTYRPmC+hZ7tsDq6wfto+xVpX1scggsU0+Qty3DPWUiwy1bBy8JR0znFG0+eDt9uBOQzqfOSjVvd8WNIKUFIAAAAA==; domain=sharepoint.com; path=/; HttpOnly
Set-Cookie: FedAuth=77u/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48U1A+RmFsc2UsMGguZnxtZW1iZXJzaGlwfDEwMDMwMDAwODc5MTUwMGVAbGl2ZS5jb20sMCMuZnxtZW1iZXJzaGlwfHRtakB3aWxkY293Lm9ubWljcm9zb2Z0LmNvbSwxMzAzNDIwOTYxNDAxMTIxMzMsRmFsc2UsV2lSQjlUVTdOSTk0MUpKRWZ5d1JDNTFPYUphMVpWNkJqWWdaVGM3MU00U3lqL2VkTnF6dVJpbXdEMnpEWk9oR1lybkFsNnpWb3M4V0FBZDk1VVYrZkt5dlkwQ3dqRTlyaEhEc256bkZUeENoODU1Rm1JZmxoYVBkMTFQS2VjWnFJN0N4OUxUOHk4enZDaVNUTGNQMzR2K3NOeHk1YXBMZ2NIWDNHR3JMcG1Ic24rQzAzUkUzakNDQWhma2F3RVRQbk03R3JycVk5amJseHJmNVNhNHZxMk91NlN1cGszZnpQMUZQTzJBc1UrRXZvSDgvWTllR2Y3c2x2dStvMnVlN3hZLy9VQ1lYU1U4b3AzckZ6c2laK0wwN1NrUnZYMTZjVklUVVZJZ0x6TGIxaTJLd2lwNGp6RHgwRFdmVWF0Rk42UVFaNWhHRzMyOHRJZjI2RXo4YldnPT0saHR0cHM6Ly93aWxkY293LnNoYXJlcG9pbnQuY29tLzwvU1A+; path=/; secure; HttpOnly
SPRequestGuid: 5bb2689c-d7c5-c07c-4890-ee32437f15f5
request-id: 5bb2689c-d7c5-c07c-4890-ee32437f15f5
SPRequestDuration: 125
SPIisLatency: 2
X-Powered-By: ASP.NET
MicrosoftSharePointTeamServices: 16.0.0.2308
X-Content-Type-Options: nosniff
X-MS-InvokeApp: 1; RequireReadOnly
P3P: CP="ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI"
Date: Thu, 09 Jan 2014 21:46:53 GMT
Content-Length: 118
<html><head><title>Object moved</title></head><body>
<h2>Object moved to here.</h2>
</body></html>
I found an answer of kind here: Accessing HTTPOnly cookies from Windows Phone 8/PCL.
Reading the post I realized that I made an error above: I was not getting the 'rtFa' cookie in the Windows Phone 7.1 app, but the 'RpsContextCookie'. The cookies I couldn't access were both marked with HttpOnly.
I also realized that I don't need to access the cookies directly. Instead, I could just reuse the handler.CookieContainer. So my code now looks like this:
var handler = new HttpClientHandler();
handler.AllowAutoRedirect = false;
var newClient = new HttpClient(handler);
var newResponse = await newClient.PostAsync(host + "/_forms/default.aspx?wa=wsignin1.0", new StringContent(binarySecurityToken));
this._cookieContainer = handler.CookieContainer;
return true;
this._cookieContainer is just a class-scoped field for storage of the cookie container. Then, once I am authenticated and I do the requests that are the actual purpose of the app, I do the following:
var handler = new HttpClientHandler(){ CookieContainer = this._cookieContainer };
var client = new HttpClient(handler);
var response = await client.GetAsync(host + "something");
So the bottom line is: I can't access the HttpOnly cookies - but I don't need to. I just reuse the cookie container, and the cookies are automatically included in the next request.
This works both in Windows Phone 7.1 apps, Windows Phone 8 apps, Console applications etc.

How do I set a cookie that expires after a certain time using Tritium?

I'd like to create a cookie that expires within 5 minutes of the user visiting my page.
I know about add_cookie() function, but have no idea how to set it to expire.
You can set cookies in the scripts/response_main.ts file as such:
set_cookie("cookie_name", "cookie_val")
cookie("cookie_name") {
cookie.expires("Wed, 09 Jun 2021 10:18:14 GMT")
}
Check out this link for more info.

Cookie doesn't expire on IE6

I am running IE6 from 6.0.3790 (hosted on Citrix Server).
In Logoff we have expired the cookie using
curDate.setTime(curDate.getTime() - 24 * 60 * 60 * 1000);
document.cookie = name + "=; expires=" + curDate.toGMTString() + "; path=/; domain=" + cookieDomain;
where name is the name of cookie.
Problem is with this browser the cookie never expr
Don't use relative date/times for the expiration value. It's safer to use an absolute one like expires=Thu, 01-Jan-1970 00:00:01 GMT;. You're depending on the client's clock to be reasonably accurate, which isn't always the case.
As well, the domain and path settings have to be identical to what they were went the cookie was originally set.
It's also best to set the cookie's value to something obvious, like "deleted", rather than a blank value (name=), in case the browser interprets the lack of a value as "nothing should be changed".