/** {@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);
    }
  }
Ejemplo n.º 2
0
  /** {@inheritDoc} */
  public AuthorizationCode readAuthorizationCode(OAuth2Request request, String code)
      throws InvalidGrantException, ServerException, NotFoundException {
    if (logger.messageEnabled()) {
      logger.message("Reading Authorization code: " + code);
    }
    final JsonValue token;

    // Read from CTS
    try {
      token = tokenStore.read(code);
    } catch (CoreTokenException e) {
      logger.error("Unable to read authorization code corresponding to id: " + code, e);
      throw new ServerException("Could not read token from CTS: " + e.getMessage());
    }

    if (token == null) {
      logger.error("Unable to read authorization code corresponding to id: " + code);
      throw new InvalidGrantException("The provided access grant is invalid, expired, or revoked.");
    }

    OpenAMAuthorizationCode authorizationCode = new OpenAMAuthorizationCode(token);
    validateTokenRealm(authorizationCode.getRealm(), request);

    request.setToken(AuthorizationCode.class, authorizationCode);
    return authorizationCode;
  }
Ejemplo n.º 3
0
  /** {@inheritDoc} */
  public AccessToken readAccessToken(OAuth2Request request, String tokenId)
      throws ServerException, InvalidGrantException, NotFoundException {

    logger.message("Reading access token");

    JsonValue token;

    // Read from CTS
    try {
      token = tokenStore.read(tokenId);
    } catch (CoreTokenException e) {
      logger.error("Unable to read access token corresponding to id: " + tokenId, e);
      throw new ServerException("Could not read token in CTS: " + e.getMessage());
    }

    if (token == null) {
      logger.error("Unable to read access token corresponding to id: " + tokenId);
      throw new InvalidGrantException("Could not read token in CTS");
    }

    OpenAMAccessToken accessToken = new OpenAMAccessToken(token);
    validateTokenRealm(accessToken.getRealm(), request);

    request.setToken(AccessToken.class, accessToken);
    return accessToken;
  }
Ejemplo n.º 4
0
  /**
   * Method which creates a DC Tree for the given org, if the <code>sunPreferredDomain</code>
   * attribute is present and has a fully qualified domain name as value.
   *
   * @param token SSOToken
   * @param orgGuid identifiication of Organization entry to be mapped from dctree to organization
   *     DIT organization
   * @param domainName set the domain this organization belongs to.
   * @param attrSet the AttrSet of the organization
   * @exception AMException if unsuccessful in creating a dc tree for the organization or
   *     unsuccessful in setting the mapping between dc tree and the organization
   */
  protected void createDomain(SSOToken token, Guid orgGuid, String domainName, AttrSet attrSet)
      throws AMException {
    if (DCTREE_START_DN == null) {
      throw new AMException(AMSDKBundle.getString("355"), "355");
    }

    // Create a DC tree for specified domain.
    if ((domainName != null) && (domainName != "")) {
      try {
        DomainComponentTree dcTree = new DomainComponentTree(token, new Guid(DCTREE_START_DN));
        dcTree.addDomain(domainName);
        // Set the domain mapping
        dcTree.setDomainMapping(domainName, orgGuid);
        String status = attrSet.getValue(INET_DOMAIN_STATUS_ATTR);
        if (status != null) {
          dcTree.setDomainStatus(domainName, status);
        }
      } catch (InvalidDCRootException ie) {
        debug.error("DCTree.createDomain(): ", ie);
        throw new AMException(AMSDKBundle.getString("343"), "343");
      } catch (UMSException ue) {
        debug.error("DCTree.createDomain(): ", ue);
        throw new AMException(AMSDKBundle.getString("344"), "344");
      }
    }
  }
Ejemplo n.º 5
0
 protected AttrSet getDomainAttributes(SSOToken token, String orgDN, String[] attrNames)
     throws AMException, SSOException {
   String domainName = null;
   try {
     AttrSet domAttrSet;
     domainName = getCanonicalDomain(token, orgDN);
     if (domainName == null) {
       debug.error("DCTree.getDomainAttributes-> " + "Domain not found for:  " + orgDN);
       return null;
     }
     DomainComponentTree dcTree = new DomainComponentTree(token, new Guid(DCTREE_START_DN));
     DomainComponent dcNode = dcTree.getDomainComponent(domainName);
     if (attrNames != null) {
       domAttrSet = dcNode.getAttributes(attrNames);
     } else {
       domAttrSet = dcNode.getAttributes(dcNode.getAttributeNames());
     }
     AttrSet[] attrArray = splitAttrSet(null, domAttrSet);
     return attrArray[1];
   } catch (UMSException umse) {
     debug.error(
         "DCTree.getDomainAttributes: " + " error getting attributes for domain " + domainName);
   }
   return null;
 }
