Questions on cookie - cookies

Need help on the following questions regarding cookie
I'm developing a standalone jar which access a http site inside the code. When i access the http site will the cookie will be stored in the client machine ??
When the cookie will be saved in client's machine ?
The cookie will be stored only when we access web application via browser or via any library and executing http request
When and how the cookie can be enabled or disabled in a client's machine.
Thanks.

Your java application will need create a cookie store and link it to the HttpClient. For example
CookieStore cookieStore = new BasicCookieStore();
// Populate cookies if needed
BasicClientCookie cookie = new BasicClientCookie("name", "value");
cookie.setDomain(".mycompany.com");
cookie.setPath("/");
cookieStore.addCookie(cookie);
// Set the store
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.build();
Reference: https://hc.apache.org/httpcomponents-client-ga/tutorial/html/statemgmt.html

Related

JMeter 5.4.1 Cookie Manager - User-Defined Cookie not added to request's cookies

Firstly, I did add the line CookieManager.check.cookies=false to jmeter.properties.
What I'm Trying to Do
I want to add a cookie to a request's existing cookies.
For example, I see the request has [edited]:
Cookie Data:
c1=sfasfsfsfsfs; c2=erqwerqwrr; c3=poiuopiupoi
Expected Results
I would like it to have:
Cookie Data:
c1=sfasfsfsfsfs; c2=erqwerqwrr; c3=poiuopiupoi; partner=favicon.ico
Here is what I tried:
BASE_URL_2 is a variable defined in the form qa.company.com.
Actual Results
Whatever I have tried so far has not made any change in the cookies.
What else shall I try?
Underlying Motivation
Recorded a Web session and played it back.
Added a RegEx Extractor to pull out a token and then added it to subsequent requests. That helped.
However, certain requests failed with an custom application exception Security violation, please refresh.
Probably session login state is not being passed, so the website thinks the call is "stale".
I've seen this on the GUI when the session expires and you try to click a button on the site.
On comparing the cookies seem in JMeter with what I saw in the Chrome Debugger, it was clear that there were more cookies in the running application than what I had in JMeter.
Are you sure you're using HTTPS protocol because if you have secure flag and using HTTP protocol - the cookie will not be sent.
Also remove = from partner= otherwise you will end up with partner==favicon.ico
Demo:
More information:
Using HTTP cookies
HTTP Cookie Manager Advanced Usage - A Guide

Pm.cookies.jar could not find cookies with secure=true

I have a list of cookies in my response that has secure=true which is not accessible by the pm.cookies.jar()
This results in an issue where i wanted to clear all the cookies under a domain, which does not happen with the below code on the secure cookies.
const jar = pm.cookies.jar();
var domain = pm.environment.get("envUrl");
jar.clear(domain, function (error){
if(error)
{
console.log("error",error);
}
});
After this script is run, i could see that the secure cookies are NOT cleared from the manage cookies window.
Using: Postman for Windows -
Version 7.16.1 -
win32 10.0.14393 / x64
Example:
I think i have a workaround for this case until the bug is solved.
postman.getResponseCookie("Cookie name");
This still can access cookie with secure=true and using pm.cookies.jar() and set(), I set cookie with the same name as Secure cookie.
This removes the Secure flag from the cookie set. Now all operations (get, unset, clear) can be used on that cookies using pm.cookies.jar().
Note that set() creates a cookie with hostOnly=true, so the set cookies are only accessible when the request URL has the same host as the set cookie.
var responseCookie= postman.getResponseCookie("CookieName");
responseCookie= responseCookie.value.toString();
const cookieJar = pm.cookies.jar();
var domain = pm.environment.get("envUrl");
cookieJar.set(domain,"CookieName",responseCookie,function(error,cookie){});
cookieJar.clear(domain, function (error){});

send a cookie with XMLHTTPRequest (TVMLJS)

