org.springframework.security.core.session.SessionInformation Java Examples

The following examples show how to use org.springframework.security.core.session.SessionInformation. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SpringSessionBackedSessionRegistryTest.java    From spring-session with Apache License 2.0 6 votes vote down vote up
@Test
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);
}
 
Example #2
Source File: RedisSessionRegistry.java    From albedo with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public List<SessionInformation> getAllSessions(Object principal,
											   boolean includeExpiredSessions) {
	Set<String> sessionsUsedByPrincipal = getPrincipals(principal);

	if (sessionsUsedByPrincipal == null) {
		return Collections.emptyList();
	}

	List<SessionInformation> list = new ArrayList<>(
		sessionsUsedByPrincipal.size());

	for (String sessionId : sessionsUsedByPrincipal) {
		SessionInformation sessionInformation = getSessionInformation(sessionId);

		if (sessionInformation == null) {
			continue;
		}

		if (includeExpiredSessions || !sessionInformation.isExpired()) {
			list.add(sessionInformation);
		}
	}

	return list;
}
 
Example #3
Source File: UserOnlineResource.java    From albedo with GNU Lesser General Public License v3.0 6 votes vote down vote up
@PreAuthorize("@pms.hasPermission('sys_userOnline_del')")
@Log(value = "在线用户删除")
@DeleteMapping
public Result remove(@RequestBody Set<String> ids, HttpServletRequest request) {
	for (String id : ids) {
		UserOnline online = userOnlineService.getById(id);
		if (online == null) {
			return Result.buildFail("用户已下线");
		}
		try {
			SessionInformation sessionInformation = sessionRegistry.getSessionInformation(online.getSessionId());
			if (sessionInformation != null) {
				if (sessionInformation.getSessionId().equals(request.getSession(false).getId())) {
					return Result.buildFail("当前登陆用户无法删除");
				}
				sessionInformation.expireNow();
				redisTemplate.boundHashOps(RedisSessionRegistry.SESSIONIDS).put(online.getSessionId(), sessionInformation);
			}
		} catch (Exception e) {
		}
		sessionRegistry.removeSessionInformation(online.getSessionId());
		userOnlineService.removeById(online);
	}
	return Result.buildOk("操作成功");
}
 
Example #4
Source File: UserOnlineResource.java    From albedo with GNU Lesser General Public License v3.0 6 votes vote down vote up
@PreAuthorize("@pms.hasPermission('sys_userOnline_logout')")
@Log(value = "在线用户强退")
@PutMapping("/batch-force-logout")
public Result batchForceLogout(@RequestBody Set<String> ids, HttpServletRequest request) {
	for (String id : ids) {
		UserOnline online = userOnlineService.getById(id);
		if (online == null) {
			return Result.buildFail("用户已下线");
		}
		SessionInformation sessionInformation = sessionRegistry.getSessionInformation(online.getSessionId());
		if (sessionInformation != null) {
			if (sessionInformation.getSessionId().equals(request.getSession(false).getId())) {
				return Result.buildFail("当前登陆用户无法强退");
			}
			sessionInformation.expireNow();
			redisTemplate.boundHashOps(RedisSessionRegistry.SESSIONIDS).put(online.getSessionId(), sessionInformation);
		}
		online.setStatus(OnlineStatus.off_line);
		userOnlineService.updateById(online);
	}
	return Result.buildOk("操作成功");
}
 
Example #5
Source File: CurationServiceImpl.java    From inception with Apache License 2.0 6 votes vote down vote up
@EventListener
@Transactional
public void onSessionDestroyed(SessionDestroyedEvent event)
{
    SessionInformation info = sessionRegistry.getSessionInformation(event.getId());
    
    if (info == null) {
        return;
    }
    
    User user = userRegistry.get((String) info.getPrincipal());
    if (user == null) {
        // This happens e.g. when a session for "anonymousUser" is destroyed or if (for some
        // reason), the user owning the session no longer exists in the system.
        return;
    }
    
    storeCurationSettings(user);
    clearState(user);
}
 
Example #6
Source File: MyInvalidSessionStrategy.java    From base-admin with MIT License 6 votes vote down vote up
@Override
public void onInvalidSessionDetected(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
    HttpSession session = httpServletRequest.getSession();
    String sessionId = httpServletRequest.getRequestedSessionId();
    if(!session.isNew()){
        //内部重定向
        httpServletResponse.sendRedirect("/loginPage");
    }else{
        //直接输出js脚本跳转
        httpServletResponse.setContentType("text/html;charset=UTF-8");
        httpServletResponse.getWriter().print("<script type='text/javascript'>window.location.href = \"/loginPage\"</script>");
    }
    SessionInformation sessionInformation = sessionRegistry.getSessionInformation(sessionId);
    if(sessionInformation != null){
        User user = (User) sessionInformation.getPrincipal();
        sessionRegistry.removeSessionInformation(sessionId);
        log.info("剔除过期用户:"+user.getUsername());
    }
    log.info("session失效处理 " + sessionRegistry.getAllPrincipals().size()+"");
    httpServletResponse.flushBuffer();
}
 