Ejemplo n.º 6
0
  static void initialize(SSOToken token) throws SMSException, SSOException {
    // Validate SSOToken
    SMSEntry.validateToken(token);

    // Check if already initialized
    if (initialized) return;
    // Initilaize the parameters
    try {
      // Get the service names and cache it
      serviceNames = CachedSubEntries.getInstance(token, serviceDN);
      if (serviceNames.getSMSEntry().isNewEntry()) {
        if (debug.warningEnabled()) {
          debug.warning("SeviceManager:: Root service node " + "does not exists: " + serviceDN);
        }
        String[] msgs = new String[1];
        msgs[0] = serviceDN;
        throw (new SMSException(
            IUMSConstants.UMS_BUNDLE_NAME, IUMSConstants.SMS_services_node_does_not_exist, msgs));
      }
    } catch (SMSException e) {
      debug.error("ServiceManager::unable to get " + "services node: " + serviceDN, e);
      throw (e);
    }
    // Check if realm is enabled and set appropriate flags
    checkFlags(token);
    initialized = true;
  }
Ejemplo n.º 7
0
  /**
   * Verify the signature in <code>Response</code>.
   *
   * @param pepEntityID entity identifier of PEP.
   * @param pdpEntityID entity identifier of PDP.
   * @param response <code>Response</code> to be verified
   * @return true if signature is valid.
   * @throws <code>SAML2Exception</code> if error in verifying the signature.
   */
  public static boolean verifySignedResponse(
      String pepEntityID, String pdpEntityID, Response response) throws SAML2Exception {
    String classMethod = "QueryClient:verifySignedResponse: ";

    String realm = "/";
    XACMLAuthzDecisionQueryConfigElement pepConfig = getPEPConfig(realm, pepEntityID);

    String wantResponseSigned =
        getAttributeValueFromPEPConfig(pepConfig, "wantXACMLAuthzDecisionResponseSigned");

    boolean valid = false;
    if (wantResponseSigned != null && wantResponseSigned.equalsIgnoreCase("true")) {
      XACMLPDPDescriptorElement pdpDescriptor =
          saml2MetaManager.getPolicyDecisionPointDescriptor(null, pdpEntityID);
      X509Certificate signingCert = KeyUtil.getPDPVerificationCert(pdpDescriptor, pdpEntityID);
      if (signingCert != null) {
        valid = response.isSignatureValid(signingCert);
        if (debug.messageEnabled()) {
          debug.message(classMethod + "Signature is valid :" + valid);
        }
      } else {
        debug.error(classMethod + "Incorrect configuration for Signing Certificate.");
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("metaDataError"));
      }
    } else {
      if (debug.messageEnabled()) {
        debug.message(classMethod + "Response doesn't need to be verified.");
      }
      valid = true;
    }
    return valid;
  }
Ejemplo n.º 8
0
 /**
  * Returns the SSOToken of the user. If user has not authenticated re-directs the user to login
  * page
  */
 private SSOToken getSSOToken(HttpServletRequest request, HttpServletResponse response)
     throws IOException {
   SSOToken token = null;
   try {
     /* SSOTokenManager.createSSOToken() throws an SSOException if the
      * token is not valid, so for a invalid token manager.isValidToken()
      * will never get executed for an invalid token.
      */
     if (((token = tokenManager.createSSOToken(request)) == null)
         || !tokenManager.isValidToken(token)) {
       if (debug.messageEnabled()) {
         debug.message(
             "CDCClientServlet.getSSOToken:SSOToken is "
                 + "either null or not valid: "
                 + token
                 + "\nRedirecting for authentication");
       }
       token = null;
     }
   } catch (com.iplanet.sso.SSOException e) {
     if (debug.messageEnabled()) {
       debug.message("CDCClientServlet.getSSOToken:SSOException " + "caught= " + e);
     }
     token = null;
   }
   return (token);
 }
