Can't find cookie if path is set to / - java

Currently using Java I am able to create a cookie and later retrieve it via Cookie[] browserCookies = request.getCookies();
The issue comes when I try create a cookie and set its path with cookie.setPath("/"); I can no longer find it later when the below code. It has a max age of 30 days so I know it's there and I see it get created but I can't find it any longer after that initial creation.
Here's what I have now which works when not setting a path to "/":
Look for a cookie with a specific name:
Cookie[] browserCookies = request.getCookies();
boolean foundCookie = false;
if (browserCookies != null) {
for (int i =0; i< browserCookies.length; i++) {
if ("foo".equalsIgnoreCase(browserCookies[i].getName())) {
foundCookie = true;
}
}
}
based on foundCookie, I do something but also based on that I create a new cookie if not found:
if (!foundCookie) {
Cookie fooCookie = new Cookie ("foo", "barValue");
fooCookie.setMaxAge(30 * 86400);
//fooCookie.setPath("/"); // If I set this, I can no longer find it later by the name
response.addCookie(fooCookie);
}
Thank you for any help

Related

Not able to get cookie in different context

i am setting cookie in context A and trying to get in context B in same domain . I am writing this code ....
Cookie cook= new Cookie("Name","value");
cook.setPath("/");
cook.setDomain(".foo.com");
response.addCookie(cook);
what is wrong here ? This is how i am getting the cookie in another context ..please note that my code is working fine in same context
Cookie cookie = null;
Cookie[] cookies = null;
cookies = request.getCookies();
out.println(cookies);
for (int i = 0; i < cookies.length; i++){
cookie = cookies[i];
if("Name".equals(cookie.getName( ))){
out.println("Name : " + cookie.getName( ) + ", ");
out.println("Value: " + cookie.getValue( )+" <br/>");
}}
Try to give the cookie a lifetime.
cookie.setMaxAge(86400) // 24h
A cookie without lifetime is bound to the browsing session. You might be in a different session when browsing in a different context.

Delete a cookie by its value

How do I delete a cookie by its value?
In my.jsp page I am setting the cookie
String timeStamp = new SimpleDateFormat("dd:MM:yyyy_HH:mm:ss:SSS").format(Calendar.getInstance().getTime());
timeStamp = timeStamp + ":" + System.nanoTime();
String loc = "/u/poolla/workspace/FirstServlet/WebContent/WEB-INF/"+timeStamp;
Cookie cookie = new Cookie("path", loc);
Multiple users will have cookies with the same name but different loc values,
So, How do I get the cookie value in servlet.java and delete a particular loca value cookie??
Cookies are not same for each user. Generally cookies are tied to the client/user/browser which is accessing the JSP/application and each client can have a cookie value of its own.
When you delete a cookie you just delete it for the client which has made the request to your application. Rest of the clients will still have their own cookie without any effect in the value. Hence, you need not to worry about deleting a cookie may affect multiple users.
In order to delete a cookie, first get all the cookies from request and delete the cookie which has particular name/value.
public void delete(MyType instance) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("test")) {
cookie.setValue(null);
cookie.setMaxAge(0);
cookie.setPath(theSamePathAsYouUsedBeforeIfAny);
response.addCookie(cookie);
}
}
}
}
You will need to call getCookies() on the request and loop through them until you find the one you're looking for.
here is a little simple example tha might help you
//declaring a cookie
Cookie cookie = new Cookie(name, value);
//getting the cookie name
String name = cookie.getName()
//getting the cookie value
String value= cookie.getValue();

How to get asp.net created cookies in Java servlet?