Example #7
Source File: SpringSessionBackedSessionRegistryTest.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test
void getAllSessionsForAuthenticatedPrincipal() {
	setUpSessions();
	List<SessionInformation> allSessionInfos = this.sessionRegistry
			.getAllSessions((AuthenticatedPrincipal) () -> USER_NAME, true);
	assertThat(allSessionInfos).extracting("sessionId").containsExactly(SESSION_ID, SESSION_ID2);
}
 
Example #8
Source File: SpringSessionBackedSessionRegistryTest.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test
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().truncatedTo(ChronoUnit.MILLIS))
			.isEqualTo(NOW.truncatedTo(ChronoUnit.MILLIS));
	assertThat(sessionInfo.getPrincipal()).isEqualTo(USER_NAME);
	assertThat(sessionInfo.isExpired()).isTrue();
}
 
Example #9
Source File: SpringSessionBackedSessionRegistryTest.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test
void getAllSessionsForPrincipal() {
	setUpSessions();
	List<SessionInformation> allSessionInfos = this.sessionRegistry.getAllSessions(new TestPrincipal(USER_NAME),
			true);
	assertThat(allSessionInfos).extracting("sessionId").containsExactly(SESSION_ID, SESSION_ID2);
}
 
Example #10
Source File: SpringSessionBackedSessionRegistryTest.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test
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().truncatedTo(ChronoUnit.MILLIS))
			.isEqualTo(NOW.truncatedTo(ChronoUnit.MILLIS));
	assertThat(sessionInfo.getPrincipal()).isEqualTo(USER_NAME);
	assertThat(sessionInfo.isExpired()).isFalse();
}
 
Example #11
Source File: SpringSessionBackedSessionRegistryTest.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test
void getNonExpiredSessions() {
	setUpSessions();

	List<SessionInformation> nonExpiredSessionInfos = this.sessionRegistry.getAllSessions(PRINCIPAL, false);

	assertThat(nonExpiredSessionInfos).extracting("sessionId").containsExactly(SESSION_ID2);
}
 
Example #12
Source File: UserSessionController.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@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/";
}
 
Example #13
Source File: SpringSessionBackedSessionRegistry.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Override
public SessionInformation getSessionInformation(String sessionId) {
	S session = this.sessionRepository.findById(sessionId);
	if (session != null) {
		return new SpringSessionBackedSessionInformation<>(session, this.sessionRepository);
	}
	return null;
}
 
Example #14
Source File: SpringSessionBackedSessionRegistry.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Override
public List<SessionInformation> getAllSessions(Object principal, boolean includeExpiredSessions) {
	Collection<S> sessions = this.sessionRepository.findByPrincipalName(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;
}
 
Example #15
Source File: DefaultCurrentUserService.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
@Transactional( readOnly = true )
public void expireUserSessions()
{
    UserDetails userDetails = getCurrentUserDetails();

    if ( userDetails != null )
    {
        List<SessionInformation> sessions = sessionRegistry.getAllSessions( userDetails, false );
        sessions.forEach( SessionInformation::expireNow );
    }
}
 
Example #16
Source File: DefaultUserService.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void expireActiveSessions( UserCredentials credentials )
{
    List<SessionInformation> sessions = sessionRegistry.getAllSessions( credentials, false );

    sessions.forEach( SessionInformation::expireNow );
}
 
Example #17
Source File: SpringSessionBackedSessionRegistry.java    From spring-session-concurrent-session-control with Apache License 2.0 5 votes vote down vote up
@Override
public SessionInformation getSessionInformation(String sessionId) {
    ExpiringSession session = sessionRepository.getSession(sessionId);
    if (session != null) {
        return new SpringSessionBackedSessionInformation(session, sessionRepository);
    }
    return null;
}
 
Example #18
Source File: SpringSessionBackedSessionRegistry.java    From spring-session-concurrent-session-control with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #19
Source File: UserSessionController.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@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/";
}
 
Example #20
Source File: UserSessionController.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@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/";
}
 
Example #21
Source File: UserSessionController.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@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/";
}
 
Example #22
Source File: UserSessionController.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@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/";
}
 
Example #23
Source File: SessionController.java    From cola with MIT License 5 votes vote down vote up
@PostMapping("/revoke")
public ResponseEntity<String> revoke(Principal principal) {
	sessionRegistry.getAllPrincipals();
	List<SessionInformation> sessionInformations = sessionRegistry
			.getAllSessions(principal, false);
	for (SessionInformation sessionInformation : sessionInformations) {
		sessionInformation.expireNow();

		sessionRegistry.removeSessionInformation(sessionInformation
				.getSessionId());

	}
	return ResponseEntity.ok().build();
}
 
Example #24
Source File: UserSessionController.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@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/";
}
 
