/**
   * Creates the final <tt>Authentication</tt> object which will be returned from the
   * <tt>authenticate</tt> method.
   *
   * @param authentication the original authentication request token
   * @param user the <tt>UserDetails</tt> instance returned by the configured
   *     <tt>UserDetailsContextMapper</tt>.
   * @return the Authentication object for the fully authenticated user.
   */
  protected Authentication createSuccessfulAuthentication(
      final UsernamePasswordAuthenticationToken authentication,
      final ExtendedLdapUserDetailsImpl user) {

    logger.finest("CustomLdapAuthenticationProvider : createSuccessfulAuthentication");
    Object password =
        useAuthenticationRequestCredentials ? authentication.getCredentials() : user.getPassword();

    CustomAuthenticationToken customAuthToken =
        new CustomAuthenticationToken(user, password, user.getAuthorities(), user.getAuthGroups());
    customAuthToken.setDetails(authentication.getDetails());

    return customAuthToken;
  }
  protected Authentication createSuccesssAuthentication(
      Object principal,
      CustomAuthenticationToken authentication,
      List<GrantedAuthority> grantedAuthoritiesList) {

    CustomAuthenticationToken result =
        new CustomAuthenticationToken(
            principal,
            authentication.getCredentials(),
            (String) authentication.getCompany(),
            grantedAuthoritiesList);

    result.setDetails(authentication.getDetails());

    return result;
  }
  @Override
  protected Authentication doAuthentication(Authentication authentication)
      throws AuthenticationException {

    if (!(authentication instanceof CustomAuthenticationToken)) {
      throw new IllegalArgumentException("Only CustomAuthenticationManager is supported");
    }

    CustomAuthenticationToken authenticationToken = (CustomAuthenticationToken) authentication;

    final String userName = (String) authenticationToken.getPrincipal();
    final String password = (String) authenticationToken.getCredentials();
    final String company = (String) authenticationToken.getCompany();

    if (AppUtil.isNullOrEmpty(userName)
        || AppUtil.isNullOrEmpty(password)
        || AppUtil.isNullOrEmpty(company)) {

      throw new BadCredentialsException("Invalid username/password");
    }

    User user = null;

    try {

      // Actual service call
      user = loginAppSvc.login(userName, password, company);

    } catch (AppSvcException ase) {
      throw new BadCredentialsException(ase.getMessage());
    }

    List<GrantedAuthority> grantedAuthoritiesList = new ArrayList<GrantedAuthority>();
    grantedAuthoritiesList.add(new GrantedAuthorityImpl("ROLE_USER"));

    return createSuccesssAuthentication(user, authenticationToken, grantedAuthoritiesList);
  }