I am trying to get the session id using spring SecurityContextHolder. like below
public static String getSessionId(){
String id = null;
SecurityContext secContext = SecurityContextHolder.getContext();
Authentication auth = secContext.getAuthentication();
if(auth!=null){
WebAuthenticationDetails details = (WebAuthenticationDetails) auth.getDetails();
if(details!=null){
id = details.getSessionId();
}
}
return id;
}
most of the times details.getSessionId(); is coming as null. sometimes it will return sessionId. I want to know what could have caused this. is it the right way of accessing sessionId?
I tried RequestContextHolder.currentRequestAttributes().getSessionId();
this returns session id properly everytime. i want to know the difference between these two way of accessing session id.
You shall not use auth.getDetails().getSessionId() to get current session. It is not intended for that usage. The java doc for WebAuthenticationDetail says :
String getSessionId() : Indicates the HttpSession id the authentication request was received from. (emphasize mine)
and for the creator :
public WebAuthenticationDetails(javax.servlet.http.HttpServletRequest request)
Records the remote address and will also set the session Id if a session already exists
(it won't create one).
Parameters:
request - that the authentication request was received from
So you get the id of the session that existed when credentials were received
Worse, if you are using a SessionFixationProtectionStrategy, the id you get should be the one from the now invalidated session that was closed to protect against session fixation attacks.
So the correct way is to use the RequestContextHolder :
sessionId = RequestContextHolder.currentRequestAttributes().getSessionId();
Pay attention that RequestContextHolder.currentRequestAttributes().getSessionId() forces session creation if no session exists at the moment of call. Moreover, RequestContextHolder#currentRequestAttributes() may produce RuntimeException.
In my point of view, for logging purposes it is better and more safe to use the following code to obtain sessionId:
ServletRequestAttributes ra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpSession session = ra != null ? ra.getRequest().getSession(false) : null;
String sessionId = session != null ? session.getId : null;
Related
On server side I'm using Java and on the client side Ionic1.
I'm setting Java object to session like this:
session.setAttribute("userId", userObj.getUserId());
After setting session i need to get that session in another method, that time I'm using like this
Long userId = (Long) session.getAttribute("userId");
Here if i send request from mobile to server I will get session.getAttribute value.
But I sent request from browser to server that time I will get session.getAttribute value is NULL
Make sure you are calling the getAttribute() only after the session has been created. Its a common mistake to access the session attributes when no session exists.
Basically, validate and make sure session exists and that the attribute value has been set in the application flow before trying to get the session attributes.
HttpSession session = request.getSession(true);
// true will create a session is does not already exists
if(session != null) {
// get your session attributes here.
// Your Session Attributes should be set before you're trying to access them
}
This question already has answers here:
How do servlets work? Instantiation, sessions, shared variables and multithreading
(8 answers)
Closed 8 years ago.
I have a servlet which have these values and I want to pass these values to the java class in session attribute. How can I access these session attributes because I am not using JSF or Struts. This is simple Java Web application.
userID=map.get("UserID");
log.debug("The UserID in case of CCM authtication are : "+userID);
session.setAttribute("UserID", userID);
String refSys="";
refSys = map.get("refSystem");
log.debug("The refSystem in case of CCM authtication is: "+refSys);
session.setAttribute("refSystem", refSys);
This is how I am trying to get in the Java class and I am getting null in the Java class.
HttpSession session = null;
session.getAttribute("UserID");
Well, your session only can be null, because you don't initialize it. You have to do something like that first to initialize the HttpSession-object:
HttpSession s = request.getSession();
After that you can access your userId via the HttpSession.
you are intially setting your session to null.
change ur code to this :
HttpSession session = null;
HttpSession session = request.getSession();
String userId =session.getAttribute("UserID");
hope it works !!
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.
I need make sessions in Java web application.
I found that sesstion makes in servlet calass by method getSession().
But i have a question about session parameters. For example i send to server login/pass and save it into session atributes. Okey. Next time i do something on client and send new params to server. Where i gonna send it? In another or same and i gonna use if else for handle params like this?
Another question: How to use params which i put in session(login/pass) in another classes?
UPDATE
I read about sessions. And have new question. How to use session params in enother class. I mean after login i send new params on server, read it in servlet and want to take a login/pass from session and send it with new params into another class.
As part of your request handling in a doGet or doPost method, here is how you can get session and use it to get and set variables.
//Obtain the session object, create a new session if doesn't exist
HttpSession session = request.getSession(true);
//set a string session attribute
session.setAttribute("MySessionVariable", "MySessionAtrValue");
//get a string sessson attribute
String strParam = session.getAttribute("MySessionVariable");
//get an integer sessioin attribute
Integer param = (Integer) session.getAttribute("MySessionVariable");
//set an integer session attribute
session.setAttribute("MySessionVariable", new Integer(param.intValue() + 1));
Session is associated with each request . Now it depends whether client join the session or not there are three overloaded methods of getSession() to get more about them please go through the documents. Now if session is aleady associated with the request get existing session set the attribute in session and vice-versa if not create new session and do the same.
if the server used only cookie-based sessions, and the client had disabled the use of cookies, then a session would be new on each request.
I hope this helped.
Hi in jsp of JavaScript i am checking userdId in session or not it always have session id if session expires also, but i checked in java Action class after session expires userid is null but not in jsp. code link
Try alerting the sessionId in your javascript code. You will find that the sessionId is different after the old one has expired.
Also check what the code is doing when a new session is created. It might be setting the userid in the new session.