i am having one jsp file with the following code
String name=request.getParameter("user");
if(name==null)
name=(String)request.getSession().getAttribute("name");
else
request.getSession().setAttribute("name", name);
i assume if the page get any request with user as parameter, it will save the value to that particular user session and in case the get request is not having any 'user' parameter it will try to read the user value from the session. The code is working perfectly when i host it from my local server(glassfish).
But when i upload it into some remote host, things are getting weird.
When i hit the page with parameter 'user', its saving the value in the session. But then again if i hit the page from some other browser(or after clearing cookie), its retrieving the previous value saved, instead of returning null
Am i doing something wrong, actually im pretty new to Java EE.
You cannot get previous value saved unless
1) Your session is not finished and same session is getting extended. Can you explain how you are clearing the cookies.
2) Are you typing the URL or trying to refresh the page after deleting the cookies.
Related
I'm working on some old Java code with broken authentication. The web application starts with a jsp file that successfully creates and authenticates a user object. Then a session variable is created with the following code.
session.setAttribute("guiUser", userIdentity);
If I decide to get this user object within the same jsp file:
UserIdentity foo = (UserIdentity) session.getAttribute("guiUser");
System.out.println(foo.getName());
I can succesfully retrieve the authenticated user object.
However, the page is then redirected to another jsp within a different project in my workspace using
response.sendRedirect(targetPage);
When I get to this new jsp page, a login check jsp is run before anything else. The login check has the following code to instantiate a user object from the session variable(or at least this is what I think it's supposed to do.)
<jsp:useBean id="guiUser" class="com.ussposco.sso.UserIdentity" scope="session"/>
<% (code that uses guiUser object) %>
This code doesn't seem to work, because the user object is null. So I tried grabbing the user object from the session with this code.
UserIdentity foo = (UserIdentity) session.getAttribute("guiUser");
System.out.println(foo.getName());
And the object is still null.
I'm pretty new to Java web applications, but I think that this is a problem with the way that the response is redirected. I can see two different cookies in Chrome when I think there should only be one. Also, on the production website, it changes the value of a different cookie than the code I'm using(obviously out of date) uses.
As you are redirecting to the different application you will not get the same session object. Something as Single Sing On (SSO) is required for this.
I set a userId in the session object on the pageload of homepage of my application like below
HttpSession session = req.getSession();
session.setAttribute("userId", validUserId);
When user navigates to different page of the application, I fetch this userId using normal way like below and I save this userId in database later.
HttpSession session = request.getSession();
String userId = (String) session.getAttribute("userId");
This works for almost 95 times out of 100 calls. I am able to fetch the userId and store in database, but for 5 calls, all I get is a blank userId object.
I am not able to reproduce this issue in lower environments, so its bit difficult to understand what the issue is.
I have set the automatic expiry of the pages to 20 mins by adding the property in web.xml and then using it in jsp page.
Can some one please guide as to what could be the root cause of this issue?
Found the root cause.
When i am displaying the expiry page and invalidating the session, if user clicks on back button of the browser, it was displaying the old page again and if data is submitted now, then this variable is not available as session is already invalidated previously. Need to fix back button issue.
1) When user logs into our system via SSO, we generate a random token and keep that in session at server side code looks like, so it will be generated only once just after user logs in
if(slingRequest.getSession().getAttribute("csrfToken") == null){
UUID uuidRandom = UUID.randomUUID();
String Guid = "_" + uuidRandom.toString();
log.info("Random CSRF number Generated is "+Guid);
slingRequest.getSession().setAttribute("csrfToken",Guid);
}
2) On every page , we are reading from session and keeping this value in a hidden field code looks like
<%String csrfToken="";
if(null != request.getSession() && null != request.getSession().getAttribute("csrfToken")){
csrfToken=(String)request.getSession().getAttribute("csrfToken");
pageContext.setAttribute("csrfToken",csrfToken);
}
%>
<input type="text" id="csrfToken" value="${csrfToken}" style="display:none;" name="csrfToken">
3) On every POST request we are sending this csrfToken which is stored in hidden field to server and validate it at backend with the values retrieved from session at server side, if it’s is same then request is valid otherwise it’s not.
if(csrfToken.equals(request.getSession().getAttribute("csrfToken").toString() ))
4) On logout we invalidate the session and remove the token from session.
request.getSession().removeAttribute("csrfToken");
request.getSession().removeAttribute("globalAccountHolder");
request.getSession().invalidate();
Issue:
Sometimes pagesource/hidden field value is shown as same as it was in previous session, which is before log out value. i.e step 2 shows older value and when step 3 gets executed the matches of token fails, but if we reload the page using Cntrl+R then hidden field value is shown correctly and works. So not able to understand if this is browser caching problem for a page??
Tried Solution: As a solution for this we have set no-cache in our response headers, but this doesn’t work .
Is there any other solution you can think of like including any meta-tag in page header, or some otherthing?
ALso this issue i am facing sometimes only not everytime
I am using the following code to delivery the user to a Welcome page if they are already logged in, or back to the login page if they are not.
HttpSession session = request.getSession(false);
if(session == null){
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}else{
//User already logged in. Send to home.
response.sendRedirect("Welcome");
}
First time around, it works fine, but if I reload the page even once it sends the user to the welcome page and inevitably sends me back a 500 error because there are elements on that page that cannot be loaded because the user log in code has not been executed.
Does a session get started automatically even if request.getSession(true) is not declared when a page is reloaded? Is there a way to prevent this?
Probably the session is being created upon forwarding to login.jsp. That's necessary because the user has to be assigned to an unauthenticated request and then authenticate it. If you want to redirect based on whether the user is logged in or not, use SessionContext's getCallerPrincipal.
For more info, check this (somewhat old, but still relevant) article
The method request.getSession(false) returns null if there is no current session. I suggest to compare a key too.
Please take a look at this threads.
Do JSPs always create a session?
How do servlets work? Instantiation, session variables and multithreading
I have a website built on App Engine(Java) and need user use Google Account to login.
The situation is that:
User Adam has multiple accounts.
User Adam login with account Adam1 and get his Adam1 data in browser page A.
He clicked logout link, but opened it in another tab page B(the same browser of course)
He login with another account Adam2 in browser page B get his Adam2 data shown.
He then returned to browser page A and made some changes to his data and then send to server, at this time my app would recognize the current user is Adam2 , and the changes would be taken on Adam2, it does not match the status with its current page A, our user may be confused.
I thought maybe I can attach a userID parameter while making change request to the server and server side will compare the current user id with this userID parameter to make the change request processed or return a refresh command to make the out-of-date page be refreshed to the current account's if the ids are not same.
What is the best practice to handle this situation?
Put a hidden field on your forms that is a combined hash of the session ID and the user ID. When your server processes the request, double check that the combined hash sent along with the request matches what you expect. If either the user or the session is wrong, the hash won't match, and you can report an error appropriately.
Presumably the user would be identified by a Session ID that is send as Cookie information. Adam on site A will have a different Session ID than Adam on site B because of the differing login. Also presumably the form page will be protected such that a user needs to be logged in in order to access it.
When Adam logs out on page B, the old session is destroyed on the server and the login becomes invalid. When Adam submits the form from page A, the browser doesn't know this has happened and will submit the form together with the old Session ID. The server will (should) reject this submit since the session has already expired.
Hence, in a properly coded Session/User management system, this becomes a non-issue. The critical point is to renew/invalidate the Session ID upon logout.