Add another cookie when session is created [duplicate] - java

This question already has an answer here:
Fill a form with saved cookies
(1 answer)
Closed 5 years ago.
In my web application developed in struts 2 (javax.servlet v 2.5 and an embedded tomcat lib), I have the JSESSIONID always automatically added to the cookies after the first request when a HttpSession is created (at first call to request.getSession()), I know that the JSESSIONID aims to identify the created http session.
Now I want to add more cookies but I don't found how to adding this cookie in the framework struts 2? and how can I remove it from the cookie of the response when user logged out.

Add cookieName Cookie:
Cookie newCookie = new Cookie("cookieName", "cookieValue");
newCookie.setMaxAge(60*60*24*365); //Store cookie for 1 year
response.addCookie(newCookie);
and then remove it:
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("cookieName")) {
cookie.setValue("");
cookie.setPath("/");
cookie.setMaxAge(0);
resp.addCookie(cookie);
}
}
}

Related

Are there any way for request to not continue user session in Spring MVC?

I need to make an ajax request to server to check if user's session expired. The problem is that this request will continue user session if session was not expired. How to tell Spring not to continue session for this particular request?
One possible way to expire the HTTP session is to expire the JSESSIONID cookie. You can get an array of cookies from HttpServletRequest's getCookies() method. You can find the cookie with name JSESSIONID from that array. We can not delete the cookie using the Cookie object though. But we can expire it by setting the max age to zero i.e. cookie.setMaxAge(0). Here is a possible implementation you can try to use:
public static void expireJSessionIdCookie(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
Optional<Cookie> cookieOpt = Stream.of(cookies)
.filter(c -> c.getName().equalsIgnoreCase("JSESSIONID"))
.findFirst();
if (cookieOpt.isPresent()) {
Cookie cookie = cookieOpt.get();
cookie.setMaxAge(0);
}
}

Read parent domain cookies in java

I want to read parent domain(domain.com) cookies
Running the code from xyz.domain.com
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
//only subdomain cookies(i.e. xyz.domain.com) are displayed
}
}
Here I am not getting domain.com cookies
Similar to the below link
Access parent domain cookies from an application running on a subdomain
Update:
Cannot edit the cookies .i.e. cannot set domain of the cookie
When cookie is created in domain.com, you need to set domain as cookie.setDomain("."), Then cookie will be available in sub domain.

How to redirect to login page if session is expired? [duplicate]

This question already has answers here:
How to redirect to Login page when Session is expired in Java web application?
(9 answers)
Closed 6 years ago.
HttpSession session = request.getSession();
User user = (User)session.getAttribute("user");
if(user == null){
response.sendRedirect("login.jsp");
}
System.out.println(user);
I am writing this code in a servlet and deploying it in Tomcat Server. After the session expires, session is automatically created but the "user" attribute becomes null. But the page is not redirected to "login.jsp" and "null" gets printed on the console.
I am using MyEclipse IDE.
That's because the call to getSession() without a boolean parameter will create another session.
Do this: HttpSession session = request.getSession(false);
Also, make sure you place this snippet before any other headers are sent to avoid confusing the browser.
However, for a more comprehensive solution, see #BalusC's comment

Invalidate session in Logout Servlet [duplicate]

