Sun Java System Access Manager 7 2005Q4 Developer's Guide

Chapter 6 Using the Policy APIs

The Sun JavaTM System Access Manager 7 2005Q4 Policy Service enables you to define, manage, and enforce policies that control access to protected resources. Administrators use the Policy Service to configure and manage conditions for applications, resources, and identities managed within the Access Manager deployment. For detailed information about what the Policy Service does and how it works, see Chapter 4, Authorization and the Policy Service, in Sun Java System Access Manager 7 2005Q4 Technical Overview.

This chapter provides information about the Policy APIs and how to use them to enable your service to use Access Manager policies. The chapter includes the following topics:

About the Policy APIs

The Policy Java APIs enable you to do the following:

This chapter describes Java Policy Service packages and classes, and provides instructions for using the Policy APIs and code samples. For a comprehensive listing of Policy Java methods and their usage, see the Sun Java System Access Manager 7 2005Q4 Java API Reference.

Access Manager also provides C APIs to enable external applications to connect to the Policy Service framework. For information about using the Policy C APIs, see Chapter 6, Policy Functions, in Sun Java System Access Manager 7 2005Q4 C API Reference Chapter 6, Policy Functions, in Sun Java System Access Manager 7 2005Q4 C API Reference.

Policy Java Packages

The following Java packages comprise the Policy APIs:

com.sun.identity.policy

Contains policy evaluation classes for policy administration and evaluation. Policy evaluation classes from this package require a direct connection to the policy data store. These classes should be used with caution, and only when classes from com.sun.identity.policy.client cannot handle your use case.

com.sun.identity.policy.client

Contains classes used by remote Java applications to evaluate policies and to get policy decisions.

com.sun.identity.policy.interfaces

Contains interfaces for writing custom Policy plug-ins for conditions, subjects, referrals and resources.

Policy Management Classes

Policy Management classes are used by system administrators to manage policies in Access Manager. The interfaces for this functionality are contained in the com.sun.identity.policy package and including the following:

PolicyManager

com.sun.identity.policy.PolicyManager is the top-level administrator class for policy management. com.sun.identity.policy.PolicyManager provides methods that enable an administrator to create, modify, or delete realm policies. The PolicyManager can be obtained by passing a privileged user’s session token or by passing a privileged user’s session token with a realm name. Some of the more widely used methods of this class include the following:

getPolicyNames

Retrieves all named policies created for the realm for which the policy manager was instantiated. This method can also take a pattern (filter) as an argument.

getPolicy

Retrieves a policy when given the policy name.

addPolicy

Adds a policy to the specified realm. If a policy with the same name already exists, it will be overwritten.

removePolicy

Removes a policy from the specified realm.

replacePolicy

Replaces policy with a new policy.

Policy

com.sun.identity.policy.Policy represents a policy definition with all its intended parts (rules, subjects, referrals, conditions, and response providers). The policy object is saved in the data store if the addPolicy or replacePolicy methods from the PolicyManager class are invoked. This class contains methods for adding, removing, replacing or getting any of the parts of a policy definition.

Policy Evaluation Classes

Policy evaluation classes compute policy decisions which allow or deny access to a protected resource. Policy evaluation classes are contained com.sun.identity.policy package and include the following:

PolicyEvaluator Class

com.sun.identity.policy.PolicyEvaluator can be integrated into Java applications to evaluate policy privileges and provide policy decisions. This class provides support for both boolean and non-boolean type policies. Create a PolicyEvaluator by calling the constructor with a service name. Public methods of this class include the following:

isAllowed

Evaluates the policy associated with the given resource and returns a boolean value indicating whether the policy evaluation resulted in an allow or deny.

getPolicyDecision

Evaluates policies and returns decisions. Returns a decision that gives a user permission to perform specified actions on a specified resource.

getResourceResult

Obtains the policy and decisions for a hierarchy of resources. Possible values for the scope of this method are self, subtree, and strict-subtree. Use the self value to get the policy decision for the specified resource only. Use the subtree value to include the policy decisions for all resources defined in the policies which are sub-resources of the specified resource.

For example, the PolicyEvaluator class can be used to display the links for a list of resources to which an authenticated user has access. The getResourceResult method is used to get the list of resources. The resourceName parameter would be http://host.domain:port which returns all the resources to which the user has access on that server. These resources are returned as a PolicyDecision based on the user’s defined policies. If the user is allowed to access resources on different servers, this method needs to be called for each server.


