Get all active HttpSession in RESTEasy implementaion - java

I need to get list of all the active Session so that I can manage them. Basically I need to manage all the logged in Users in application.
Using HttpServletRequest req I am able to get current session but
need to get all the sessions
Something like this:
public EmployeeTO getEmployeeById(int id, HttpServletRequest req) {
EmployeeTO employeeTO = null;
try{
HttpSession session = req.getSession();
HttpSessionContext httpSessionContext = session.getSessionContext();
}catch(Exception e){
e.printStackTrace();
}
return employeeTO;
}
Am using RESTFul implementation with JASS for Login

I have a screen which shows the list of all active Users. If I check one
User and click close session. I need to terminate that users session.
To do that I need to have sessions somewhere accessible.
Using the HttpServletRequest, you will be able to get only the current request's (user's) session object. But if you want to track all session objects, you can do that by implementing HttpSessionListener as shown below:
public class MyProjectSessionListenerAndInvalidator
implements HttpSessionListener {
private static Map<String,Session> sessions = new HashMap<>();
#Override
public void sessionCreated(HttpSessionEvent event) {
//add your code here,
//this will be invoked whenever there is a new session object created
//Get the newly created session
Session session = event.getSession();
//get userId or unique field from session
sessions.put(userId, session);
}
#Override
public void sessionDestroyed(HttpSessionEvent event) {
//add your code here
//this will be invoked whenever there is a new session object removed
//Get the removed session
Session session = event.getSession();
//get userId or unique field from session
sessions.remove(userId);
}
public R getSessions() {
//add code here
}
public void invalidateSession(String userId) {
//add code here
}
}
N.B.: I recommend to use getSessions() and invalidateSession() carefully.

Related

How to see who's logged in from server.xml file?

I have configured the server.xml file in a Java Spring application to authenticate users when logging in from database tables and roles. I'm wondering how in Java code can I check who's logged in to the application?
I know that in a jsp file I can just use this following syntax to show the name:
${pageContext.request.userPrincipal.name} .
In your Spring MVC Controller, just add the following statement:
String loggedUser = request.getUserPrincipal().getName();
where request is the object of HttpRequest type, made available to you by Spring on demand.
There is very beautiful article for this is given at http://www.baeldung.com/spring-security-track-logged-in-users
You can leverage the HttpSessionBindingListener to update the list of logged in users whenever user information is added to the session or removed from the session based on user logs into the system or logs out from the system.
It will listen to events of type HttpSessionBindingEvent, which are triggered whenever a value is set or removed, or, in other words, bound or unbound, to the HTTP session.
#Component
public class LoggedUser implements HttpSessionBindingListener {
private String username;
private ActiveUserStore activeUserStore;
public LoggedUser(String username, ActiveUserStore activeUserStore) {
this.username = username;
this.activeUserStore = activeUserStore;
}
public LoggedUser() {}
#Override
public void valueBound(HttpSessionBindingEvent event) {
List<String> users = activeUserStore.getUsers();
LoggedUser user = (LoggedUser) event.getValue();
if (!users.contains(user.getUsername())) {
users.add(user.getUsername());
}
}
#Override
public void valueUnbound(HttpSessionBindingEvent event) {
List<String> users = activeUserStore.getUsers();
LoggedUser user = (LoggedUser) event.getValue();
if (users.contains(user.getUsername())) {
users.remove(user.getUsername());
}
}
// standard getter and setter
}
You can go through the whole code here
You can also retrieve the current logged in user from Spring security
Go through this artical
Or through Request also
request.getUserPrincipal().getName();
You can write a method to get current logged in user as you might need this various places like below :
public User getCurrentLoggedInUser() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
Object principal = auth.getPrincipal();
if (principal instanceof User) {
return ((User) principal);
}
}
}

How to set cookies in Spark Java being deployed in Apache Tomcat