Ejemplo n.º 9
0
 /**
  * This method parses out the local_attribute=source_attributes as they are encapsulated in the
  * authN module configurations into a more usable, Map<String, String> format.
  *
  * @param configuredMappings The set of local=source mappings.
  * @return The derived Map instance.
  */
 public static Map<String, String> parseMappings(Set<String> configuredMappings) {
   Map<String, String> parsedMappings = new HashMap<String, String>();
   for (String mapping : configuredMappings) {
     if (mapping.indexOf(EQUALS) == -1) {
       continue;
     }
     StringTokenizer tokenizer = new StringTokenizer(mapping, EQUALS);
     final String key = tokenizer.nextToken();
     final String value = tokenizer.nextToken();
     /*
     The ldap_attr=spource_attr mapping is user-generated, so I want to warn about duplicate entries. In a
     HashMap, repeated insertion of the same key will over-write previous entries, but I want to warn about
     duplicate entries, and will persist the first entry.
      */
     if (!parsedMappings.containsKey(key)) {
       parsedMappings.put(key, value);
     } else {
       if (debug.warningEnabled()) {
         debug.warning(
             "In MappingUtils.parseMappings, the user-entered attribute mappings contain "
                 + "duplicate entries. The first entry will be preserved: "
                 + configuredMappings);
       }
     }
   }
   if (parsedMappings.isEmpty()) {
     throw new IllegalArgumentException(
         "The mapping Set does not contain any mappings in format "
             + "local_attribute=source_attribute.");
   }
   return Collections.unmodifiableMap(parsedMappings);
 }
 private Map<String, Object> createRSAJWK(RSAPublicKey key, KeyUse use, String alg)
     throws ServerException {
   String alias = null;
   try {
     alias = getStringSetting(realm, OAuth2Constants.OAuth2ProviderService.KEYSTORE_ALIAS);
   } catch (SSOException | SMSException e) {
     logger.error(e.getMessage());
     throw new ServerException(e);
   }
   if (StringUtils.isBlank(alias)) {
     logger.error("Alias of ID Token Signing Key not set.");
     throw new ServerException("Alias of ID Token Signing Key not set.");
   } else if ("test".equals(alias)) {
     logger.warning("Alias of ID Token Signing Key should be changed from default, 'test'.");
   }
   String kid =
       Hash.hash(alias + key.getModulus().toString() + key.getPublicExponent().toString());
   return json(object(
           field("kty", "RSA"),
           field(OAuth2Constants.JWTTokenParams.KEY_ID, kid),
           field("use", use.toString()),
           field("alg", alg),
           field("n", Base64url.encode(key.getModulus().toByteArray())),
           field("e", Base64url.encode(key.getPublicExponent().toByteArray()))))
       .asMap();
 }