Note –

Not all resources that have policy decisions are accessible to the user. Access depends on ActionDecision(s) contained in policy decisions.


ProxyPolicyEvaluator Class

com.sun.identity.policy.ProxyPolicyEvaluator allows a privileged user (top-level administrator, organization administrator, policy administrator, or organization policy administrator) to get policy privileges and evaluate policy decisions for any user in their respective scope of administration. com.sun.identity.policy.ProxyPolicyEvaluatorFactory is the singleton class used to get ProxyPolicyEvaluator instances.


Example 6–1 Public Methods For ProxyPolicyEvaluator


    /**
     * Evaluates a simple privilege of boolean type. The privilege
     * indicates if the user identified by the principalName
     * can perform specified action on the specified resource.
     *
     * @param principalName principal name for whom to
     * compute the privilege.
     * @param resourceName name of the resource
     * for which to compute policy result.
     * @param actionName name of the action the user is trying to
     * perform on the resource
     * @param env run time environment parameters
     *
     * @return the result of the evaluation as a boolean value
     *
     * @throws PolicyException exception form policy framework
     * @throws SSOException if sso token is invalid
     *
     */
    public boolean isAllowed(String principalName, String resourceName,
        String actionName, Map env) throws PolicyException, SSOException;

    /**
     * Gets policy decision for the user identified by the
     * principalName for the given resource
     *
     * @param principalName principal name for whom to compute the
     * policy decision
     * @param resourceName name of the resource for which to
     * compute policy decision
     * @param env run time environment parameters
     *
     * @return the policy decision for the principal for the given
     * resource
     * @throws PolicyException exception form policy framework
     * @throws SSOException if sso token is invalid
     *
     */
    public PolicyDecision getPolicyDecision(String principalName,
        String resourceName, Map env)
        throws PolicyException, SSOException;

    /**
     * Gets protected resources for a user identified by the
     * principalName. Conditions defined in the policies
     * are ignored while computing protected resources.
     * Only resources that are  subresources of the  given
     * rootResource or equal to the  given rootResource would
     * be returned.
     * If all policies applicable to a resource are
     * only referral policies, no ProtectedResource would be
     * returned for such a resource.
     * @param principalName principal name for whom
     * to compute the privilege.
     * @param rootResource  only resources that are subresources
     * of the given rootResource or equal to the  given
     * rootResource would be returned. If
     * <code>PolicyEvaluator.ALL_RESOURCES</code>
     * is passed as rootResource, resources under
     * all root  resources of the service
     * type are considered while computing protected
     * resources.
     *
     * @return set of protected resources. The set contains
     * ProtectedResource objects.
     *
     * @throws PolicyException exception form policy framework
     * @throws SSOException if sso token is invalid
     * @see ProtectedResource
     *
     */
    public Set getProtectedResourcesIgnoreConditions(String principalName,
        String rootResource)  throws PolicyException, SSOException
                  

Client PolicyEvaluator Class

com.sun.identity.policy.client.PolicyEvaluator evaluates policies and provides policy decisions for remote applications. This does not require direct access to a policy stores such as Directory Server (for example, if there is a firewall). com.sun.identity.policy.client.PolicyEvaluator get policy decision from Access Manager using XML over HTTP(s). It stores a cache of policy decisions for faster responses and maintains the cache in sync with the Policy Service on the instance of Access Manager using the notification and polling mechanism.

PolicyEvent Class

com.sun.identity.policy.PolicyEvent represents a policy event that could potentially change the current access status. For example, a policy event is created and passed to the registered policy listeners whenever there is a change in a policy rule. This class works with the PolicyListener class in the com.sun.identity.policy.interface package.

Policy Plug-In APIs

The Policy plug-in classes are contained in the com.sun.identity.policy.interfaces package. The following classes are used by service developers and policy administrators who need to provide additional policy features as well as support for legacy policies.

ResourceName

Provides methods to determine the hierarchy of the resource names for a determined service type. For example, these methods can check to see if two resources names are the same or if one is a sub-resource of the other.

Subject

Defines methods that can determine if an authenticated user (possessing an SSOToken) is a member of the given subject.

