@Override protected void allowableSessionsExceeded(List<SessionInformation> sessions, int allowableSessions, SessionRegistry registry) throws SessionAuthenticationException { SessionInformation leastRecentlyUsed = null; for (SessionInformation session : sessions) { if ((leastRecentlyUsed == null) || session.getLastRequest().before(leastRecentlyUsed.getLastRequest())) { leastRecentlyUsed = session; } } if(leastRecentlyUsed instanceof SessionInformationObject){ SessionInformationObject sessionObject=(SessionInformationObject)leastRecentlyUsed; sessionObject.setKickAway(true); } leastRecentlyUsed.expireNow(); }
@Test @WithMockUser("user123") public void testFindProfileActiveSessions() throws Exception { final UserEntity user = new UserEntity().setUsername("user123"); when(sessionRegistry.getAllPrincipals()).thenReturn(Collections.singletonList(user)); final SessionInformation sessionInformation = new SessionInformation("1", "1", new Date()); when(sessionRegistry.getAllSessions(user, true)) .thenReturn(Collections.singletonList(sessionInformation)); MockHttpServletRequestBuilder request = get("/api/profile/sessions") .contentType(MediaType.APPLICATION_JSON); MockHttpServletResponse response = mockMvc.perform(request) .andDo(document("user-profile-sessions-list")) .andReturn() .getResponse(); assertThat(response.getStatus()).isEqualTo(200); List<SessionInformation> expectedValue = Collections .singletonList(new SessionInformation("user123", "1", sessionInformation.getLastRequest())); assertThat(response.getContentAsByteArray()).isEqualTo(objectMapper.writeValueAsBytes(expectedValue)); verify(sessionRegistry).getAllPrincipals(); verify(sessionRegistry).getAllSessions(user, true); }
@Override @PreAuthorize("hasRole('ROLE_ADMIN')") public void kickUser(String ssoId){ final List<Object> allPrincipals = sessionRegistry.getAllPrincipals(); for (final Object principal : allPrincipals) { if (principal instanceof UserDetails && ((UserDetails) principal).getUsername().equals(ssoId)) { List<SessionInformation> activeUserSessions = sessionRegistry.getAllSessions(principal, false); if (!activeUserSessions.isEmpty()) { for(SessionInformation i : activeUserSessions){ i.expireNow(); } } } } }
public List<SessionInformation> getAllSessions(Object principal, boolean includeExpiredSessions) { final Set<String> sessionsUsedByPrincipal = principals.get(principal); if (sessionsUsedByPrincipal == null) { return Collections.emptyList(); } List<SessionInformation> list = new ArrayList<SessionInformation>(sessionsUsedByPrincipal.size()); for (String sessionId : sessionsUsedByPrincipal) { SessionInformation sessionInformation = getSessionInformation(sessionId); if (sessionInformation == null) { continue; } if (includeExpiredSessions || !sessionInformation.isExpired()) { list.add(sessionInformation); } } return list; }
@RequestMapping(value = "/expire.xhtml", method = RequestMethod.GET) public String expireSession(Model model, @RequestParam("session") String sessionid, RedirectAttributes redirectAttributes) { boolean expire = true; Object[] principals = cojSessionRegistryImpl.getAllPrincipals().toArray(); for (int i = 0; i < principals.length && expire; i++) { Object[] sessions = cojSessionRegistryImpl.getAllSessions(principals[i], true).toArray(); for (int j = 0; j < sessions.length && expire; j++) { SessionInformation s = (SessionInformation) sessions[j]; if (sessionid.equals(s.getSessionId())) { s.expireNow(); s.refreshLastRequest(); expire = false; cojSessionRegistryImpl.removeSessionInformation(sessionid); } } } redirectAttributes.addFlashAttribute("message", Notification.getSuccesfullDelete()); return "redirect:/admin/sessions.xhtml"; }
@ModelAttribute("activeUsers") public Map<Object, Date> listActiveUsers(Model model) { Map<Object, Date> lastActivityDates = new HashMap<Object, Date>(); for (Object principal : sessionRegistry.getAllPrincipals()) { for (SessionInformation session : sessionRegistry.getAllSessions(principal, false)) { if (lastActivityDates.get(principal) == null) { lastActivityDates.put(principal, session.getLastRequest()); } else { Date prevLastRequest = lastActivityDates.get(principal); if (session.getLastRequest().after(prevLastRequest)) { lastActivityDates.put(principal, session.getLastRequest()); } } } } return lastActivityDates; }
@RequestMapping(value = "/logoutUsers", method = RequestMethod.GET) @ResponseBody public String logoutUsers(HttpServletRequest req,HttpServletResponse res) { String sessionId = req.getRequestedSessionId(); System.out.print("sessionId;:"+sessionId); JSONObject resJson = new JSONObject(); LOGGER.log(Level.INFO,"EXPIRE SESSION::::::"+sessionId); logout(req); if(sessionId!=null) { //List<Object> principals = sessionRegistry.getAllPrincipals(); sessionRegistry.removeSessionInformation(sessionId); if(sessionRegistry.getSessionInformation(sessionId) != null){ SessionInformation session = sessionRegistry.getSessionInformation(sessionId); boolean isexpired = sessionRegistry.getSessionInformation(sessionId).isExpired(); resJson.put("isexpired",isexpired); if(!isexpired) { sessionRegistry.getSessionInformation(sessionId).expireNow(); } } resJson.put("Result",0); resJson.put("msg","Successfully logged out on LeafSchool"); } return resJson.toString(); }
@Override public List<SessionInformation> getAllSessions(Object principal, boolean includeExpiredSessions) { Collection<S> sessions = this.sessionRepository.findByIndexNameAndIndexValue( FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, name(principal)).values(); List<SessionInformation> infos = new ArrayList<>(); for (S session : sessions) { if (includeExpiredSessions || !Boolean.TRUE.equals(session .getAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR))) { infos.add(new SpringSessionBackedSessionInformation<>(session, this.sessionRepository)); } } return infos; }
@Test public void expireNow() { Session session = createSession(SESSION_ID, USER_NAME, NOW); when(this.sessionRepository.findById(SESSION_ID)).thenReturn(session); SessionInformation sessionInfo = this.sessionRegistry .getSessionInformation(SESSION_ID); assertThat(sessionInfo.isExpired()).isFalse(); sessionInfo.expireNow(); assertThat(sessionInfo.isExpired()).isTrue(); ArgumentCaptor<Session> captor = ArgumentCaptor.forClass(Session.class); verify(this.sessionRepository).save(captor.capture()); assertThat(captor.getValue().<Boolean>getAttribute( SpringSessionBackedSessionInformation.EXPIRED_ATTR)) .isEqualTo(Boolean.TRUE); }
@Override public List<Object> getAllPrincipals() { logger.debug("getAllPrincipals"); Map allSessions = sessionIds.getAllWithLoader(sessionIds.getKeys(), null); Set<Object> principals = new HashSet<Object>(); for (Object valObj : allSessions.values()) { SessionInformation info = (SessionInformation)valObj; principals.add(info.getPrincipal()); } List<Object> principalsList = new ArrayList<Object>(principals.size()); principalsList.addAll(principals); return principalsList; }
@Override public List<SessionInformation> getAllSessions(Object principal, boolean includeExpiredSessions) { logger.debug("Called with includeExpiredSession "+includeExpiredSessions); Set<String> sessionsUsedByPrincipal = getSessionIds(principal); List<SessionInformation> list = new ArrayList<SessionInformation>(); Iterator<String> iter = sessionsUsedByPrincipal.iterator(); while (iter.hasNext()) { String sessionId = iter.next(); SessionInformation sessionInformation = getSessionInformation(sessionId); if (includeExpiredSessions || !sessionInformation.isExpired()) { list.add(sessionInformation); } } logger.debug("List size "+list.size()); return list; }
@GetMapping("/sessions") public List<SessionInformation> findProfileActiveSessions(Authentication authentication) { if (authentication == null || authentication.getPrincipal() == null) return Collections.emptyList(); List<SessionInformation> sessions = new ArrayList<>(); for (Object principal : sessionRegistry.getAllPrincipals()) { UserEntity user = (UserEntity) principal; if (!user.getUsername().equals(authentication.getName())) continue; sessions.addAll(sessionRegistry.getAllSessions(user, true)); } return sessions.stream() .map(i -> new SessionInformation(authentication.getName(), i.getSessionId(), i.getLastRequest())) .collect(Collectors.toList()); }
@RequestMapping(value = "list", method = RequestMethod.GET) public ModelMap list() { ModelMap map = new ModelMap(); List<SessionInformation> sessions = new ArrayList<>(); for(Object principal : this.sessionRegistry.getAllPrincipals()) { sessions.addAll(this.sessionRegistry.getAllSessions(principal, true)); } map.put("timestamp", System.currentTimeMillis()); map.put("numberOfSessions", sessions.size()); map.put("sessions", sessions); return map; }
@DeleteMapping(value="/user/sessions/{sessionId}") public String removeSession(@PathVariable String sessionId, RedirectAttributes redirectAttrs) { SessionInformation sessionInformation = sessionRegistry.getSessionInformation(sessionId); if(sessionInformation != null) { sessionInformation.expireNow(); } redirectAttrs.addFlashAttribute("message", "Session was removed"); return "redirect:/user/sessions/"; }
@RequestMapping(value="/user/sessions/{sessionId}", method = RequestMethod.DELETE) public String removeSession(@PathVariable String sessionId, RedirectAttributes redirectAttrs) { SessionInformation sessionInformation = sessionRegistry.getSessionInformation(sessionId); if(sessionInformation != null) { sessionInformation.expireNow(); } redirectAttrs.addFlashAttribute("message", "Session was removed"); return "redirect:/user/sessions/"; }
@Override @PreAuthorize("isAnonymous() or isAuthenticated()") public boolean isUserOnline(String ssoId){ final List<Object> allPrincipals = sessionRegistry.getAllPrincipals(); for (final Object principal : allPrincipals) { if (principal instanceof UserDetails && ((UserDetails) principal).getUsername().equals(ssoId)) { List<SessionInformation> activeUserSessions = sessionRegistry.getAllSessions(principal, false); if (!activeUserSessions.isEmpty()) { return true; } } } return false; }
public void refreshLastRequest(String sessionId) { Assert.hasText(sessionId, "SessionId required as per interface contract"); SessionInformation info = getSessionInformation(sessionId); if (info != null) { info.refreshLastRequest(); } }
public void removeSessionInformation(String sessionId) { Assert.hasText(sessionId, "SessionId required as per interface contract"); SessionInformation info = getSessionInformation(sessionId); if (info == null) { return; } if (logger.isTraceEnabled()) { logger.debug("Removing session " + sessionId + " from set of registered sessions"); } sessionIds.remove(sessionId); Set<String> sessionsUsedByPrincipal = principals.get(info.getPrincipal()); if (sessionsUsedByPrincipal == null) { return; } if (logger.isDebugEnabled()) { logger.debug("Removing session " + sessionId + " from principal's set of registered sessions"); } sessionsUsedByPrincipal.remove(sessionId); if (sessionsUsedByPrincipal.isEmpty()) { // No need to keep object in principals Map anymore if (logger.isDebugEnabled()) { logger.debug("Removing principal " + info.getPrincipal() + " from registry"); } principals.remove(info.getPrincipal()); } if (logger.isTraceEnabled()) { logger.trace("Sessions used by '" + info.getPrincipal() + "' : " + sessionsUsedByPrincipal); } }
protected String determineExpiredUrl(HttpServletRequest request, SessionInformation info) { HttpSession session=request.getSession(); if(info instanceof SessionInformationObject){ SessionInformationObject sessionObject=(SessionInformationObject)info; if(sessionObject.isKickAway()){ session.setAttribute(SessionStateConstants.SESSION_STATE, SessionStateConstants.KICKAWAY); return sessionKickAwayUrl; } } session.setAttribute(SessionStateConstants.SESSION_STATE, SessionStateConstants.EXPIRED); return super.determineExpiredUrl(request, info); }
public NoneLoginException(String msg) { super(msg); HttpServletRequest request=ContextHolder.getRequest(); if(request==null){ return; } HttpSession session = request.getSession(false); if (session == null) { return; } String state=(String)session.getAttribute(SessionStateConstants.SESSION_STATE); if(state==null){ SessionRegistry sessionRegistry=ContextHolder.getBean("bdf2.sessionRegistry"); SessionInformation info = sessionRegistry.getSessionInformation(session.getId()); if(info==null){ return; } if(info instanceof SessionInformationObject){ SessionInformationObject obj=(SessionInformationObject)info; if(obj.isKickAway()){ session.setAttribute(SessionStateConstants.SESSION_STATE, SessionStateConstants.KICKAWAY); this.sessionKickAway=true; } }else if(info.isExpired()){ session.setAttribute(SessionStateConstants.SESSION_STATE, SessionStateConstants.EXPIRED); } }else if(state.equals(SessionStateConstants.KICKAWAY)){ this.sessionKickAway=true; } }
@Override public List<SessionInformation> getAllSessions(Object principal, boolean includeExpiredSessions) { return sessionRepository .findByIndexNameAndIndexValue(PRINCIPAL_NAME_INDEX_NAME, name(principal)) .values() .stream() .filter(session -> includeExpiredSessions || !session.isExpired()) .map(session -> new SpringSessionBackedSessionInformation(session, sessionRepository)) .collect(toList()); }
@Override public SessionInformation getSessionInformation(String sessionId) { ExpiringSession session = sessionRepository.getSession(sessionId); if (session != null) { return new SpringSessionBackedSessionInformation(session, sessionRepository); } return null; }
/** * 활성화돤 사용자를 찾는다 * */ @RequestMapping(value = "/uat/uia/listActiveUsers.do") @Secured("ROLE_ADMIN") public String listActiveUsers(ModelMap model) { Map<Object, Date> lastActivityDates = new HashMap<Object, Date>(); for(Object principal: sessionRegistry.getAllPrincipals()) { for(SessionInformation session: sessionRegistry.getAllSessions(principal, true)) { lastActivityDates.put(principal, session.getLastRequest()); } } model.addAttribute("activeUsers", lastActivityDates); return "aramframework/com/uat/uia/ListActiveUsers"; }
@RequestMapping(value = "/tables/sessions.xhtml", method = RequestMethod.GET) public String tablesSessions(Model model) { Object[] principals = cojSessionRegistryImpl.getAllPrincipals().toArray(); List<Session> allsessions = new LinkedList<Session>(); for (int i = 0; i < principals.length; i++) { Object[] sessions = (Object[]) cojSessionRegistryImpl.getAllSessions(principals[i], true).toArray(); for (int j = 0; j < sessions.length; j++) { SessionInformation s = (SessionInformation) sessions[j]; allsessions.add(new Session(((User) s.getPrincipal()).getUsername(), s.getSessionId(), s.getLastRequest(), s.isExpired())); } } model.addAttribute("sessions", allsessions); return "/admin/tables/sessions"; }
@RequestMapping(value = "/loginUsers", method = RequestMethod.GET) @ResponseBody public String loginUsers(HttpServletRequest req,HttpServletResponse res) { String sessionId = req.getRequestedSessionId(); System.out.print("sessionId;:"+sessionId); JSONObject resJson = new JSONObject(); if(sessionId!=null) { //List<Object> principals = sessionRegistry.getAllPrincipals(); SessionInformation sessioninfo = sessionRegistry.getSessionInformation(sessionId); if(sessioninfo!= null) { String userName =((User) sessioninfo.getPrincipal()).getUsername(); DriverManagerDataSource datasource = new JdbcUtil().getAccountsDataSource(); // Inject the datasource into the dao JdbcUserDAO userDAO = new JdbcUserDAO(); userDAO.setDataSource(datasource); LeafUser user = userDAO.loadUserByUsername(userName); resJson = new JSONObject(); resJson.put("lid", user.getLid()); resJson.put("username", user.getUsername()); resJson.put("enabled", user.getEnabled()); resJson.put("email", user.getEmail()); resJson.put("dob", user.getDob()); } } return resJson.toString(); }
@Override public SessionInformation getSessionInformation(String sessionId) { S session = this.sessionRepository.findById(sessionId); if (session != null) { return new SpringSessionBackedSessionInformation<>(session, this.sessionRepository); } return null; }
@Test public void sessionInformationForExistingSession() { Session session = createSession(SESSION_ID, USER_NAME, NOW); when(this.sessionRepository.findById(SESSION_ID)).thenReturn(session); SessionInformation sessionInfo = this.sessionRegistry .getSessionInformation(SESSION_ID); assertThat(sessionInfo.getSessionId()).isEqualTo(SESSION_ID); assertThat(sessionInfo.getLastRequest().toInstant()).isEqualTo(NOW); assertThat(sessionInfo.getPrincipal()).isEqualTo(USER_NAME); assertThat(sessionInfo.isExpired()).isFalse(); }
@Test public void sessionInformationForExpiredSession() { Session session = createSession(SESSION_ID, USER_NAME, NOW); session.setAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR, Boolean.TRUE); when(this.sessionRepository.findById(SESSION_ID)).thenReturn(session); SessionInformation sessionInfo = this.sessionRegistry .getSessionInformation(SESSION_ID); assertThat(sessionInfo.getSessionId()).isEqualTo(SESSION_ID); assertThat(sessionInfo.getLastRequest().toInstant()).isEqualTo(NOW); assertThat(sessionInfo.getPrincipal()).isEqualTo(USER_NAME); assertThat(sessionInfo.isExpired()).isTrue(); }
@Test public void getAllSessions() { setUpSessions(); List<SessionInformation> allSessionInfos = this.sessionRegistry .getAllSessions(PRINCIPAL, true); assertThat(allSessionInfos).extracting("sessionId").containsExactly(SESSION_ID, SESSION_ID2); }
@Test public void getNonExpiredSessions() { setUpSessions(); List<SessionInformation> nonExpiredSessionInfos = this.sessionRegistry .getAllSessions(PRINCIPAL, false); assertThat(nonExpiredSessionInfos).extracting("sessionId") .containsExactly(SESSION_ID2); }
/** * This method has been copied from ConcurrentSessionControlStrategy and modified to * better ensure that more that the allowed number of sessions are never valid * at the same time. * * @see ConcurentSessionControlStrategy.allowableSessionsExceeded */ protected void allowableSessionsExceeded(List<SessionInformation> sessions, int allowableSessions, SessionRegistry registry) throws SessionAuthenticationException { if (exceptionIfMaximumExceeded || (sessions == null)) { throw new SessionAuthenticationException(messages.getMessage( "ConcurrentSessionControlStrategy.exceededAllowed", new Object[] {new Integer(allowableSessions)}, "Maximum sessions of {0} for this principal exceeded")); } //BEGIN CUSTOMIZATIONS log.debug("allowableSessionExceeded. allowed: " + allowableSessions + " Current: " + sessions.size()); //sort the session by recency, increasing Collections.sort(sessions, comparator); //note - sessions does not include the new session being authenticated int sessionsToExpire = sessions.size() - allowableSessions + 1; //remove the first sessionToExpire sessions from the sorted list for (int i = 0; i < sessionsToExpire; i++) { sessions.get(i).expireNow(); } }
private Set<String> getSessionIds(Object principal) { logger.debug("sessionIds.getKeys(): " + sessionIds.getKeys()); Map<Object, SessionInformation> collection = sessionIds.getAllWithLoader(sessionIds.getKeys(), null); Set<String> ids = new HashSet<String>(); for (SessionInformation info : collection.values()) { if (info != null && info.getPrincipal().equals(principal)) { ids.add(info.getSessionId()); } } return ids; }
@Override public SessionInformation getSessionInformation(String sessionId) { Assert.hasText(sessionId, "SessionId required as per interface contract"); Element element = sessionIds.get(sessionId); if(element == null) { logger.debug("Session was null"); return null; } else{ SessionInformation session = (SessionInformation) element.getValue(); logger.debug("getSessionInformation: Returning session: "+session.getSessionId() + " principal "+session.getPrincipal()+ " session expired "+session.isExpired()); return session; } }
@Override public void refreshLastRequest(String sessionId) { SessionInformation info = getSessionInformation(sessionId); if (info != null) { info.refreshLastRequest(); } }