I solved this issue with the help of a filter
public class SessionReplicationFilter implements Filter {
@Inject
SessionReplicationManager manager;
public SessionReplicationFilter() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
//Process chain first
if (chain != null) {
chain.doFilter(request, response);
}
//check http request
if (request instanceof HttpServletRequest) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
// Retrieve the session and the principal (authenticated user)
// The principal name is actually the username
HttpSession session = httpRequest.getSession();
Principal principal = httpRequest.getUserPrincipal();
if (principal != null && principal.getName() != null && session != null) {
manager.checkExistingSession(principal.getName(), session))
}
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}
The Manager looks following
@ApplicationScoped
public class SessionReplicationManager {
private Map<String, HttpSession> map = new ConcurrentHashMap<String, HttpSession>();
public boolean checkExistingSession(String user, HttpSession session) {
if (map.keySet().contains(user)) {
if (!session.getId().equals(map.get(user).getId())) {
System.out.println("User already logged in ");
HttpSession oldSession = map.get(user);
// copies all attributes from the old session to the new session (replicate the session)
Enumeration<String> enumeration = oldSession.getAttributeNames();
while (enumeration.hasMoreElements()) {
String name = enumeration.nextElement();
System.out.println("Chaning attribut " + name);
session.setAttribute(name, oldSession.getAttribute(name));
}
// invalidates the old user session (this keeps one session per user)
oldSession.invalidate();
map.put(user, session);
return true;
}
} else {
System.out.println("Putting "+user+" into session cache");
map.put(user, session);
return false;
}
return false;
}
}
It works very well with CoDI ViewScoped annotated Beans
If the first user gets invalidated every (AJAX) request causes a session expired exception which could easily be handled even with a restore session button
Only minor problem with the viewscoped beans is, that they get a new view id. By changing them back to the origin one everything works fine.
Things I need to add :
- Auto logout ( ajax polling, websockets,...)
- Some kind of registry where all viewscoped-id are stored
Missing in this comment :
Regards