Working with Security
This information describes some of the tasks that are related to client-side security as you develop your applications.
Obtaining a LoginContext
AJava™ Authentication and Authorization (JAAS)
login consists of three steps: obtaining a LoginContext object,
calling the LoginContext.login method, and impersonating
the logged in user to perform the actual work.
Obtaining
a LoginContext object requires a tag to indicate
some particular configuration in the JAAS login
configuration file. If your login configuration file has an
entry for "other", then it does not matter what tag you use in the
call to the constructor of LoginContext because the
call falls back to the entry "other" in the configuration file. You
also need to supply a CallbackHandler to provide
the credentials (user name and password). If you would like to be
prompted for that information, you can provide a new instance of one
of Sun's sample callback handlers, such as com.sun.security.auth.callback.DialogCallbackHandler (as
shown in the following example) or TextCallbackHandler.
The login method calls the callback handler, and if this handler is a Oracle
WebLogic or IBM®
WebSphere® Application Server handler, the credentials are
authenticated.
A UserContext object
is associated with each thread that accesses the Content Engine Java API. A JAAS Subject is
associated with the thread, by calling UserContext.pushSubject,
before any calls that cause the API to access the Content Engine server. Note that the UserContext class
provides a helper method that can perform the JAAS login for you in
the common username/password case. This approach is typically taken when your
application is using the Content Engine Java API instead of the web service
transport. The following example uses the EJB transport for all subsequent Content Engine Java API calls. To instead use the web service
transport, change the JAAS configuration stanza name in the UserContext.createSubject call
from "FileNetP8" to "FileNetP8WSI".
Java Example
// Perform the login.
static void performLogin(
Connection con,
String userName, // Example: "username@testdom.local"
String passWord) throws Exception
{
// *** Step 1: Obtain login context. ***
// Determine call back handler.
CallbackHandler handler = null;
if (userName != null)
{
// Call user-created class that implements CallbackHandler.
handler = new UserPasswordHandler(userName, passWord);
}
else
{
handler = new DialogCallbackHandler();
}
// Get login context.
LoginContext lc = new LoginContext("mysystem", handler);
// *** Step 2: Call login method. ***
// Attempt to login.
try
{
lc.login();
System.out.println("Login succeeded");
}
catch (Exception exc)
{
System.out.println("Login failed");
throw exc;
}
// *** Step 3: Impersonate logged in user. ***
// Get user context.
UserContext uc = UserContext.get();
// Determine subject.
Subject sub = null;
if (userName != null)
{
// Example for EJB transport. Stanza name is FileNetP8 for EJB and FileNetP8WSI for WSI.
sub = UserContext.createSubject(con, userName, passWord, "FileNetP8");
}
else
{
sub = lc.getSubject();
}
// Associate the JAAS Subject with the UserContext.
uc.pushSubject(sub);
try
{
// do work
}
finally
{
uc.popSubject();
}
}
Setting Permissions
The following code example shows
how to set access rights for a new user added to a document's access
permission list. An AccessPermission object is created, set with
permission information about the new user, and added to the document's
access permission list. Constants are used to express the combination
of access rights, which are set on the AccessMask property of the AccessPermission object.
Java Example
// Constants specify combination of access rights.
private static final int LOAN_CREATOR = AccessRight.READ_ACL.getValue() | AccessRight.CHANGE_STATE.getValue() | AccessRight.CREATE_INSTANCE.getValue()
| AccessRight.VIEW_CONTENT.getValue() |AccessRight.MINOR_VERSION.getValue() | AccessRight.UNLINK.getValue()
| AccessRight.LINK.getValue() |AccessRight.WRITE.getValue() | AccessRight.READ.getValue();
private static final int LOAN_REVIEWER = AccessRight.VIEW_CONTENT.getValue() | AccessRight.READ_ACL.getValue() | AccessRight.READ.getValue()
| AccessRight.LINK.getValue();
// Adds new user to document's access permission list. Permissions are
// determined by user's group membership.
private AccessPermissionList setPermissions(AccessPermissionList apl, User newUser)
{
AccessPermission ap = Factory.AccessPermission.createInstance();
ap.set_GranteeName(newUser.get_DistinguishedName());
ap.set_AccessType(AccessType.ALLOW);
GroupSet groups = newUser.get_MemberOfGroups();
Iterator iter = groups.iterator();
while (iter.hasNext() == true)
{
Group group = (Group) iter.next();
// Set permissions based on whether user is in one of the following two groups.
if (group.get_DisplayName().equalsIgnoreCase("LoanReviewers") )
{
ap.set_AccessMask(LOAN_REVIEWER);
apl.add(ap);
break;
}
else if (group.get_DisplayName().equalsIgnoreCase("LoanCreators") )
{
ap.set_AccessMask(LOAN_CREATOR);
apl.add(ap);
break;
}
}
return apl;
}
C# Example
// Constants specify combination of access rights.
private const int LOAN_CREATOR = (int)AccessRight.READ_ACL | (int)AccessRight.CHANGE_STATE | (int)AccessRight.CREATE_INSTANCE
| (int)AccessRight.VIEW_CONTENT | (int)AccessRight.MINOR_VERSION | (int)AccessRight.UNLINK
| (int)AccessRight.LINK | (int)AccessRight.WRITE | (int)AccessRight.READ;
private const int LOAN_REVIEWER = (int)AccessRight.VIEW_CONTENT |(int)AccessRight.READ_ACL | (int)AccessRight.READ
| (int)AccessRight.LINK;
// Adds new user to document's access permission list. Permissions are
// determined by user's group membership.
private IAccessPermissionList setPermissions(IAccessPermissionList apl, IUser newUser)
{
IAccessPermission ap = Factory.AccessPermission.CreateInstance();
ap.GranteeName = newUser.DistinguishedName;
ap.AccessType = AccessType.ALLOW;
IGroupSet groups = newUser.MemberOfGroups;
foreach (IGroup group in groups)
{
// Set permissions based on whether user is in one of the following two groups.
if (group.DisplayName.Equals("LoanReviewers", StringComparison.OrdinalIgnoreCase))
{
ap.AccessMask = LOAN_REVIEWER;
apl.Add(ap);
break;
}
else if (group.DisplayName.Equals("LoanCreators, StringComparison.OrdinalIgnoreCase))
{
ap.AccessMask = LOAN_CREATOR;
apl.Add(ap);
break;
}
}
return apl;
}
Modifying Permissions
The following code example shows how to change permissions for a particular group with access to a class of documents. Users in the LoanReviewers group have permission to view security on instances of the Loans class, a subclass of Documents. The right to view security is removed.
Java Example
private static final PropertyFilter PF;
static
{
PF= new PropertyFilter();
PF.addIncludeProperty(new FilterElement(null, null, null, "DefaultInstancePermissions", null));
}
// Gets Loans subclass.
ClassDefinition cd=Factory.ClassDefinition.fetchInstance(os, new Id("{3B71BC99-FD11-4E15-9CF5-83887ED1C42F}"), PF);
// Gets permissions from Loans subclass.
AccessPermissionList apl = cd.get_DefaultInstancePermissions();
apl = cd.get_Permissions();
// Iterates permissions in search of LoanReviewers group.
// Removes the access right for viewing security on Loans instances.
// Saves the modified permission for the LoanReviewers group.
Iterator iter = apl.iterator();
while (iter.hasNext())
{
AccessPermission ap = (AccessPermission)iter.next();
if (ap.get_GranteeName().equalsIgnoreCase("LOANREVIEWERS@process.auto.acme.com"))
{
int rights = ap.get_AccessMask();
rights &= ~AccessRight.READ_ACL.getValue();
ap.set_AccessMask(rights);
apl.add(ap);
cd.set_Permissions(apl);
cd.save(RefreshMode.REFRESH);
break;
}
}
C# Example
private static readonly PropertyFilter PF;
{
PF = new PropertyFilter();
PF.AddIncludeProperty(new FilterElement(null, null, null, PropertyNames.DEFAULT_INSTANCE_PERMISSIONS, null));
}
// Gets Loans subclass.
IClassDefinition cd = Factory.ClassDefinition.FetchInstance(os, new Id("{3B71BC99-FD11-4E15-9CF5-83887ED1C42F}"), PF);
// Gets permissions from Loans subclass.
IAccessPermissionList apl = cd.Permissions;
// Iterates permissions in search of LoanReviewers group.
// Removes the access right for viewing security on Loans instances.
// Saves the modified permission for the LoanReviewers group.
foreach (IAccessPermission ap in apl)
{
if (ap.GranteeName.Equals("LOANREVIEWERS@process.auto.acme.com", StringComparison.OrdinalIgnoreCase))
{
int rights = (int)ap.AccessMask;
rights &= ~(int)AccessRight.READ_ACL;
ap.AccessMask = rights;
apl.Add(ap);
cd.Permissions = apl;
cd.Save(RefreshMode.REFRESH);
break;
}
} Checking Permissions
The following code example
shows how to check a user's permissions on a Document object
to run a particular operation. Individual access rights are used to
test permissions.
Java Example
private static final PropertyFilter PF;
static
{
PF= new PropertyFilter();
PF.addIncludeProperty(new FilterElement(null, null, null, PropertyNames.ID, null));
}
private static final int ACCESS_REQUIRED = AccessRight.DELETE.getValue() | AccessRight.WRITE.getValue() | AccessRight.MAJOR_VERSION.getValue();
...
Document doc=Factory.Document.fetchInstance(os, new Id("{BBC0B2D5-9850-4F48-9AC9-7DBC38A9C89D}"), PF);
int accessMask = doc.getAccessAllowed();
// Does user have the following rights on the document?
if ( (accessMask & ACCESS_REQUIRED) == ACCESS_REQUIRED)
{
// do something applicable to these rights.
}
C# Example
private static readonly PropertyFilter PF;
static checkPermissions()
{
PF = new PropertyFilter();
PF.AddIncludeProperty(new FilterElement(null, null, null, PropertyNames.ID, null));
}
private const int ACCESS_REQUIRED = (int)AccessRight.DELETE | (int)AccessRight.WRITE | (int)AccessRight.MAJOR_VERSION;
...
IDocument doc = Factory.Document.FetchInstance(os, new Id("{BBC0B2D5-9850-4F48-9AC9-7DBC38A9C89D}"), PF);
int accessMask = (int)doc.GetAccessAllowed();
// Does user have the following rights?
if ( (accessMask & ACCESS_REQUIRED) == ACCESS_REQUIRED)
{
// do something applicable to these rights.
}
Getting Access Permission Descriptions
The following examples show how to retrieve access permission descriptions (APDs) to populate a user interface (UI) for selecting permissions (UI code and code for setting permissions is not included). The code creates a collection of APDs from the Folder class description, and then iterates the collection to get descriptive information from each AccessPermissionDescription object. The output listing follows the examples.
Java Example
String apdClass = ClassNames.FOLDER;
ClassDescription cd = Factory.ClassDescription.getInstance(os, apdClass);
cd.fetchProperty(PropertyNames.PERMISSION_DESCRIPTIONS, null);
AccessPermissionDescriptionList apdl = cd.get_PermissionDescriptions();
System.out.println(apdClass + " has this many APDs: " + apdl.size());
for (Iterator it = apdl.iterator(); it.hasNext();)
{
AccessPermissionDescription apd = (AccessPermissionDescription)it.next();
String dn = apd.get_DisplayName();
String dt = apd.get_DescriptiveText();
dt = (dn.equals(dt) ? "" : ": " + dt);
String pt = apd.get_PermissionType().toString();
pt += " ".substring(pt.length());
System.out.println(pt + " " + dn + dt);
}
C# Example
String apdClass = ClassNames.FOLDER ;
IClassDescription cd = Factory.ClassDescription.GetInstance(os, apdClass);
cd.FetchProperty(PropertyNames.PERMISSION_DESCRIPTIONS, null);
IAccessPermissionDescriptionList apdl = cd.PermissionDescriptions;
System.Console.WriteLine(apdClass + " has this many APDs: " + apdl.Count);
foreach (IAccessPermissionDescription apd in apdl)
{
String dn = apd.DisplayName;
String dt = apd.DescriptiveText;
dt = (dn.Equals(dt) ? "" : ": " + dt);
String pt = apd.PermissionType.ToString();
pt += " " .Substring(pt.Length);
System.Console.WriteLine(pt + " " + dn + dt);
}
Output Listing
Folder has this many APDs: 21
LEVEL Full Control
LEVEL Modify properties
LEVEL Add to Folder
LEVEL_DEFAULT View properties
RIGHT View all properties
RIGHT Modify all properties
RIGHT Reserved12 (Deploy is deprecated)
RIGHT Reserved13 (Archive is deprecated)
RIGHT File in folder / Annotate
RIGHT Unfile from folder
RIGHT Create instance
RIGHT Create subfolder
RIGHT Delete
RIGHT Read permissions
RIGHT Modify permissions
RIGHT Modify owner
RIGHT_INHERIT_ONLY Minor versioning
RIGHT_INHERIT_ONLY Major versioning
RIGHT_INHERIT_ONLY View content
RIGHT_INHERIT_ONLY Change state
RIGHT_INHERIT_ONLY Publish
Working with Marking Objects
The following code snippet
retrieves all MarkingSet objects from the FileNet
P8
domain.
Java Example
Domain domain = Factory.Domain.fetchInstance(conn, "Domain", null);
domain.get_MarkingSets();
Implementing Kerberos
Kerberos can be implemented for single sign-on (SSO) authentication on the client. For more information about Kerberos, see Kerberos for Content Engine.
Prerequisites
A number of prerequisites must be met before you can use Kerberos for SSO authentication.
System Prerequisites
- Only Windows clients can authenticate by using Kerberos, but regardless of operating system, any Content Engine server can accept Kerberos credentials. Both client and server Windows systems must be running on the Windows 2000 (or later) operating system.
- CEMP servers that run Windows or running supported non-Windows operating systems must also be using Active Directory as the directory service provider. In the case of a Windows Content Engine server, the server must be a member of an Active Directory domain.
Domain/Account Prerequisites
- A Windows client system needs to be in a domain (not a workgroup) and the user must be logged in as a domain account. (Logging in as a local account does not work.)
- A Windows server system also needs to be a member of a domain (not a workgroup); however, there is no restriction on whether the logged in account is in the domain or is local. Non-Windows Content Engine servers need access to Active Directory only.
- The client system and the Content Engine server system must be in the same domain (or in the case of non-Windows servers, access the same Active Directory), unless the steps described in the Cross-realm Kerberos authentication section of the IBM FileNet P8 Security documentation are followed.
Standalone .NET Client Prerequisites
- For Content Engine .NET API or COM compatibility layer clients, the Microsoft .NET Framework 3.0 or later, with its built-in Windows Communication Foundation (WCF) support, must be installed and a reference set to FileNet.Api.dll (which is included in the COM compatibility layer software).
- For pure .NET web service clients, .NET 1.1 and Microsoft Web Services Extensions (WSE) 2.0 must be installed on the client system.
Content Engine Java Server Prerequisites
- A minimum of Java Runtime
Environment (JRE) 1.5.0. It is recommended that you install Java Development Kit (JDK) 1.5.0
to use its Kerberos utilities. Although not required, you can also
set the JAVA_HOME environment variable to allow the Java tools in the JDK to be accessed on Windows systems. For example:
- Windows:
set JAVA_HOME=c:\j2sdk1.5.0.11 %JAVA_HOME%\bin\ktab - non-Windows:
JAVA_HOME=/opt/j2sdk1.5.0.11; export JAVA_HOME; ${JAVA_HOME}/bin/ktab
- Windows:
- A Kerberos configuration file (krb5.ini) must be available to the Java virtual machine (JVM). A sample file is provided and installed as part of the Content Engine software installation in the following location: <installation_directory>\FileNet\ContentEngine\Kerberos\krb5.ini or <installation_directory>/FileNet/ContentEngine/Kerberos/krb5.ini. For information about the steps to take to modify this file for your environment, see Kerberos for Content Engine.
- A Microsoft change
to security in Windows 2000
SP4, Windows XP SP2, and Windows 2003 impacted the ability
of Java to use the system's
cached Kerberos Ticket Granting Tickets (TGTs) for integrated logins.
You can apply a patch to correct this problem by locating and double-clicking
the following file:
<installation_directory>:\FileNet\Content Engine\Kerberos\AllowTgtSessionKey_fix_for_Krb5LoginModule.reg
RegEdit is started to add a value to the Windows system registry that disables the new security feature. This registry edit can also be used harmlessly on earlier Windows service packs.
Using Kerberos on an API Client
The following example illustrates how to use Kerberos authentication with a Content Engine .NET API client:
Java Example
// Java clients currently do not support Kerberos authentication.
C# Example
KerberosCredentials creds = new KerberosCredentials();
ClientContext.SetThreadCredentials(creds);
IConnection conn = Factory.Connection.GetConnection(strURI);
IDomain domain = Factory.Domain.GetInstance(conn, strP8Domain);
The C# example uses the identity of the Windows system that is logged in user for each Content Engine command.
Working with Security Policies
The following Java and C# code examples show you how to work with security policies and security templates. These examples, show you how to create and assign a security policy. Other examples show you how to apply an application security template to an object, and how to retrieve permission information from a security template. The last example shows you how to remove a security policy from both an object and from an object store.
Creating a Security Policy
The following Java and
C# examples show how to create a SecurityPolicy object. To start, three SecurityTemplate objects
are created and added to a SecurityTemplateList object.
Two of the templates are of type VersioningSecurityTemplate, and one is of type ApplicationSecurityTemplate. The VersioningSecurityTemplate objects
are intended to be applied automatically to released and superseded
versions of an object. The ApplicationSecurityTemplate object
must be applied to an object manually (see Applying
an ApplicationSecurityTemplate). For each template, the TemplatePermissions
property is set to an AccessPermissionList object,
which is returned by the setPermissions method (not
shown).
Next, a SecurityPolicy object
is created and its SecurityTemplates property is set to the SecurityTemplateList. Note that
the security policy's PreserveDirectPermissions property is set to false;
therefore, when the security policy is assigned to an object, the
object's original direct permissions are replaced by the permissions
that are defined in the security policy's templates.
Java Example
public void createSecurityObject(ObjectStore os)
{
// Access rights for released, superseded, and obsolete objects
int permReleased = AccessRight.READ_ACL_AS_INT | AccessRight.CHANGE_STATE_AS_INT
| AccessRight.CREATE_INSTANCE_AS_INT | AccessRight.VIEW_CONTENT_AS_INT
| AccessRight.MINOR_VERSION_AS_INT | AccessRight.UNLINK_AS_INT
| AccessRight.LINK_AS_INT | AccessRight.MAJOR_VERSION_AS_INT
| AccessRight.WRITE_AS_INT | AccessRight.READ_AS_INT;
int permSuperseded = AccessRight.READ_ACL_AS_INT | AccessRight.VIEW_CONTENT_AS_INT
| AccessRight.READ_AS_INT;
int permObsolete = AccessRight.READ_ACL_AS_INT | AccessRight.READ_AS_INT
| AccessRight.DELETE_AS_INT;
// Create security templates.
VersioningSecurityTemplate vst1 = Factory.VersioningSecurityTemplate.createInstance(os);
VersioningSecurityTemplate vst2 = Factory.VersioningSecurityTemplate.createInstance(os);
ApplicationSecurityTemplate vst3 = Factory.ApplicationSecurityTemplate.createInstance(os);
SecurityTemplateList stl = Factory.SecurityTemplate.createList();
vst1.set_ApplyStateID(VersionStatusId.RELEASED);
vst1.set_TemplatePermissions( setPermissions("#AUTHENTICATED-USERS", permReleased) );
vst1.set_DisplayName("Version Template for Released Object");
vst1.set_IsEnabled(Boolean.TRUE);
stl.add(vst1);
vst2.set_ApplyStateID(VersionStatusId.SUPERSEDED);
vst2.set_TemplatePermissions( setPermissions("#AUTHENTICATED-USERS", permSuperseded) );
vst2.set_DisplayName("Version Template for Superseded Object");
vst2.set_IsEnabled(Boolean.TRUE);
stl.add(vst2);
vst3.set_ApplyStateID(new Id("{21a47705-d20a-4b65-938e-2ddcefa45927}") );
vst3.set_TemplatePermissions( setPermissions("#AUTHENTICATED-USERS", permObsolete) );
vst3.set_DisplayName("Application Template for Obsolete Objects");
vst3.set_IsEnabled(Boolean.TRUE);
stl.add(vst3);
// Create the security policy.
SecurityPolicy sp = Factory.SecurityPolicy.createInstance(os, ClassNames.SECURITY_POLICY);
sp.set_SecurityTemplates(stl);
sp.set_DisplayName("Security Policy with Version and Application Templates");
sp.set_PreserveDirectPermissions(Boolean.FALSE);
sp.save(RefreshMode.REFRESH);
}
C# Example
public void createSecurityObject(IObjectStore os)
{
// Access rights for released, superseded, and obsolete objects
int permReleased = (int)AccessRight.READ_ACL | (int)AccessRight.CHANGE_STATE
| (int)AccessRight.CREATE_INSTANCE | (int)AccessRight.VIEW_CONTENT
| (int)AccessRight.MINOR_VERSION | (int)AccessRight.UNLINK
| (int)AccessRight.LINK | (int)AccessRight.MAJOR_VERSION
| (int)AccessRight.WRITE | (int)AccessRight.READ;
int permSuperseded = (int)AccessRight.READ_ACL | (int)AccessRight.VIEW_CONTENT
| (int)AccessRight.READ;
int permObsolete = (int)AccessRight.READ_ACL| (int)AccessRight.READ
| (int)AccessRight.DELETE;
// Create security templates.
IVersioningSecurityTemplate vst1 = Factory.VersioningSecurityTemplate.CreateInstance(os);
IVersioningSecurityTemplate vst2 = Factory.VersioningSecurityTemplate.CreateInstance(os);
IApplicationSecurityTemplate vst3 = Factory.ApplicationSecurityTemplate.CreateInstance(os);
ISecurityTemplateList stl = Factory.SecurityTemplate.CreateList();
vst1.ApplyStateID = VersionStatusId.RELEASED;
vst1.TemplatePermissions = setPermissions("#AUTHENTICATED-USERS", permReleased);
vst1.DisplayName = "Version Template for Released Object";
vst1.IsEnabled = true;
stl.Add(vst1);
vst2.ApplyStateID = VersionStatusId.SUPERSEDED;
vst2.TemplatePermissions = setPermissions("#AUTHENTICATED-USERS", permSuperseded);
vst2.DisplayName = "Version Template for Superseded Object";
vst2.IsEnabled = true;
stl.Add(vst2);
vst3.ApplyStateID = new Id("{21a47705-d20a-4b65-938e-2ddcefa45927}");
vst3.TemplatePermissions = setPermissions("#AUTHENTICATED-USERS", permObsolete);
vst3.DisplayName = "Application Template for Obsolete Objects";
vst3.IsEnabled = true;
stl.Add(vst3);
// Create the security policy.
ISecurityPolicy sp = Factory.SecurityPolicy.CreateInstance(os, ClassNames.SECURITY_POLICY);
sp.SecurityTemplates = stl;
sp.DisplayName = "Security Policy with Version and Application Templates";
sp.PreserveDirectPermissions = false;
sp.Save(RefreshMode.REFRESH);
}
Assigning a Security Policy
The following Java and
C# examples show how to assign a security policy to a class. The Id objects
for the ClassDefinition and the SecurityPolicy are passed to the method, which
creates the ClassDefinition and the SecurityPolicy objects.
Using the helper method getPropertyDefinition (not
shown), the code retrieves the class's PropertyDefinition object
for SecurityPolicy, then sets it to the SecurityPolicy object.
Note that the security policy is automatically applied to new object instances of the class, but not to existing object instances of the class. You must explicitly set the security policy on the existing object instances of the class.
Java Example
public void assignSecurityPolicy(ObjectStore os, Id classId, Id securityPolicyId)
{
ClassDefinition cd = Factory.ClassDefinition.fetchInstance(os, classId, null);
SecurityPolicy sp = Factory.SecurityPolicy.getInstance(os, ClassNames.SECURITY_POLICY, securityPolicyId);
PropertyDefinition pd = getPropertyDefinition(cd.get_PropertyDefinitions(), ClassNames.SECURITY_POLICY);
(pd.getProperties().get(PropertyNames.PROPERTY_DEFAULT_OBJECT)).setObjectValue(sp);
cd.save(RefreshMode.REFRESH);
}
C# Example
public void assignSecurityPolicy(IObjectStore os, Id classId, Id securityPolicyId)
{
IClassDefinition cd = Factory.ClassDefinition.FetchInstance(os, classId, null);
ISecurityPolicy sp = Factory.SecurityPolicy.GetInstance(os, ClassNames.SECURITY_POLICY, securityPolicyId);
IPropertyDefinition pd = getPropertyDefinition(cd.PropertyDefinitions, ClassNames.SECURITY_POLICY);
(pd.Properties.GetProperty(PropertyNames.PROPERTY_DEFAULT_OBJECT)).SetObjectValue(sp);
cd.Save(RefreshMode.REFRESH);
}
Applying an Application Security Template
The following Java and
C# examples show how to apply an ApplicationSecurityTemplate to an object. The
examples iterate a Folder object, filtering all documents
that have not been modified for over one year. For the documents that
meet the criterion, an application security template with delete permission
is applied. The examples assume that the documents in the folder were
previously assigned a SecurityPolicy containing the application security
template with delete permission.
Java Example
public void applyApplicationSecurityTemplate(ObjectStore os, Id folderId)
{
// Create a folder object.
Folder folder = Factory.Folder.fetchInstance(os, folderId, null);
// Get all documents in folder
DocumentSet ds = folder.get_ContainedDocuments();
// Get current date to compare against dates of documents.
Calendar cal = new GregorianCalendar();
int currYear = cal.get(Calendar.YEAR);
int currMonth = cal.get(Calendar.MONTH);
// Iterate folder documents and check last modification date.
// If over one year, apply ApplicationSecurityTemplate with delete permission.
Iterator iter = ds.iterator();
while (iter.hasNext())
{
Document doc = (Document) iter.next();
Date docDate = doc.get_DateLastModified();
cal.setTime(docDate);
if (cal.get(Calendar.YEAR) < currYear && cal.get(Calendar.MONTH) < currMonth )
{
doc.applySecurityTemplate(new Id("{21a47705-d20a-4b65-938e-2ddcefa45927}") );
doc.save(RefreshMode.REFRESH);
}
}
}
C# Example
public void applyApplicationSecurityTemplate(IObjectStore os, Id folderId)
{
// Create a folder object.
IFolder folder = Factory.Folder.FetchInstance(os, folderId, null);
// Get all documents in folder
IDocumentSet ds = folder.ContainedDocuments;
// Get current date to compare against dates of documents.
int currYear = DateTime.Now.Year;
int currMonth = DateTime.Now.Month;
// Iterate folder documents and check last modification date.
// If over one year, apply ApplicationSecurityTemplate with delete permission.
System.Collections.IEnumerator iter = ds.GetEnumerator();
while (iter.MoveNext())
{
IDocument doc = (IDocument) iter.Current;
DateTime docDate = (DateTime) doc.DateLastModified;
if (docDate.Year < currYear+1 && docDate.Month < currMonth+1)
{
doc.ApplySecurityTemplate(new Id("{21a47705-d20a-4b65-938e-2ddcefa45927}") );
doc.Save(RefreshMode.REFRESH);
}
}
}
Getting Security Template Information
You can get descriptive permission information from a security
template. A SecurityTemplate object includes the
TemplatePermissionDescriptions property, which contains a list of AccessPermissionDescription objects, from which
you can get information about access rights.
The following Java and C# examples get permission
descriptions for every SecurityTemplate object contained
in a SecurityPolicy object passed to the method. Iterating
the list of security templates (SecurityTemplateList),
the method retrieves the TemplatePermissionDescriptions property from
a security template. It then iterates the AccessPermissionDescriptionList and
prints information from each AccessPermissionDescription object.
Java Example
public void getSecurityTemplateInformation(ObjectStore os, Id secPolicyId)
{
SecurityPolicy sp = Factory.SecurityPolicy.fetchInstance(os, secPolicyId, null );
SecurityTemplateList stl = sp.get_SecurityTemplates();
Iterator outerIter = stl.iterator();
while (outerIter.hasNext())
{
SecurityTemplate st = (SecurityTemplate) outerIter.next();
AccessPermissionDescriptionList apdl = st.get_TemplatePermissionDescriptions();
Iterator innerIter = apdl.iterator();
System.out.println("Security template is " + st.get_DisplayName());
while (innerIter.hasNext())
{
AccessPermissionDescription apd = (AccessPermissionDescription) innerIter.next();
System.out.println("Permission is " + apd.get_DescriptiveText() + "\n" +
"Permission type is " + apd.get_PermissionType().toString() + "\n" +
"Access mask is " + apd.get_AccessMask()
);
}
System.out.println("=============================\n");
}
}
C# Example
public void getSecurityTemplateInformation(IObjectStore os, Id secPolicyId)
{
ISecurityPolicy sp = Factory.SecurityPolicy.FetchInstance(os, secPolicyId, null);
ISecurityTemplateList stl = sp.SecurityTemplates;
System.Collections.IEnumerator outerIter = stl.GetEnumerator();
while (outerIter.MoveNext())
{
ISecurityTemplate st = (ISecurityTemplate) outerIter.Current;
IAccessPermissionDescriptionList apdl = st.TemplatePermissionDescriptions;
System.Collections.IEnumerator innerIter = apdl.GetEnumerator();
System.Console.WriteLine("Security template is " + st.DisplayName);
while (innerIter.MoveNext())
{
IAccessPermissionDescription apd = (IAccessPermissionDescription) innerIter.Current;
System.Console.WriteLine("Permission is " + apd.DescriptiveText + "\n" +
"Permission type is " + apd.PermissionType.ToString() + "\n" +
"Access mask is " + apd.AccessMask
);
}
System.Console.WriteLine("=============================\n");
}
}
Removing a Security Policy
You can remove a security policy from an object by setting
the object's SecurityPolicy property to null. If
the object is a class, you set the class's PropertyDefinition object
for SecurityPolicy to null. You can also remove a
security policy from an object store but only if no objects hold a
reference to it.
The following Java and C# examples first show how to remove a security policy from a class, and then how to delete the security policy from an object store. Note that removing a security policy from a class does not remove the security policy from objects based on that class. Before you can delete a security policy from an object store, you must explicitly remove the security policy from every object that holds a reference to it.
Java Example
public void removeSecurityObject(Id classId, ObjectStore os)
{
// Get the class from which the security object will be removed.
ClassDefinition cd = Factory.ClassDefinition.fetchInstance(os, classId, null);
// Get the property definition for SecurityPolicy.
// Helper method getPropertyDefinition not shown.
PropertyDefinition pd = getPropertyDefinition(cd.get_PropertyDefinitions(), ClassNames.SECURITY_POLICY);
// Get the Id of the SecurityObject to be removed.
SecurityPolicy spTarget = (SecurityPolicy) (pd.getProperties().get(PropertyNames.PROPERTY_DEFAULT_OBJECT)).getObjectValue();
Id spTargetId = spTarget.get_Id();
// Remove SecurityObject from the class.
(pd.getProperties().get(PropertyNames.PROPERTY_DEFAULT_OBJECT)).setObjectValue(null);
cd.save(RefreshMode.REFRESH);
// Delete SecurityObject from the object store.
SecurityPolicySet sps = os.get_SecurityPolicies();
Iterator outerIter = sps.iterator();
while (outerIter.hasNext())
{
SecurityPolicy sp = (SecurityPolicy) outerIter.next();
if (sp.get_Id().equals(spTargetId) )
{
sp.delete();
sp.save(RefreshMode.REFRESH);
}
}
}
C# Example
public void removeSecurityObject(Id classId, IObjectStore os)
{
// Get the class from which the security object will be removed.
IClassDefinition cd = Factory.ClassDefinition.FetchInstance(os, classId, null);
// Get the property definition for SecurityPolicy.
// Helper method getPropertyDefinition not shown.
IPropertyDefinition pd = getPropertyDefinition(cd.PropertyDefinitions, ClassNames.SECURITY_POLICY);
// Get the Id of the SecurityObject to be removed.
ISecurityPolicy spTarget = (ISecurityPolicy)(pd.Properties.GetProperty(PropertyNames.PROPERTY_DEFAULT_OBJECT)).GetObjectValue();
Id spTargetId = spTarget.Id;
// Remove SecurityObject from the class.
(pd.Properties.GetProperty(PropertyNames.PROPERTY_DEFAULT_OBJECT)).SetObjectValue(null);
cd.Save(RefreshMode.REFRESH);
// Delete SecurityObject from the object store.
ISecurityPolicySet sps = os.SecurityPolicies;
System.Collections.IEnumerator outerIter = sps.GetEnumerator();
while (outerIter.MoveNext())
{
ISecurityPolicy sp = (ISecurityPolicy)outerIter.Current;
if (sp.Id.Equals(spTargetId))
{
sp.Delete();
sp.Save(RefreshMode.REFRESH);
}
}
}