Showing posts with label API. Show all posts
Showing posts with label API. Show all posts

Friday, January 10, 2014

Provisioning OID Groups to User as Per Assigned Roles in OIM

Here is the sample java code to provision groups in OID to user as per the assigned role in OIM. The roles have access policy attached to them.


import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import com.thortech.xl.vo.AccessPolicyResourceData;
import com.thortech.xl.vo.PolicyChildTableRecord;
import oracle.iam.identity.rolemgmt.api.RoleManager;
import oracle.iam.identity.rolemgmt.vo.Role;
import oracle.iam.identity.usermgmt.api.UserManager;
import oracle.iam.identity.usermgmt.vo.User;
import oracle.iam.platform.OIMClient;
import oracle.iam.platform.Platform;
import Thor.API.tcResultSet;
import Thor.API.tcUtilityFactory;
import Thor.API.Operations.tcAccessPolicyOperationsIntf;
import Thor.API.Operations.tcFormInstanceOperationsIntf;
import Thor.API.Operations.tcLookupOperationsIntf;
import Thor.API.Operations.tcObjectOperationsIntf;
import Thor.API.Operations.tcUserOperationsIntf;

public class ForceUserProvisioning {
 private static final String OIM_URL = "t3s://<>:14001";
 private static final String AUTH_CONF = "<>";
 private static final String OIM_USERNAME = "<>";
 private static final String OIM_PASSWORD = "<>";
 private static OIMClient oimClient = null;
 Hashtable env = new Hashtable();
 private static final String LOOKUP_COLUMN_DECODE = "Lookup Definition.Lookup Code Information.Decode";
 public tcAccessPolicyOperationsIntf moAccesspolicyutility;
 private tcObjectOperationsIntf objectOp = null;
 private tcUserOperationsIntf userOp = null;
 private tcFormInstanceOperationsIntf formOp = null;

 public ForceUserProvisioning() {
  try {
   env.put(OIMClient.JAVA_NAMING_FACTORY_INITIAL,
     "weblogic.jndi.WLInitialContextFactory");
   env.put(OIMClient.JAVA_NAMING_PROVIDER_URL, OIM_URL);
   System.setProperty("java.security.auth.login.config", AUTH_CONF);
   System.setProperty("OIM.AppServerType", "wls");
   System.setProperty("APPSERVER_TYPE", "wls");
   oimClient = new OIMClient(env);
   oimClient.login(OIM_USERNAME, OIM_PASSWORD.toCharArray());
  } catch (Exception e) {
   e.printStackTrace();
  }
 }


//This method add the groups to the user in OID
 public void updateUserGroups(String userLogin) {
  try {
   HashSet existingUserGroups = new HashSet();
   Long userKey = Long.parseLong(getUserKey(userLogin));
   userOp = oimClient.getService(tcUserOperationsIntf.class);
   objectOp = oimClient.getService(tcObjectOperationsIntf.class);
   formOp = oimClient.getService(tcFormInstanceOperationsIntf.class);
   tcResultSet userObjects = userOp.getObjects(userKey);
            String objName = userObjects.getStringValue("Objects.Name"); // OID User 
            long procKey = userObjects.getLongValue("Process Instance.Key"); 
            long  objKey = userObjects.getLongValue("Objects.Key"); 
            long  childFormKey;
            long parentformkey = formOp.getProcessFormDefinitionKey(procKey); 
            int parentformver = formOp.getProcessFormVersion(procKey); 
            tcResultSet childforms = formOp.getChildFormDefinition(parentformkey, parentformver); 
            String plChildTableName = childforms.getStringValue("Structure Utility.Table Name"); 
            long formkey = childforms.getLongValue("Structure Utility.Child Tables.Child Key"); 
            tcResultSet childFormData = formOp.getProcessFormChildData(formkey, procKey); 
            HashSet groupSet =  getAccessPolicyMapping(userLogin);
            for(int k =0;k             childFormData.goToRow(k);
             String group = childFormData.getStringValue("UD_OID_GRP_GROUP_NAME");


//Get existing set of groups assigned to the user.
             existingUserGroups.add(group);


//This will remove the extra groups which shouldn't be assigned to the user as per the assigned roles.

             if(!groupSet.contains(group)) {
              System.out.println ("Removing Group " + group);
             long plChildFormPrimaryKey = childFormData.getLongValue("UD_OID_GRP_KEY");
             formOp.removeProcessFormChildData( formkey, plChildFormPrimaryKey );
             }
            }       

// This add groups as per the roles.
     
             HashSet addGroups = new HashSet(groupSet);
             addGroups.removeAll(existingUserGroups);
             Iterator itrAdd = addGroups.iterator();
             System.out.println(" Add " + addGroups.size());
             if(addGroups.size()!=0) {
             while(itrAdd.hasNext()) {
              String groupName = itrAdd.next().toString();
              HashMap groupHash = new HashMap(); 
              groupHash.put("UD_OID_GRP_GROUP_NAME", groupName); 
              System.out.println(" Add " + groupName);
            formOp.addProcessFormChildData(formkey, procKey, groupHash);
             }
             }         
  }catch(Exception e) {
   e.printStackTrace();
  }
 }

//Get list of groups that needs to be assigned as per the Access Policy attached to the assigned roles in OIM

