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

The following examples show how to use org.springframework.security.core.session.SessionInformation. These examples are extracted from open source projects. 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 Project: base-admin   Source File: MyInvalidSessionStrategy.java    License: 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 2
Source Project: inception   Source File: CurationServiceImpl.java    License: 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 3
@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 4
@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 5
@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 6
@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 7
Source Project: cola   Source File: SessionController.java    License: 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 8
Source Project: base-admin   Source File: LogoutHandlerConfig.java    License: MIT License 5 votes vote down vote up
@Override
public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
    //剔除退出用户
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    if (principal !=null){
        List<SessionInformation> allSessions = sessionRegistry.getAllSessions(principal, false);
        if (allSessions != null) {
            for (SessionInformation sessionInformation : allSessions) {
                sessionInformation.expireNow();
                sessionRegistry.removeSessionInformation(sessionInformation.getSessionId());
            }
        }
    }
}
 
Example 9
Source Project: blog-sample   Source File: LoginController.java    License: 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 + "个";
}
 
Example 10
Source Project: blog-sample   Source File: LoginController.java    License: 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 + "个";
}
 
Example 11
Source Project: blog-sample   Source File: ApiController.java    License: 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 12
Source Project: blog-sample   Source File: ApiController.java    License: 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 13
Source Project: inception   Source File: RecommendationServiceImpl.java    License: 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 14
@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 15
@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 16
@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 17
@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 18
@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 19
@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
@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
@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
@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 23
@Override
public SessionInformation getSessionInformation(String sessionId) {
    ExpiringSession session = sessionRepository.getSession(sessionId);
    if (session != null) {
        return new SpringSessionBackedSessionInformation(session, sessionRepository);
    }
    return null;
}
 
Example 24
@Override
public void expireActiveSessions( UserCredentials credentials )
{
    List<SessionInformation> sessions = sessionRegistry.getAllSessions( credentials, false );

    sessions.forEach( SessionInformation::expireNow );
}
 
Example 25
@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 26
@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 27
@Override
public SessionInformation getSessionInformation(String sessionId) {
	S session = this.sessionRepository.findById(sessionId);
	if (session != null) {
		return new SpringSessionBackedSessionInformation<>(session, this.sessionRepository);
	}
	return null;
}
 
Example 28
@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 29
@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 30
@Test
void getAllSessionsForAuthenticatedPrincipal() {
	setUpSessions();
	List<SessionInformation> allSessionInfos = this.sessionRegistry
			.getAllSessions((AuthenticatedPrincipal) () -> USER_NAME, true);
	assertThat(allSessionInfos).extracting("sessionId").containsExactly(SESSION_ID, SESSION_ID2);
}