Example #25
Source File: SysUserOnlineListener.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Async
@Order
@EventListener(SysUserOnlineRefreshLastRequestEvent.class)
public void saveSysUserOnlineRefreshLastRequestEvent(SysUserOnlineRefreshLastRequestEvent event) {
	SessionInformation sessionInformation = (SessionInformation) event.getSource();
	UserOnline userOnline = userOnlineService.getById(sessionInformation.getSessionId());
	if (userOnline != null) {
		userOnline.setLastAccessTime(sessionInformation.getLastRequest());
		userOnlineService.updateById(userOnline);
	} else {
		log.debug("sessionInformation sessionId " + sessionInformation.getSessionId() + ", onlineUser is null");
	}

}
 
Example #26
Source File: RedisSessionRegistry.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void refreshLastRequest(String sessionId) {
	Assert.hasText(sessionId, "SessionId required as per interface contract");

	SessionInformation info = getSessionInformation(sessionId);
	if (info != null) {
		long lastRequestTime = info.getLastRequest().getTime();
		info.refreshLastRequest();
		int dbSyncSessionPeriodTime = applicationProperties.getDbSyncSessionPeriod() * 60 * 1000;
		if (dbSyncSessionPeriodTime < info.getLastRequest().getTime() - lastRequestTime) {
			SpringContextHolder.publishEvent(new SysUserOnlineRefreshLastRequestEvent(info));
		}
	}

}
 
Example #27
Source File: RecommendationServiceImpl.java    From inception with Apache License 2.0 5 votes vote down vote up
@EventListener
@Order(Ordered.HIGHEST_PRECEDENCE)
public void onSessionDestroyed(SessionDestroyedEvent event)
{
    SessionInformation info = sessionRegistry.getSessionInformation(event.getId());
    // Could be an anonymous session without information.
    if (info != null) {
        String username = (String) info.getPrincipal();
        clearState(username);
        schedulingService.stopAllTasksForUser(username);
    }
}
 
Example #28
Source File: ApiController.java    From blog-sample with Apache License 2.0 5 votes vote down vote up
/**
 * 踢出指定用户
 * todo: 还需要清理持久化表,不然无法踢出自动登陆用户,我就不做了
 */
@PostMapping("/kick")
public ResultMap removeUserSessionByUsername(String username) {
    int count = 0;

    // 获取session中所有的用户信息
    List<Object> users = sessionRegistry.getAllPrincipals();
    for (Object principal : users) {
        if (principal instanceof User) {
            String principalName = ((User) principal).getUsername();
            if (principalName.equals(username)) {
                /*
                 * 获取指定用户所有的 session 信息
                 * 参数二:是否包含过期的Session
                 */
                List<SessionInformation> sessionsInfo = sessionRegistry.getAllSessions(principal, false);
                if (null != sessionsInfo && sessionsInfo.size() > 0) {
                    for (SessionInformation sessionInformation : sessionsInfo) {
                        sessionInformation.expireNow();
                        count++;
                    }
                }
            }
        }
    }

    return new ResultMap(getClass() + ":removeUserSessionByUsername()", "操作成功,清理session共" + count + "个");
}
 
Example #29
Source File: ApiController.java    From blog-sample with Apache License 2.0 5 votes vote down vote up
/**
 * 踢出指定用户
 * todo: 还需要清理持久化表,不然无法踢出自动登陆用户,我就不做了
 */
@PostMapping("/kick")
public ResultMap removeUserSessionByUsername(String username) {
    int count = 0;

    // 获取session中所有的用户信息
    List<Object> users = sessionRegistry.getAllPrincipals();
    for (Object principal : users) {
        if (principal instanceof User) {
            String principalName = ((User) principal).getUsername();
            if (principalName.equals(username)) {
                /*
                 * 获取指定用户所有的 session 信息
                 * 参数二:是否包含过期的Session
                 */
                List<SessionInformation> sessionsInfo = sessionRegistry.getAllSessions(principal, false);
                if (null != sessionsInfo && sessionsInfo.size() > 0) {
                    for (SessionInformation sessionInformation : sessionsInfo) {
                        sessionInformation.expireNow();
                        count++;
                    }
                }
            }
        }
    }

    return new ResultMap(getClass() + ":removeUserSessionByUsername()", "操作成功,清理session共" + count + "个");
}
 
Example #30
Source File: LoginController.java    From blog-sample with Apache License 2.0 5 votes vote down vote up
@GetMapping("/kick")
@ResponseBody
public String removeUserSessionByUsername(@RequestParam String username) {
    int count = 0;

    // 获取session中所有的用户信息
    List<Object> users = sessionRegistry.getAllPrincipals();
    for (Object principal : users) {
        if (principal instanceof User) {
            String principalName = ((User) principal).getUsername();
            if (principalName.equals(username)) {
                /*
                 * 获取指定用户所有的 session 信息
                 * 参数二:是否包含过期的Session
                 */
                List<SessionInformation> sessionsInfo = sessionRegistry.getAllSessions(principal, false);
                if (null != sessionsInfo && sessionsInfo.size() > 0) {
                    for (SessionInformation sessionInformation : sessionsInfo) {
                        sessionInformation.expireNow();
                        count++;
                    }
                }
            }
        }
    }
    return "操作成功,清理session共" + count + "个";
}