Why Isn't Session Null - java

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

Related

In Wicket 9, when the user's session expires in certain pages, they are redirected to the login page not the Session Expired page

While upgrading some legacy code from Wicket 1.5 to Wicket 9, I found that redirection to a "Session expired" notification page seems to be partially broken.
I have the following statement, which always used to work before, in the main application file:
getApplicationSettings().setPageExpiredErrorPage(MyErrorPage.class);
Here is the scenario which should trigger redirection to "MyErrorPage":
The user successfully logs in and goes into any menu option.
They sit around for a while, doing nothing, and their session times out.
After this period of inactivity, they click on a link or attempt to submit a form.
At this point, they ought to be redirected to "MyErrorPage".
The menu option invoked in point (1) - lets call it MyMenuPage - could have been invoked with two possible types of syntax:
Either:
setResponsePage(MyMenuPage.class);
Or:
setResponsePage(new MyMenuPage(params));
It seems that the user will only be redirected to my custom error page if the original menu page was invoked with the SECOND syntax.
If the original page was invoked with the FIRST syntax, the user is sent straight to the login page, without any explanation about the fact that their page has expired.
Please can someone advise me how to get the same result in both types of page - which are not stateless, because the user has logged in.
There is a difference between page being expired and http session expiration.
As PageExpiredException's javadoc [I] explains there are three possible reasons for it:
the page have never been stored there, e.g. an error occurred during the storing process
the http session has expired and thus all pages related to this session are erased too
the page instance has been erased because the store size is exceeded
Wicket stores all stateful pages on the disk. Later when you use such page, e.g. by clicking a link, Wicket loads the page instance, executes the click, and render the response.
If the http session is expired then most probably your authentication strategy kicks in and redirects to the login page without even trying to load the old page. If you use Component#continueToOriginalDestination() after successful login then the user will be navigated to a new instance of the old page.
To summarize:
if the http session expires then your application redirect to the LoginPage
if a page instance is expired then by default Wicket will create a new instance of it (see PageSettings#setRecreateBookmarkablePagesAfterExpiry(boolean)) or show the configured getApplicationSettings().setPageExpiredErrorPage(MyPage.class); will be rendered
To debug what happens in your case put some breakpoints at the following places:
https://github.com/apache/wicket/blob/6a7e4c3d770324f125fbf43615c7708b67c8d8c5/wicket-core/src/main/java/org/apache/wicket/Component.java#L1061
https://github.com/apache/wicket/blob/6a7e4c3d770324f125fbf43615c7708b67c8d8c5/wicket-auth-roles/src/main/java/org/apache/wicket/authroles/authentication/AuthenticatedWebApplication.java#L134
I. https://github.com/apache/wicket/blob/master/wicket-core/src/main/java/org/apache/wicket/protocol/http/PageExpiredException.java#L31
Seems like I just have to work round this by always using the following syntax:
setResponsePage(new MyPage());
This is not the end of the world, because at least I don't have to pass any parameters in, in order to trigger the required "Go to session expired page" behaviour.

How do I have my JavaBean retain when a user leaves and comes back?

I'm trying to learn how JavaEE. I've previously used JSP a little but I've never messed with scopes and servlets.
I've got a servlet that is called when a user submits a form, and a UserBean bean is created & added to the session.
UserBean userBean = new UserBean();
userBean.setLogin(user);
userBean(setPassword(pass);
request.getSession().setAttribute("user", userBean);
RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response);
This forwards me to index.jsp, on which I display the value that I just set... index.jsp is just this:
${sessionScope.user.login}
This prints whatever I set the username to in the form. That's correct. That's great. Now I go back to mysite.com/index.jsp by typing the URL (not just refreshing - that's fine) and the information has gone. There's nothing. My bean has been lost. I thought a session meant an extended period of time. How can I retain my beans after the user goes away for 30 minutes and comes back by typing my URL?
I'm messing with a user account system so I would want the user to be able to leave and come back a few minutes later and not have to log in again. Is there a scope for this? I tried switching from sessionScope to dependent, but no difference.
Figured it out. Thanks to the replies, I knew that it probably wasn't a misunderstanding on my part about what "session" means, and that there was an issue with the server.
After some more digging, I found out that the issue was because I was running the application on a server which I was accessing through just its IP address. I went through an actual domain instead and it works fine! Something about how browsers don't like accepting cookies from sites without a domain was supposedly making me create a new session whenever I reload.

Using session.setAttribute in a deployed system

I have a system that is deployed with the link http://192.168.2.6:8484/DTR and upon logging in, it stores the user's info via session.setAttribute("user", user); However, when another user logs in, it overwrites the info of the first user as it again calls session.setAttribute("user", user);. So how can I really save the user's info so that more than two people can access the system at the same time?
This is what is currently happening:
I have two websites that are open.
I login in the first website (username: user1). Shows Hello, user1
I login in the second website (username: user2). Shows Hello, user2
I refresh the first website. It will now show Hello, user2
So how can I enable multiple users to access the website?
As discussed in the comments, the reason is both the users are logged in from the same browser and same system. So the JSessionId is same and hence the attributes are overriden.
Solution:Try with a different browser
You first get user attribute and set it if it's not there and session is new
user = session.getAttribute("user");
if (user == null&& session.isNew())
session.setAttribute("user", user);
Also please check if you are getting different session for different users session.getId() ... if not it might be the problem JSESSIONID cookie. The servletcontainer set a Cookie in the Set-Cookie header of the HTTP response with JSESSIONID as cookie name and the unique session ID as cookie value.

httpsession verification if exists

strong textI am new, need a proper way to validate. I followed
5 line code. it doent have a httpsession but still going to appointment.jsp . why so?
I followed How to check if session exists or not?
it is giving a session. org.apache.catalina.session.StandardSessionFacade#3b59e880 but the user is not login in...
it does. but I dont know why and how it got one?
if (request.getSession(false) == null) {
request.getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
} else if (request.getSession(false) != null) {
request.getServletContext().getRequestDispatcher("/appointment.jsp").forward(request, response);
}
Session is not created after your user logs in, It is created at the first request to the container from a browser. This enables container to track subsequent requests from same browser. This is implemented usually using a cookie with unique id(session id).
So even it depends on what is happening at user logout? are you calling session.invalidate().
We cant say a user as authenticated just because session object is not null.
There will always be a HttpSession object (ok, not always, but most of the time) - this is not an indicator for an authenticated user.
You need to set a session attribute eg. "authenticated" to flag this session as authenticated or not.
You can add this by calling request.getSession().setAttribute(...)
By default, a JSP will create a session. You probably don't want that behavior for your login page, so use the page directive in login.jsp:
<%# page session="false" %>
You would also need to make sure that any other JSP that is accessed before a successful login does not create a session.
if (request.getSession(false).getAttribute("userLoggedIn") != null ) {
if((Boolean)request.getSession(false).getAttribute("userLoggedIn") ) {
request.getServletContext().getRequestDispatcher("/appointment.jsp").forward(request, response);
}
} else {
request.getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
}

How to manage multiple accounts login and logout in different browser pages?

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.

Categories

Resources