Referral

Defines methods used to delegate the policy definition or evaluation of a selected resource (and its sub-resources) to another realm or policy server.

Condition

Provides methods used to constrain a policy to , for example, time-of-day or IP address. This interface allows the pluggable implementation of the conditions.

PolicyListener

Defines an interface for registering policy events when a policy is added, removed or changed. PolicyListener is used by the Policy Service to send notifications and by listeners to review policy change events.

Using the Policy Code Samples

Access Manager provide Policy code samples to perform the following tasks:

All the files you need to run the policy code samples are located in the following directories:

Solaris Platform

AccessManager-base/samples/policy

Linux Platform

AccessManager-base/identity

Use Cases Illustrated by Policy Code Samples

Each of the following sections describes a sequence of steps you must take when using various means to run a policy evaluation program or to create policies. Each step in a sequence is linked to detailed instructions further down in this chapter.

ProcedureTo Run a Policy Evaluation Program for the URL Policy Agent Service

Use this sequence to runs a policy evaluation program for the iPlanetAMWebAgentService service.

  1. Compile the Policy code samples.

    See Compiling the Policy Code Samples.

  2. Develop and run a Policy evaluation program.

    See Developing and Running a Policy Evaluation Program.

ProcedureTo Run a Policy Evaluation Program for the URL Policy Agent Service and More

This sequence runs the evaluation program for iPlanetAMWebAgentService and the sample subject, condition, and referral implementations.

  1. Compile the Policy code samples.

    See Compiling the Policy Code Samples.

  2. Develop custom subjects, conditions, and referrals.

    See Developing Custom Subjects, Conditions, and Referrals.

  3. Develop and run a Policy evaluation program.

    See Developing and Running a Policy Evaluation Program.

ProcedureTo Run a Policy Evaluation Program for the Sample Service

This sequence runs the evaluation program for the SampleWebService.

  1. Compile the Policy code samples.

    See Compiling the Policy Code Samples.

  2. Add a Policy-enabled service to Access Manager.

    See Adding a Policy-Enabled Service to Access Manager.

  3. Create policies for the new service.

    See Creating Policies for a New Service.

  4. Develop and run a Policy evaluation program.

    Developing and Running a Policy Evaluation Program.

ProcedureTo Run a Policy Evaluation Program for the Sample Service and More

This sequence runs the evaluation program forSampleWebService and the sample subject, condition, and referral implementations.

  1. Compile the Policy code samples.

    See Compiling the Policy Code Samples.

  2. Add a Policy-enabled service to Access Manager.

    See Adding a Policy-Enabled Service to Access Manager.

  3. Develop custom subjects, conditions, and referrals.

    See Developing Custom Subjects, Conditions, and Referrals.

  4. Create policies for the new service.

    See Creating Policies for a New Service.

  5. Develop and run a Policy evaluation program.

    See Developing and Running a Policy Evaluation Program.

To Use amadmin to Create Policies for the URL Policy Agent Service

Use amadmin to create policies for the service. See Creating Policies in Sun Java System Access Manager 7 2005Q4 Administration Guide for detailed instructions.

ProcedureTo Use amadmin to Create Policies for the Sample Service

This sequences creates policies for SampleWebService.

  1. Compile the Policy code samples.

    See Compiling the Policy Code Samples.

  2. Develop and run a Policy evaluation program.

    See Developing and Running a Policy Evaluation Program.

ProcedureTo Programmatically Construct Policies

This sequence constructs policies and adds them to the policy store.

  1. Compile the Policy code samples.

    See Compiling the Policy Code Samples.

  2. Programmatically construct policies.

    See Programmatically Constructing Policies.

Compiling the Policy Code Samples

Samples can be run both on Solaris and Linux platforms. In the sample files, root suffix DNs are specified as dc=example,dc=com. Substitute the root suffix with the actual root suffix of your Access Manager installation.

ProcedureTo Compile the Policy Code Samples

  1. Set the following variables in the Makefile:

    BASE

    Set this to refer the directory where Access Manager is installed.

    JAVA_HOME

    Set this variable to your installation of JDK. The JDK version should be higher than JDK 1.4

  2. To compile the sample program, run the gmake all command.

  3. In the sample files, replace the root suffix DNs with values appropriate for your environment.