Ejemplo n.º 11
0
 // Get cookies string from HTTP request object
 private String getCookiesFromRequest(HttpServletRequest request) {
   Cookie cookies[] = CookieUtils.getCookieArrayFromReq(request);
   // above call would return pure sid in iPlanetDirectoryPro cookie
   // independent of container encoding
   StringBuilder cookieStr = null;
   String strCookies = null;
   if (cookies != null) {
     for (int nCookie = 0; nCookie < cookies.length; nCookie++) {
       String cookieName = cookies[nCookie].getName();
       String cookieVal = cookies[nCookie].getValue();
       if (cookieName.equals(CookieUtils.getAmCookieName()) && cookieEncoding) {
         cookieVal = URLEncDec.encode(cookieVal);
       }
       if (debug.messageEnabled()) {
         debug.message("CDCClientServlet.getCookiesFromRequest:" + "Cookie name = " + cookieName);
         debug.message("CDCClientServlet.getCookiesFromRequest:" + "Cookie val= " + cookieVal);
       }
       if (cookieStr == null) {
         cookieStr = new StringBuilder();
       } else {
         cookieStr.append(SEMI_COLON).append(SPACE);
       }
       cookieStr.append(cookieName).append(EQUAL_TO).append(cookieVal);
     }
   }
   if (cookieStr != null) {
     strCookies = cookieStr.toString();
   }
   return strCookies;
 }
 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 synchronized ScopeValidator getScopeValidator() throws ServerException {
    if (scopeValidator == null) {
      try {
        final String scopeValidatorClassName =
            getStringSettingValue(OAuth2ProviderService.SCOPE_PLUGIN_CLASS);
        if (isEmpty(scopeValidatorClassName)) {
          logger.message("Scope Validator class not set.");
          throw new ServerException("Scope Validator class not set.");
        }

        final Class<?> scopeValidatorClass = Class.forName(scopeValidatorClassName);

        if (Scope.class.isAssignableFrom(scopeValidatorClass)) {
          final Scope scopeClass =
              InjectorHolder.getInstance(scopeValidatorClass.asSubclass(Scope.class));
          return new LegacyScopeValidator(scopeClass);
        }

        scopeValidator =
            InjectorHolder.getInstance(scopeValidatorClass.asSubclass(ScopeValidator.class));

      } catch (ClassNotFoundException e) {
        logger.error(e.getMessage());
        throw new ServerException(e);
      }
    }
    return scopeValidator;
  }
  private ResponseTypeHandler wrap(String responseTypeName, String responseTypeHandlerClassName)
      throws UnsupportedResponseTypeException {

    if (responseTypeHandlerClassName == null || responseTypeHandlerClassName.isEmpty()) {
      logger.warning(
          "Requested a response type that is not configured. response_type=" + responseTypeName);
      throw new UnsupportedResponseTypeException("Response type is not supported");
    } else if (responseTypeHandlerClassName.equalsIgnoreCase("none")) {
      return new NoneResponseTypeHandler();
    }
    try {
      final Class<?> responseTypeHandlerClass = Class.forName(responseTypeHandlerClassName);
      if (ResponseType.class.isAssignableFrom(responseTypeHandlerClass)) {
        ResponseType responseType =
            InjectorHolder.getInstance(responseTypeHandlerClass.asSubclass(ResponseType.class));
        return new LegacyResponseTypeHandler(
            responseType, realm, getSSOCookieName(), cookieExtractor);
      }

      return InjectorHolder.getInstance(
          responseTypeHandlerClass.asSubclass(ResponseTypeHandler.class));

    } catch (ClassNotFoundException e) {
      logger.error(e.getMessage());
      throw new UnsupportedResponseTypeException("Response type is not supported");
    }
  }
Ejemplo n.º 15
0
 /**
  * removes the listener from the list of Persistent Search listeners of the asynchronous seach for
  * the given search ID.
  *
  * @param request The request returned by the addListener
  * @supported.api
  */
 protected void removeListener(Request request) {
   LDAPConnection connection = request.getLDAPConnection();
   if (connection != null) {
     if (debugger.messageEnabled()) {
       debugger.message(
           "EventService.removeListener(): Removing "
               + "listener requestID: "
               + request.getRequestID()
               + " Listener: "
               + request.getListener());
     }
     try {
       if ((connection != null) && (connection.isConnected())) {
         connection.abandon(request.getId());
         connection.disconnect();
       }
     } catch (LDAPException le) {
       // Might have to check the reset codes and try to reset
       if (debugger.warningEnabled()) {
         debugger.warning(
             "EventService.removeListener(): " + "LDAPException, when trying to remove listener",
             le);
       }
     }
   }
 }
Ejemplo n.º 16
0
  protected HashMap<String, String> getAttributeNameToSection() {
    HashMap<String, String> result = new HashMap<String, String>();
    InputStream inputStream =
        getClass()
            .getClassLoader()
            .getResourceAsStream("/" + schema.getName() + ".section" + ".properties");

    if (inputStream != null) {
      String line;
      BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
      try {
        while ((line = reader.readLine()) != null) {
          if (!(line.matches("^\\#.*") || line.isEmpty())) {
            String[] attributeValue = line.split("=");
            final String sectionName = attributeValue[0];
            result.put(attributeValue[1], sectionName);
          }
        }
      } catch (IOException e) {
        if (debug.errorEnabled()) {
          debug.error("Error reading section properties file", e);
        }
      }
    }
    return result;
  }
