示例#1
0
  private Authentication fresh(Authentication authentication, ServletRequest req) {
    HttpServletRequest request = (HttpServletRequest) req;

    HttpSession session = request.getSession(false);

    if (session != null) {
      SessionRegistry sessionRegistry =
          (SessionRegistry) SpringBeanUtil.getBeanByName("sessionRegistry");
      SessionInformation info = sessionRegistry.getSessionInformation(session.getId());

      if (info != null) {
        // Non-expired - update last request date/time
        Object principal = info.getPrincipal();
        if (principal instanceof org.springframework.security.core.userdetails.User) {
          org.springframework.security.core.userdetails.User userRefresh =
              (org.springframework.security.core.userdetails.User) principal;
          ServletContext sc = session.getServletContext();
          HashSet<String> unrgas = springSecurityService.getUsersNeedRefreshGrantedAuthorities();
          if (unrgas.size() > 0) {
            HashSet<String> loginedUsernames = new HashSet<String>();

            List<Object> loggedUsers = sessionRegistry.getAllPrincipals();
            for (Object lUser : loggedUsers) {
              if (lUser instanceof org.springframework.security.core.userdetails.User) {
                org.springframework.security.core.userdetails.User u =
                    (org.springframework.security.core.userdetails.User) lUser;
                loginedUsernames.add(u.getUsername());
              }
            }
            // 清除已经下线的但需要刷新的username
            for (Iterator iterator = unrgas.iterator(); iterator.hasNext(); ) {
              String unrgs = (String) iterator.next();
              if (!loginedUsernames.contains(unrgs)) {
                iterator.remove();
              }
            }
            if (unrgas.contains(userRefresh.getUsername())) {
              // 如果需要刷新权限的列表中有当前的用户,刷新登录用户权限
              // FIXME:与springSecurityServiceImpl中的功能,相重复,需重构此方法和springSecurityServiceImpl
              MyJdbcUserDetailsManager mdudm =
                  (MyJdbcUserDetailsManager)
                      SpringBeanUtil.getBeanByType(MyJdbcUserDetailsManager.class);
              SecurityContextHolder.getContext()
                  .setAuthentication(
                      new UsernamePasswordAuthenticationToken(
                          userRefresh,
                          userRefresh.getPassword(),
                          mdudm.getUserAuthorities(userRefresh.getUsername())));
              session.setAttribute(
                  HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                  SecurityContextHolder.getContext());
              unrgas.remove(userRefresh.getUsername());
              return SecurityContextHolder.getContext().getAuthentication();
            }
          }
        }
      }
    }
    return authentication;
  }
  @Override
  public void contextDestroyed(ServletContextEvent sce) {
    // 在容器销毁时把未正常结束遗留的登录记录信息强制设置登出时间
    logger.info("ServletContext destroy force setup session user logout time...");

    UserLogonLogService userLogonLogService =
        SpringContextHolder.getBean(UserLogonLogService.class);
    GroupPropertyFilter groupPropertyFilter = new GroupPropertyFilter();
    groupPropertyFilter.and(new PropertyFilter(MatchType.NU, "logoutTime", Boolean.TRUE));
    List<UserLogonLog> userLogonLogs = userLogonLogService.findByFilters(groupPropertyFilter);
    if (!CollectionUtils.isEmpty(userLogonLogs)) {

      Set<String> sessionIdSet = new HashSet<String>();
      SessionRegistry sessionRegistry = SpringContextHolder.getBean(SessionRegistry.class);
      List<Object> principals = sessionRegistry.getAllPrincipals();
      for (Object principal : principals) {
        List<SessionInformation> sessionInformations =
            sessionRegistry.getAllSessions(principal, true);
        for (SessionInformation sessionInformation : sessionInformations) {
          sessionIdSet.add(sessionInformation.getSessionId());
        }
      }
      Date now = new Date();
      Date yesterday = new DateTime().minusDays(1).toDate();
      for (UserLogonLog userLogonLog : userLogonLogs) {
        if (userLogonLog.getLogonTime().before(yesterday)) {
          Date logoutTime = new DateTime(userLogonLog.getLogonTime()).plusHours(1).toDate();
          userLogonLog.setLogoutTime(logoutTime);
        } else {
          if (sessionIdSet.contains(userLogonLog.getHttpSessionId())) {
            userLogonLog.setLogoutTime(now);
          } else {
            continue;
          }
        }
        logger.debug(" - Setup logout time for session ID: {}", userLogonLog.getHttpSessionId());
        userLogonLog.setLogonTimeLength(
            userLogonLog.getLogoutTime().getTime() - userLogonLog.getLogonTime().getTime());
        userLogonLogService.save(userLogonLog);
      }
    }
  }