Adding a Policy-Enabled Service to Access Manager

You can load into Access Manager a service that already contains policy schema. Access Manager provides a sample XML file for a new service that contains policy schema. You can modify AccessManager-base/SUNWam/samples/policy/SampleWebService.xml to fit your needs, and then add your service to Access Manager.

The Policy element contains AttributeSchema elements to define applicable actions and values for actions. While defining policies, you can define access rules for those actions.

Examples include canForwardEmailAddress and canChangeSalaryInformation . The actions specified by these attributes can be associated with a resource if the IsResourceNameAllowed element is specified in the attribute definition. For example, in the web agent XML service file, amWebAgent.xml , GET and POST are defined as policy attributes with an associated URL resource as IsResourceNameAllowed is specified.


Example 6–2 SampleWebService.xml

<!DOCTYPE ServicesConfiguration
    PUBLIC "=//iPlanet//Service Management Services (SMS) 1.0 DTD//EN"
    "jar://com/sun/identity/sm/sms.dtd">

<ServicesConfiguration>
    <Service name="SampleWebService" version="5.0">
        <Schema 
            serviceHierarchy="/DSAMEConfig/SampleWebService"
            i18nFileName="SampleWebService" 
            i18nKey="SampleWebService">*
	    <Global>
		<AttributeSchema name="serviceObjectClasses"  type="list" syntax="string"
								i18nKey="SampleWebService"/>
            </Global>
	    <Policy>
		<AttributeSchema name="GET"
                    type="single"
                    syntax="boolean"
                    uitype="radio"
                    i18nKey="get">
                    <IsResourceNameAllowed/>
                    <BooleanValues>
                        <BooleanTrueValue i18nKey="allow">allow</BooleanTrueValue>
                        <BooleanFalseValue i18nKey="deny">deny</BooleanFalseValue>
                    </BooleanValues>
		</AttributeSchema>

		<AttributeSchema name="POST"
		    type="single"
                    syntax="boolean"
                    uitype="radio"
		    i18nKey="post">
		    <IsResourceNameAllowed/>
                    <BooleanValues>
                        <BooleanTrueValue i18nKey="allow">allow</BooleanTrueValue>
                        <BooleanFalseValue i18nKey="deny">deny</BooleanFalseValue>
                    </BooleanValues>
		</AttributeSchema>

		<AttributeSchema name="PUT"
		    type="single"
                    syntax="boolean"
                    uitype="radio"
		    i18nKey="put">
		    <IsResourceNameAllowed/>
                    <BooleanValues>
                        <BooleanTrueValue i18nKey="allow">allow</BooleanTrueValue>
                        <BooleanFalseValue i18nKey="deny">deny</BooleanFalseValue>
                    </BooleanValues>
		</AttributeSchema>

		<AttributeSchema name="DELETE"
		    type="single"
                    syntax="boolean"
                    uitype="radio"
		    i18nKey="delete">
		    <IsResourceNameAllowed/>
                    <BooleanValues>
                        <BooleanTrueValue i18nKey="allow">allow</BooleanTrueValue>
                        <BooleanFalseValue i18nKey="deny">deny</BooleanFalseValue>
                    </BooleanValues>
		</AttributeSchema>

	    </Policy>
        </Schema>
    </Service>
</ServicesConfiguration>

ProcedureTo Add a New Service to Access Manager

  1. Run the amadmin command to load that service.


    AccessManager-base/bin/amadmin
         	--runasdn "uid=amAdmin,ou=People,<default_org>,<
    root_suffix>"
    			--password <password>
    			--schema AccessManager-base/samples/policy/SampleWebService.xml
    
  2. Copy the properties file to the locale directory of the Access Manager installation.

    cp SampleWebService.properties AccessManager-base/locale

  3. Create a service XML files that conforms to AccessManager-base/dtd/sms.dtd, and contains the <Policy> element. See example below.

  4. Create and copy locale properties file to AccessManager-base/locale.

  5. Use amadmin to load the service into Access Manager.

    Once the new service is added, you can define rules for the new service in policy definitions.


Example 6–3 XML for Policy-Enabled Service

/etc/opt/SUNWam/config/xml/amWebAgent.xml (Solaris) /etc/opt/sun/identity/config/xml/amWebAgent.xml on (Linux)