Ejemplo n.º 17
0
  /**
   * Creates Organization within OpenAM
   *
   * @param ocm Organization Configuration Manager
   * @param jVal JSONvalue that contains the payload
   * @param realm Name of the realm to be created
   * @throws SMSException
   * @throws Exception
   */
  private void createOrganization(
      OrganizationConfigManager ocm, JsonValue jVal, String realm, String realmPath)
      throws Exception {

    Map defaultValues = null;
    OrganizationConfigManager realmCreatedOcm;
    if (realmPath != null && !realmPath.endsWith("/")) {
      realmPath = realmPath + "/";
    }
    try {
      JsonValue realmDetails = jVal;
      if (jVal != null) {
        defaultValues = createServicesMap(jVal);
      }
      ocm.createSubOrganization(realm, defaultValues);
      // Get the Organization Configuration Manager for the new Realm
      realmCreatedOcm = new OrganizationConfigManager(getSSOToken(), realmPath + realm);
      List newServiceNames = realmDetails.get(SERVICE_NAMES).asList();
      if (newServiceNames != null && !newServiceNames.isEmpty()) {
        // assign services to realm
        assignServices(realmCreatedOcm, newServiceNames);
      }
    } catch (SMSException smse) {
      debug.error("RealmResource.createOrganization()", smse);
      throw smse;
    } catch (Exception e) {
      debug.error("RealmResource.createOrganization()", e);
      throw e;
    }
  }
  /** {@inheritDoc} */
  public AMIdentity searchUser(AMIdentityRepository idrepo, Map<String, Set<String>> attr) {
    AMIdentity identity = null;

    if (attr == null || attr.isEmpty()) {
      debug.warning("DefaultAccountMapper.searchUser: empty search");
      return null;
    }

    IdSearchControl ctrl = getSearchControl(IdSearchOpModifier.OR, attr);
    IdSearchResults results;
    try {
      results = idrepo.searchIdentities(IdType.USER, "*", ctrl);
      Iterator<AMIdentity> iter = results.getSearchResults().iterator();
      if (iter.hasNext()) {
        identity = iter.next();
        if (debug.messageEnabled()) {
          debug.message("getUser: user found : " + identity.getName());
        }
      }
    } catch (IdRepoException ex) {
      debug.error(
          "DefaultAccountMapper.searchUser: Problem while searching for the user. IdRepo", ex);
    } catch (SSOException ex) {
      debug.error(
          "DefaultAccountMapper.searchUser: Problem while searching for the user. SSOExc", ex);
    }

    return identity;
  }
Ejemplo n.º 19
0
 /**
  * Returns the Policy Decision Point End Point (PDP) URL.
  *
  * @param pdpEntityID entity Identifier of the PDP.
  * @return the PDP endpoint URL.
  * @exception if there is an error retreiving the endpoint from the configuration.
  */
 private static String getPDPEndPoint(String pdpEntityID) throws SAML2Exception {
   String endPoint = null;
   String classMethod = "QueryClient:getPDPEndPoint";
   if (saml2MetaManager != null) {
     try {
       XACMLPDPDescriptorElement pdpDescriptor =
           saml2MetaManager.getPolicyDecisionPointDescriptor(null, pdpEntityID);
       if (pdpDescriptor != null) {
         List xacmlPDP = pdpDescriptor.getXACMLAuthzService();
         if (xacmlPDP != null) {
           Iterator i = xacmlPDP.iterator();
           while (i.hasNext()) {
             Object o = (Object) i.next();
             if (o instanceof XACMLAuthzServiceElement) {
               XACMLAuthzServiceElement xType = (XACMLAuthzServiceElement) o;
               endPoint = xType.getLocation();
               if (debug.messageEnabled()) {
                 debug.message(classMethod + "EndPoint :" + endPoint);
               }
             }
             break;
           }
         }
       }
     } catch (SAML2MetaException sme) {
       if (debug.messageEnabled()) {
         debug.message(classMethod + "Error retreiving PDP Meta", sme);
       }
       String[] args = {pdpEntityID};
       LogUtil.error(Level.INFO, LogUtil.PDP_METADATA_ERROR, args);
       throw new SAML2Exception(SAML2SDKUtils.BUNDLE_NAME, "pdpMetaRetreivalError", args);
     }
   }
   return endPoint;
 }
  /** {@inheritDoc} */
  public AMIdentity provisionUser(AMIdentityRepository idrepo, Map<String, Set<String>> attributes)
      throws AuthLoginException {

    AMIdentity identity = null;
    try {
      String userId;
      Set<String> idAttribute = attributes.get(idNameAttribute);
      if (idAttribute != null && !idAttribute.isEmpty()) {
        userId = idAttribute.iterator().next();
      } else {
        userId = UUID.randomUUID().toString();
      }
      identity = idrepo.createIdentity(IdType.USER, userId, attributes);
    } catch (IdRepoException ire) {
      debug.error("DefaultAccountMapper.getAccount: IRE ", ire);
      debug.error("LDAPERROR Code = " + ire.getLDAPErrorCode());
      if (ire.getLDAPErrorCode() != null && !ire.getLDAPErrorCode().equalsIgnoreCase("68")) {
        throw new AuthLoginException("Failed to create user");
      }
    } catch (SSOException ex) {
      debug.error(
          "DefaultAccountMapper.getAttributes: Problem while creating the user. SSOExc", ex);
      throw new AuthLoginException("Failed to create user");
    }

    return identity;
  }