Recently I started using Spark Java Framework (2.7.2) to create a lightweight web application. One of its requirements is that the application must be deployed to an Apache Tomcat Server 8.5.
I've managed to set things going, but I have not been able to set any custom cookie.
I have used the following method but none worked.
response.cookie("my_cookie", "value");
response.cookie("/path", "my_cookie", "value", -1, false, true);
It seems like tomcat is setting correctly the JSESSIONID cookie but I have no control over this cookie generation and I would like to generate a random and unique cookie, in order to be used for user authorization.
EDIT:
The control flow for setting the cookie is this
// In the main application
before("/*", AccessController.setSession);
// Method for setting an existing session
public static Filter setSession = (Request request, Response response) -> {
// If the user is not set in the session
if (!SessionUtil.hasSession(request)) {
// Obtain the cookie session ID
String sessionId = SessionUtil.getCookie(request);
System.out.println(sessionId);
// Obtain the user according to the session ID
User user = app.getUserFromSession(sessionId);
System.out.println(user != null);
// if does exists we set the session
if (user != null)
SessionUtil.setSession(request, user);
}
};
// Methods for the session
public static boolean hasSession(Request request) {
if (request.session().attribute("user") == null)
return false;
return true;
}
public static String getCookie(Request request) {
return request.cookie(COOKIE_NAME);
}
public static void setSession(Request request, User user) {
request.session().attribute("user", user);
}
This is called when a login is succesfull. Cookie is stored in the user database persisting sessions
public static void setSession(Response response, String cookie) {
response.cookie(COOKIE_NAME, cookie);
}

How to check in servlet that is an user new with session?

