Access same name cookie in different application tabs - java

I have an application running on localhost:8080 and it create a cookie with name jsessionid. Now I need to open another tabs for different application which is running on localhost:8090 which also create a cookie with same name that is jsessionid.
I need to access cookie of first application tab in second application tab..
how can I access both cookies... many tried but no luck...

You can write a servlet filter that would run before page gets rendered (in the atlassian-plugin.xml)
<servlet-filter name="My Filter" i18n-name-key="home-page-redirect-filter.name"
key="home-page-redirect-filter" class="mypackage.CookieFilter"
location="before-dispatch" weight="100">
<description key="home-page-redirect-filter.description">Some description</description>
<url-pattern>WHEN_TO_RUN</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</servlet-filter>
and then you can intercept cookies
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
Cookie[] myCookies=request.getCookies();
//do something with cookies
}

Looks like I misread your question. JSESSIONID is an httponly cookie and you won't be able to use document.cookie in the javascript to get it.
Maybe take a look at Jsoup Cookies for HTTPS scraping and Sending POST request with username and password and save session cookie for some ideas.

Related

How to avoid request to Java Web Application servlet from outside some network?

I am trying to build a web application which is only meant to be accessed from inside a specific network, lets say a company's network. If anyone tries the URL for the application from outside the company's network then the access should be denied. I know I can use doFilter method for this task. But I am not really sure how to start checking the requests that are only coming from inside the company's network.
Can anyone point me to any useful resource or tell me how to achieve this in Java?
try to implement
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
String validParams = request.getParameter("validParams");
if(!"blockTheRequest".equals(validParams)){
filterChain.doFilter(request, response);
return;
}
HttpResponse httpResponse = (HttpResponse) httpResponse;
httpResponse.getWriter().write("a different response... e.g in HTML");
}
and you need do configure it with in web.xml
<filter>
<filter-name>yourFilterURL</filter-name>
<filter-class>servlets.SimpleServletFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>yourFilterURL</filter-name>
<url-pattern>*.pattern</url-pattern>
</filter-mapping>

New session always being created when using getSession()

This is a duplicate of this question, but that question is over 4 years old and doesn't have an accepted answer. I'll offer bounty from this question if it does not get an answer.
In my J2EE web application, I have a Filter called AlwaysCreateSessionFilter. Here is my doFilter method:
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) {
if (request instanceof HttpServletRequest) {
((HttpServletRequest) request).getSession();
}
chain.doFilter(request, response);
}
And in this war's web.xml, I have:
<session-config>
<session-timeout>30</session-timeout>
<cookie-config>
<http-only>true</http-only>
<secure>true</secure>
</cookie-config>
<tracking-mode>COOKIE</tracking-mode>
</session-config>
The browser always correctly includes a JSESSIONID cookie with the value from the server's most recent response (provided in the response's Set-Cookie header). But the problem is that the server always provides a brand new value for JSESSIONID in the Set-Cookie header, not the same one provided with the request. So the server is creating a new session on each request.
I have set a breakpoint in the doFilter method, and can confirm that request.getSession(false) returns a valid session with the correct id that corresponds to the value of the JSESSIONID cookie being provided with the request. It's just that, when the server responds, it always has that Set-Cookie header set to a brand new JSESSIONID, and I can't figure out what is doing it.
Here is crude diagram to illustrate what is happening:
Any help would be appreciated.

JavaEE Webapp Custom authorization from outside a Servlet

I'm having a JavaEE Website running on a cloud-platform.
Now I want to use two types of authentications:
Is from an SSO-System, which is well integrated in the platfrom and works very nicely.
Is the problematic part: I want to authorize a user from 1) for the time of a session, and give him access to a more restricted resource.
Some details
I get the user and his data from 1).
The user first has to ask for permission to 2), which can be denyed or granted. A user gets authorization from a service, which is outside of the scope of his servlet.
For this purpose I pass a User-POJO (with the session of this user as a member) to a service.
If the service grants the rights to this user, it will set an attribute to the user session:
userSession.setAttribute("auth", "granted");
To restrict access to that resource I use a Filter:
#WebFilter("/supersecret/*")
public class NiceFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
HttpSession session = req.getSession();
// check
if (session.getAttribute("auth") != "granted")
// redirect to login
else
chain.doFilter(req, res);
}
//...
While this is currently working, I feel that my solution is very sloppy.
Altering the user-session outside the scope of a servlet seems to be bad practice.
Adding an attribute to the session for security-purposes is probably not a good idea?
I'd rather want to use standard JavaEE-mechanisms, but most of them are already used for auth-method 1), like declaring login-config in the web.xml.
Any ideas for a more robust solution to this problem?
Thanks in advance :)