I am developing an application for my AppleTV. The App will read movies from an online website that hasn't developed any API for this kind of thing.
I use XMLHTTPRequest to get the different URLs and have the user search for his movie, etc... Everything is working fine, except for a single request. To get the movie URL, I have to send a get request to a specific address (let's say http://example.com/getmovie.html) with a constant cookie (let's say mycookie=cookie).
I've tried using setRequestHeader:
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.withCredentials = true;
xhr.setRequestHeader('Cookie', 'mycookie=cookie');
xhr.send();
But no cookie seems to be sent.
I also tried setting the cookie with Document.cookie like I would have probably done in a "normal" js script (running in my browser) but no luck either.
This is extremely frustrating, especially since I'm stuck so close to the end of my app.
I guess cross-origin might be the issue but I'm able to get URLs without issues if I don't have to set cookies, so I am a bit lost there.
Please let me know how I can get http://example.com/getmovie.html with a specific cookie header.
Thanks for your help
im sorry to inform you but the xmlHTTPRequest function of javascript does not allow a cookie header to be set for security reasons as shown here: Why cookies and set-cookie headers can't be set while making xmlhttprequest using setRequestHeader? the best way i could see you making that get request would be to a proxy server that you would be running. I believe that it is built this way to prevent you from setting cookies on domains that you do not own, furthermore i do not see an alternate resolution to this problem as no were in the docs i looked at was cookie persistence or management mentioned
In case someone has the same issue:
I didn't find a solution to sending a cookie with javascript. However, in my situation, the origin of the request didn't matter, only the cookie did. My solution was then to create a PHP file receiving the destination URL and the cookie content as parameters, and then sending the get request with the cookie as a request header. (more information about how to do so here: PHP GET Request, sending headers).
In my javascript I then use XMLHttpRequest to connect to my PHP file (hosted online) with simple get parameters and I then receive the response from the PHP. That trick of course won't work if the origin of the request matters (except if you host your file at home I guess, but in my case I want my application to work even if my WAMP isn't on).
Well... the problem here is the line xhr.setRequestHeader('Cookie', 'mycookie=cookie'); line just because the 'Cookie' header is reserved for the client browser to send the stored cookies. This means you are trying to do what the browser already does. When you send a any request, the client browser automatlycally will take all the cookies related to the site you are requesting and put them on the 'Cookie' header, you don't need to do anything else, if your cookie exist in your browser, it will be send.
Cordova how to send session cookie, allow credentials with XMLhttprequest:
// JS
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/ajax.php', true);
xhr.withCredentials = true;
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
// alert(xhr.responseText);
// Get header from php server request if you want for something
var cookie = xhr.getResponseHeader("Cookie");
// alert("Cookie: " + cookie);
}
}
xhr.send();
// Php
// You can add cookie to header and get with (session works without it)
header('Cookie: PHPSESSID='.$_COOKIE['PHPSESSID']);
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With, Set-Cookie, Cookie, Bearer');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400');

Add cookie to HTTP header for SOAP call in ColdFusion