Ejemplo n.º 21
0
 /** Gets list of replicated servers from local OpenDJ directory. */
 public static Set getServerSet(LDAPConnection lc) {
   final String[] attrs = {"uniqueMember"};
   Debug debug = Debug.getInstance(SetupConstants.DEBUG_NAME);
   try {
     if (lc != null) {
       LDAPEntry le = lc.read(replDN, attrs);
       if (le != null) {
         Set hostSet = new HashSet();
         LDAPAttribute la = le.getAttribute(attrs[0]);
         if (la != null) {
           Enumeration en = la.getStringValues();
           while (en != null && en.hasMoreElements()) {
             String val = (String) en.nextElement();
             // strip "cn="
             hostSet.add(val.substring(3, val.length()));
           }
         }
         return hostSet;
       } else {
         debug.error(
             "EmbeddedOpenDS:syncOpenDSServer():" + "Could not find trustkey for:" + replDN);
       }
     } else {
       debug.error(
           "EmbeddedOpenDS:syncOpenDSServer():" + "Could not connect to local opends instance.");
     }
   } catch (Exception ex) {
     debug.error("EmbeddedOpenDS.syncOpenDSServer()." + " Error getting replication key:", ex);
   }
   return null;
 }
Ejemplo n.º 22
0
  /** {@inheritDoc} */
  public Promise<ResourceResponse, ResourceException> readInstance(
      Context context, String resourceId, ReadRequest request) {

    final String realm = getRealm(context);

    debug.message("ServerInfoResource :: READ : in realm: " + realm);

    if (COOKIE_DOMAINS.equalsIgnoreCase(resourceId)) {
      return getCookieDomains();
    } else if (ALL_SERVER_INFO.equalsIgnoreCase(resourceId)) {
      return getAllServerInfo(context, realm);
    } else { // for now this is the only case coming in, so fail if otherwise
      final ResourceException e =
          new NotSupportedException("ResourceId not supported: " + resourceId);
      if (debug.errorEnabled()) {
        debug.error(
            "ServerInfoResource :: READ : in realm: "
                + realm
                + ": Cannot receive information on requested resource: "
                + resourceId,
            e);
      }
      return e.asPromise();
    }
  }
Ejemplo n.º 23
0
  /**
   * Method which removes the DC Tree corresponding to the Org
   *
   * @param token SSOToken
   * @param orgDN String representing the DN correponding to the organization
   * @exception AMException if error occured in accessing the org corresponding to orgDN or during
   *     the removal of the dc tree corresponding to the orgDN
   */
  protected void removeDomain(SSOToken token, String orgDN) throws AMException {

    // String orgAttribute[] = {IPLANET_DOMAIN_NAME_ATTR};
    try {
      PersistentObject po = UMSObject.getObject(token, new Guid(orgDN));
      if (!(po instanceof com.iplanet.ums.Organization)) {
        if (debug.messageEnabled()) {
          debug.message("DCTree.removeDomain-> " + orgDN + " is not an organization");
        }
        return;
      }
      String domainName = getCanonicalDomain(token, orgDN);
      if (debug.messageEnabled()) {
        debug.message("DCTree.removeDomain-> " + "Obtained canon domain " + domainName);
      }
      if ((domainName != null) && (domainName.length() > 0)) {
        DomainComponentTree dcTree = new DomainComponentTree(token, new Guid(DCTREE_START_DN));
        if (debug.messageEnabled()) {
          debug.message("DCTree.removeDomain: removing domain: " + domainName);
        }
        dcTree.removeDomain(domainName);
      } else {
        if (debug.warningEnabled()) {
          debug.warning("DCTree.removeDomain(): " + " unable to get domain for " + orgDN);
        }
      }
    } catch (UMSException ue) {
      if (debug.warningEnabled()) {
        debug.warning("DCTree.removeDomain(): ", ue);
      }
    }
  }