This question already has answers here:
Prevent user from seeing previously visited secured page after logout
(7 answers)
Closed 7 years ago.
HttpSession session = request.getSession();
try
{
session.removeAttribute("logonSessData");
session.invalidate();
String pageToForward = request.getContextPath();
response.sendRedirect(pageToForward);
}
catch (Exception sqle)
{
System.out.println("error UserValidateServlet message : " + sqle.getMessage());
System.out.println("error UserValidateServlet exception : " + sqle);
}
in Logout servlet I wrote above code in doPost and doGet method. After logout it shows login screen and then if I press back button it shows previous screen before logout and then if I click on any page it shows "HTTP Status 500" and now if I press F5 then it's heating login Servlet and getting the full access of user.
How to stop this problem show that after Logout using back button and F5 user can not use any page?
What you are doing is good. Browser is caching the previous pages, and when you click back button it is taking to previous cached page.
You need to add Cache headers which does not allow browser to cache page.
Cache-Control: no-cache
1)When you are clicking on back button on browser you are getting previous page because of browser cache.
2)When you are clicking on any page after backing you are getting status 500 because there is null pointer exception because of session object is invalidate already.
3)When you refresh new request is going to your servlet or JSP, there your are calling request.getSession(); method, which is creating new session object for you.
as a result you are getting full access to all pages again.
To avoid this problem you can follow the below steps.
1)In the application create one servlet Ex:LoginCheckerServlet
2)for the above servlet give url pattern /*
3)So the servlet will be executed for all the request
4)Now in LoginCheckerServlet check for username and password in request parameters
5)If they are coming perform login checking operation and display welcome page
6)If user name password are not coming, there are two meanings
i)user is already logged in
ii)user is trying to access your app illegally
7)Now call request.getSession(false); method which will give you session object is there is session already existing for this user so you can redirect to welcome page with trust on user.
8)request.getSession(false); will give you null value if there is no session existing for this user.
9)In case if you are not getting username and password in request parameters as well as request.getSession(false); is giving you null value means user is trying to access your application without logging in, now you can happily display forbidden page.
In every servlet, check whether Session is null or not. If session is not null then only do the request processing else redirect to login page.
HttpSession session = request.getSession();
if(Session !=null)
{
try
{
// acutal servlet actions
}else
{
// redirect to login page
}
Also it would be good if you add null check for session in your above code.
HttpSession session = request.getSession();
if(session !=null)
try
{
session.removeAttribute("logonSessData");
session.invalidate();
String pageToForward = request.getContextPath();
response.sendRedirect(pageToForward); }
catch (Exception sqle)
{
System.out.println("error UserValidateServlet message : " + sqle.getMessage());
System.out.println("error UserValidateServlet exception : " + sqle);
}
}else
{
//session already null/ expired
}
What you need to do is set the session into an attribute based on the session.
request.getSession().setAttribute("sess",request.getSession());
Use this to compare it to the current session. If this comparison fails, then redirect to the login page. This should be done in each page.
This will create a new session
HttpSession ss = request.getSession(true); //creates a new session.
if(ss.isNew()){
ss.invalidate(); //this clears the session
ss = request.getSession(true); // creates a new session
}

Cookie handling with Servlet

I am having a problem of setting the data of a (persistent/cross browser session) cookie correctly inside a Servlet and the reading it in a Filter.
the code of the Servlet (running at log-in time) is:
String encodedValue = new String(Base64
.encodeBase64(req.getParameter("account").getBytes()));
Cookie cookie = new Cookie("projectAuthenticationCookie", encodedValue );
cookie.setMaxAge(24*60*60);
cookie.setPath("/");
res.addCookie(cookie);
This will get the cookie inside the response, but the when I read it within my filter with the following code:
Cookie authenticationCookie = null;
Cookie[] cookies = ((HttpServletRequest) request).getCookies();
for (Cookie cookie : cookies){
if ("projectAuthenticationCookie".equals(cookie.getName())) {
authenticationCookie = cookie;
}
}
I only get the value I set right, all other fields are either null, empty or different. Max age for example always returns -1 and thus the cookie will never persist.
I tried setting the expires-header with:
res.setDateHeader("Expires", System.currentTimeMillis() + 24*60*60*1000);
as I read that without a valid expires-header the session will timeout anyway (correct me if I am wrong), but that didn't help either...
One issue I am thinking of is that I am running on localhost (tried setting cookie.setDomain("localhost") but also no luck). My web server/serclet container is Jetty 7 but I do not think that this is relevant...
Any hints?
The fields other than name and value are not populated (and thus not meaningful) on cookies you get from a request.
These fields are intended to inform the browser about the max age; path, etc. of the cookie, but the browser doesn't send back this information to the server. The only time where it's important to have the correct max age, path, etc. is when you create a cookie and add it to the response. Use your browser to check if it stores the correct information instead of trying to find it at server-side.

Categories

Resources