private Set<String> getWithoutTranslations(String key, Set<String> cached)
     throws ServerException {
   if (cached != null) {
     return cached;
   }
   Set<String> claims = new HashSet<>();
   try {
     synchronized (attributeCache) {
       for (String claim : getSetting(realm, key)) {
         int pipe = claim.indexOf('|');
         if (pipe > -1) {
           claims.add(claim.substring(0, pipe));
         } else {
           claims.add(claim);
         }
       }
       return claims;
     }
   } catch (SMSException e) {
     logger.error(e.getMessage());
     throw new ServerException(e);
   } catch (SSOException e) {
     logger.error(e.getMessage());
     throw new ServerException(e);
   }
 }
  private void deleteSubConfigToRoot(String serviceName, String subConfigName) throws CLIException {
    SSOToken adminSSOToken = getAdminSSOToken();
    IOutput outputWriter = getOutputWriter();
    String[] params = {subConfigName, serviceName};

    writeLog(LogWriter.LOG_ACCESS, Level.INFO, "ATTEMPT_DELETE_SUB_CONFIGURATION", params);

    try {
      ServiceConfigManager scm = new ServiceConfigManager(serviceName, adminSSOToken);
      ServiceConfig sc = scm.getGlobalConfig(null);
      deleteSubConfig(sc, subConfigName);
      writeLog(LogWriter.LOG_ACCESS, Level.INFO, "SUCCEED_DELETE_SUB_CONFIGURATION", params);
      outputWriter.printlnMessage(
          MessageFormat.format(
              getResourceString("delete-sub-configuration-succeed"), (Object[]) params));
    } catch (SSOException e) {
      String[] args = {subConfigName, serviceName, e.getMessage()};
      debugError("DeleteSubConfiguration.deleteSubConfigToRoot", e);
      writeLog(LogWriter.LOG_ERROR, Level.INFO, "FAILED_DELETE_SUB_CONFIGURATION", args);
      throw new CLIException(e, ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
    } catch (SMSException e) {
      String[] args = {subConfigName, serviceName, e.getMessage()};
      debugError("DeleteSubConfiguration.deleteSubConfigToRoot", e);
      writeLog(LogWriter.LOG_ERROR, Level.INFO, "FAILED_DELETE_SUB_CONFIGURATION", args);
      throw new CLIException(e, ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
    }
  }
  /** {@inheritDoc} */
  public Map<String, ResponseTypeHandler> getAllowedResponseTypes()
      throws UnsupportedResponseTypeException, ServerException {
    try {
      Set<String> responseTypeSet = getSetting(realm, OAuth2ProviderService.RESPONSE_TYPE_LIST);
      if (responseTypeSet == null || responseTypeSet.isEmpty()) {
        return Collections.emptyMap();
      }
      Map<String, ResponseTypeHandler> responseTypes = new HashMap<String, ResponseTypeHandler>();
      for (String responseType : responseTypeSet) {
        String[] parts = responseType.split("\\|");
        if (parts.length != 2) {
          logger.error("Response type wrong format for realm: " + realm);
          continue;
        }
        responseTypes.put(parts[0], wrap(parts[0], parts[1]));
      }
      return responseTypes;

    } catch (SMSException e) {
      logger.error(e.getMessage());
      throw new ServerException(e);
    } catch (SSOException e) {
      logger.error(e.getMessage());
      throw new ServerException(e);
    }
  }
  /**
   * Services a Commandline Request.
   *
   * @param rc Request Context.
   * @throw CLIException if the request cannot serviced.
   */
  public void handleRequest(RequestContext rc) throws CLIException {
    super.handleRequest(rc);
    ldapLogin();

    String serviceName = getStringOptionValue(IArgument.SERVICE_NAME);
    String i18nKey = getStringOptionValue(ARGUMENT_I18N_KEY);

    ServiceSchemaManager ssm = getServiceSchemaManager();
    IOutput outputWriter = getOutputWriter();

    try {
      String[] params = {serviceName, i18nKey};
      writeLog(LogWriter.LOG_ACCESS, Level.INFO, "ATTEMPT_SET_SERVICE_SCHEMA_I18N_KEY", params);
      ssm.setI18NKey(i18nKey);
      writeLog(LogWriter.LOG_ACCESS, Level.INFO, "SUCCEED_SET_SERVICE_SCHEMA_I18N_KEY", params);
      outputWriter.printlnMessage(
          MessageFormat.format(
              getResourceString("service-schema-set-i18n-key-succeed"), (Object[]) params));
    } catch (SSOException e) {
      String[] args = {serviceName, i18nKey, e.getMessage()};
      debugError("SetServiceSchemaI18nKey.handleRequest", e);
      writeLog(LogWriter.LOG_ERROR, Level.INFO, "FAILED_SET_SERVICE_SCHEMA_I18N_KEY", args);
      throw new CLIException(e, ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
    } catch (SMSException e) {
      String[] args = {serviceName, i18nKey, e.getMessage()};
      debugError("SetServiceSchemaI18nKey.handleRequest", e);
      writeLog(LogWriter.LOG_ERROR, Level.INFO, "FAILED_SET_SERVICE_SCHEMA_I18N_KEY", args);
      throw new CLIException(e, ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
    }
  }
 /**
  * Constructor for FAMSecurityToken
  *
  * @param ssoToken Single Sign on token of the subject.
  * @throws com.sun.identity.wss.security.SecurityException
  */
 public FAMSecurityToken(SSOToken ssoToken) throws SecurityException {
   try {
     SSOTokenManager.getInstance().validateToken(ssoToken);
     tokenID = ssoToken.getTokenID().toString();
     tokenType = SecurityToken.WSS_FAM_SSO_TOKEN;
     appTokenID = (WSSUtils.getAdminToken()).getTokenID().toString();
   } catch (SSOException se) {
     throw new SecurityException(se.getMessage());
   }
 }
 /** {@inheritDoc} */
 public KeyPair getServerKeyPair() throws ServerException {
   try {
     return getServerKeyPair(realm);
   } catch (SMSException e) {
     logger.error(e.getMessage());
     throw new ServerException(e);
   } catch (SSOException e) {
     logger.error(e.getMessage());
     throw new ServerException(e);
   }
 }
 /** {@inheritDoc} */
 public boolean issueRefreshTokens() throws ServerException {
   try {
     return getBooleanSetting(realm, OAuth2ProviderService.ISSUE_REFRESH_TOKEN);
   } catch (SMSException e) {
     logger.error(e.getMessage());
     throw new ServerException(e);
   } catch (SSOException e) {
     logger.error(e.getMessage());
     throw new ServerException(e);
   }
 }
 private Set<String> getSettingStrings(String key) throws ServerException {
   try {
     return getSetting(realm, key);
   } catch (SMSException e) {
     logger.error(e.getMessage());
     throw new ServerException(e);
   } catch (SSOException e) {
     logger.error(e.getMessage());
     throw new ServerException(e);
   }
 }
 @Override
 public boolean isRegistrationAccessTokenGenerationEnabled() throws ServerException {
   try {
     return getBooleanSetting(realm, OAuth2ProviderService.GENERATE_REGISTRATION_ACCESS_TOKENS);
   } catch (SSOException e) {
     logger.message(e.getMessage());
     throw new ServerException(e);
   } catch (SMSException e) {
     logger.message(e.getMessage());
     throw new ServerException(e);
   }
 }
 @Override
 public Map<String, String> getAMRAuthModuleMappings() throws ServerException {
   try {
     return getMapSetting(realm, OAuth2ProviderService.AMR_VALUE_MAPPING);
   } catch (SSOException e) {
     logger.message(e.getMessage());
     throw new ServerException(e);
   } catch (SMSException e) {
     logger.message(e.getMessage());
     throw new ServerException(e);
   }
 }
 @Override
 public boolean isOpenDynamicClientRegistrationAllowed() throws ServerException {
   try {
     return getBooleanSetting(realm, OAuth2ProviderService.OPEN_DYNAMIC_REGISTRATION_ALLOWED);
   } catch (SSOException e) {
     logger.message(e.getMessage());
     throw new ServerException(e);
   } catch (SMSException e) {
     logger.message(e.getMessage());
     throw new ServerException(e);
   }
 }
  @Override
  public boolean getClaimsParameterSupported() throws ServerException {
    try {
      return getBooleanSetting(realm, OAuth2ProviderService.CLAIMS_PARAMETER_SUPPORTED);
    } catch (SSOException e) {
      logger.error(e.getMessage());
      throw new ServerException(e);
    } catch (SMSException e) {
      logger.error(e.getMessage());
    }

    return false;
  }
Beispiel #13
0
 public Map getAttributeValues(String universalId) throws AMConsoleException {
   try {
     AMIdentity amid = IdUtils.getIdentity(adminSSOToken, universalId);
     Map values = AgentConfiguration.getAgentAttributes(amid, true);
     return values;
   } catch (IdRepoException re) {
     throw new AMConsoleException(re.getMessage());
   } catch (SMSException se) {
     throw new AMConsoleException(se.getMessage());
   } catch (SSOException ssoe) {
     throw new AMConsoleException(ssoe.getMessage());
   }
 }
  /**
   * Services a Commandline Request.
   *
   * @param rc Request Context.
   * @throws CLIException if the request cannot serviced.
   */
  public void handleRequest(RequestContext rc) throws CLIException {
    super.handleRequest(rc);

    SSOToken adminSSOToken = getAdminSSOToken();
    IOutput outputWriter = getOutputWriter();
    String realm = getStringOptionValue(IArgument.REALM_NAME);
    String idName = getStringOptionValue(ARGUMENT_ID_NAME);
    String type = getStringOptionValue(ARGUMENT_ID_TYPE);
    IdType idType = convert2IdType(type);
    String[] params = {realm, type, idName};

    try {
      AMIdentityRepository amir = new AMIdentityRepository(adminSSOToken, realm);
      Set set = amir.getAllowedIdOperations(idType);
      if (!set.contains(IdOperation.SERVICE)) {
        throw new CLIException(
            MessageFormat.format(
                getResourceString("realm-does-not-support-service"), (Object[]) params),
            ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
      }

      writeLog(LogWriter.LOG_ACCESS, Level.INFO, "ATTEMPT_GET_ASSIGNED_SERVICES", params);
      AMIdentity amid = new AMIdentity(adminSSOToken, idName, idType, realm, null);
      Set services = amid.getAssignedServices();

      if ((services != null) && !services.isEmpty()) {
        String msg = getResourceString("assigned-service-result");
        String[] arg = {""};
        for (Iterator i = services.iterator(); i.hasNext(); ) {
          arg[0] = (String) i.next();
          outputWriter.printlnMessage(MessageFormat.format(msg, (Object[]) arg));
        }
      } else {
        outputWriter.printlnMessage(getResourceString("no-service-assigned"));
      }
      writeLog(LogWriter.LOG_ACCESS, Level.INFO, "SUCCEED_GET_ASSIGNED_SERVICES", params);
    } catch (IdRepoException e) {
      String[] args = {realm, type, idName, e.getMessage()};
      debugError("GetAssignedServices.handleRequest", e);
      writeLog(LogWriter.LOG_ERROR, Level.INFO, "FAILED_GET_ASSIGNED_SERVICES", args);
      throw new CLIException(e, ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
    } catch (SSOException e) {
      String[] args = {realm, type, idName, e.getMessage()};
      debugError("GetAssignedServices.handleRequest", e);
      writeLog(LogWriter.LOG_ERROR, Level.INFO, "FAILED_GET_ASSIGNED_SERVICES", args);
      throw new CLIException(e, ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
    }
  }
Beispiel #15
0
  /**
   * Services a Commandline Request.
   *
   * @param rc Request Context.
   * @throw CLIException if the request cannot serviced.
   */
  public void handleRequest(RequestContext rc) throws CLIException {
    super.handleRequest(rc);
    ldapLogin();

    SSOToken adminSSOToken = getAdminSSOToken();
    IOutput outputWriter = getOutputWriter();
    String realm = getStringOptionValue(IArgument.REALM_NAME);
    String agentGroupName = getStringOptionValue(IArgument.AGENT_GROUP_NAME);
    List agentNames = rc.getOption(IArgument.AGENT_NAMES);
    String[] params = {realm, agentGroupName, ""};
    String agentName = "";
    try {
      AMIdentity amidGroup =
          new AMIdentity(adminSSOToken, agentGroupName, IdType.AGENTGROUP, realm, null);

      for (Iterator i = agentNames.iterator(); i.hasNext(); ) {
        agentName = (String) i.next();
        params[2] = agentName;
        writeLog(LogWriter.LOG_ACCESS, Level.INFO, "ATTEMPT_ADD_AGENT_TO_GROUP", params);
        AMIdentity amid = new AMIdentity(adminSSOToken, agentName, IdType.AGENTONLY, realm, null);
        AgentConfiguration.AddAgentToGroup(amidGroup, amid);
        writeLog(LogWriter.LOG_ACCESS, Level.INFO, "SUCCEED_ADD_AGENT_TO_GROUP", params);
      }

      if (agentNames.size() > 1) {
        outputWriter.printlnMessage(getResourceString("add-agent-to-group-succeeded-pural"));
      } else {
        outputWriter.printlnMessage(getResourceString("add-agent-to-group-succeeded"));
      }
    } catch (IdRepoException e) {
      String[] args = {realm, agentGroupName, agentName, e.getMessage()};
      debugError("AddAgentsToGroup.handleRequest", e);
      writeLog(LogWriter.LOG_ERROR, Level.INFO, "FAILED_ADD_AGENT_TO_GROUP", args);
      throw new CLIException(e, ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
    } catch (ConfigurationException e) {
      String[] args = {realm, agentGroupName, agentName, e.getMessage()};
      debugError("AddAgentsToGroup.handleRequest", e);
      writeLog(LogWriter.LOG_ERROR, Level.INFO, "FAILED_ADD_AGENT_TO_GROUP", args);
      throw new CLIException(e, ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
    } catch (SSOException e) {
      String[] args = {realm, agentGroupName, agentName, e.getMessage()};
      debugError("AddAgentsToGroup.handleRequest", e);
      writeLog(LogWriter.LOG_ERROR, Level.INFO, "FAILED_ADD_AGENT_TO_GROUP", args);
      throw new CLIException(e, ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
    }
  }
Beispiel #16
0
  /**
   * Services a Commandline Request.
   *
   * @param rc Request Context.
   * @throw CLIException if the request cannot serviced.
   */
  public void handleRequest(RequestContext rc) throws CLIException {
    super.handleRequest(rc);

    SSOToken adminSSOToken = getAdminSSOToken();
    IOutput outputWriter = getOutputWriter();
    String realm = getStringOptionValue(IArgument.REALM_NAME);
    String idName = getStringOptionValue(ARGUMENT_ID_NAME);
    String type = getStringOptionValue(ARGUMENT_ID_TYPE);
    String serviceName = getStringOptionValue(IArgument.SERVICE_NAME);
    IdType idType = convert2IdType(type);
    String datafile = getStringOptionValue(IArgument.DATA_FILE);
    List attrValues = rc.getOption(IArgument.ATTRIBUTE_VALUES);

    if ((datafile == null) && (attrValues == null)) {
      throw new CLIException(
          getResourceString("missing-attributevalues"),
          ExitCodes.INCORRECT_OPTION,
          rc.getSubCommand().getName());
    }

    Map attributeValues = AttributeValues.parse(getCommandManager(), datafile, attrValues);
    String[] params = {realm, type, idName, serviceName};

    try {
      writeLog(LogWriter.LOG_ACCESS, Level.INFO, "ATTEMPT_IDREPO_ASSIGN_SERVICE", params);
      AMIdentity amid = new AMIdentity(adminSSOToken, idName, idType, realm, null);
      amid.assignService(serviceName, attributeValues);

      outputWriter.printlnMessage(
          MessageFormat.format(
              getResourceString("idrepo-assign-service-succeed"), (Object[]) params));
      writeLog(LogWriter.LOG_ACCESS, Level.INFO, "SUCCEED_IDREPO_ASSIGN_SERVICE", params);
    } catch (IdRepoException e) {
      String[] args = {realm, type, idName, serviceName, e.getMessage()};
      debugError("AssignService.handleRequest", e);
      writeLog(LogWriter.LOG_ERROR, Level.INFO, "FAILED_IDREPO_ASSIGN_SERVICE", args);
      throw new CLIException(e, ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
    } catch (SSOException e) {
      String[] args = {realm, type, idName, serviceName, e.getMessage()};
      debugError("AssignService.handleRequest", e);
      writeLog(LogWriter.LOG_ERROR, Level.INFO, "FAILED_IDREPO_ASSIGN_SERVICE", args);
      throw new CLIException(e, ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
    }
  }
 private SSOToken validateAssertionSubjectSession(
     TokenGenerationServiceInvocationState invocationState) throws ForbiddenException {
   SSOToken subjectToken;
   SSOTokenManager tokenManager;
   try {
     tokenManager = SSOTokenManager.getInstance();
     subjectToken = tokenManager.createSSOToken(invocationState.getSsoTokenString());
   } catch (SSOException e) {
     logger.debug(
         "Exception caught creating the SSO token from the token string, almost certainly "
             + "because token string does not correspond to a valid session: "
             + e);
     throw new ForbiddenException(e.toString(), e);
   }
   if (!tokenManager.isValidToken(subjectToken)) {
     throw new ForbiddenException("SSO token string does not correspond to a valid SSOToken");
   }
   try {
     AMIdentity subjectIdentity = IdUtils.getIdentity(subjectToken);
     String invocationRealm = invocationState.getRealm();
     String subjectSessionRealm = DNMapper.orgNameToRealmName(subjectIdentity.getRealm());
     logger.debug(
         "TokenGenerationService:validateAssertionSubjectSession subjectRealm "
             + subjectSessionRealm
             + " invocation realm: "
             + invocationRealm);
     if (!invocationRealm.equalsIgnoreCase(subjectSessionRealm)) {
       logger.error(
           "TokenGenerationService:validateAssertionSubjectSession realms do not match: Subject realm : "
               + subjectSessionRealm
               + " invocation realm: "
               + invocationRealm);
       throw new ForbiddenException("SSO token subject realm does not match invocation realm");
     }
   } catch (SSOException | IdRepoException e) {
     logger.error(
         "TokenGenerationService:validateAssertionSubjectSession error while validating identity : "
             + e);
     throw new ForbiddenException(e.toString(), e);
   }
   return subjectToken;
 }
 @Override
 public Map<String, AuthenticationMethod> getAcrMapping() throws ServerException {
   try {
     final Map<String, String> map = getMapSetting(realm, OAuth2ProviderService.ACR_VALUE_MAPPING);
     final Map<String, AuthenticationMethod> methods =
         new HashMap<String, AuthenticationMethod>(map.size());
     for (Map.Entry<String, String> entry : map.entrySet()) {
       methods.put(
           entry.getKey(),
           new OpenAMAuthenticationMethod(entry.getValue(), AuthContext.IndexType.SERVICE));
     }
     return methods;
   } catch (SSOException e) {
     logger.message(e.getMessage());
     throw new ServerException(e);
   } catch (SMSException e) {
     logger.message(e.getMessage());
     throw new ServerException(e);
   }
 }
  private void addSubConfigToRoot(
      String serviceName, String subConfigName, String subConfigId, Map attrValues, int priority)
      throws CLIException {
    SSOToken adminSSOToken = getAdminSSOToken();
    IOutput outputWriter = getOutputWriter();
    String[] params = {subConfigName, serviceName};

    writeLog(LogWriter.LOG_ACCESS, Level.INFO, "ATTEMPT_ADD_SUB_CONFIGURATION", params);

    try {
      ServiceConfigManager scm = new ServiceConfigManager(serviceName, adminSSOToken);
      ServiceConfig sc = scm.getGlobalConfig(null);

      if (sc == null) {
        String[] args = {subConfigName, serviceName, "no global configiration"};
        writeLog(LogWriter.LOG_ERROR, Level.INFO, "FAILED_ADD_SUB_CONFIGURATION", args);
        String[] ar = {serviceName};
        String message =
            MessageFormat.format(
                getResourceString("add-sub-configuration-no-global-config"), (Object[]) ar);
        throw new CLIException(message, ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
      }

      addSubConfig(sc, subConfigName, subConfigId, attrValues, priority);
      writeLog(LogWriter.LOG_ACCESS, Level.INFO, "SUCCEED_ADD_SUB_CONFIGURATION", params);
      outputWriter.printlnMessage(
          MessageFormat.format(
              getResourceString("add-sub-configuration-succeed"), (Object[]) params));
    } catch (SSOException e) {
      String[] args = {subConfigName, serviceName, e.getMessage()};
      debugError("AddSubConfiguration.addSubConfigToRoot", e);
      writeLog(LogWriter.LOG_ERROR, Level.INFO, "FAILED_ADD_SUB_CONFIGURATION", args);
      throw new CLIException(e, ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
    } catch (SMSException e) {
      e.printStackTrace();
      String[] args = {subConfigName, serviceName, e.getMessage()};
      debugError("AddSubConfiguration.addSubConfigToRoot", e);
      writeLog(LogWriter.LOG_ERROR, Level.INFO, "FAILED_ADD_SUB_CONFIGURATION", args);
      throw new CLIException(e, ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
    }
  }
  private void addSubConfigToRealm(
      String realmName,
      String serviceName,
      String subConfigName,
      String subConfigId,
      Map attrValues,
      int priority)
      throws CLIException {
    SSOToken adminSSOToken = getAdminSSOToken();
    IOutput outputWriter = getOutputWriter();
    String[] params = {realmName, subConfigName, serviceName};

    writeLog(LogWriter.LOG_ACCESS, Level.INFO, "ATTEMPT_ADD_SUB_CONFIGURATION_TO_REALM", params);

    try {
      ServiceConfigManager scm = new ServiceConfigManager(serviceName, adminSSOToken);
      ServiceConfig sc = scm.getOrganizationConfig(realmName, null);

      if (sc == null) {
        sc = scm.createOrganizationConfig(realmName, null);
      }
      addSubConfig(sc, subConfigName, subConfigId, attrValues, priority);
      writeLog(LogWriter.LOG_ACCESS, Level.INFO, "SUCCEED_ADD_SUB_CONFIGURATION_TO_REALM", params);
      outputWriter.printlnMessage(
          MessageFormat.format(
              getResourceString("add-sub-configuration-to-realm-succeed"), (Object[]) params));
    } catch (SSOException e) {
      String[] args = {realmName, subConfigName, serviceName, e.getMessage()};
      debugError("AddSubConfiguration.addSubConfigToRealm", e);
      writeLog(LogWriter.LOG_ERROR, Level.INFO, "FAILED_ADD_SUB_CONFIGURATIONT_TO_REALM", args);
      throw new CLIException(e, ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
    } catch (SMSException e) {
      String[] args = {realmName, subConfigName, serviceName, e.getMessage()};
      debugError("AddSubConfiguration.addSubConfigToRealm", e);
      writeLog(LogWriter.LOG_ERROR, Level.INFO, "FAILED_ADD_SUB_CONFIGURATIONT_TO_REALM", args);
      throw new CLIException(e, ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
    }
  }
  /**
   * Services a Commandline Request.
   *
   * @param rc Request Context.
   * @throws CLIException if the request cannot serviced.
   */
  public void handleRequest(RequestContext rc) throws CLIException {
    super.handleRequest(rc);
    ldapLogin();

    SSOToken adminSSOToken = getAdminSSOToken();
    IOutput outputWriter = getOutputWriter();
    String realm = getStringOptionValue(IArgument.REALM_NAME);
    String agentGroupName = getStringOptionValue(IArgument.AGENT_GROUP_NAME);
    String outfile = getStringOptionValue(IArgument.OUTPUT_FILE);
    String[] params = {realm, agentGroupName};

    try {
      writeLog(LogWriter.LOG_ACCESS, Level.INFO, "ATTEMPT_SHOW_AGENT_GROUP", params);
      AMIdentity amid =
          new AMIdentity(adminSSOToken, agentGroupName, IdType.AGENTGROUP, realm, null);
      if (!amid.isExists()) {
        String[] args = {realm, agentGroupName, "agent group did not exist"};
        writeLog(LogWriter.LOG_ERROR, Level.INFO, "FAILED_SHOW_AGENT_GROUP", args);
        Object[] p = {agentGroupName};
        String msg = MessageFormat.format(getResourceString("show-agent-group-does-not-exist"), p);
        throw new CLIException(msg, ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
      }
      Map values = AgentConfiguration.getAgentGroupAttributes(adminSSOToken, realm, agentGroupName);

      Set passwords =
          AgentConfiguration.getAttributesSchemaNames(amid, AttributeSchema.Syntax.PASSWORD);

      if ((values != null) && !values.isEmpty()) {
        StringBuilder buff = new StringBuilder();
        // Used to generated a sorted list of property names for easier viewing
        List<String> sortedKeys = new ArrayList<String>(values.keySet());
        Collections.sort(sortedKeys);
        for (String attrName : sortedKeys) {

          if (passwords.contains(attrName)) {
            buff.append(attrName).append("=********\n");
          } else {
            Set vals = (Set) values.get(attrName);

            if (vals.isEmpty()) {
              buff.append(attrName).append("=").append("\n");
            } else {
              for (Iterator j = vals.iterator(); j.hasNext(); ) {
                String val = (String) j.next();
                buff.append(attrName).append("=").append(val).append("\n");
              }
            }
          }
        }
        if (outfile == null) {
          outputWriter.printlnMessage(buff.toString());
        } else {
          writeToFile(outfile, buff.toString());
          outputWriter.printlnMessage(getResourceString("show-agent-group-to-file"));
        }
      } else {
        outputWriter.printlnMessage(getResourceString("show-agent-group-no-attributes"));
      }
      writeLog(LogWriter.LOG_ACCESS, Level.INFO, "SUCCEED_SHOW_AGENT_GROUP", params);
    } catch (SMSException e) {
      String[] args = {realm, agentGroupName, e.getMessage()};
      debugError("ShowAgentGroup.handleRequest", e);
      writeLog(LogWriter.LOG_ERROR, Level.INFO, "FAILED_SHOW_AGENT_GROUP", args);
      throw new CLIException(e, ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
    } catch (IdRepoException e) {
      String[] args = {realm, agentGroupName, e.getMessage()};
      debugError("ShowAgentGroup.handleRequest", e);
      writeLog(LogWriter.LOG_ERROR, Level.INFO, "FAILED_SHOW_AGENT_GROUP", args);
      throw new CLIException(e, ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
    } catch (SSOException e) {
      String[] args = {realm, agentGroupName, e.getMessage()};
      debugError("ShowAgentGroup.handleRequest", e);
      writeLog(LogWriter.LOG_ERROR, Level.INFO, "FAILED_SHOW_AGENT_GROUP", args);
      throw new CLIException(e, ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
    }
  }
Beispiel #22
0
  /**
   * Services a Commandline Request.
   *
   * @param rc Request Context.
   * @throws CLIException if the request cannot serviced.
   */
  public void handleRequest(RequestContext rc) throws CLIException {
    super.handleRequest(rc);

    SSOToken adminSSOToken = getAdminSSOToken();
    IOutput outputWriter = getOutputWriter();
    String realm = getStringOptionValue(IArgument.REALM_NAME);
    String idName = getStringOptionValue(ARGUMENT_ID_NAME);
    String type = getStringOptionValue(ARGUMENT_ID_TYPE);
    List privileges = (List) rc.getOption(IArgument.PRIVILEGES);
    IdType idType = convert2IdType(type);
    String[] params = {realm, type, idName};

    try {
      writeLog(LogWriter.LOG_ACCESS, Level.INFO, "ATTEMPT_IDREPO_ADD_PRIVILEGES", params);

      DelegationManager mgr = new DelegationManager(adminSSOToken, realm);
      Set privilegeObjects = mgr.getPrivileges();

      AMIdentity amid = new AMIdentity(adminSSOToken, idName, idType, realm, null);
      if (!amid.isExists()) {
        Object[] p = {idName, type};
        throw new CLIException(
            MessageFormat.format(getResourceString("idrepo-add-privileges-do-not-exist"), p),
            ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
      }
      String uid = amid.getUniversalId();

      DelegationPrivilege newDp = null;
      for (Iterator i = privileges.iterator(); i.hasNext(); ) {
        String name = (String) i.next();
        DelegationPrivilege dp = getDelegationPrivilege(name, privilegeObjects);
        if (dp != null) {
          Set subjects = dp.getSubjects();
          if (!subjects.contains(uid)) {
            subjects.add(uid);
            newDp = new DelegationPrivilege(name, subjects, realm);
            mgr.addPrivilege(newDp);
          } else {
            String[] args = {idName, name};
            String msg =
                MessageFormat.format(
                    getResourceString("delegation-already-has-privilege"), (Object[]) args);
            throw new CLIException(msg, ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
          }
        } else {
          Set subjects = new HashSet(2);
          subjects.add(uid);
          newDp = new DelegationPrivilege(name, subjects, realm);
          mgr.addPrivilege(newDp);
        }
      }

      outputWriter.printlnMessage(
          MessageFormat.format(
              getResourceString("idrepo-add-privileges-succeed"), (Object[]) params));
      writeLog(LogWriter.LOG_ACCESS, Level.INFO, "SUCCEED_IDREPO_ADD_PRIVILEGES", params);
    } catch (IdRepoException e) {
      String[] args = {realm, type, idName, e.getMessage()};
      debugError("AddPrivileges.handleRequest", e);
      writeLog(LogWriter.LOG_ERROR, Level.INFO, "FAILED_IDREPO_ADD_PRIVILEGES", args);
      throw new CLIException(e, ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
    } catch (DelegationException e) {
      String[] args = {realm, type, idName, e.getMessage()};
      debugError("AddPrivileges.handleRequest", e);
      writeLog(LogWriter.LOG_ERROR, Level.INFO, "FAILED_IDREPO_ADD_PRIVILEGES", args);
      throw new CLIException(e, ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
    } catch (SSOException e) {
      String[] args = {realm, type, idName, e.getMessage()};
      debugError("AddPrivileges.handleRequest", e);
      writeLog(LogWriter.LOG_ERROR, Level.INFO, "FAILED_IDREPO_ADD_PRIVILEGES", args);
      throw new CLIException(e, ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
    }
  }
Beispiel #23
0
  /*
   * Process the XMLRequest
   */
  private AuthXMLResponse processAuthXMLRequest(
      String xml,
      AuthXMLRequest authXMLRequest,
      HttpServletRequest servletRequest,
      HttpServletResponse servletResponse) {
    if (messageEnabled) {
      debug.message("authXMLRequest is : " + authXMLRequest);
    }
    int requestType = authXMLRequest.getRequestType();
    String sessionID = authXMLRequest.getAuthIdentifier();
    String orgName = authXMLRequest.getOrgName();
    AuthContextLocal authContext = authXMLRequest.getAuthContext();
    LoginState loginState = AuthUtils.getLoginState(authContext);
    String params = authXMLRequest.getParams();
    List envList = authXMLRequest.getEnvironment();
    Map envMap = toEnvMap(envList);
    AuthXMLResponse authResponse = new AuthXMLResponse(requestType);
    authResponse.setAuthContext(authContext);
    authResponse.setAuthIdentifier(sessionID);
    if (messageEnabled) {
      debug.message("authContext is : " + authContext);
      debug.message("requestType : " + requestType);
    }
    if (authXMLRequest.getValidSessionNoUpgrade()) {
      authResponse.setAuthXMLRequest(authXMLRequest);
      authResponse.setValidSessionNoUpgrade(true);
      return authResponse;
    }
    String securityEnabled = null;
    try {
      securityEnabled = AuthUtils.getRemoteSecurityEnabled();
    } catch (AuthException auExp) {
      debug.error("Got Exception", auExp);
      setErrorCode(authResponse, auExp);
      return authResponse;
    }
    if (debug.messageEnabled()) {
      debug.message("Security Enabled = " + securityEnabled);
    }

    if (requestType != 0) {
      if ((securityEnabled != null) && (securityEnabled.equals("true"))) {
        security = true;
        String indexNameLoc = authXMLRequest.getIndexName();
        AuthContext.IndexType indexTypeLoc = authXMLRequest.getIndexType();
        if (indexTypeLoc == null) {
          indexTypeLoc = AuthUtils.getIndexType(authContext);
          indexNameLoc = AuthUtils.getIndexName(authContext);
        }
        if (debug.messageEnabled()) {
          debug.message("Index Name Local : " + indexNameLoc);
          debug.message("Index Type Local : " + indexTypeLoc);
        }
        if (((indexTypeLoc == null) || (indexNameLoc == null))
            || !((indexTypeLoc == AuthContext.IndexType.MODULE_INSTANCE)
                && indexNameLoc.equals("Application"))) {
          try {
            String ssoTokenID = authXMLRequest.getAppSSOTokenID();

            if (debug.messageEnabled()) {
              debug.message("Session ID = : " + ssoTokenID);
            }

            SSOTokenManager manager = SSOTokenManager.getInstance();
            SSOToken appSSOToken = manager.createSSOToken(ssoTokenID);

            // if the token isn't valid, let the client know so they
            // retry
            if (!manager.isValidToken(appSSOToken)) {
              if (debug.messageEnabled()) {
                debug.message("App SSOToken is not valid");
              }

              setErrorCode(
                  authResponse,
                  new AuthException(AMAuthErrorCode.REMOTE_AUTH_INVALID_SSO_TOKEN, null));
              return authResponse;
            } else {
              debug.message("App SSOToken is VALID");
            }
          } catch (SSOException ssoe) {
            // token is unknown to OpenAM, let the client know so they
            // can retry
            if (debug.messageEnabled()) {
              debug.message("App SSOToken is not valid: " + ssoe.getMessage());
            }

            setErrorCode(
                authResponse,
                new AuthException(AMAuthErrorCode.REMOTE_AUTH_INVALID_SSO_TOKEN, null));
            return authResponse;
          } catch (Exception exp) {
            debug.error("Got Exception", exp);
            setErrorCode(authResponse, exp);
            return authResponse;
          }
        }
      }
    } else {
      security = false;
    }

    // if index type is level and choice callback has a
    // selected choice then start module based authentication.
    if ((AuthUtils.getIndexType(authContext) == AuthContext.IndexType.LEVEL)
        || (AuthUtils.getIndexType(authContext) == AuthContext.IndexType.COMPOSITE_ADVICE)) {
      Callback[] callbacks = authXMLRequest.getSubmittedCallbacks();
      if (messageEnabled) {
        debug.message("Callbacks are  : " + callbacks);
      }
      if (callbacks != null) {
        if (messageEnabled) {
          debug.message("Callback length is : " + callbacks.length);
        }

        if (callbacks[0] instanceof ChoiceCallback) {
          ChoiceCallback cc = (ChoiceCallback) callbacks[0];
          int[] selectedIndexes = cc.getSelectedIndexes();
          int selected = selectedIndexes[0];
          String[] choices = cc.getChoices();
          String indexName = choices[selected];
          if (messageEnabled) {
            debug.message("Selected Index is : " + indexName);
          }
          authXMLRequest.setIndexType("moduleInstance");
          authXMLRequest.setIndexName(indexName);
          authXMLRequest.setRequestType(AuthXMLRequest.LoginIndex);
          requestType = AuthXMLRequest.LoginIndex;
        }
      }
    }

    AuthContext.Status loginStatus = AuthContext.Status.IN_PROGRESS;
    HttpServletRequest clientRequest = authXMLRequest.getClientRequest();
    if (loginState != null) {
      loginState.setHttpServletRequest(clientRequest);
      loginState.setHttpServletResponse(authXMLRequest.getClientResponse());
      if (clientRequest != null) {
        loginState.setParamHash(AuthUtils.parseRequestParameters(clientRequest));
      }
    }
    switch (requestType) {
      case AuthXMLRequest.NewAuthContext:
        try {
          processNewRequest(servletRequest, servletResponse, authResponse, loginState, authContext);
          postProcess(loginState, authResponse);
        } catch (Exception ex) {
          debug.error("Error in NewAuthContext ", ex);
          setErrorCode(authResponse, ex);
        }
        break;
      case AuthXMLRequest.Login:
        try {
          if (sessionID != null && sessionID.equals("0")) {
            processNewRequest(
                servletRequest, servletResponse, authResponse, loginState, authContext);
          }
          String clientHost = null;
          if (security) {
            clientHost = authXMLRequest.getHostName();
            if (messageEnabled) {
              debug.message("Client Host from Request = " + clientHost);
            }
          }
          if ((clientHost == null) && (servletRequest != null)) {
            clientHost = ClientUtils.getClientIPAddress(servletRequest);
          }
          loginState.setClient(clientHost);
          authContext.login();
          // setServletRequest(servletRequest,authContext);
          processRequirements(xml, authContext, authResponse, params, servletRequest);
          loginStatus = authContext.getStatus();
          authResponse.setRemoteRequest(loginState.getHttpServletRequest());
          authResponse.setRemoteResponse(loginState.getHttpServletResponse());

          postProcess(loginState, authResponse);
          checkACException(authResponse, authContext);
        } catch (Exception ex) {
          debug.error("Error during login ", ex);
          setErrorCode(authResponse, ex);
          authResponse.setLoginStatus(authContext.getStatus());
        }
        break;
      case AuthXMLRequest.LoginIndex:
        try {
          AuthContext.IndexType indexType = authXMLRequest.getIndexType();
          String indexName = authXMLRequest.getIndexName();
          if (messageEnabled) {
            debug.message("indexName is : " + indexName);
            debug.message("indexType is : " + indexType);
          }
          if (sessionID != null && sessionID.equals("0")) {
            processNewRequest(
                servletRequest, servletResponse, authResponse, loginState, authContext);
          }
          String clientHost = null;
          if (security) {
            clientHost = authXMLRequest.getHostName();
            if (messageEnabled) {
              debug.message("Client Host from Request = " + clientHost);
            }
          }
          if ((clientHost == null) && (servletRequest != null)) {
            clientHost = ClientUtils.getClientIPAddress(servletRequest);
          }
          loginState.setClient(clientHost);
          String locale = authXMLRequest.getLocale();
          if (locale != null && locale.length() > 0) {
            if (debug.messageEnabled()) {
              debug.message("locale is : " + locale);
            }
            authContext.login(indexType, indexName, envMap, locale);
          } else {
            authContext.login(indexType, indexName, envMap, null);
          }
          // setServletRequest(servletRequest,authContext);
          processRequirements(xml, authContext, authResponse, params, servletRequest);
          loginStatus = authContext.getStatus();
          authResponse.setRemoteRequest(loginState.getHttpServletRequest());
          authResponse.setRemoteResponse(loginState.getHttpServletResponse());
          postProcess(loginState, authResponse);
          checkACException(authResponse, authContext);
        } catch (Exception ex) {
          debug.error("Exception during LoginIndex", ex);
          setErrorCode(authResponse, ex);
        }
        break;
      case AuthXMLRequest.LoginSubject:
        try {
          Subject subject = authXMLRequest.getSubject();
          authContext.login(subject);
          // setServletRequest(servletRequest,authContext);
          processRequirements(xml, authContext, authResponse, params, servletRequest);
          postProcess(loginState, authResponse);
          loginStatus = authContext.getStatus();
          checkACException(authResponse, authContext);
        } catch (AuthLoginException ale) {
          debug.error("Exception during LoginSubject", ale);
          setErrorCode(authResponse, ale);
        }
        break;
      case AuthXMLRequest.SubmitRequirements:
        try {
          // setServletRequest(servletRequest,authContext);
          Callback[] submittedCallbacks = authXMLRequest.getSubmittedCallbacks();
          authContext.submitRequirements(submittedCallbacks);
          Callback[] reqdCallbacks = null;
          if (authContext.hasMoreRequirements()) {
            reqdCallbacks = authContext.getRequirements();
            authResponse.setReqdCallbacks(reqdCallbacks);
          }
          authResponse.setRemoteRequest(loginState.getHttpServletRequest());
          authResponse.setRemoteResponse(loginState.getHttpServletResponse());
          postProcess(loginState, authResponse);
          loginStatus = authContext.getStatus();
          authResponse.setLoginStatus(loginStatus);
          InternalSession oldSession = loginState.getOldSession();
          authResponse.setOldSession(oldSession);
          checkACException(authResponse, authContext);
        } catch (Exception ex) {
          debug.error("Error during submit requirements ", ex);
          setErrorCode(authResponse, ex);
        }
        break;
      case AuthXMLRequest.QueryInformation:
        try {
          if (sessionID != null && sessionID.equals("0")) {
            processNewRequest(
                servletRequest, servletResponse, authResponse, loginState, authContext);
          }
          Set moduleNames = authContext.getModuleInstanceNames();
          authResponse.setModuleNames(moduleNames);
          authResponse.setAuthContext(authContext);
          postProcess(loginState, authResponse);
          checkACException(authResponse, authContext);
        } catch (Exception ex) {
          debug.error("Error during Query Information", ex);
          setErrorCode(authResponse, ex);
        }
        break;
      case AuthXMLRequest.Logout:
        // Object loginContext = null;
        // InternalSession intSess = null;
        // SSOToken token = null;
        // boolean logoutCalled = false;
        if (sessionID != null && !sessionID.equals("0")) {
          /*intSess = AuthD.getSession(sessionID);
                 try {
                     token = SSOTokenManager.getInstance().
                         createSSOToken(sessionID);
                     if (debug.messageEnabled()) {
                         debug.message("AuthXMLHandler."
                             + "processAuthXMLRequest: Created token "
                             + "during logout = "+token);
                     }
          } catch (com.iplanet.sso.SSOException ssoExp) {
                    if (debug.messageEnabled()) {
          debug.message("AuthXMLHandler.processAuthXMLRequest:"
                        + "SSOException checking validity of SSO Token");
                    }
          }*/
          try {
            AuthUtils.logout(sessionID, servletRequest, servletResponse);
          } catch (com.iplanet.sso.SSOException ssoExp) {
            if (debug.messageEnabled()) {
              debug.message(
                  "AuthXMLHandler.processAuthXMLRequest:"
                      + "SSOException checking validity of SSO Token");
            }
          }
        }

        /*if (intSess != null) {
                   loginContext = intSess.getObject(ISAuthConstants.
                       LOGIN_CONTEXT);
               }
               try {
                   if (loginContext != null) {
                       if (loginContext instanceof
                           javax.security.auth.login.LoginContext) {
                           javax.security.auth.login.LoginContext lc =
                               (javax.security.auth.login.LoginContext)
                                loginContext;
                           lc.logout();
                       } else {
                           com.sun.identity.authentication.jaas.LoginContext
                               jlc = (com.sun.identity.authentication.jaas.
                               LoginContext) loginContext;
                           jlc.logout();
                       }
                       logoutCalled = true;
                   }
               } catch (javax.security.auth.login.LoginException loginExp) {
                   debug.error("AuthXMLHandler.processAuthXMLRequest: "
                       + "Cannot Execute module Logout", loginExp);
               }
               Set postAuthSet = null;
               if (intSess != null) {
                   postAuthSet = (Set) intSess.getObject(ISAuthConstants.
                       POSTPROCESS_INSTANCE_SET);
               }
               if ((postAuthSet != null) && !(postAuthSet.isEmpty())) {
                   AMPostAuthProcessInterface postLoginInstance=null;
                   for(Iterator iter = postAuthSet.iterator();
                   iter.hasNext();) {
                       try {
                    postLoginInstance =
                  (AMPostAuthProcessInterface) iter.next();
                            postLoginInstance.onLogout(servletRequest,
                                servletResponse, token);
                       } catch (Exception exp) {
                          debug.error("AuthXMLHandler.processAuthXMLRequest: "
                              + "Failed in post logout.", exp);
                       }
            }
               } else {
                   String plis = null;
                   if (intSess != null) {
                       plis = intSess.getProperty(
                           ISAuthConstants.POST_AUTH_PROCESS_INSTANCE);
                   }
                   if (plis != null && plis.length() > 0) {
                       StringTokenizer st = new StringTokenizer(plis, "|");
                       if (token != null) {
                           while (st.hasMoreTokens()) {
                               String pli = (String)st.nextToken();
                               try {
                                   AMPostAuthProcessInterface postProcess =
                                           (AMPostAuthProcessInterface)
                                           Thread.currentThread().
                                           getContextClassLoader().
                                           loadClass(pli).newInstance();
                                   postProcess.onLogout(servletRequest,
                                       servletResponse, token);
                               } catch (Exception e) {
                                   debug.error("AuthXMLHandler."
                                       + "processAuthXMLRequest:" + pli, e);
                               }
                           }
                       }
                   }
               }
               try {
                   boolean isTokenValid = SSOTokenManager.getInstance().
                       isValidToken(token);
                   if ((token != null) && isTokenValid) {
                       AuthD.getAuth().logLogout(token);
                       Session session = Session.getSession(
                           new SessionID(sessionID));
                       session.logout();
                       debug.message("logout successful.");
                   }
        } catch (com.iplanet.dpro.session.SessionException
                   sessExp) {
                   if (debug.messageEnabled()) {
                       debug.message("AuthXMLHandler."
                           + "processAuthXMLRequest: SessionException"
                           + " checking validity of SSO Token");
                   }
        } catch (com.iplanet.sso.SSOException ssoExp) {
                   if (debug.messageEnabled()) {
                       debug.message("AuthXMLHandler."
                           + "processAuthXMLRequest: SSOException "
                           + "checking validity of SSO Token");
                   }
               }*/
        authResponse.setLoginStatus(AuthContext.Status.COMPLETED);
        break;
      case AuthXMLRequest.Abort:
        try {
          authContext.abort();
          loginStatus = authContext.getStatus();
          authResponse.setLoginStatus(loginStatus);
          checkACException(authResponse, authContext);
        } catch (AuthLoginException ale) {
          debug.error("Error aborting ", ale);
          setErrorCode(authResponse, ale);
        }
        break;
    }

    if (messageEnabled) {
      debug.message("loginStatus: " + loginStatus);

      if (authContext != null) {
        debug.message("error Code: " + authContext.getErrorCode());
        debug.message("error Template: " + authContext.getErrorTemplate());
      }
    }

    if (loginStatus == AuthContext.Status.FAILED) {
      if ((authContext.getErrorMessage() != null)
          && (authContext
              .getErrorMessage()
              .equals(
                  AMResourceBundleCache.getInstance()
                      .getResBundle(
                          "amAuthLDAP",
                          com.sun.identity.shared.locale.Locale.getLocale(loginState.getLocale()))
                      .getString(ISAuthConstants.EXCEED_RETRY_LIMIT)))) {
        loginState.setErrorCode(AMAuthErrorCode.AUTH_LOGIN_FAILED);
      }
      if ((authContext.getErrorCode() != null) && ((authContext.getErrorCode()).length() > 0)) {
        authResponse.setErrorCode(authContext.getErrorCode());
      }
      checkACException(authResponse, authContext);
      if ((authContext.getErrorTemplate() != null)
          && ((authContext.getErrorTemplate()).length() > 0)) {
        authResponse.setErrorTemplate(authContext.getErrorTemplate());
      }
      // Account Lockout Warning Check
      if ((authContext.getErrorCode() != null)
          && (authContext.getErrorCode().equals(AMAuthErrorCode.AUTH_INVALID_PASSWORD))) {
        String lockWarning = authContext.getLockoutMsg();
        if ((lockWarning != null) && (lockWarning.length() > 0)) {
          authResponse.setErrorMessage(lockWarning);
        }
      }
    }

    return authResponse;
  }
Beispiel #24
0
  /**
   * Returns the <code>AMIdentity</code> object for the given parameters. If there is no such
   * identity, or there is more then one matching identity, then an AuthException will be thrown.
   *
   * @param idType Identity Type.
   * @param idName Identity Name.
   * @param orgName organization name.
   * @return <code>AMIdentity</code> object.
   * @throws AuthException if there was no result, or if there was more results then one.
   */
  public AMIdentity getIdentity(IdType idType, String idName, String orgName) throws AuthException {
    if (debug.messageEnabled()) {
      debug.message("IdType is :" + idType);
      debug.message("IdName is :" + idName);
      debug.message("orgName is :" + orgName);
    }
    AMIdentity amIdentity = null;

    // Try getting the identity using IdUtils.getIdentity(...)
    try {
      if (debug.messageEnabled()) {
        debug.message("AuthD.getIdentity() from IdUtils Name: " + idName + " Org: " + orgName);
      }
      amIdentity = IdUtils.getIdentity(getSSOAuthSession(), idName, orgName);
      if ((amIdentity != null)
          && (amIdentity.isExists())
          && (amIdentity.getType().equals(idType))
          && (amIdentity.getAttributes() != null)) {
        if (debug.messageEnabled()) {
          debug.message(
              "AuthD.getIdentity obtained identity" + "using IdUtil.getIdentity: " + amIdentity);
        }
        return (amIdentity);
      }
    } catch (IdRepoException e) {
      // Ignore this exception and continue with search
      if (debug.messageEnabled()) {
        debug.message(
            "AuthD.getIdentity: Got IdRepoException while "
                + "getting Identity from IdUtils: "
                + e.getMessage());
      }
    } catch (SSOException ssoe) {
      // Ignore this exception and continue with search
      if (debug.messageEnabled()) {
        debug.message(
            "AuthD.getIdentity: Got SSOException while "
                + "getting Identity from IdUtils: "
                + ssoe.getMessage());
      }
    }

    // Obtain AMIdentity object by searching within IdRepo
    try {
      amIdentity = null;
      idName = DNUtils.DNtoName(idName);
      AMIdentityRepository amIdRepo = getAMIdentityRepository(orgName);
      IdSearchControl idsc = new IdSearchControl();
      idsc.setRecursive(true);
      idsc.setTimeOut(0);
      idsc.setMaxResults(0);
      idsc.setAllReturnAttributes(false);
      IdSearchResults searchResults = amIdRepo.searchIdentities(idType, idName, idsc);
      Set results = Collections.EMPTY_SET;
      if (searchResults != null) {
        results = searchResults.getSearchResults();
      }

      if ((results != null) && (results.size() > 1)) {
        // multiple user match found, throw exception,
        // user need to login as super admin to fix it
        debug.error("getIdentity: Multiple matches found for " + "user '" + idName);
        throw new AuthException(AMAuthErrorCode.AUTH_ERROR, null);
      }

      Iterator users = results.iterator();
      if (users.hasNext()) {
        amIdentity = (AMIdentity) users.next();
      }
    } catch (SSOException sso) {
      if (debug.messageEnabled()) {
        debug.message("getIdentity error " + sso.getMessage());
      }
    } catch (IdRepoException ide) {
      if (debug.messageEnabled()) {
        debug.message("IdRepoException error " + ide.getMessage());
      }
    }
    if (amIdentity == null) {
      throw new AuthException(AMAuthErrorCode.AUTH_PROFILE_ERROR, null);
    }

    return amIdentity;
  }