public boolean onRegister(Authentication auth, String sessionId, SessionRegistry registry)
      throws SessionException {
    List<Sessioninfo> sessions = registry.getSessioninfos(auth.getName(), false);
    int sessionCount = 0;
    if (sessions != null) sessionCount = sessions.size();

    if (sessionCount <= 0) return allocate(auth, sessionId);

    boolean allocated = false;
    int allowableSessions = getMaxSessions(auth);
    if (sessionCount < allowableSessions || allowableSessions == -1) {
      allocated = allocate(auth, sessionId);
    }

    // Determine least recently used session, and mark it for invalidation
    if (!allocated) {
      Sessioninfo leastRecentlyUsed = null;
      for (int i = 0; i < sessions.size(); i++) {
        if ((leastRecentlyUsed == null)
            || sessions.get(i).getLoginAt().before(leastRecentlyUsed.getLoginAt())) {
          leastRecentlyUsed = sessions.get(i);
        }
      }
      if (null != leastRecentlyUsed) {
        registry.expire(leastRecentlyUsed.getId());
        allocated = true;
      }
    }
    return allocated;
  }
 /**
  * Ensures the authentication object in the secure context is set to null when authentication
  * fails.
  */
 protected void unsuccessfulAuthentication(
     HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) {
   SecurityContextHolder.clearContext();
   if (null != sessionRegistry) sessionRegistry.remove(request.getSession().getId());
   if (null != failed) {
     logger.debug("Cleared security context due to exception", failed);
     request
         .getSession()
         .setAttribute(AbstractAuthenticationFilter.SECURITY_LAST_EXCEPTION_KEY, failed);
     if (failed instanceof UsernameNotFoundException) {
       throw failed;
     }
   }
 }
 /** Do the actual authentication for a pre-authenticated user. */
 private void doAuthenticate(HttpServletRequest request, HttpServletResponse response) {
   Authentication authResult = null;
   PreauthAuthentication auth = getPreauthAuthentication(request, response);
   if (auth == null) {
     logger.debug("No pre-authenticated principal found in request");
     return;
   } else {
     logger.debug("trying to authenticate preauth={}", auth);
   }
   try {
     auth.setDetails(authenticationDetailsSource.buildDetails(request));
     authResult = authenticationManager.authenticate(auth);
     sessionRegistry.register(authResult, request.getSession().getId());
     successfulAuthentication(request, response, authResult);
   } catch (AuthenticationException failed) {
     unsuccessfulAuthentication(request, response, failed);
     if (!continueOnFail) {
       throw failed;
     }
   }
 }