Setting cookie from doFilter method

I have a filter class with doFilter method. In the doFilter method, I am setting a cookie as follows
HttpServletResponse httpResp=(HttpServletResponse)servletResponse;
Cookie myCookie=new Cookie("test","");
myCookie.setValue("testValue");
myCookie.setPath("/");
myCookie.setDomain(".mydomain.com");
httpResp.addCookie(myCookie);
filterChain.doFilter(servletRequest,servletResponse);
Should this ideally work? Setting a cookie in httpResp(HttpServletResponse) object and then just forwarding servletResponse(ServletResponse) object
Strangely the cookie is set for some clients but for some others the cookie is not set. I have checked the cookie settings on client's browser and it looks ok.
You can use the HttpServletResponseWrapper to enable the filter to control the response over down stream filters or servlets are
https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletResponseWrapper.html
Here is a pretty good explanation of the wrapper: https://stackoverflow.com/a/7047298/1676293
This will work except you need to refactor the code to:
filterChain.doFilter(servletRequest,servletResponse);
HttpServletResponse httpResp=(HttpServletResponse)servletResponse;
Cookie myCookie=new Cookie("test","");
myCookie.setValue("testValue");
myCookie.setPath("/");
myCookie.setDomain(".mydomain.com");
httpResp.addCookie(myCookie);
Add the cookie after the filterChain call so that another filter/servlet cannot do something that conflicts.

Servlet's sendRedirect() kills my session attributes

I am working on a webapp in WinXP, Eclipse Indigo and Google web plugin.
I have a simple form that takes a value from user (e.g email) , passes it to a servlet named SignIn.java that processes it and saves the email value to the session.
The SignIn code is very simple , here is what its doGet mostly does:
String email = req.getParameter("email"); //getting the parameter from html form
...
...
HttpSession session = req.getSession(); //create a new session
session.setAttribute("email", email);
So far so good, I've verified that the values aren't null at this point. Now comes the problem, I want to redirect to another servlet (ShowOnline.java) that needs to do some more processing. When I write
resp.sendRedirect(resp.encodeRedirectURL("/ShowOnlineServlet"));
ShowOnline gets null session values (the same email attribute I saved a second before is now null)
When I write
getServletConfig().getServletContext().getRequestDispatcher("/ShowOnlineServlet");
everything is OK, the email attribute from before isn't null!
What is going on? sendRedirect() just makes your browser send a new request, it shouldn't affect the session scope. I have checked the cookies and they are fine (it is the same session from before for sure since it is the first and only session my webapp creates and furthermore I even bothered and checked the sesison ID's and they're the same on both requests).
Why would there be a difference between sendRedirect() and forward()? The easy solution would be to use forward() but I want to get to the bottom of this before I just let go , I think it is important for me to understand what happened. I'm not sure I like the idea of not knowing what's going on on such basic concepts (my whole webapp is very simple and basic at this point since I'm a beginner).
Any thoughts ideas or suggestions would be warmly welcome !
If your SignIn servlet is only saving a request parameter (email), then you could also replace the servlet with a filter, e.g. SignInFilter.
SignInFilter would contain the same logic as your SignIn servlet (copying the email from the request parameters to the session), but would call the next item in the chain (which will be your ShowOnline servlet) instead of doing any redirect/forward.
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession();
String email = req.getParameter("email");
session.setAttribute("email", email);
chain.doFilter(req, res); // continue to 'ShowOnline'
}
Set up your form to POST to the ShowOnline servlet instead, and configure your new SignInFilter to execute before ShowOnline (servlet mapping omitted below for brevity).
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<filter>
<filter-name>SignInFilter</filter-name>
<filter-class>com.example.SignInFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SignInFilter</filter-name>
<url-pattern>/ShowOnline</url-pattern>
</filter-mapping>
</web-app>
As far as my knowledge, sendRedirect() just redirects the control to another page without transfering the associated request & response object of parent page, but RequestDispatcher(object) will dispatch the ServletRequest and ServletResponse to the page mentioned in path argument { getServletContext().getRequestDispatcher("path")} after that you can either forward the objects to that page or include the objects. So by this container becomes assured that he has to use the previous request and response object from of the parent page instead of creating new one.
Specially if you are using session management the best option is RequestDispatcher.
Hope that answers the question.
To All :- Please correct me if i am wrong.
#rs

Categories

Resources