<!DOCTYPE ServicesConfiguration
    PUBLIC "=//iPlanet//Service Management Services (SMS) 1.0 DTD//EN"
    "jar://com/sun/identity/sm/sms.dtd">

<ServicesConfiguration>
    <Service name="iPlanetAMWebAgentService" version="1.0">
	<Schema
            i18nFileName="amWebAgent"
            i18nKey="iplanet-am-web-agent-service-description">
	<Global>
		<AttributeSchema name="serviceObjectClasses"
                    type="list"
                    syntax="string"
	i18nKey="">
                    <DefaultValues>
			<Value>iplanet-am-web-agent-service</Value>
	</DefaultValues>
		</AttributeSchema>
            </Global>

            <Policy>
		<AttributeSchema name="GET"
                    type="single"
	syntax="boolean"
                    uitype="radio"
                    i18nKey="GET">
	<IsResourceNameAllowed/>
                    <BooleanValues>
			<BooleanTrueValue i18nKey="allow">allow</BooleanTrueValue>
			<BooleanFalseValue i18nKey="deny">deny</BooleanFalseValue>
                    </BooleanValues>
		</AttributeSchema>
		<AttributeSchema name="POST"
                    type="single"
	syntax="boolean"
                    uitype="radio"
                    i18nKey="POST">
	<IsResourceNameAllowed/>
                    <BooleanValues>
       			<BooleanTrueValue i18nKey="allow">allow</BooleanTrueValue>
			<BooleanFalseValue i18nKey="deny">deny</BooleanFalseValue>
                    </BooleanValues>
		</AttributeSchema>
            </Policy>
	</Schema>
    </Service>
</ServicesConfiguration>

Developing Custom Subjects, Conditions, and Referrals

Access Manager provides subject, condition and referral interfaces that enable you to develop your own custom subjects, conditions and referrals. A sample implementation is provided for the three interfaces. SampleSubject.java implements the Subject interface. This subject applies to all the authenticated users who have valid SSOTokens. SampleCondition.java implements the Condition interface. This condition makes the policy applicable to those users whose user name length is greater than or equal to the length specified in the condition.

SampleReferral.java implements the Referral interface. SampleReferral.java gets the referral policy decision from a text file SampleReferral.properties located in the /samples directory.

You must add the subject, condition and, referral implementations to iPlanetAMPolicyService and iPlanetAMPolicyConfigService in order to make them available for policy definitions. These services are loaded into Access Manager during installation. To add the sample implementations to the Policy framework, modify the iPlanetAMPolicy service and iPlanetAMPolicyConfig service.

ProcedureTo Add Sample Implementation to the Policy Framework

  1. Use db2ldif to back up iPlanetAMPolicy and iPlanetAMPolicyConfig services.


     
    cd DirectoryServer-base/slapd-hostname
          db2ldif -n userRoot
              -s "ou=iPlanetAMPolicyService,ou=services,root_suffix"
          db2ldif -n userRoot
              -s "ou=iPlanetAMPolicyConfigService,ou=services,root_suffix
    
    "
              
  2. Set the environment variable LD_LIBRARY_PATH.

    On Solaris, add /usr/lib/mps/secv1 to LD_LIBRARY_PATH.

    On Linux, add /opt/sun/private/lib to LD_LIBRARY_PATH.

  3. Run the following commands:


    cd AccessManager-base/samples/policy
          AccessManager-base/bin/amadmin
              --runasdn "uid=amAdmin,ou=People,default_org,
    root_suffix
              --password password 
              --schema amPolicy_mod.xml
          AccessManager-base/bin/amadmin
              --runasdn "uid=amAdmin,ou=People,default_org,
    root_suffix
              --password password 
              --data amPolicyConfig_mod.xml
  4. Change the properties files of the iPlanetAMPolicy and iPlanetAMPolicyConfig services.


    cd AccessManager-base/locale
          mv amPolicy.properties amPolicy.properties.bak
          mv amPolicy_en.properties amPolicy_en.properties.bak
          mv amPolicyConfig.properties amPolicyConfig.properties.bak
          mv amPolicyConfig_en.properties amPolicyConfig_en.properties.bak
          cp AccessManager-base/samples/policy/amPolicy.properties .
          cp AccessManager-base/samples/policy/amPolicy_en.properties .
          cp AccessManager-base/samples/policy/amPolicyConfig.properties .
          cp AccessManager-base/samples/policy/amPolicyConfig_en.properties .
          
  5. Deploy the sample plug-ins.

    Copy SampleSubject.class , SampleCondition.class and SampleReferral.class from the /sample directory to AccessManager-base/lib .

  6. Restart the Access Manager server.

    The sample subject, condition and referral implementations are now available for policy definitions through the administration console or amadmin tool.