I am very new to java servlet programming. I have been writing a simple program for practicing java session. There are two .jsp file. first one called index.jsp, and another one is selection.jsp. And there is a servlet called controller. At first the index.jsp will be called, and user will be submit a input. That will be redirect in servlet controller. In that servlet will check whether it is new request or not. If new then it redirect to other page, else will do some other work.
I am checking whether it is new request or not by session.isNew() method. But it always says it is not new session. But, if I disable the browser cookies option then it is working fine. Now what is my observation is that when in the first I request the index.jsp to the container it assign a session along with that request. So when it comes to servlet it treat as a old session. I got this idea from Head first book Servlet and JSP.
Here is my servlet code -
public class Controller extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user;
HttpSession session = request.getSession(false);
if (session == null) {
user = request.getParameter("user");
if (user == null) {
response.sendRedirect("index.jsp");
}
session.setAttribute("username", user);
SelectItem selectItem = new SelectItem();
selectItem.setUser(user);
response.sendRedirect("selection.jsp");
session.setAttribute("selectItem", selectItem);
} else {
String selectionItem = request.getParameter("selection");
SelectItem selectItem = (SelectItem) session.getAttribute("selectItem");
if (selectItem != null) {
selectItem.add(selectionItem);
session.setAttribute("selectItem", selectItem);
}
response.sendRedirect("selection.jsp");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
So, how to determine whether it is a new session or old one? Thank you.
HttpSession.isNew API:
Returns true if the client does not yet know about the session or if the client chooses not to join the session. For example, 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.
So, you're getting true because the client has cookies disabled. The "new session" check in done in the else block of this check:
HttpSession session = request.getSession(false);
if (session == null) {
// create new session
session = request.getSession();
} else {
// existing session so don't create
}
In your code, you don't appear to be creating a new session when a new session is detected. Perhaps that's where you're stumbling.
Note: learning the basic Servlet API is a good thing. However, for my professional work I use frameworks which simplify my programming, like Spring Boot and Spring Security.

Java web application HttpServletRequest in an HttpSessionListener

I am trying to use a HttpSessionListener to check for a cookie and get the IP address of the request.
However I don't have access to the HttpServletRequest in the listener to pass to STKUserCookie or to get the IP.
public STKUserCookie(HttpServletRequest request)
public void sessionCreated(HttpSessionEvent se) {
HttpSession httpSes = se.getSession();
if ( se.getSession().getAttribute("STKUserSession") == null) {
STKUserCookie userCookie = new STKUserCookie(request); <------- ERROR on this line "request" not available
String userBadge = userCookie.getUserID();
STKUserDAO userDAO = new STKUserDAO();
STKUser user = userDAO.getUser(userBadge);
if (user != null) {
user.setIpAddress(se.getRemoteAddr()); <------- ERROR on this line "getRemoteAddr" not a method of se
userDAO.updateLogin(user);
httpSes.setMaxInactiveInterval(36000); //set to 10 hours
httpSes.setAttribute("STKUserSession", user);
}
}
}
The above used to be a scriptlet that I was including in all my jsp pages and I am trying to refactor it into a listener, rather than a filter since I only want it to be called once per session to reduce overhead. Or should I not worry about the overhead and stick the method into a filter??
Don't worry about the overhead of a no-op filter. It is negligible.

Google AppEngine Session Example

I just enabled Session in my Google AppEngine/Java + GWT application. And how do I use it? How do I get session ID and play will all good stuff from it? Are there any real examples of simple login page where I'm just entering LoginName and Password, then it goes to the server over RPC call, authenticates against database and sends Session ID back to the client.
I have following code already but don't know what to do next:
GWT Login Form:
public class LoginForm {
private final LoginServiceAsync loginService = GWT.create(LoginService.class);
VerticalPanel loginVp = new VerticalPanel();
TextBox loginTxt = new TextBox();
TextBox passTxt = new TextBox();
Button loginBtn = new Button("Login");
public Widget getLoginWidget(){
loginBtn.addClickHandler(new ClickHandler(){
public void onClick(ClickEvent arg0) {
loginService.authenticateUser(loginTxt.getText(), passTxt.getText(),
new AsyncCallback<String>(){
public void onFailure(Throwable caught) {
InfoPanel.show(InfoPanelType.HUMANIZED_MESSAGE, "No Connetion", "Problem conneting to the server.");
}
public void onSuccess(String result) {
InfoPanel.show(InfoPanelType.HUMANIZED_MESSAGE, "Session ID", "Your session id is: " + result);
GWT.log("Setting up session", null);
String sessionID = result;
final long DURATION = 1000 * 60 * 60 * 24 * 14; //duration remembering login. 2 weeks
Date expires = new Date(System.currentTimeMillis() + DURATION);
Cookies.setCookie("sid", sessionID, expires, null, "/", false);
}
}
);
}
});
loginVp.add(loginTxt);
loginVp.add(passTxt);
loginVp.add(loginBtn);
return loginVp;
}
}
RPC Servlet:
public class LoginServiceImpl extends RemoteServiceServlet implements LoginService{
//Sends back to the client session id
public String authenticateUser(String login, String password){
String sessionId = new String();
// TODO: figure out how to work with session id in GAE/J
sessionId = "How to get session id?";
return sessionId;
}
public Boolean checkIfSessionIsValid(String sessionId){
//TODO: figure out how to check user's credentials
return true;
}
}
Any hints in the right direction would be helpful.
Thanks.
Enabling session support gives you a standard Servlet HttpSession.
This will be tracked by means of a cookie (called JSESSONID), which is managed by the servlet container under the covers. You do not need to care about the session id.
You can then set attributes (server-side) that will be associated with the session (so that you can retrieve them later).
HttpServletRequest request = this.getThreadLocalRequest();
HttpSession session = request.getSession();
// in your authentication method
if(isCorrectPassword)
session.setAttribute("authenticatedUserName", "name");
// later
if (session.getAttribute("authenticatedUserName") != null)
This should also work with Ajax requests from GWT.
Please refer to any Servlet tutorial for more details.
The drawback of sessions on GAE (compared to other servlet engines) is that they are serialized in and loaded from the database every time, which could be expensive, especially if you put a lot of data in there.
Here is how you can get the session in GAE:
this.getThreadLocalRequest().getSession();

Categories