Ejemplo n.º 24
0
  /**
   * Perform a remote setProperty on the Session using the remote Service URL.
   *
   * <p>{@inheritDoc}
   */
  public void setProperty(Session session, String name, String value) throws SessionException {
    if (debug.messageEnabled()) {
      debug.message(MessageFormat.format("Remote setProperty {0} {1}={2}", session, name, value));
    }

    SessionID sessionID = session.getID();
    SessionRequest sreq =
        new SessionRequest(SessionRequest.SetProperty, sessionID.toString(), false);
    sreq.setPropertyName(name);
    sreq.setPropertyValue(value);
    if (SystemProperties.isServerMode() && InternalSession.isProtectedProperty(name)) {
      try {
        SSOToken admSSOToken = SessionUtils.getAdminToken();
        sreq.setRequester(RestrictedTokenContext.marshal(admSSOToken));
      } catch (SSOException e) {
        throw new SessionException(e);
      } catch (Exception e) {
        throw new SessionException(e);
      }

      if (debug.messageEnabled()) {
        debug.message(
            "Session.setProperty: "
                + "added admSSOToken in sreq to set "
                + "externalProtectedProperty in remote server");
      }
    }
    requests.sendRequestWithRetry(session.getSessionServiceURL(), sreq, session);
  }
Ejemplo n.º 25
0
  /**
   * Method which creates a <Code>Domain Component Tree </Code> for the given organization, if the
   * <code>sunPreferredDomain</code> attribute is present and has a fully qualified domain name as
   * value.
   *
   * @param token SSO Token
   * @param orgGuid identifiication of organization entry to be mapped from <Code>dctree</Code> to
   *     organization DIT organization
   * @param attrSet the attributes to be set on creation of domain.
   * @exception AMException if unsuccessful in creating a dc tree for the organization or
   *     unsuccessful in setting the mapping between dc tree and the organization
   */
  protected void createDomain(SSOToken token, Guid orgGuid, AttrSet attrSet)
      throws AMException, SSOException {
    if (DCTREE_START_DN == null) {
      throw new AMException(AMSDKBundle.getString("355"), "355");
    }

    // Create a DC tree is value is specified for
    // sunPreferredDomain attribute
    String domainName = attrSet.getValue(IPLANET_DOMAIN_NAME_ATTR);
    // remove the attribute from the attribute set.
    attrSet.remove(IPLANET_DOMAIN_NAME_ATTR);
    if ((domainName != null) && (domainName != "")) {
      try {
        DomainComponentTree dcTree = new DomainComponentTree(token, new Guid(DCTREE_START_DN));
        dcTree.addDomain(domainName);
        // Set the domain mapping
        dcTree.setDomainMapping(domainName, orgGuid);
        String status = attrSet.getValue(INET_DOMAIN_STATUS_ATTR);
        if (status != null) {
          dcTree.setDomainStatus(domainName, status);
        }
        AttrSet[] attrSetArray = splitAttrSet(orgGuid.getDn(), attrSet);
        if (attrSetArray[1] != null) {
          setDomainAttributes(token, orgGuid.getDn(), attrSetArray[1]);
        }
      } catch (InvalidDCRootException ie) {
        debug.error("DCTree.createDomain(): ", ie);
        throw new AMException(AMSDKBundle.getString("343"), "343");
      } catch (UMSException ue) {
        debug.error("DCTree.createDomain(): ", ue);
        throw new AMException(AMSDKBundle.getString("344"), "344");
      }
    }
  }
Ejemplo n.º 26
0
 /**
  * Response message carries a LDAP error. Response with the code 0 (SUCCESS), should never be
  * received as persistent search never completes, it has to be abandon. Referral messages are
  * ignored
  */
 protected boolean processResponseMessage(LDAPResponse rsp, Request request) {
   _retryErrorCodes = getPropertyRetryErrorCodes(EVENT_CONNECTION_ERROR_CODES);
   int resultCode = rsp.getResultCode();
   if (_retryErrorCodes.contains("" + resultCode)) {
     if (debugger.messageEnabled()) {
       debugger.message(
           "EventService.processResponseMessage() - "
               + "received LDAP Response for requestID: "
               + request.getRequestID()
               + " Listener: "
               + request.getListener()
               + "Need restarting");
     }
     resetErrorSearches(false);
   } else if (resultCode != 0 || resultCode != LDAPException.REFERRAL) {
     // If not neither of the cases then
     if (resultCode == LDAPException.BUSY) {
       debugger.error(
           "EventService.processResponseMessage() - received error BUSY, call retryManager");
       return retryManager(false);
     }
     LDAPException ex =
         new LDAPException(
             "Error result", rsp.getResultCode(), rsp.getErrorMessage(), rsp.getMatchedDN());
     dispatchException(ex, request);
   }
   return true;
 }