Creating Policies for a New Service

Access Manager policies are managed through the Administration console or through the amadmin command. However, policies cannot be modified using amadmin command. You must delete the policy and then add the modified policy using amadmin. To add policies using amadmin, policy XML file must be developed following AccessManager-base/dtd/policy.dtd. Once the Policy XML file is developed, you can load the Policy XML file.

In the Policy /samples directory, there are two sample Policy XML files. They define policies for theSampleWebService service. SamplePolicy.xml defines a normal policy for SampleWebService with a SampleSubject and a SampleCondition. SamplereferralPolicy.xml defines a referral policy for SampleWebService with a SampleReferral.

ProcedureTo Load a Policy XML File

Before You Begin

You must compile the Policy code samples and develop custom subjects, conditions, and referrals before you can load policies present in the Policy XML files. See Compiling the Policy Code Samples and Developing Custom Subjects, Conditions, and Referrals for detailed instructions.

  1. Run the following command:


     
    AccessManager-base/bin/amadmin
    					--runasdn "uid=amAdmin,ou=People,<default_org>,<
    root_suffix>"
    					--password <password>
    				 	--data <policy.xml>         
  2. Run the following command:


    AccessManager-base/bin/amadmin
           				 --runasdn "uid=amAdmin,ou=People,default_org,
    root_suffix"
    					--password password
    					--data AccessManager-base/samples/policy/SamplePolicy.xml
        				AccessManager-base/bin/amadmin
    					--runasdn "uid=amAdmin,ou=People,default_org,
    root_suffix"
    					--password password
    					--data AccessManager-base/samples/policy/
    									SampleReferralPolicy.xml

    You can verify the newly added policies in Administration Console.

Developing and Running a Policy Evaluation Program

Access Manager provides a Policy Evaluation API. This API has one Java class, PolicyEvaluator. The package for this class is com.sun.identity.policy.PolicyEvaluator . Access Manager provides a sample policy evaluator program, PolicyEvaluation.java . You can use this program to run policy evaluations for different services. The policy evaluation is always based on a service such as iPlanetAMWebAgentService or SampleWebService. The sample policy evaluation program uses the PolicyEvaluation.properties file. Specify the input for the evaluation program in this file. Examples are service name, action names, condition environment parameters, user name, and user password.

ProcedureTo Set Policy Evaluation Properties

  1. Set the value of pe.servicename to the service name.

    Examples: iPlanetAMWebAgentService or SampleWebService .

  2. Set the pe.resoucename to the name of the resource that you want to evaluate the policy against.

  3. Specify the action names in the pe.actionnames.

    Separate the action names with a colon (:) If you want to get all the action values, leave the pe.actionnamesblank.

  4. Set other required properties such as pe.username and pe.password.

  5. (Optional) Set the following properties pe.authlevel, pe.authscheme, pe.requestip, pe.dnsname , pe.time if you use the corresponding conditions in your policy definitions.

    If you don't want to set these environment parameters, just leave their values as blank.

    pe.authlevel

    Used to evaluate AuthLevel Condition. pe.authlevel takes a positive integer.

    pe.authscheme

    Used to evaluate AuthScheme Condition. pe.authschemet takes a set of colon— separated AuthScheme names.

    pe.requestip

    Used to evaluate the IP Condition. pe.requestip takes an IP address string.

    pe.dnsname

    Used to evaluate the IP Condition. pe.dnsname takes a set of colon— separated DNS names.

    property pe.time

    Used to evaluate the Simple Time Condition. property pe.time specifies the request time in milliseconds. If its value is set to the current time, then it takes the current time in milliseconds.

ProcedureTo Run a Policy Evaluation Program

Before You Begin

