0

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!

Shelton
  • 47
  • 5
  • 3
    Check whether your frontend programs allow cookies. Some network libraries do not contain cookies by default. The implementation of the session depends on the jsessionid stored in the cookie. If cookies are not supported, a new session is created for each request. – HUTUTU Feb 09 '22 at 03:44
  • @HUTUTU I can find the jsessionid int response header. I don't find it in the cookies tab – Shelton Feb 09 '22 at 04:13
  • @HUTUTU Can you tell me how I can add those cookies to the browser cookies? – Shelton Feb 09 '22 at 05:55
  • If you are using Chrome, you need to check "show filtered request cookies". Check two different network requests to see if JSESSIONID is the same. What network library do you use in react? – HUTUTU Feb 09 '22 at 06:25
  • @HUTUTU I'm using fetch API to get the data from java – Shelton Feb 09 '22 at 06:44
  • https://stackoverflow.com/questions/51291831/fetch-api-call-causes-new-asp-net-session – HUTUTU Feb 09 '22 at 06:57
  • @HUTUTU I tried this out and it was raising a pre-flight CORS. Is there something that I have to add on the server side as well? – Shelton Feb 09 '22 at 09:09
  • Did you set credentials to include? If so, I think it should be set to same-origin. – HUTUTU Feb 09 '22 at 09:29
  • @HUTUTU In the client side, I have this header ```credentials: "include"``` In the server side I have ``` response.setHeader("Access-Control-Allow-Credentials", "same-origin");``` Still getting CORS error. Anything else I'm supposed to add – Shelton Feb 09 '22 at 12:24
  • credentials:"same-origin" – HUTUTU Feb 10 '22 at 01:06

0 Answers0