 public HashSet getAccessPolicyMapping(String userLogin) {
  HashSet mappingSet = new HashSet();
  try {
   tcUtilityFactory ioUtilityFactory = new tcUtilityFactory(env,
     OIM_USERNAME, OIM_PASSWORD);
   moAccesspolicyutility = (tcAccessPolicyOperationsIntf) ioUtilityFactory
   .getUtility("Thor.API.Operations.tcAccessPolicyOperationsIntf");
   HashSet roleSet = getUserRoles(userLogin);
   System.out.println(" Roles Assigned to the User " + userLogin + " are " + roleSet.toString());
   Iterator itr = roleSet.iterator();
   while(itr.hasNext()) {
    String policyName = itr.next().toString();
    HashMap searchPolicy = new HashMap();
    searchPolicy.put("Access Policies.Name", policyName);
    tcResultSet result = moAccesspolicyutility
      .findAccessPolicies(searchPolicy);
    HashMap parentFormData = new HashMap();
    ArrayList groupList = new ArrayList();
    for (int i = 0; i < result.getTotalRowCount(); i++) {
     result.goToRow(i);
     long policyKey = result.getLongValue("Access Policies.Key");
     tcResultSet policyresult = moAccesspolicyutility
       .getDataSpecifiedFor(policyKey);
     for (int f = 0; f < policyresult.getTotalRowCount(); f++) {
      policyresult.goToRow(f);
      long formKey = policyresult
        .getLongValue("Structure Utility.Key");
      long objectKey = policyresult.getLongValue("Objects.Key");
      tcResultSet groupResult = moAccesspolicyutility
        .getAssignedGroups(policyKey);
      for (int j = 0; j < groupResult.getTotalRowCount(); j++) {
       groupResult.goToRow(j);
       AccessPolicyResourceData policyData = moAccesspolicyutility
         .getDataSpecifiedForObject(policyKey,
           objectKey, formKey);
       HashMap pData = policyData
         .getChildTables();
       parentFormData= policyData.getFormData();
       Set formSet = parentFormData.keySet();
       Iterator formIterator = formSet.iterator();
       while(formIterator.hasNext()) {
        String key = formIterator.next().toString();
       }
       Set s = pData.keySet();
       Iterator it = s.iterator();
       while (it.hasNext()) {
        String tableKey = it.next().toString();
        PolicyChildTableRecord[] pChildTableData = policyData
          .getChildTableRecords(tableKey);
        for (int g = 0; g < pChildTableData.length; g++) {
         String EDRGroupName = pChildTableData[g]
           .getValue("UD_OID_GRP_GROUP_NAME");
         //System.out.println(EDRGroupName);
         mappingSet.add(EDRGroupName);
        
        }
       }
      }
     }
    }
   }
  }catch(Exception e) {
   e.printStackTrace();
  }
  return mappingSet;
 }
 

// This method return set containing roles assigned to the user.

 public HashSet getUserRoles(String userLogin) {
  HashSet roleSet = new HashSet();
  try {
   RoleManager rolemanager = oimClient.getService(RoleManager.class);
   List groupList = rolemanager
   .getUserMemberships(getUserKey(userLogin), false);
   for (Role role : groupList) {
    roleSet.add(role.getName().trim());
   }
  }catch(Exception e) {
   e.printStackTrace();
  }
  return roleSet;
 }

 public HashSet readLookup() {
  String lookupDecode = "Lookup.FTB.IgnoreRole";
  HashSet filterRoles = new HashSet();
  try {
  //Read Lookup to Find FilteredRoles
  tcLookupOperationsIntf lookupOps = oimClient.getService(tcLookupOperationsIntf.class);
  tcResultSet lookupResultSet = lookupOps.getLookupValues(lookupDecode);
  for (int i = 0; i < lookupResultSet.getRowCount(); i++) {
   lookupResultSet.goToRow(i);
   String decode = lookupResultSet.getStringValue(
     LOOKUP_COLUMN_DECODE).trim();
   filterRoles.add(decode);
  }
  }catch(Exception e) {
   e.printStackTrace();
  }
  return filterRoles;
 }

 public String getUserKey(String userLogin) {
  UserManager usrMgr = oimClient.getService(UserManager.class);
  User user = null;
  try {
   user = usrMgr.getDetails(userLogin, null, true);
  } catch (Exception e) {
   e.printStackTrace();
  }
  return user.getAttribute("usr_key").toString();
 }


 
  public static void main(String args[]) throws Exception {
   ForceUserProvisioning obj = new ForceUserProvisioning(); 
   obj.updateUserGroups("UserID");
   System.out.println("Program Complete");
  }
 }


Note: I wrote this code for temporary use as in one of the environment, group provisioning via access policy stopped working.

Java Code to Add Entry in Lookup & Display Lookup Values

Here is the same java code to add entry in existing OIM Lookup and display all the Values from an existing OIM Lookup

