How to access session data across servlets in java? - java

I am working on an application with react on the front end and java(running on tomcat server JDK17) in the backend. Whenever I login into the application, I send the user data to the server(java) and see if the user exists in the database. Whenever I move across the components in the react application, I would like to check if the user is authenticated/allowed to use that particular component. Hence I stored the data onto a session in the login servlet. I tried to access the session from another servlet called AuthenticationServlet, it returns null. Do I have to configure something so that I can access the data across all the servlets.
This is how I set the session data in the login servlet:
HttpSession session = request.getSession();
session.setAttribute("uname", uname);
Printing it on the console in the same servlet displays the username.
This is where I'm accessing it(AuthenticationServlet)
HttpSession session = request.getSession();
String k = (String) session.getAttribute("uname");
System.out.println(k);
This displays null. What am I doing wrong or did I miss something. Much appreciated!

Related

JAVA SESSION Cookie issue

I want my web application to resume its session when the browser is restarted. So I had use the following code in cookie Filter to create SESSION cookie for any request other than login and logout.
HttpSession browserSession = httpRequest.getSession();
Cookie cookie = new Cookie("SESSION", browserSession.getId());
cookie.setMaxAge(Integer.MAX_VALUE);
httpResponse.addCookie(cookie);
If I login to my appl and restart the browser and access url, it's getting login automatically (as expected). But if I logout in that session and then try to login in that session, it's not getting logged in. What's causing this issue?
when i fetch cookies from request(httpRequest.getCookies()), i get 2 cookies with SESSION name , one is browser created and one is which my code created but while debuging both are having the same max age i.e -1 when i set my cookie max age as Integer.MaxValue()?? why is this happening
You can try deleting the coockie when logged out, this way user will be identified by the coockie created while logging in and will be valid for a session (from login to logout) and as soonest as user logs out earlier coockie will be deleted.

login form using jsp and servlets without DBMS

I'm trying to create a login form for a blog system. I have completed the login form using jsp, now i need to use a servlet to process the login details. However the tutorial i am following uses a dbms to query the form details and authenticate a user. How can i go about this WITHOUT using a database?
this is the tutorial i am following,
http://www.ganeshtechblog.in/2013/09/creating-simple-login-form-using-eclipse.html
You could use a local database ? TIP: XAMPP
or you can hardcode the user id and pw in your servlet.
You can make them as following:
# the top of your servlet add:
private static final String ID="idvalue",PW="pwvalue";
Then
String userId = request.getParameter("userId");
String password = request.getParameter("pwd");
You get those two values from your View...
Now you just have to simply check if they are correct witht the hard coded ones...
if(userId.equals(ID) && password.equals(PW)){
// fetch the session from request, create new session if session
// is not present in the request
HttpSession session = request.getSession(true);
session.setAttribute("FirstName", rs.getString("firstname"));
session.setAttribute("LastName", rs.getString("lastname"));
// redirect to success page
response.sendRedirect("LoginSuccess.jsp");
}else{ // redirect to error page
response.sendRedirect("LoginFailure.jsp");
}
I wouldn't use it as a real application though...
PS. this is one simple solution, there are many better way's...

java sessions - when does a session actually gets created?

my code,
HttpSession session = request.getSession(false);
// Details.l.info(" 1>>>>session ID is : " + session.getId());
Details.l.info("["+this.getClass()+"]"+"request from "+request.getRemoteHost());
if(session==null){
session = request.getSession(true);
Details.l.info("["+this.getClass()+"]"+"Session Created!!!!!!!!!!!!!!!!!!!#####$####");
Details.l.info(" 2>>>>>session ID is : " + session.getId());
}
Details.l.info(" 3>>>>>session ID is : " + session.getId());
// System.out.println("session ID is : " + session.getId());
Details DTO = new Details(request);
String loc = DTO.findMyLocation();
session.invalidate();
here, i am creating a session at the very beginning of the servlet with a logic that if the session already exists, then give hat session ID for that particular user or if a session does not exist for this particular user, please create a new session and then give the new session ID, here the new session is created inside the IF condition and i have tested in all possible ways (i have used two different systems and tried hitting to the servlet on one system too) but the control never gets into this loop where the session is getting created. but i see every time i hit to the servlet i get a new session ID!!! can someone please exlain this behavior of my servlet?? i am very new to sessions and servlets!!
Thanks in Advance..
JSPs implicitely create a session, unless session is set to false in the page directive:
<%# page session="false" %>
That's why your servlet always sees an already existing session. Simply enter the address of the servlet in the browser address bar (provided the code you posted is in the doGet() method), instead of going through the JSP to invoke it, and you should see the servlet create a new session.
EDIT: note that the spec says about this session attribute that it can be used to specify that the JSP doesn't participate in the session. Nothing guarantees that no session will be created when invoking the JSP. Only that, if you try to access the session from this JSP, you'll get an exception.
You may want to use request.getSession(true) to always create a session.

Session from JSP to Servlet lost (Cookie changes)