Ejemplo n.º 27
0
 @Override
 public void updateRefreshToken(RefreshToken refreshToken) {
   try {
     deleteRefreshToken(refreshToken.getTokenId());
     tokenStore.create(refreshToken);
   } catch (CoreTokenException e) {
     logger.error(
         "DefaultOAuthTokenStoreImpl::Unable to create refresh token " + refreshToken.getTokenId(),
         e);
     throw new OAuthProblemException(
         Status.SERVER_ERROR_INTERNAL.getCode(),
         "Internal error",
         "Could not create token in CTS",
         null);
   } catch (InvalidRequestException e) {
     logger.error(
         "DefaultOAuthTokenStoreImpl::Unable to delete refresh token " + refreshToken.getTokenId(),
         e);
     throw new OAuthProblemException(
         Status.SERVER_ERROR_INTERNAL.getCode(),
         "Internal error",
         "Could not delete token in CTS",
         null);
   }
 }
Ejemplo n.º 28
0
  /** Create naming event from a change control */
  private DSEvent createDSEvent(LDAPEntry entry, LDAPEntryChangeControl changeCtrl, Request req)
      throws Exception {
    DSEvent dsEvent = new DSEvent();

    if (debugger.messageEnabled()) {
      debugger.message(
          "EventService.createDSEvent() - Notifying event " + "to: " + req.getListener());
    }

    // Get the dn from the entry
    String dn = entry.getDN();
    dsEvent.setID(dn);

    // Get information on the type of change made
    int changeType = changeCtrl.getChangeType();
    dsEvent.setEventType(changeType);

    // Pass the search ID as the event's change info
    dsEvent.setSearchID(req.getRequestID());

    // set the object class name
    String className = entry.getAttribute("objectclass").toString();
    dsEvent.setClassName(className);

    return dsEvent;
  }
  @Override
  public boolean action(InternalSession is, Map<String, Long> sessions) {

    String nextExpiringSessionID = null;
    long smallestExpTime = Long.MAX_VALUE;
    for (Map.Entry<String, Long> entry : sessions.entrySet()) {
      String sid = entry.getKey();
      long expirationTime = entry.getValue();
      if (expirationTime < smallestExpTime) {
        smallestExpTime = expirationTime;
        nextExpiringSessionID = sid;
      }
    }
    if (nextExpiringSessionID != null) {
      SessionID sessID = new SessionID(nextExpiringSessionID);
      try {
        Session s = sessionCache.getSession(sessID);
        s.destroySession(s);
      } catch (SessionException e) {
        if (debug.messageEnabled()) {
          debug.message("Failed to destroy the next " + "expiring session.", e);
        }
        // deny the session activation request
        // in this case
        return true;
      }
    }
    return false;
  }
Ejemplo n.º 30
0
  /**
   * Converts a JAXB object to a <code>org.w3c.dom.Element</code>.
   *
   * @param jaxbObj a JAXB object
   * @return a <code>org.w3c.dom.Element</code>
   * @throws JAXBException if an error occurs while converting JAXB object.
   * @supported.api
   */
  public static Element convertJAXBToElement(Object jaxbObj, boolean checkIdref)
      throws JAXBException {
    Marshaller m = jc.createMarshaller();
    try {
      m.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapperImpl());

    } catch (PropertyException ex) {
      debug.error("Utils.convertJAXBToElement", ex);
    }

    if (!checkIdref) {
      m.setEventHandler(
          new DefaultValidationEventHandler() {
            public boolean handleEvent(ValidationEvent event) {
              if (event instanceof NotIdentifiableEvent) {
                return true;
              }
              return super.handleEvent(event);
            }
          });
    }

    Document doc = null;
    try {
      doc = XMLUtils.newDocument();
    } catch (Exception ex) {
      debug.error("Utils.convertJAXBToElement:", ex);
    }
    m.marshal(jaxbObj, doc);
    return doc.getDocumentElement();
  }