示例#3
0
  public static User getUser(String sessionID) {
    User user = null;
    if (sessionRegistry == null) {
      sessionRegistry = SpringContextUtils.getBean("sessionRegistry");
    }
    if (sessionRegistry == null) {
      log.debug("没有从spring中获取到sessionRegistry");
      return null;
    }
    SessionInformation info = sessionRegistry.getSessionInformation(sessionID);
    if (info == null) {
      log.debug("没有获取到会话ID为:" + sessionID + " 的在线用户");
      return null;
    }
    user = (User) info.getPrincipal();
    log.debug("获取到会话ID为:" + sessionID + " 的在线用户");

    return user;
  }
  /**
   * In addition to the steps from the superclass, the sessionRegistry will be updated with the new
   * session information.
   */
  public void onAuthentication(
      Authentication authentication, HttpServletRequest request, HttpServletResponse response) {

    final List<SessionInformation> sessions =
        sessionRegistry.getAllSessions(authentication.getPrincipal(), false);

    int sessionCount = sessions.size();
    int allowedSessions = getMaximumSessionsForThisUser(authentication);

    if (sessionCount < allowedSessions) {
      // They haven't got too many login sessions running at present
      return;
    }

    if (allowedSessions == -1) {
      // We permit unlimited logins
      return;
    }

    if (sessionCount == allowedSessions) {
      HttpSession session = request.getSession(false);

      if (session != null) {
        // Only permit it though if this request is associated with one of the
        // already registered sessions
        for (SessionInformation si : sessions) {
          if (si.getSessionId().equals(session.getId())) {
            return;
          }
        }
      }
      // If the session is null, a new one will be created by the parent class,
      // exceeding the allowed number
    }

    allowableSessionsExceeded(request, sessions, allowedSessions, sessionRegistry);
  }
示例#5
0
 public static List<User> getUser(Org org, Role role) {
   if (sessionRegistry == null) {
     sessionRegistry = SpringContextUtils.getBean("sessionRegistry");
   }
   if (sessionRegistry == null) {
     log.info("没有从spring中获取到sessionRegistry");
     return null;
   }
   List<Object> users = sessionRegistry.getAllPrincipals();
   List<User> result = new ArrayList<User>();
   log.info("获取在线用户,org:" + org + ",role:" + role);
   if (org == null && role == null) {
     // 返回所有在线用户
     for (Object obj : users) {
       User user = (User) obj;
       log.info(
           "获取到会话ID为:"
               + sessionRegistry.getAllSessions(obj, false).get(0).getSessionId()
               + " 的在线用户");
       result.add(user);
     }
   }
   // 取交集
   if (org != null && role != null) {
     // 返回特定组织架构及其所有子机构 且 属于特定角色的在线用户
     int roleId = role.getId();
     List<Integer> orgIds = OrgService.getChildIds(org);
     orgIds.add(org.getId());
     log.info("特定组织架构及其所有子机构:" + orgIds);
     for (Object obj : users) {
       User user = (User) obj;
       log.info(
           "获取到会话ID为:"
               + sessionRegistry.getAllSessions(obj, false).get(0).getSessionId()
               + " 的在线用户");
       if (orgIds.contains(user.getOrg().getId())) {
         for (Role r : user.getRoles()) {
           if (r.getId() == roleId) {
             result.add(user);
             break;
           }
         }
       }
     }
     return result;
   }
   if (org != null) {
     // 返回特定组织架构及其所有子机构的在线用户
     List<Integer> ids = OrgService.getChildIds(org);
     ids.add(org.getId());
     log.info("特定组织架构及其所有子机构:" + ids);
     for (Object obj : users) {
       User user = (User) obj;
       log.info(
           "获取到会话ID为:"
               + sessionRegistry.getAllSessions(obj, false).get(0).getSessionId()
               + " 的在线用户");
       if (ids.contains(user.getOrg().getId())) {
         result.add(user);
       }
     }
   }
   if (role != null) {
     // 返回属于特定角色的在线用户
     int id = role.getId();
     for (Object obj : users) {
       User user = (User) obj;
       log.info(
           "获取到会话ID为:"
               + sessionRegistry.getAllSessions(obj, false).get(0).getSessionId()
               + " 的在线用户");
       for (Role r : user.getRoles()) {
         if (r.getId() == id) {
           result.add(user);
           break;
         }
       }
     }
   }
   return result;
 }