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.
Related
Lets say..
if i hit google with https://www.google.com it will create a session, for the responce it
will create url with session tokn like..
https://www.google.co.in/?gfe_rd=cr&ei=oFBjVJSvLqnM8gft5YDwAQ&gws_rd=ssl.
My question is
am connecting to google with the code:
URL url = new URL(test);
URLConnection conn = url.openConnection();
this will connect to google.
for this google creates a session.
then how would i get a session token back to my code?
You can get the session token from the cookie of the browser. You can, find the cookie settings->advanced settings->privacy->content settings->allcookie and site data then search www.google.com and select sid and copy the content .
You can extract any cookie, not only the one containing the session with the following approach:
Since a server may set multiple cookies in a single request, we will need to loop through the response headers, looking for all headers named "Set-Cookie".
String headerName=null;
for (int i=1; (headerName = uc.getHeaderFieldKey(i))!=null; i++) {
if (headerName.equals("Set-Cookie")) {
String cookie = urlConn.getHeaderField(i);
The string returned by the getHeaderField(int index) method is a series of name=value separated by semi-colons (;). The first name/value pairing is actual data string we are interested in (i.e. "sessionId=0949eeee22222rtg"), the subsequent name/value pairings are meta-information that we would use to manage the storage of the cookie (when it expires, etc.).
cookie = cookie.substring(0, cookie.indexOf(";"));
String cookieName = cookie.substring(0, cookie.indexOf("="));
String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
This is basically it. We now have the cookie name (cookieName) and the cookie value (cookieValue).
the above explanation was based on example provided in http://www.hccp.org/java-net-cookie-how-to.html#retrieving_cookies
A more sophisticated approach is to use CookieAccessor class:
public void getCookieUsingCookieHandler() {
try {
// Instantiate CookieManager;
// make sure to set CookiePolicy
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
// get content from URLConnection;
// cookies are set by web site
URL url = new URL("http://host.example.com");
URLConnection connection = url.openConnection();
connection.getContent();
// get cookies from underlying
// CookieStore
CookieStore cookieJar = manager.getCookieStore();
List <HttpCookie> cookies =
cookieJar.getCookies();
for (HttpCookie cookie: cookies) {
System.out.println("CookieHandler retrieved cookie: " + cookie);
}
} catch(Exception e) {
System.out.println("Unable to get cookie using CookieHandler");
e.printStackTrace();
}
}
In any approach you follow you need to know what is the name of the cookie holding the session id, so that you can get the value from it. E.g a java web application usually creates a cookie with name "JSESSIOINID"
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
I'm implementing a client to a web service (and the guys maintaining the web service have been a litte unresponsive..) I've used axis and WSDL2Java to generate java classes and I can call their login-method on their authentication-service ok, and get a sessionId back (eg z4zojhiqkw40lj55kgtn1oya). However, it seems that i cannot use this sessionId as a parameter anywhere. Even a call to their hasSession()-method directly after login returned false. I managed to solve this by setting setMaintainSession(true) on the Locator-object for this service. But the problem is, that this first service, the Authentication-service, is only used for authentification. If I then call setMaintainSession(true) on eg ProductServiceLocator, and call some method on it, I will get an error because of unauthenticated session. I have to find a way to share the session between the services on the client side.
Looking on their php code example-it seeems like they are storing the session in a cookie. How can I mimic this behaviour in my java client?
php-code:
$authentication = new SoapClient ( "https://webservices.24sevenoffice.com/authenticate/authenticate.asmx?wsdl", $options );
// log into 24SevenOffice if we don't have any active session. No point doing this more than once.
$login = true;
if (!empty($_SESSION['ASP.NET_SessionId'])){
$authentication->__setCookie("ASP.NET_SessionId", $_SESSION['ASP.NET_SessionId']);
try{
$login = !($authentication->HasSession()->HasSessionResult);
}
catch ( SoapFault $fault ) {
$login = true;
}
}
if( $login ){
$result = ($temp = $authentication->Login($params));
// set the session id for next time we call this page
$_SESSION['ASP.NET_SessionId'] = $result->LoginResult;
// each seperate webservice need the cookie set
$authentication->__setCookie("ASP.NET_SessionId", $_SESSION['ASP.NET_SessionId']);
// throw an error if the login is unsuccessful
if($authentication->HasSession()->HasSessionResult == false)
throw new SoapFault("0", "Invalid credential information.");
}
My code is the following:
AuthenticateLocator al = new AuthenticateLocator();
al.setMaintainSession(true);
Credential c = new Credential(CredentialType.Community,username,password,guid);
AuthenticateSoap s = al.getAuthenticateSoap();
String sessionId = s.login(c);
System.out.println("Session id was: "+sessionId);
System.out.println("Has Session: "+s.hasSession()); //Hooray, now works after setMaintainSession(true)
//And now trying to call another Service
CompanyServiceLocator cl = new CompanyServiceLocator();
cl.setMaintainSession(true);
CompanyServiceSoap css = cl.getCompanyServiceSoap();
css.getCountryList(); //FAILS!
So what can I do to make this work?
Hooray, I finally solved it myself :-D
Thanx a lot to the excellent article at http://www.nsftools.com/stubby/ApacheAxisClientTips.htm
I had to do the following with my code to make it work:
CompanyServiceLocator cl = new CompanyServiceLocator();
cl.setMaintainSession(true);
CompanyServiceSoap css = cl.getCompanyServiceSoap();
((Stub)css)._setProperty(HTTPConstants.HEADER_COOKIE, "ASP.NET_SessionId="+sessionId); //New line that does the magic
css.getCountryList(); //SUCCESS :-D
Operating in the high-level abstraction of the autogenerated classes, it was unknown to me that casting the service classes to Stub would expose more methods and properties that could be set. Good to know for later I guess :-)
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
This question already has answers here:
How do I keep a user logged into my site for months?
(2 answers)
Closed 5 years ago.
I have a login screen and i am authenticating users by checking credentials from database. But how can i implement Remember me check box? Like in gmail remember me(stay signed in) is present. I am using sign.jsp and Auth servlet (doPost) and oracle 10g ee for authentication.
You can use cookies for this purpose.
In your servlet response handler (doPost, doGet etc.) create a cookie in the following way -
if(remember_me_is_checked)
{
Cookie c = new Cookie("userid", userId.toString());
c.setMaxAge(24*60*60);
response.addCookie(c); // response is an instance of type HttpServletReponse
}
To read them, you can use something like this -
Cookie[] cookies = request.getCookies(); // request is an instance of type
//HttpServletRequest
boolean foundCookie = false;
for(int i = 0; i < cookies.length; i++)
{
Cookie c = cookies[i];
if (c.getName().equals("userid"))
{
string userId= c.getValue();
foundCookie = true;
}
}
Here is the official documentation for the Cookie class.
You can use cookies to help with your implementation. Something like this .
String userIdendificationKey="UserName";
Cookie cookie = new Cookie ("userIdendificationKey",userIdendificationKey);
// Set the age of the cokkie
cookie.setMaxAge(365 * 24 * 60 * 60);
//Then add the cookies to the response
response.addCookie(cookie);
and then check against the particular value later .
I don't know whether it is secure or not,but this is what i did.
In login.jsp head tag
<script type="text/javascript">
var isLoggedIn = "${isLoggedIn}";
if(isLoggedIn === true)
window.location.href="Home.jsp";
</script>
in body tag i added a check box for Remember Me as below
<input type="checkbox" id="RememberMe" name="rememberMe">
<label for="RememberMe">Remember Me</label>
In servlet doPost method i added the code below
if(userdetails are verified)
{
if(request.getParameter("rememberMe")!=null){
request.getSession().setAttribute("isLoggedIn", true);
}
RequestDispatcher rs = request.getRequestDispatcher("Home.jsp");
rs.forward(request, response);
}
else
{
RequestDispatcher rs = request.getRequestDispatcher("fail.jsp");
rs.include(request, response);
}
using this it will ask for the credentials at first time login,and it will store the login info in session parameters,if you try to access the site second time it will automatically goes to "Home.jsp" instead of "login.jsp"
please comment whether this method is good practice,any other modifications can be done.
Suggestions are welcome.
Take a look at Spring SecurityIt
It is a powerful and highly customizable authentication and access-control framework.
You can also check the code from Rose India, this will be more helpful to you.