I basically want to add the ASP.NET_SessionId cookie to my HTTP request header when calling a SOAP web service through ColdFusion.
The web service is registered in the OnApplicationStart function of the Application.cfc component in ColdFusion.
<cfscript>
objSoapHeader = XmlParse("<wsse:Security mustUnderstand=""true"" xmlns:wsse=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd""><wsse:UsernameToken><wsse:Username>MY_USERNAME</wsse:Username><wsse:Password>MY_PASSWORD</wsse:Password></wsse:UsernameToken></wsse:Security>");
Application.UserWebService = CreateObject("webservice","MY_URL/UserService.asmx?WSDL");
addSOAPRequestHeader(Application.UserWebService,"","",objSoapHeader,true);
</cfscript>
My web service is called as such:
<cfset Result = "#Application.UserWebService.SomeFunction("1", "DATA")#">
In order for the .Net server (where the web services are located) to remember my session state, I must pass the ASP.NET_SessionId cookie in the HTTP request header, but have no idea if this is even possible in ColdFusion.
I've researched for several hours but nothing has come of it as of yet, so has anyone successfully managed to pull this off?
Short Answer:
For CF9 / Axis1 try enabling sessions on the web service object.
ws = createObject("webservice", "http://localhost/MyWebService.asmx?wsdl");
ws.setMaintainSession( true );
For CF10+ / Axis2, see longer answer below:
(Disclaimer: Using cfhttp might be simpler, but I was curious and did some digging ..)
From what I have read, since CF10+ uses Axis2 for web services it should be possible to use the underlying methods to maintain session state through HTTP cookies.
How to set Cookies in ColdFusion SOAP requests - (circa 2006) - Written for a much older version of CF/Axis, so some of it is outdated, but it still provides a good overview of the general concept.
Maintain session in Axis2
Java axis web service client setMaintainSession on multiple services (cookies?)
Axis2 Manage Session Cookie Manually
Using the the links above, I put together a quick POC using a basic web service and was able to extract the cookie header from the web service client response:
// make initial request
ws = createObject("webservice", "http://localhost/MyWebService.asmx?wsdl");
ws.firstMethod();
// For maintainability, use constants instead of hard coded strings
wsdlConstants = createObject("java", "org.apache.axis2.wsdl.WSDLConstants");
// Extract headers
operation = ws._getServiceClient().getLastOperationContext();
context = operation.getMessageContext( wsdlConstants.MESSAGE_LABEL_IN_VALUE );
headers = context.getProperty( context.TRANSPORT_HEADERS );
Then set the cookie and instruct the web service client to send it with subsequent requests:
if ( structKeyExists(headers, "Set-Cookie") ) {
// include http cookies with request
httpConstants = createObject("java", "org.apache.axis2.transport.http.HTTPConstants");
options = ws._getServiceClient().getOptions();
options.setManageSession( true );
options.setProperty( httpConstants.COOKIE_STRING, headers["Set-Cookie"] );
}
// ... more requests
ws.secondMethod();
ws.thirdMethod();
NB: Side note, I noticed you are storing the instance in the shared Application scope. Just keep in mind web service instances are probably NOT thread safe.
Inside your CFHPPT tags, set the cookie with CFHTTPPARAM

Losing cookies in WKWebView

When I create new request for WKWebView with authentication cookie and send the request, WKWebView correctly loads protected web page:
let req = NSMutableURLRequest(URL: NSURL(string: urlPath)!)
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies([myAuthCookie]);
req.allHTTPHeaderFields = headers;
webView.loadRequest(req)
The problem is, that when user clicks on a any link in the web page, with new request WKWebView loses authentication cookie and is redirected to logon page. Cookie domain and path are filled and correct.
I am aware of the missing functionality of WKWebView mentioned here.
Thanks in advance for any idea.
The best thing to do is to store your cookie into the
[NSHTTPCookieStorage sharedHTTPCookieStorage]
Then each time you want to load the request, call this function instead:
- (void)loadRequest:(NSURLRequest *)request {
if (request.URL) {
NSDictionary *cookies = [NSHTTPCookie requestHeaderFieldsWithCookies:[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:request.URL]];
if ([cookies objectForKey:#"Cookie"]) {
NSMutableURLRequest *mutableRequest = request.mutableCopy;
[mutableRequest addValue:cookies[#"Cookie"] forHTTPHeaderField:#"Cookie"];
request = mutableRequest;
}
}
[_wkWebView loadRequest:request];
}
It extract the right cookies from shared cookies and includes it into your request
I suppose when you set it in the request you are sending the cookie to the server but NOT setting it in the WKWebview. The cookies are usually set by the server in the "Set-Cookie" header and then it should be persisted. So if if you don't have an issue with cookie passing all the way to the server and back you can do a trick:
send the cookie in the first request
make the server send it back in the "Set-Cookie" header
every subsequent request should have the cookie
I haven't tried the approach yet but will be very surprised if it doesn't work.
The alternative as mentioned by Sebastien could be do inject it via javascript. Be mindful though that you cannot set "HTTP-Only" flag this way and the cookie will be available by all the scripts running (https://www.owasp.org/index.php/HttpOnly).
I'm still trying to find a natural way to set the cookie but I don't think it exists.
Hope it helps.
You can inject some javascript into the we view to load the cookies so that requests initiated by the web view will also have your cookies. See the answer to this question for more details:
https://stackoverflow.com/a/26577303/251687