I come back with the same question but this time more documented. i have a web application with many servlets and JSPs. The application has a LogIn option. In the LogIn servlet i start a new session, and after placing some informations in the session i go forward to a JSP.
LogIn.java relevant code:
HttpSession sess = request.getSession(true);
sess.setAttribute("GLN", user);
rd.forward(request, response);
After I forward, I get a Jsp page called Insert.jsp where I get the sessions attributes.
Insert.jsp relevant code:
HttpSession sess = request.getSession(false);
if (sess != null){
out.println(sess.getAttribute("GLN"));
}
After this i have a form that directs me to a servlet Adaugare.java. Here i do the same thing:
Adaugare.java code:
HttpSession sess = request.getSession(false);
Here comes the problem. Later edit: This returns null, as no session exists. Then i forward to same Insert.jsp file and there, even if i have HttpSession sess = request.getSession(false);, a new session with a new session ID is created different from the first one. So obviously
out.println(sess.getAttribute("GLN")); returns null.
This is the long story. The short version:
When i go from a servlet to a jsp, session is ok, when i go from a jsp to a servlet, session is nowhere to be found . Then a new session is created when i forward to a JSP. Practically it creates a new cookie. If i print the contextPath from JSP and serlet, it's the same.
But here is the strange thing. This happens when i run the application on a apache with a mod_jk. When i run the app from a tomcat, it works fine.......
Please help, i've been stuck for 2 weeks on this problem.
Answer to dan: (Text to long for comment and need to wait 7 hours to reply my own question)
I deleted all comented lines. Hope that is ok. I'm not the one in charge with the server, but the one who is told me it's not multiple workers.
worker.list=jk-status
worker.jk-status.type=status
worker.jk-status.read_only=true
worker.list=jk-manager
worker.jk-manager.type=status
worker.list=balancer
worker.balancer.type=lb
worker.balancer.error_escalation_time=0
worker.balancer.max_reply_timeouts=10
worker.balancer.balance_workers=node1
worker.node1.reference=worker.template
worker.node1.host=localhost
worker.node1.port=8109
worker.node1.activation=A
worker.balancer.balance_workers=node2
worker.node2.reference=worker.template
worker.node2.host=localhost
worker.node2.port=8209
worker.node2.activation=A
worker.template.type=ajp13
worker.template.socket_connect_timeout=5000
worker.template.socket_keepalive=true
worker.template.ping_mode=A
worker.template.ping_timeout=10000
worker.template.connection_pool_minsize=0
worker.template.connection_pool_timeout=600
worker.template.reply_timeout=300000
worker.template.recovery_options=3
If the requests are balanced between multiple workers you should set the session stickiness flag to true. See: http://tomcat.apache.org/connectors-doc/reference/workers.html for more details. You should try:
worker.balancer.sticky_session=True

Java Web App Security using Cookies

I'm finishing a Cattle Drive assignment where a small Java web application manages a movie library for the client. The assignment is to put some security on the application using cookies, so that a "hacker" couldn't just guess one of the URLs that would lead to another part of the application. The user will be directed to login to the site and not be allowed to view other pages until logged in.
The parts of the web app are:
1. index.html
2. VideoServlet
3. listvideos.jsp
4. addvideo.jsp
5. videologin,jsp
The entry point is request URL http://localhost:8080/videos, which loads the index.html file. This page just has a link which redirects the user to the VideoServlet. From there, the servlet forwards the HTTP request and response to listvideos.jsp, which has a link to add videos if the users wants to do that.
I'm having trouble understanding how to implement the security using cookies, while keeping everything in the MVC2 pattern (the servlet is the controller, the jsp's are the view).
Here is the program flow I came up with, but I think I'm missing the point somewhere:
user enters URL http://localhost:8080/videos, which pulls the index.html file by default.
the index.html file basically sends an HTTP Get to VideoServlet. The servlet somehow knows the user isn't logged in yet, so forwards the request/response to the videologin.jsp.
a login is presented and asks the user for a password (this is a standard html form). The user enters the password and clicks submit. This sends an HTTP Post to the servlet.
the servlet checks the password and if correct, the user is logged in and the servlet forwards to listvideos.jsp.
I don't get where cookies come in or how they can help prevent a hacker from guessing a URL and gaining direct access to, for example, addvideos.jsp. Is a cookie being used to verify if the user has already logged in?
Cookies are some plain text values (stored in text files in browser cache normally) that you could use to store data on client side. When the user makes a request to a particular URL, all cookies stored on that server (domain) are passed with it, so that the server can read up those values.
In Java, you can set a cookie like this in your servlet (in your case, when user logs in, create a cookie and store a value in it (ex. username=josh). You could do this in your login servlet after a successful login.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Verify login, and get the username. Assume it's josh
Cookie cookie = new Cookie("username", "josh");
cookie.setMaxAge(60*60*24); // 24 hours for expiry
response.addCookie(cookie);
}
Later on, you can check for the existence of the cookie and if it exists, then the user has logged in. If not, you can send a redirect to the login page.
You can check for cookies like this in your servlet.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
String username = null;
for (Cookie c : cookies) {
if ("_username".equals(c.getName())) {
username = c.getValue();
break;
}
}
if (username == null) {
// Not Logged in. Redirect to Login
}
// User Logged In. Proceed
}
Instead of putting this code in all your Servlets + JSPs, you can easily put this into a Servlet Filter class. You can read up on more on that here: http://javaboutique.internet.com/tutorials/Servlet_Filters/
Ideally, you could provide a Logout feature also, which will remove the value assigned to the username cookie by replacing it with null.
I showed the above example because you mentioned that you need to use cookies for your assignment. But if you can, try to use the Sessions (which in turn uses cookies most of the time) to store logged in user details. With sessions, you can use session timeouts to ensure that idle users will be automatically logged off after a while and so on.
the index.html file basically sends an HTTP Get to VideoServlet. The servlet somehow knows the user isn't logged in yet, so forwards the request/response to the videologin.jsp.
The somehow knows is due to looking for the presence of the cookie in the request. Make sure the contents of the cookie are protected by a message authentication code, so you can be sure that your server actually handed out the cookie. It'd also be a good idea to encode into the cookie the specific IP address being used by the client, so an attacker can't hijack a cookie. (If a client changes IP address during a session, requiring them to log in again isn't horrible. Maybe annoying, but not unexpected.)
the servlet checks the password and if correct, the user is logged in and the servlet forwards to listvideos.jsp.
the user is logged in -- set the cookie into the browser for future requests.

Categories