import java.util.HashMap;
import java.util.Hashtable;
import oracle.iam.platform.OIMClient;
import Thor.API.tcResultSet;
import Thor.API.Operations.tcLookupOperationsIntf;

public class UpdateLookup {

 private static final String OIM_URL = "t3s://<>:14001";
 private static final String AUTH_CONF = "<< Path of authwl.conf >>";
 private static final String OIM_USERNAME = "<< UserID >>";
 private static final String OIM_PASSWORD = "<< Password >>";
 private static OIMClient oimClient = null;
 Hashtable env = new Hashtable();

 public UpdateLookup() {
  try {
   env.put(OIMClient.JAVA_NAMING_FACTORY_INITIAL,
     "weblogic.jndi.WLInitialContextFactory");
   env.put(OIMClient.JAVA_NAMING_PROVIDER_URL, OIM_URL);
   System.setProperty("java.security.auth.login.config", AUTH_CONF);
   System.setProperty("OIM.AppServerType", "wls");
   System.setProperty("APPSERVER_TYPE", "wls");
   oimClient = new OIMClient(env);
   oimClient.login(OIM_USERNAME, OIM_PASSWORD.toCharArray());
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public void addLookupEntry(String LookupCode,String Lookup) {
  try {
   tcLookupOperationsIntf lookupOps = oimClient
     .getService(tcLookupOperationsIntf.class);
   lookupOps.addLookupValue("<>", LookupKey,
     LookupValue, "", "");

  } catch (Exception e) {
   e.printStackTrace();
  }
 }


 public void displayLookup(String lookupname) {
  try {
   tcLookupOperationsIntf lookupOps = oimClient
     .getService(tcLookupOperationsIntf.class);
   tcResultSet values = lookupOps.getLookupValues(lookupname);
   for (int i = 0; i < values.getRowCount(); i++) {
    values.goToRow(i);
    System.out
      .print(values
        .getStringValue("Lookup Definition.Lookup Code Information.Decode"));
    System.out
      .println(","
        + values.getStringValue("Lookup Definition.Lookup Code Information.Code Key"));
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public static void main(String args[]) {
   UpdateLookup obj = new UpdateLookup();
   obj.addLookupEntry("LookupKey","LookupValue");

   obj.displayLookup("LookupName");
 }
}


Reference:

http://docs.oracle.com/cd/E17904_01/apirefs.1111/e17334/toc.htm

Java Code to Create OIM 11g R1 Role Category

Here is the sample java code to create role cateogry in OIM 11gR1:


import java.util.HashMap;
import java.util.Hashtable;
import oracle.iam.identity.rolemgmt.api.RoleCategoryManager;
import oracle.iam.identity.rolemgmt.vo.RoleCategory;
import oracle.iam.identity.rolemgmt.vo.RoleManagerResult;
import oracle.iam.platform.OIMClient;


public class CreateRoleCategory {

 private static final String OIM_URL = "t3s://<>:14001";
 private static final String AUTH_CONF = "<< Path of authwl.conf File >>";
 private static final String OIM_USERNAME = "<< UserID >>";
 private static final String OIM_PASSWORD = "<< Password >>";
 private static OIMClient oimClient = null;
 Hashtable env = new Hashtable();

 public CreateRoleCategory() {
  try {
   env.put(OIMClient.JAVA_NAMING_FACTORY_INITIAL,
     "weblogic.jndi.WLInitialContextFactory");
   env.put(OIMClient.JAVA_NAMING_PROVIDER_URL, OIM_URL);
   System.setProperty("java.security.auth.login.config", AUTH_CONF);
   System.setProperty("OIM.AppServerType", "wls");
   System.setProperty("APPSERVER_TYPE", "wls");
   oimClient = new OIMClient(env);
   oimClient.login(OIM_USERNAME, OIM_PASSWORD.toCharArray());
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public void createCategory(String categoryName, String categoryDescription) {
  try {
   RoleCategoryManager rmgr = oimClient.getService(RoleCategoryManager.class);
   RoleCategory rcategory = new RoleCategory(categoryName);
   rcategory.setDescription(categoryDescription);
   rcategory.setName(categoryName);
   RoleManagerResult result = rmgr.create(rcategory);
   System.out.println(" Role Category " + categoryName + " Status " + result.getStatus());
  }catch(Exception e) {
   e.printStackTrace();
  }
 }


 public  static void main(String args[]) {
  try {
   CreateRoleCategory obj = new CreateRoleCategory();
   obj.createCategory("CategoryName","CategoryDescription");
  }catch(Exception e) {
   e.printStackTrace();
  }
 }
}


References:

http://docs.oracle.com/cd/E17904_01/apirefs.1111/e17334/toc.htm


Thursday, November 7, 2013

OIM 11g: Create Access Policy using JAVA APIs

Here is the sample code to create access policies using JAVA APIs:

package junit.accesspolicy;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import com.thortech.xl.vo.AccessPolicyResourceData;
import com.thortech.xl.vo.PolicyChildTableRecord;
import oracle.iam.identity.rolemgmt.api.RoleManager;
import oracle.iam.identity.rolemgmt.api.RoleManagerConstants.RoleAttributeName;
import oracle.iam.identity.rolemgmt.vo.Role;
import oracle.iam.platform.OIMClient;
import oracle.iam.platform.Platform;
import oracle.iam.platform.entitymgr.vo.SearchCriteria;
import Thor.API.tcResultSet;
import Thor.API.Operations.tcAccessPolicyOperationsIntf;
import Thor.API.Operations.tcFormDefinitionOperationsIntf;
import Thor.API.Operations.tcITResourceInstanceOperationsIntf;
import Thor.API.Operations.tcObjectOperationsIntf;


public class createAccessPolicy { private static final String OIM_URL = "t3s://host:port";
 private static final String AUTH_CONF = "C:/designconsole/config/authwl.conf";
 private static final String OIM_USERNAME = "<>";
 private static final String OIM_PASSWORD = "<>;

 private static OIMClient oimClient = null;
 Hashtable env = new Hashtable();
 HashMap> mapping = new HashMap>();
 public tcAccessPolicyOperationsIntf moAccesspolicyutility;
 private static final String objName = "OID User"; //Object Name private static final String fParentName = "UD_OID_USR"; // Parent Process Form
 private static final String fChildName = "UD_OID_GRP"; // Child Process Form
 private static final String ITResourceName = "OID Server"; // IT Resource
 private static final String groupSuffix = ",cn=Groups,<>"; // Group DN


 public createAccessPolicy() {
  try {
   env.put(OIMClient.JAVA_NAMING_FACTORY_INITIAL,
     "weblogic.jndi.WLInitialContextFactory");
   env.put(OIMClient.JAVA_NAMING_PROVIDER_URL, OIM_URL);
   System.setProperty("java.security.auth.login.config", AUTH_CONF);
   System.setProperty("OIM.AppServerType", "wls");
   System.setProperty("APPSERVER_TYPE", "wls");
   oimClient = new OIMClient(env);
   oimClient.login(OIM_USERNAME, OIM_PASSWORD.toCharArray());
  } catch (Exception e) {
   e.printStackTrace();
  }
  return;
 }


 public void PolicyCreation(String policyName, String[] groups) {
  try {
   tcAccessPolicyOperationsIntf moAccesspolicyutility = oimClient
     .getService(tcAccessPolicyOperationsIntf.class);
   System.out.println(policyName);
   HashMap attr = new HashMap();
   attr.put("Access Policies.Name", policyName); // Policy Name
   attr.put("Access Policies.Description", policyName); // Description same as Policy Name
   attr.put("Access Policies.Retrofit Flag", "1"); // Retrofit Flag
   attr.put("Access Policies.By Request", "0"); // Without Approval

   Long objKey = findObjectKey();
 
  long[] provObjKeys = { objKey }; //Object Key of Resource to be provisioned
   boolean[] revokeObgIsNotApply = { true }; //Revoke If No Longer Applies Flag
   long[] denyObjKeys = {}; //Object key of Resource to be denied
   Long roleKey = Long.parseLong(getRoleKey(policyName)); // Role attached to the Policy
   long[] groupKeys = { roleKey };  //In my case, Policy Name is same as Role Name
   String groupPrefix = findITResourceKey() + "~cn=";
   //Populate Parent Form Data
   HashMap parentFormData = new HashMap();
   parentFormData.put("UD_OID_USR_SERVER",findITResourceKey());
   parentFormData.put("UD_OID_USR_ORG_DN",findITResourceKey()+"~users");
   parentFormData.put("UD_OID_USR_PREF_LANG","en");
   int groupLength = groups.length;
   //Populate Child Form Data
   AccessPolicyResourceData policyData[] = new AccessPolicyResourceData[groupLength+1];
   for (int i = 0; i < groupLength; i++) {
    String groupName = groupPrefix + groups[i].trim() + groupSuffix;
    System.out.println(groupName);
    policyData[i] = new AccessPolicyResourceData(findObjectKey(),
      objName, findParentFormKey(), fParentName, "P");
    HashMap childTableMap = new HashMap();
    childTableMap.put("UD_OID_GRP_GROUP_NAME", groupName);
    policyData[i] = new AccessPolicyResourceData(findObjectKey(),
      objName, findParentFormKey(), fParentName, "P");
    PolicyChildTableRecord pChildTableData = policyData[i]
      .addChildTableRecord(findChildFormKey(), "fChildName",
        "Add", childTableMap);
   }
   System.out.println(policyData.length);
   AccessPolicyResourceData formData = new AccessPolicyResourceData(findObjectKey(),
     objName, findParentFormKey(), fParentName, "P");
   formData.setFormData(parentFormData);
   policyData[groupLength] = formData;
   moAccesspolicyutility.createAccessPolicy(attr, provObjKeys,
     revokeObgIsNotApply, denyObjKeys, groupKeys, policyData);
   System.out.println(policyName + " Policy Created ");
  } catch (Exception e) {
   e.printStackTrace();
  }

 }

 public String findChildFormKey() {
  String ChildformKey = null;
  try {
   final String METHOD_NAME = "findChildFormKey :: ";
   tcFormDefinitionOperationsIntf objIntf = oimClient
     .getService(tcFormDefinitionOperationsIntf.class);
   HashMap attributes = new HashMap();
   attributes.put("Structure Utility.Table Name", fChildName);
   tcResultSet resultSet = objIntf.findForms(attributes);
   for (int i = 0; i < resultSet.getRowCount(); i++) {
    ChildformKey = resultSet
      .getStringValue("Structure Utility.Key");
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return ChildformKey;
 }


 public Long findParentFormKey() {
  String ParentformKey = null;
  try {
   final String METHOD_NAME = "findParentFormKey :: ";
   tcFormDefinitionOperationsIntf objIntf = oimClient
     .getService(tcFormDefinitionOperationsIntf.class);
   HashMap attributes = new HashMap();
   attributes.put("Structure Utility.Table Name", fParentName);
   tcResultSet resultSet = objIntf.findForms(attributes);
   for (int i = 0; i < resultSet.getRowCount(); i++) {
    ParentformKey = resultSet
      .getStringValue("Structure Utility.Key");
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return Long.parseLong(ParentformKey);
 }


 public String findITResourceKey() {
  String ITResourceKey = null;
  try {
   final String METHOD_NAME = "findITResourceKey :: ";
   tcITResourceInstanceOperationsIntf objIntf = oimClient
     .getService(tcITResourceInstanceOperationsIntf.class);
   HashMap attributes = new HashMap();
   attributes = objIntf.getITResourceInstances(ITResourceName);
   Set s = attributes.keySet();
   Iterator it = s.iterator();
   while (it.hasNext()) {
    ITResourceKey = it.next().toString();
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return ITResourceKey;
 }


 public String getRoleKey(String roleName) {
  RoleManager rmgr = oimClient.getService(RoleManager.class);
  Set retAttrs = new HashSet();
  String roleKey = null;
  try {
   retAttrs.add(RoleAttributeName.DISPLAY_NAME.getId());
   SearchCriteria criteria = null;
   criteria = new SearchCriteria(RoleAttributeName.NAME.getId(),
     roleName, SearchCriteria.Operator.EQUAL);
   List roles = rmgr.search(criteria, retAttrs, null);
   roleKey = roles.get(0).getEntityId();
  } catch (Exception e) {
  }
  return roleKey;
 }


 public Long findObjectKey() {
  String objectKey = null;
  try {
   HashMap attributes = new HashMap();
   attributes.put("Objects.Name", objName);
   tcObjectOperationsIntf objIntf = oimClient
     .getService(tcObjectOperationsIntf.class);
   tcResultSet resultSet = objIntf.findObjects(attributes);
   for (int i = 0; i < resultSet.getRowCount(); i++) {
    objectKey = resultSet.getStringValue("Objects.Key");
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return Long.parseLong(objectKey);
 }


 public static void main(String args[]) {
  createAccessPolicy obj = new createAccessPolicy();
  try {
  String Line = null;
  String File = "<>";
  //File Format is #AccessPolicyName,Groups to be added in child form
  BufferedReader buff = new BufferedReader(new FileReader(File));
  buff.readLine();
  while ((Line = buff.readLine()) != null) {
   String split[] = Line.split(",");
   String policyName = split[0].trim();
   String groupList[] = split[1].split(";");
   obj.PolicyCreation(policyName, groupList);
  }
  }catch(Exception e) {
   e.printStackTrace();
  }
 }

}

References:

http://docs.oracle.com/cd/E17904_01/apirefs.1111/e17334/Thor/API/Operations/tcAccessPolicyOperationsIntf.html

http://docs.oracle.com/cd/E27559_01/apirefs.1112/e28159/com/thortech/xl/vo/AccessPolicyResourceData.html

http://docs.oracle.com/cd/E27559_01/apirefs.1112/e28159/com/thortech/xl/vo/PolicyChildTableRecord.html


 

Wednesday, October 23, 2013

OIM11g: Searching & retrieve Authorization Policy Data using APIs

Here is the sample code to search and retrieve "Role Management" type Authorization Policy Data:

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import oracle.iam.authzpolicydefn.api.Action;
import oracle.iam.authzpolicydefn.api.AuthzPolicyConstants.AuthzPolicyAttributes;
import oracle.iam.authzpolicydefn.api.Feature;
import oracle.iam.authzpolicydefn.api.PolicyDefinitionService;
import oracle.iam.authzpolicydefn.vo.AuthzPolicy;
import oracle.iam.authzpolicydefn.vo.RoleDataConstraint;
import oracle.iam.identity.vo.Identity;
import oracle.iam.platform.OIMClient;
import oracle.iam.platform.entitymgr.vo.SearchCriteria;

 public void getPolicyDetails(String policyName) {
  try {
   PolicyDefinitionService policyService = oimClient.getService(PolicyDefinitionService.class);
   SearchCriteria criteria = new SearchCriteria(AuthzPolicyAttributes.NAME.getId(),policyName,SearchCriteria.Operator.EQUAL);
   List policies = policyService.search(criteria);
   for (AuthzPolicy policy : policies) {


// Returns Display Name of Policy
    System.out.println(" Policy Name : " + policy.getDisplayName()); 


//Returns Description of the Policy
    System.out.println(" Description : " + policy.getDescription());   


//Returns the Enabled Permissions
    List
actions = policy.getActions();
    for(Action action: actions) {
     System.out.println(action.getDisplayName());
    }
  
    //Returns Type of Policy i.e., Role Management
    Feature features = policy.getFeature();
    System.out.println(" Entity Name : " + features.getDisplayName());
  
    //Returns the Assignment i.e., roles that are added to the Policy
    ArrayList
userList = policy.getRoleAssignees();
  for(Identity id: userList) {
   System.out.println(" Assign by Role : " + id.getAttribute("Role Name"));
  }

// Data Constraints i.e., Returns the Role Name attached with Policy
 RoleDataConstraint rDataConstraint = (RoleDataConstraint) policy.getDataSecurity();
 ArrayList
roles = rDataConstraint.getRoles();
 for(Identity role: roles) {
  System.out.println(role.getAttribute("Role Name"));
 }
}
}
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}

Note: The APIs used above are not documented by Oracle.

OIM: Code to get Recon Event Data given a Recon Event Key

Here is a sample code to get the Recon Event Information & Recon Target Attibute given a Recon Event Key

 public void getReconEventData() {
  try {
   ReconOperationsService reconOpService = oimClient.getService(ReconOperationsService.class);
   EventMgmtService eventService = oimClient.getService(EventMgmtService.class);
   ReconSearchCriteria criteria = new ReconSearchCriteria() ;
   Vector order = new Vector();
   order.add(EventConstants.RECON_EVENT_KEY);
   boolean ascOrderFlag = true;
   Object reKey = 2901; // Recon Event Key
   criteria.addExpression(EventConstants.RECON_EVENT_KEY, reKey, ReconSearchCriteria.Operator.EQUAL);
   List output = eventService.search(criteria,order, ascOrderFlag, 0, 100);
  
   for(ReconEvent event: output) {
    System.out.println(" Profile Name " + event.getProfileName());
    System.out.println(" Key Fields " + event.getReKeyField());
    System.out.println(" Resource Name " + event.getResourceName());
    System.out.println(" Current Status " + event.getReStatus());
    System.out.println(" Entity " + event.getReEntityType());
    System.out.println(" Date and Time " + event.getReModify());
    System.out.println(" Job ID " + event.getRjKey());
    System.out.println(" Linked By " + event.getLinkSource()); 
    ReconEventData eventData = eventService.getReconEventData(event);
    List reconAttributes = eventData.getSingleValuedAttrs();
    System.out.println(reconAttributes.size());
    for(ReconTargetAttribute reconAttribute: reconAttributes) {
     System.out.print(reconAttribute.getOimMappedFieldDescription()+" - ");
     System.out.println(reconAttribute.getStringVal());
    }
   }


References:

http://docs.oracle.com/cd/E14571_01/apirefs.1111/e17334/oracle/iam/reconciliation/api/ReconOperationsService.html
http://docs.oracle.com/cd/E17904_01/apirefs.1111/e17334/
http://docs.oracle.com/cd/E17904_01/apirefs.1111/e17334/oracle/iam/reconciliation/vo/ReconSearchCriteria.html#addExpression_java_lang_String__java_lang_Object__oracle_iam_reconciliation_vo_ReconSearchCriteria_Operator_http://docs.oracle.com/cd/E17904_01/apirefs.1111/e17334/oracle/iam/reconciliation/vo/ReconTargetAttribute.html

Thursday, October 10, 2013

Reading OIM System Property in Custom Code

Here are the APIs to read/create/update System Property in OIM:


// You can use this API to only read the system property
tcPropertyOperationsIntf property = Platform.getService(tcPropertyOperationsIntf.class);
String pvalue = property.getPropertyValue("Property Name");
 

// You can use this API to read/create/update/delete the system property
SystemConfigurationService sc = Platform.getService(SystemConfigurationService.class);
SystemProperty sr = sc.getSystemProperty("Property Name");
String pvalue = sr.getPtyValue();


API Reference:

http://docs.oracle.com/cd/E27559_01/apirefs.1112/e28159/oracle/iam/conf/api/SystemConfigurationService.html

http://docs.oracle.com/cd/E23943_01/apirefs.1111/e17334/Thor/API/Operations/tcPropertyOperationsIntf.html
 

Monday, September 9, 2013

OIM: How to Disable/Enable User Resource Object using API

Here is the sample code to disable the resource objects allocated to a user:
 
 
Long userKey = Long.parseLong(getUserKey(
"y9506a"));
 
userOp = oimClient.getService(tcUserOperationsIntf.class);
 
tcResultSet userObjects = userOp.getObjects(userKey);
 
Long processKey = userObjects.getLongValue(Users-Object Instance For User.Key");
 
 // Disable the Resource Object
 
userOp.disableAppForUser(userKey, processKey);
 
// Enable the Resource Object
 
userOp.enableAppForUser(userKey, processKey);
 
String ostatus = userObjects.getStringValue(
"Objects.Object Status.Status");
 
System.
out.println(ostatus);






 

Thursday, August 29, 2013

OIM - Code to Revoke Resource Object from User Profile

Here is the sample code to revoke the resource object for a user:
 
   Long userKey = getUserKey("OIMUSER0176");
   tcUtilityFactory ioUtilityFactory = new tcUtilityFactory(env,
     OIM_USERNAME, OIM_PASSWORD);
   userOp = (tcUserOperationsIntf) ioUtilityFactory
     .getUtility("Thor.API.Operations.tcUserOperationsIntf");
   tcResultSet resultSet = userOp.getObjects(userKey);
   long key = resultSet.getLongValue("Users-Object Instance For User.Key");
   userOp.revokeObject(userKey, key);

 
 
       

Saturday, February 2, 2013

OIM11g: Bulk Load the Data in Access Policies

Hi All,

The requirement for the code that you see below comes from my client who while learning to create access policies asked me below question:

In OIM, you cannot add multiple groups in single iteration to AccessPolicy but you can remove multiple groups. What's the rationale behind this?

Well, I couldn't agree more with him and I have no answer for him and before he could throw any other question or think of asking me to modifying the OIM UI to provide capability to add multiple groups to Access Policy, I told him that I can create a Bulk Data Load Utility which can be used for loading the groups in bulk to access policies and below is the code for that:

package security.provisioning;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.thortech.xl.vo.AccessPolicyResourceData;
import com.thortech.xl.vo.PolicyChildTableRecord;
import Thor.API.tcResultSet;
import Thor.API.Operations.tcAccessPolicyOperationsIntf;
import oracle.iam.identity.rolemgmt.api.RoleManager;
import oracle.iam.identity.rolemgmt.api.RoleManagerConstants.RoleAttributeName;
import oracle.iam.identity.rolemgmt.vo.Role;
import oracle.iam.platform.Platform;
import oracle.iam.platform.entitymgr.vo.SearchCriteria;
import oracle.iam.scheduler.vo.TaskSupport;
import com.thortech.util.logging.Logger;

public class InitialAccessPolicyLoad extends TaskSupport {
 HashMap> mapping = new HashMap>();
 tcAccessPolicyOperationsIntf moAccesspolicyutility = null;
 private static final Logger logger = Logger.getLogger("SECURITY.EVENTS");
 private static final String CLASS_NAME = "security.provisioning.InitialAccessPolicyLoad : ";
 private static final long formKey = 25;
 private static final long objectKey = 24;
 private static final String tableKey = "22";
 private static final String objName = "OID User";
 private static final String fName = "UD_OID_USR";
 private static final String groupPrefix ="41~cn=";
 private static final String groupSuffix=",cn=Groups,dc=sample,dc=com";

 public void execute(HashMap arg0) {
  final String METHOD_NAME = "execute :: ";
  try {

   logger.debug(CLASS_NAME + METHOD_NAME + "Entering Method - execute");
   // Output File Name
   String inputFileName = arg0.get("Input File Name").toString();
   logger.debug(CLASS_NAME + METHOD_NAME + " Input File Name "
     + inputFileName);

   // Delimiter for EDR Group List
   String ROLE_DELIMITER = arg0.get("List Delimiter").toString();
   logger.debug(CLASS_NAME + METHOD_NAME + " List Delimiter "
     + ROLE_DELIMITER);

   // Delimiter for the Attributes in the Input File
   String FILE_DELIMITER = arg0.get("Field Delimiter").toString();
   logger.debug(CLASS_NAME + METHOD_NAME + " Field Delimiter "
     + FILE_DELIMITER);

   // Read Input File
   BufferedReader buff = new BufferedReader(new FileReader(inputFileName));
   buff.readLine();
   String Line = null; 
   boolean isValidRecord = true;
   String PolicyName = null;
   String RoleName = null;
   String Groups = null;
   ArrayList GroupList = new ArrayList();
   while ((Line = buff.readLine()) != null) {
  
    if (Line.startsWith("#")) {
     isValidRecord = false;
    }
  
    String[] values = Line.split(FILE_DELIMITER);
  
    if (values.length == 1) {
     PolicyName = values[0];
     isValidRecord = false;

    } else if (values.length == 2) {
     PolicyName = values[0];
     RoleName = values[1];
     isValidRecord = false;

    } else if (values.length == 3) {
     isValidRecord = true;
     PolicyName = values[0];
     RoleName = values[1];
     Groups = values[2];
     String[] gList = Groups.split(ROLE_DELIMITER);
     for(int i=0;i      GroupList.add(gList[i]);
     }
    }
  
  
    if (isValidRecord) {
     uploadPolicyData(PolicyName,RoleName,GroupList);
     logger.debug(CLASS_NAME + METHOD_NAME + "ADDING RECORD: " + Line);
    } else {
     logger.debug(CLASS_NAME + METHOD_NAME + "INVALID RECORD: " + Line);
    }

   }
   

   logger.info(CLASS_NAME + METHOD_NAME
     + " Access Policies Data Loaded");

  } catch (Exception e) {
   logger.error(CLASS_NAME + METHOD_NAME + e.getMessage());
  }
 }

 public void uploadPolicyData(String PolicyName, String RoleName, ArrayList GroupList) {
  final String METHOD_NAME = "uploadPolicyData :: ";

  try {

   tcAccessPolicyOperationsIntf moAccesspolicyutility = Platform
     .getService(tcAccessPolicyOperationsIntf.class);
   HashMap searchPolicy = new HashMap();
   searchPolicy.put("Access Policies.Name", PolicyName);
   tcResultSet result = moAccesspolicyutility.findAccessPolicies(searchPolicy);
 
   long policyKey = result.getLongValue("Access Policies.Key");
   logger.debug(CLASS_NAME + METHOD_NAME + "Access Policies.Key" +policyKey);
 
   Long roleKey = Long.parseLong(getRoleKey(RoleName));
   long[] roleKeys = { roleKey };
 
   //Add the Role NAME
   moAccesspolicyutility.assignGroups(policyKey, roleKeys);
   logger.info(CLASS_NAME + METHOD_NAME
     + " Role: "+ RoleName +" is attached to the Access Policy: " + PolicyName);
 
   for(int i = 0;i  
    HashMap childTableMap = new HashMap();
    String groupName = groupPrefix+GroupList.get(i)+groupSuffix;
    logger.debug(CLASS_NAME + METHOD_NAME + "OID Group Name: " +groupName);
    childTableMap.put("UD_OID_GRP_GROUP_NAME", groupName);
    AccessPolicyResourceData policyData = new AccessPolicyResourceData(objectKey,objName,formKey,fName,"P");
    PolicyChildTableRecord pChildTableData = policyData.addChildTableRecord(tableKey, "UD_OID_GRP", "Add", childTableMap);
    moAccesspolicyutility.setDataSpecifiedForObject(policyKey, objectKey, formKey, policyData);
    logger.info(CLASS_NAME + METHOD_NAME
      + " Group: "+ GroupList.get(i) +" attached to the Access Policy: " + PolicyName);
   }

  } catch (Exception e) {
   logger.error(CLASS_NAME + METHOD_NAME + e.getMessage());
  }
 }



 public String getRoleKey(String roleName) {

  final String METHOD_NAME = "getRoleKey :: ";
  System.out.println(CLASS_NAME + METHOD_NAME
    + "Entering Method - getRoleKey");

  RoleManager rmgr = Platform.getService(RoleManager.class);
  Set retAttrs = new HashSet();
  String roleKey = null;
  try {
   retAttrs.add(RoleAttributeName.DISPLAY_NAME.getId());
   SearchCriteria criteria = null;
   criteria = new SearchCriteria(RoleAttributeName.NAME.getId(),
     roleName, SearchCriteria.Operator.EQUAL);
   List roles = rmgr.search(criteria, retAttrs, null);
   roleKey = roles.get(0).getEntityId();
  } catch (Exception e) {
   logger.error(CLASS_NAME + METHOD_NAME + e.getMessage());
  }
  return roleKey;
 }

 // Method to check if  Role exists in OIM or not
 public boolean isRoleExist(String[] roles) {

  String METHOD_NAME = "isRoleExist :: ";
  logger.debug(CLASS_NAME + METHOD_NAME +"Entering Method - isRoleExist");
  boolean roleExist = false;
  boolean roleListEmpty = false;
  if(Arrays.toString(roles).length() == 2) {
   roleListEmpty = true;
  }

  try {
   if (!roleListEmpty) {
   RoleManager rmgr = Platform.getService(RoleManager.class);
   Set retAttrs = new HashSet();
   retAttrs.add(RoleAttributeName.DISPLAY_NAME.getId());
   SearchCriteria criteria = null;
   for (int i = 0; i < roles.length; i++) {
    criteria = new SearchCriteria(RoleAttributeName.NAME.getId(),
      roles[i], SearchCriteria.Operator.EQUAL);
    List role = rmgr.search(criteria, retAttrs, null);
    if (role.size() != 0) {
     roleExist = true;
    } else {
     logger.debug(CLASS_NAME + METHOD_NAME + roles[i]
       + " DOESN'T EXIST IN OIM");
     roleExist = false;
    }
   }
  }
   }catch (Exception e) {
    logger.error(CLASS_NAME + METHOD_NAME + e.getMessage());
  }
  return roleExist;
 }

 public HashMap getAttributes() {
  return null;
 }

 public void setAttributes() {
 }

}
I don't know how easy/hard is to modify the UI to provide the capability but considering this as "Nice To Have" requirement, I think the above solution is good enough. There are couple of things like Checking if OID Group exist or not or update(add & delete) the Groups I might need to add later.

Note: This code is specific to OID Resource and assume that access policy is already created.