You must set up policies before running a policy evaluation program.

  1. Set the environment variable LD_LIBRARY_PATH.

    On Solaris add /usr/lib/mps/secv1 to LD_LIBRARY_PATH .

    On Linux add /opt/sun/private/lib to LD_LIBRARY_PATH.

  2. Run the gmake run command.

Programmatically Constructing Policies

Access Manager provides Policy Management APIs that enable you to programmatically create, add, update and remove policies. The sample program PolicyCreator.java demonstrates how to programmatically construct policies and add them to policy store. The program creates one normal policy named policy1 and one referral policy named refpolicy1 and adds both policies to the policy store. The normal policy has one subject of each subject type and one condition of each condition type comes with Access Manager at installation.


Example 6–4 Sample Program PolicyCreator.java

/**
 * $Id: PolicyCreator.java,v 1.5 2005/06/24 16:53:50 vs125812 Exp $
 * Copyright © 2005 Sun Microsystems, Inc.  All rights reserved.
 *
 

import com.sun.identity.policy.PolicyManager;
import com.sun.identity.policy.ReferralTypeManager;
import com.sun.identity.policy.SubjectTypeManager;
import com.sun.identity.policy.ConditionTypeManager;
import com.sun.identity.policy.Policy;
import com.sun.identity.policy.Rule;
import com.sun.identity.policy.interfaces.Referral;
import com.sun.identity.policy.interfaces.Subject;
import com.sun.identity.policy.interfaces.Condition;
import com.sun.identity.policy.PolicyException;

import com.iplanet.sso.SSOToken;
import com.iplanet.sso.SSOException;

import java.util.Set;
import java.util.HashSet;
import java.util.Map;
import java.util.HashMap;

public class PolicyCreator {

    public static final String DNS_NAME="DnsName";
    public static final String DNS_VALUE="*.red.iplanet.com";
    public static final String START_TIME="StartTime";
    public static final String START_TIME_VALUE="08:00";
    public static final String END_TIME="EndTime";
    public static final String END_TIME_VALUE="21:00";
    public static final String AUTH_LEVEL="AuthLevel";
    public static final String AUTH_LEVEL_VALUE="0";
    public static final String AUTH_SCHEME="AuthScheme";
    public static final String AUTH_SCHEME_VALUE="LDAP";


    private String orgDN;
    private SSOToken ssoToken;
    private PolicyManager pm;

    private PolicyCreator() throws PolicyException, SSOException {
        BaseUtils.loadProperties();
        orgDN = BaseUtils.getProperty("pe.realmname");
        System.out.println("realmDN = " + orgDN);
        ssoToken = BaseUtils.getToken();
        pm = new PolicyManager(ssoToken, orgDN);
    }

    public static void main(String[] args) {
        try {
            PolicyCreator pc = new PolicyCreator();
            pc.addReferralPolicy();
            pc.addNormalPolicy();
            System.exit(0);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    private void addNormalPolicy() throws PolicyException, SSOException {
        System.out.println("Creating normal policy in realm:" + orgDN);
        PolicyManager pm = new PolicyManager(ssoToken, orgDN);
        SubjectTypeManager stm = pm.getSubjectTypeManager();
        ConditionTypeManager ctm = pm.getConditionTypeManager();

        Policy policy = new Policy("policy1", "policy1 description");
        Map actions = new HashMap(1);
        Set values = new HashSet(1);
        values.add("allow");
        actions.put("GET", values);
        String resourceName = "http://myhost.com:80/hello.html";
        Rule rule = new Rule("rule1", "iPlanetAMWebAgentService", 
                resourceName, actions);
        policy.addRule(rule);

        Subject subject = stm.getSubject("Organization");
        Set subjectValues = new HashSet(1);
        subjectValues.add(orgDN);
        subject.setValues(subjectValues);
        policy.addSubject("organization", subject);

        subject = stm.getSubject("LDAPUsers");
        subjectValues = new HashSet(1);
        String userDN = "uid=user1,ou=people" + "," + orgDN;
        subjectValues.add(userDN);
        subject.setValues(subjectValues);
        policy.addSubject("ldapusers", subject);

        subject = stm.getSubject("LDAPGroups");
        subjectValues = new HashSet(1);
        String groupDN = "cn=group1,ou=groups" + "," + orgDN;
        subjectValues.add(groupDN);
        subject.setValues(subjectValues);
        policy.addSubject("ldapgroups", subject);

        subject = stm.getSubject("LDAPRoles");
        subjectValues = new HashSet(1);
        String roleDN = "cn=role1" + "," + orgDN;
        subjectValues.add(roleDN);
        subject.setValues(subjectValues);
        policy.addSubject("ldaproles", subject);

        subject = stm.getSubject("IdentityServerRoles");
        subjectValues = new HashSet(1);
        roleDN = "cn=role1" + "," + orgDN;
        subjectValues.add(roleDN);
        subject.setValues(subjectValues);
        policy.addSubject("is-roles", subject);

        Condition condition = ctm.getCondition("IPCondition");
        Map conditionProperties = new HashMap(1);
        Set propertyValues = new HashSet(1);
        propertyValues.add(DNS_VALUE);
        conditionProperties.put(DNS_NAME, propertyValues);
        condition.setProperties(conditionProperties);
        policy.addCondition("ip_condition", condition);

        condition = ctm.getCondition("SimpleTimeCondition");
        conditionProperties = new HashMap(1);
        propertyValues = new HashSet(1);
        propertyValues.add(START_TIME_VALUE);
        conditionProperties.put(START_TIME, propertyValues);
        propertyValues = new HashSet(1);
        propertyValues.add(END_TIME_VALUE);
        conditionProperties.put(END_TIME, propertyValues);
        condition.setProperties(conditionProperties);
        policy.addCondition("time_condition", condition);

        condition = ctm.getCondition("AuthLevelCondition");
        conditionProperties = new HashMap(1);
        propertyValues = new HashSet(1);
        propertyValues.add(AUTH_LEVEL_VALUE);
        conditionProperties.put(AUTH_LEVEL, propertyValues);
        condition.setProperties(conditionProperties);
        policy.addCondition("auth_level_condition", condition);


        condition = ctm.getCondition("AuthSchemeCondition");
        conditionProperties = new HashMap(1);
        propertyValues = new HashSet(1);
        propertyValues.add(AUTH_SCHEME_VALUE);
        conditionProperties.put(AUTH_SCHEME, propertyValues);
        condition.setProperties(conditionProperties);
        policy.addCondition("auth_scheme_condition", condition);


        pm.addPolicy(policy);

        System.out.println("Created  normal policy");
    }

    private void addReferralPolicy() 
            throws PolicyException, SSOException {
        System.out.println("Creating referral policy for realm1");
        ReferralTypeManager rtm = pm.getReferralTypeManager();
        String subOrgDN = "o=realm1" +  ",ou=services," + orgDN;
        Policy policy = new Policy("refpolicy1", "ref to realm1", 
                true);
        Map actions = new HashMap(1);
        Rule rule = new Rule("rule1", "iPlanetAMWebAgentService", 
                "http://myhost.com:80/realm1", actions);
        policy.addRule(rule);
        Referral referral = rtm.getReferral("SubOrgReferral");
        Set referralValues = new HashSet(1);
        referralValues.add(subOrgDN);
        referral.setValues(referralValues);
        policy.addReferral("ref to realm1" , referral);
        pm.addPolicy(policy);
        System.out.println("Created referral policy for realm1");
    }

}

ProcedureTo Run the Sample Program PolicyCreator.java

  1. Compile the sample code.

    See Compiling the Policy Code Samples above.

  2. Set the environment variable LD_LIBRARY_PATH.

    On Solaris add /usr/lib/mps/secv1 to LD_LIBRARY_PATH.

    On Linux add /opt/sun/private/lib to LD_LIBRARY_PATH .

  3. Use the administration console to create the following objects in your root realm:

    • A subrealm named realm1

    • A user nameduser1

    • A group named group1

    • A role named role1

    See Managing Directory Objects in Sun Java System Access Manager 7 2005Q4 Administration Guide for information about creating directory objects.

  4. Set the following properties in the PolicyEvaluation.properties file:

    pe.realmname

    DN of the root realm.

    pe.username

    UserId to authenticate as.

    pe.password

    Password to use to authenticate.

  5. Run the gmake command.

    gmake createPolicies .

    Use the administration console to verify that the policies policy1 and refpolicy1 are added to Access Manager.