I am using Rest response to set cookies on the client side. But I cannot see the cookie being set when I open up 'Resources' in Chrome. But interestingly, when I go to chrome settings and check all cookies, I find the cookies I am setting. Again, getCookie() javascript function from w3schools (or better version to handle all possibilities) fetch me nothing. I tried firefox, there same thing happens. When I see all cookies, I see my cookies, but JS function getCookie() does not return me anything. I think the cookies are not getting set properly.
Here is my JAX-RS response :
Cookie c1 = new Cookie(Constants.SESSION_TOKEN, response
.getSessionToken().getValue());
Cookie c2 = new Cookie(Constants.USER_IDENTIFIER,
response.getUserIdentifier());
NewCookie cookie1 = new NewCookie(c1);
NewCookie cookie2 = new NewCookie(c2);
return Response.ok(jsonResponse, MediaType.APPLICATION_JSON)
.cookie(cookie1,cookie2).build();
And this is my JS getCookie() function
function getCookies() {
var c = document.cookie, v = 0, cookies = {};
if (document.cookie.match(/^\s*\$Version=(?:"1"|1);\s*(.*)/)) {
c = RegExp.$1;
v = 1;
}
if (v === 0) {
c
.split(/[,;]/)
.map(
function(cookie) {
var parts = cookie.split(/=/, 2), name = decodeURIComponent(parts[0]
.trimLeft()), value = parts.length > 1 ? decodeURIComponent(parts[1]
.trimRight())
: null;
cookies[name] = value;
});
} else {
c
.match(
/(?:^|\s+)([!#$%&'*+\-.0-9A-Z^`a-z|~]+)=([!#$%&'*+\-.0-9A-Z^`a-z|~]*|"(?:[\x20-\x7E\x80\xFF]|\\[\x00-\x7F])*")(?=\s*[,;]|$)/g)
.map(
function($0, $1) {
var name = $0, value = $1.charAt(0) === '"' ? $1
.substr(1, -1).replace(/\\(.)/g, "$1")
: $1;
cookies[name] = value;
});
}
return cookies;
}
function getCookie(name) {
return getCookies()[name];
}
That's strange. I've tried to reproduce your problem, but everything worked fine:
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
#GET
#Path(value = "/test")
public Response test() {
NewCookie c = new NewCookie("name1", "value1");
Cookie cookie = new Cookie("name2", "value2");
NewCookie c2 = new NewCookie(cookie);
return Response.ok("response1").cookie(c, c2).build();
}
curl -i $URL gave me:
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Server: Apache-Coyote/1.1
Set-Cookie: name1=value1; Version=1
Set-Cookie: name2=value2; Version=1
Date: Thu, 19 Sep 2013 13:52:43 GMT
Content-Type: application/json
Content-Length: 13
["a","b","c"]
The cookies also showed up in Chrome's Resources.
Not sure why your function doesn't get you your cookie information, but I might have an idea why it doesn't show up in your browser.
It helped me to remember that you need to visit the specific path that the cookie was set on for the browser to display the cookie in the console.
In the example above, make sure to visit the url displayed in the "Path:" section.
For somebody landing on this issue.
This problem occurs when the domain or the path values are not set properly
Use the below snippet to set the path and domain
NewCookie cookie = new NewCookie("cookie-name", "cookie-value,"/", "", "cookie description", 1000000, false);
For example, In your browser you should see these values after its set
Set-Cookie:x-auth-cookie=eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJtbTMiLCJhdWRpZW5jZSI6IkJST1dTRVIiLCJjcmVhdGVkIjoxNDg1MjU4MDcwMzQ2LCJyb2xlcyI6WyJBRE1JTiIsIlRFQUNIRVIiXSwiZXhwIjoxNDg2MjU4MDcwfQ.TM6oiCsOXh2zNou00H-5tkafAj40AngkbrCA62Vdyi5si_5hZFdmZFfitmK_bgRJexmFC49KlpAaRzGJF8bvMQ;Version=1;Comment="cookie description";Domain=;Path=/;Max-Age=1000000
Related
I own 2 domains, A and B, hosted with web applications.
From an application in domain A, I call a service in B, which takes some time.
So I show a loading GIF.
In the service in B, I set a cookie along with the response in Java:
HttpResponse resp;
Cookie fileDownloadStatus = new Cookie("fileDownload", "true");
fileDownloadStatus.setPath ("/App");
fileDownloadStatus.setDomain("x.x.x.x");
resp.addCookie(fileDownloadStatus);
In A, I keep looking for the cookie, so I can stop the loading GIF, but I am unable to get the cookie in JavaScript, even though I tried setting the path of the cookie and the domain for the cookie as if it were sent from A:
var fileDownloadCheckTimer;
fileDownloadCheckTimer = window.setInterval(function () {
var cookies = document.cookie;
console.log(cookies);
var cookieArray = cookies.split(';');
console.log(cookieArray);
for(var i=0;i<cookieArray.length;i++)
{
var reqCookie = cookieArray[i].split('=');
console.log(reqCookie);
if(reqCookie[0]=="fileDownload")
{
if(reqCookie[1] == "true")
finishDownload();
}
}
}, 1000);
Please assist.
I have my cookies in a CookieStore Object, but to stream a video I need to convert my CookieStore to a String, but my API in NodeJS (using express, cookie-parser and passport-local) never recognizes the value of the cookie, whenever I try to encode/decode it before. I think it's a stupid problem just I'm not really good in HTTP Headers so I'm doing it wrong.
There is the code:
Method setVideoURIMethod = videovvw.getClass().getMethod("setVideoURI", Uri.class, Map.class);
Map<String, String> params = new HashMap<String, String>(1);
params.put("Cookie", ARequestAPI.getCookieString());
setVideoURIMethod.invoke(videovvw, uri[0], params);
I had the code from here so normally it should work perfectly: Authentication for Videoview in android
I think the problem comes from "ARequest.getCookieString()":
protected static CookieStore _cookies = null;
...
...
...
public static String getCookieString() {
String cookieString = "";
Log.v("Debug", _cookies.toString());
for (Cookie cookie : _cookies.getCookies()) {
try {
Log.v("Debug", "Decode: " + URLDecoder.decode(cookie.getValue(), "UTF-8"));
Log.v("Debug", "Encode: " + URLEncoder.encode(cookie.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
cookieString += cookie.getName() + "=" + cookie.getValue()+ ";";
}
return cookieString;
}
The display in LogCat:
And the log on my API:
When I do a request using CookieStore:
{ 'connect.sid': 's:NUTf8t9o8cepR1yYItMexMxy.WFv/ZlktryfpVZHweVozabW1US4UBvGlWxQR7G7Aamc' }
When I do the request with my function which convert the CookieStore to a String:
{ 'connect.sid': 's:AZXpZmQGX7eJgej9hVA1qaAk.7vWP756Flwbte/qxBRcLOhl/CXMlVO3HVvmsvsEBpzA' }
I tried all the options, even encode(decode()), ... but it is never a good one on my API.
The weird thing is that I tried to decode 's%3ANUTf...' (so cookie.getValue()) with the javascript function "decodeURIComponent()" and I found exactly 's:NUTf8t9o8cepR1yYItMexMxy.WFv/ZlktryfpVZHweVozabW1US4UBvGlWxQR7G7Aamc', so my cookie is good, but I think I'm doing something wrong on the encode/decode part.
Thanks for your help.
Edit: After many tests, I saw that on the API the value for the cookie is always the same, whenever I use URLDecoder.decode(), URLDecoder.decode() or event directly cookie.getValue(), the only time I get the right value is when I "choose/write" the value myself like "totoauzoo" for example with this wring I get exactly the same value on the API. But it's not working with my old cookie value like "s:DMCBao7zeS9B2jwIfeQoDZtl.3XPIYIm7y2Bz9/o468v4wxvFZmjDrc6hKk4ty89sIX4".
Edit2: I probably found what is wrong, I get that on the API:
request with HttpGet and CookieStore:
headers { host: 'xxx',
connection: 'Keep-Alive',
'user-agent': 'Apache-HttpClient/UNAVAILABLE (java 1.4)',
cookie: 'connect.sid=s%3AGRGciNxOcR4BXHrUG8PikHMX.MyWa6vjW%2BBlcUaaCHHendqc7DEK4aoNFDzm5aabOkDM',
cookie2: '$Version=1' }
cookies { 'connect.sid': 's:GRGciNxOcR4BXHrUG8PikHMX.MyWa6vjW+BlcUaaCHHendqc7DEK4aoNFDzm5aabOkDM' }
request with setVideoURI:
headers { host: 'xxx',
connection: 'keep-alive',
cookie: 'connect.sid=s%3AKWKdcuXqUpzBIMv0sOGpPxqM.xb14kPsGKvn%2Fv%2BVcfUDzxWsye8QdJfuQgonNocsX3k8',
'user-agent': 'stagefright/1.2 (Linux;Android 4.1.2)',
'accept-encoding': 'gzip,deflate' }
cookies { 'connect.sid': 's:KWKdcuXqUpzBIMv0sOGpPxqM.xb14kPsGKvn/v+VcfUDzxWsye8QdJfuQgonNocsX3k8' }
How can I fix that?
I would suggest inspecting the network traffic itself.
Cookies are nothing else than HTTP headers ...
HTTP/1.0 200 OK
Content-type: text/html
Set-Cookie: name=value
Set-Cookie: name2=value2; Expires=Wed, 09 Jun 2021 10:18:14 GMT
or
GET /spec.html HTTP/1.1
Host: www.example.org
Cookie: name=value; name2=value2
Accept: */*
I'm not familiar with the classes you are using to set the cookies, but I would inspect two places:
1:
params.put("Cookie", ARequestAPI.getCookieString());
Is this call setting the headers or are you setting POST parameters? This should be visible in the network traffic. What are params? Headers, query string?
2:
ARequestAPI.getCookieString()
Is the output of this function in correct cookie value format, or what is it?
Most probably in one of those places lies the error.
I have a situation where i need to set cookie in JSP and i need to get those cookie in normal java class.
The JSP:
CookieManager manager = new CookieManager();
CookieHandler.setDefault(manager);
CookieStore cookieJar = manager.getCookieStore();
// create cookie
HttpCookie cookie = new HttpCookie("UserName", "John Doe");
// add cookie to CookieStore for a
// particular URL
URL url = new URL("http://localhost:8080");
url.openConnection().connect();
cookieJar.add(url.toURI(), cookie);
System.out.println("Added cookie using cookie handler");
%>
Below is the Java class [not a servlet class] and this class is running in the server and this is invoked not after the JSP call but somewhere in the application only if any event occurs. below is the code where i wrote to capture cookies.
URL url = new URL("http://localhost:8080");
URLConnection conn = url.openConnection();
conn.getContent();
CookieManager cm = new CookieManager();
CookieHandler.setDefault(cm);
cm.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieStore cs = cm.getCookieStore();
List <HttpCookie> cookies = cs.getCookies();
for (HttpCookie cookie: cookies) {
System.out.println("CookieHandler retrieved cookie: " + cookie);
}
would this scenario works if i want to retrieve the cookies in non servlet class?
The output of the above code will return empty list.
However if i write a servet class with request.getCookie("UserName") I will see the cookie value.
Here i need to understand how would i get the cookie value without using request object.
Because request object is not always passed in multiple invocation of java class. And i am not using session.
please let me know if you have any better approach.
Thanks-
Instead Use the getHeaderFields() method from the connection Object to get the full list of Name-Value pairs representing the header fields of the specific connection
Cookie information(if present)should be under the “Set-Cookie” header field.
Map<String, List<String>> headerFields = conn.getHeaderFields();
Set<String> headerFieldsSet = headerFields.keySet();
Iterator<String> hearerFieldsIter = headerFieldsSet.iterator();
Then iterate over the Set and check if the cookie is present. If it is present print it out.
while (hearerFieldsIter.hasNext()) {
String headerFieldKey = hearerFieldsIter.next();
if ("Set-Cookie".equalsIgnoreCase(headerFieldKey)) {
List<String> headerFieldValue = headerFields.get(headerFieldKey);
for (String headerValue : headerFieldValue) {
System.out.println("Cookie Found...");
String[] fields = headerValue.split(";\s*");
String cookieValue = fields[0];
System.out.println("cookieValue:" + cookieValue);
}
}
}
Y0u can refer this examle
For a while now I have been trying to find a way for jython to access site using NTLM. I have just basic knowledge of python and next to none in java, so I could use some help (or an example) how to make the request use NTLM in this script part I have found. I am using this with open source application grinder.
First I start with importing jcifs in script along with others used by grinder:
from net.grinder.script import Test
from net.grinder.script.Grinder import grinder
from net.grinder.plugin.http import HTTPPluginControl, HTTPRequest
from HTTPClient import NVPair
from jcifs.ntlmssp import Type1Message
from jcifs.ntlmssp import Type2Message, Type3Message
from jcifs.util import Base64
This code part was provided in example I found. It was the closes thing I could find, that would fit my needs, since I just need to get the full response to request.
def NTLMAuthentication1(url, request, info, NTLMfield):
token_type1 = info.token_type1()
params = (NVPair("Authorization", "NTLM "+token_type1), )
result = request.GET(url, None, params)
NTLMfield = result.getHeader("WWW-Authenticate")
return NTLMAuthentication2(url, request, info, NTLMfield)
def NTLMAuthentication2(url, request, info, NTLMfield):
if NTLMfield.startswith("Negotiate"):
token_type2 = NTLMfield[len("Negotiate "):]
else:
token_type2 = NTLMfield[5:]
token_type3 = info.token_type3(token_type2)
params = (NVPair("Cookie", "WSS_KeepSessionAuthenticated=80"),
NVPair("Authorization", "NTLM " + token_type3), )
result = request.GET(url, None, params)
return result
# this function validate request and its result to see if the NTLM authentication is required
def NTLMAuthentication(lastResult, request, info):
# get last http request's url
url = lastResult.getEffectiveURI().toString()[len(request.getUrl()):]
# The result is ask for authentication
if lastResult.statusCode != 401 and lastResult.statusCode != 407:
return lastResult
NTLMfield = lastResult.getHeader("WWW-Authenticate")
if NTLMfield == None:
return lastResult
# check it is the first shakehands
if NTLMfield == "Negotiate, NTLM" or NTLMfield == "NTLM":
return NTLMAuthentication1(url, request, info, NTLMfield)
# check it is the second shakehands
elif len(NTLMfield) > 4 and NTLMfield[:4] == "NTLM":
return NTLMAuthentication2(url, request, info, NTLMfield)
else:
return lastResult
class NTLMAuthenticationInfo:
def __init__(self, domain, host, user, passwd):
self.domain = 'domain'
self.host = 'host'
self.user = 'user'
self.passwd = 'password'
def token_type1(self):
msg = Type1Message(Type1Message.getDefaultFlags(), self.domain, self.host)
return Base64.encode(msg.toByteArray())
def token_type3(self, token_type2):
msg2 = Type2Message(Base64.decode(token_type2))
#if jcifs 1.3.7 using msg3 = Type3Message(msg2, self.passwd, self.domain, self.user, self.host)
msg3 = Type3Message(msg2, self.passwd, self.domain, self.user, self.host)
return Base64.encode(msg3.toByteArray())
In the main part the request looks something like this:
result = request101.GET('/')
where request101 has been predefined with URL and header. So, basically, I don't have a clue how to implement the
I have tried this
result = request101.GET('/')
print str(NTLMAuthentication(result, request101, NTLMAuthenticationInfo))
as well as just this
NTLMAuthentication(request101.GET('/'), request101, NTLMAuthenticationInfo)
but neither of these worked. Any tips on how to run this?
try this
ai = NTLMAuthenticationInfo("domain", "your host", "user", "password")
result = request101.GET('/')
result = NTLMAuthentication(result, request101, ai)
Download popup dialog can be displayed by
window.location = "someUrl"
or just simply have a link that send HTTP GET method and so on. I've done this successfully.
But now I want to do Ajax with HTTP POST. The POST body has JSON like
{"val1":"key1", "val2":"key2"}
Then in servlet side, it read the JSON and execute query against DB to get data then generate Excel based on the query data.
The part I can't get it working is client side.
Assugming that my servlet at resources/report/schedule generates Excel file.
This does not popup download dialog when using Ajax :(
Can anybody help me how to have download dialog with Ajax?
function post25() {
var jsonInput = {};
jsonInput['作業区コード'] = "481";
jsonInput['機械コード'] = "11";
jsonInput['作業日'] = "2000/01/01";
jsonInput = JSON.stringify(jsonInput);
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function() {
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
var res = ajaxRequest.responseText;
//location.href = "../resources/report/schedule";
}
else if(ajaxRequest.status == 409 || ajaxRequest.status == 500 || ajaxRequest.status == 204) {
alert(ajaxRequest.status);
document.getElementById("showMessage").innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open("POST", "../resources/report/schedule", true);
ajaxRequest.setRequestHeader("Content-Type", "application/json");
ajaxRequest.send(jsonInput);
}//end post25()
For security reason it is not allowed to download file using ajax.