How to get ASP.NET created cookies in a Java servlet?
This is My Cookie In ASP.NET
emid=11&eud=11&euid=33zU4Yq/p3k=&euseremail=F/zVoXtd4NoAd7yj6Z47gxFVaMCMYha/La6IzlC+xQo=&euserid=33zU4Yq/p3k=&emdn=testing
But when I try To Call it in Servlet it only prints: emid [only print the starting string before first equal to (=) sign]
I'm using the following code in Servlet to print cookies..
Cookie cookie = null;
Cookie[] cookies = null;
cookies = request.getCookies();
if( cookies != null ){
out.println("<h2> Found Cookies Name and Value</h2>");
for (int I = 0; I < cookies.length; I++){
cookie = cookies[I];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" \n");
}
}else{
out.println(
"<h2>No cookies founds</h2>");
}
Whats wrong with my code?
The equals character is a reserved character in a cookie value. The specification compliant way of fixing this is to quote the cookie value by surrounding it with double quotes. However, some browsers don't handle this very well. If you are using Tomcat you can set the system property -Dorg.apache.tomcat.util.http.ServerCookie.ALLOW_EQUALS_IN_VALUE=true to allow equals in cookie values.

Tomcat - SSO Without Realm?

I'm trying to enable SSO under Tomcat such that users who go to http://mydomain.com and http://www.mydomain.com will have their session cookie available for requests made to http://subdomain.mydomain.com. All three of these domains go to the same webapp, so ideally I'd like to not mess with SSO at all and just set the domain on the standard JSESSIONID cookie.
However, that doesn't seem possible, so I'm trying to enable Tomcat's SSO Valve. The problem is that the Valve requires a definition of a Realm, and a Realm is supposed to specify a database of users and roles. However, I am not using container-based authentication nor role-based authorization, so I do not need or want to configure a Realm. All I want is for the session cookie(s) to be able to be shared across each of these different subdomains.
Is there any straightforward way to do this?
Edit
My current workaround for this is to have the server redirect every incoming request to the "canonical" server name. This works well enough, but obviously it is not actually solving the problem.
We were having the same problem and created a Tomcat Valve that would overwrite or set the Domain part of the session Cookie. Quite a simple thing and it already works for many years. The code goes like this:
public class CrossSubdomainSessionValve extends ValveBase {
public CrossSubdomainSessionValve() {
super();
info = "common-tomcat-CrossSubdomainSessionValve";
}
#Override
public void invoke(Request request, Response response) throws IOException, ServletException {
// cookie will only need to be changed, if this session is created by this request.
if (request.getSession(true).isNew()) {
Cookie sessionCookie = findSessionCookie(response.getCookies());
if (sessionCookie != null) {
String cookieDomainToSet = getCookieDomainToSet(request.getServerName());
if (cookieDomainToSet != null) {
// changing the cookie only does not help, because tomcat immediately sets
// a string representation of this cookie as MimeHeader, thus we also
// have to change this representation
replaceCookie(response.getCoyoteResponse().getMimeHeaders(), sessionCookie, cookieDomainToSet);
}
}
}
// process the next valve
getNext().invoke(request, response);
}
protected Cookie findSessionCookie(Cookie[] cookies) {
if (cookies != null)
for (Cookie cookie : cookies)
if (Globals.SESSION_COOKIE_NAME.equals(cookie.getName())) {
return cookie;
return null;
}
protected void replaceCookie(MimeHeaders headers, Cookie originalCookie, String domainToSet) {
// if the response has already been committed, our replacementstrategy will have no effect
// find the Set-Cookie header for the existing cookie and replace its value with new cookie
for (int i = 0, size = headers.size(); i < size; i++) {
if (headers.getName(i).equals("Set-Cookie")) {
MessageBytes value = headers.getValue(i);
if (value.indexOf(originalCookie.getName()) >= 0) {
if (originalCookie.getDomain() == null) {
StringBuilder builder = new StringBuilder(value.getString()).append("; Domain=").append(domainToSet);
value.setString(builder.toString());
} else {
String newDomain = value.getString().replaceAll("Domain=[A-Za-z0-9.-]*", "Domain=" + domainToSet);
value.setString(newDomain);
}
}
}
}
}
protected String getCookieDomainToSet(String cookieDomain) {
String[] parts = cookieDomain.split("\\.");
if (parts.length >= 3) {
return "." + parts[parts.length - 2] + "." + parts[parts.length - 1];
}
return null;
}
public String toString() {
return ("CrossSubdomainSessionValve[container=" + container.getName() + ']');
}
}
The algorithm works like this:
- Only if the session is new - find the session cookie
- Get the requested host name
- Split the host name with '.'
- If it has at least 3 parts (like www.google.de), remove first part (to .google.de)
- Reset the cookie
In your Context configuration you can apply the valve like this
<Valve className="my.package.CrossSubdomainSessionValve" httpOnlyEnabled="true" />
Caveat: In the code the Valve creates a session if no session was created before and does not care if you need a session at all...
Hope that helps... Good luck!

Can't log out from Oracle SSO

I’m building a J2EE web application which uses Oracle SSO with an OID back-end as the means for authenticating users.
If a user wants to use the application, first he must provide a valid login/password at SSO's login page.
When the user is done using the application, he may click on the logout button; behind the scenes, the action associated with this button invalidates the user’s session and clears up the cookies using the following Java code:
private void clearCookies(HttpServletResponse res, HttpServletRequest req) {
res.setContentType("text/html");
for (Cookie cookie : req.getCookies()) {
cookie.setMaxAge(0);
cookie.setPath("/");
cookie.setDomain(req.getHeader("host"));
res.addCookie(cookie);
}
}
Also, I have an onclick JavaScript event associated with the logout button, which is supposed to delete the SSO cookies by calling the delOblixCookie() function (as found in some Oracle forum):
function delCookie(name, path, domain) {
var today = new Date();
// minus 2 days
var deleteDate = new Date(today.getTime() - 48 * 60 * 60 * 1000);
var cookie = name + "="
+ ((path == null) ? "" : "; path=" + path)
+ ((domain == null) ? "" : "; domain=" + domain)
+ "; expires=" + deleteDate;
document.cookie = cookie;
}
function delOblixCookie() {
// set focus to ok button
var isNetscape = (document.layers);
if (isNetscape == false || navigator.appVersion.charAt(0) >= 5) {
for (var i=0; i<document.links.length; i++) {
if (document.links.href == "javascript:top.close()") {
document.links.focus();
break;
}
}
}
delCookie('ObTEMC', '/');
delCookie('ObSSOCookie', '/');
// in case cookieDomain is configured delete same cookie to all subdomains
var subdomain;
var domain = new String(document.domain);
var index = domain.indexOf(".");
while (index > 0) {
subdomain = domain.substring(index, domain.length);
if (subdomain.indexOf(".", 1) > 0) {
delCookie('ObTEMC', '/', subdomain);
delCookie('ObSSOCookie', '/', subdomain);
}
domain = subdomain;
index = domain.indexOf(".", 1);
}
}
However, my users are not getting logged out from SSO after they hit the logout button: although a new session is created if they try to access the index page, the SSO login page is not presented to them and they can go straight to the main page without having to authenticate. Only if they manually delete the cookies from the browser, the login page shows up again - not what I need: the users must provide their login/password every time they log out from the application, so I believe there must be something wrong in the code that deletes the cookies.
I’d greatly appreciate any help with this problem, thanks in advance.
Oracle have two web SSO products - Oracle Access Manager and Oracle Single Sign On. The Javascript code you have posted is for Access Manager, so it won't help you. Besides, you shouldn't need to do anything in Javascript to log the user out.
Have a look at the logout section of the OSSO docs. It recommends using the following code:
// Clear application session, if any
String l_return_url := return url to your application
response.setHeader( "Osso-Return-Url", l_return_url);
response.sendError( 470, "Oracle SSO" );
You need a page, with a name of logout, that includes those JavaScript functions.
That's what the documentation says:
The WebGate logs a user out when it receives a URL containing
"logout." (including the "."), with the exceptions of logout.gif and
logout.jpg, for example, logout.html or logout.pl. When the WebGate
receives a URL with this string, the value of the ObSSOCookie is set
to "logout.
Cookies don't "delete" untill the browser is closed.

Categories

Resources