April 1, 2020
Estimated Post Reading Time ~

How to add ACL to a node

Use case: Some time you want to associate ACL on a node based on certain events (For example page creation under certain path).

Solution: You can use the below code to associate ACL with a node.

add ACL to Node
There are two ways you can add ACL to a node. You can either chose a CRX or Jackrabbit way. Both examples are given below.

private static final String READ_ACCESS = "jcr:read";
AccessControlManager accessControlManager = jackrabbitSession.getAccessControlManager();
AccessControlPolicy[] accessControlPolicies = accessControlManager.getEffectivePolicies(path);
for(AccessControlPolicy accessControlPolicy:accessControlPolicies){
JackrabbitAccessControlList accessControlList = (JackrabbitAccessControlList)accessControlPolicy;
AccessControlEntry[] accessControlEntries = accessControlList.getAccessControlEntries();
for(AccessControlEntry accessControlEntry:accessControlEntries){
//Using CRX Way
String[] privilege = {READ_ACCESS};
//AclPolicy aclPolicy = new AclPolicy(accessControlEntry.getPrincipal().getName(),privilege,false);
//CRXPolicyManager crxPolicyManager = new CRXPolicyManager(jackrabbitSession);
//crxPolicyManager.applyPolicy(path, aclPolicy);

//Jackrabiit way
Privilege[] privileges = new
Privilege[]{accessControlManager.privilegeFromName(Privilege.JCR_READ)};
JackrabbitAccessControlList acl;
try {
acl = (JackrabbitAccessControlList)
accessControlManager.getApplicablePolicies(path).nextAccessControlPolicy();
} catch (NoSuchElementException e) {
// ignore
acl = (JackrabbitAccessControlList) accessControlManager.getPolicies(path)[0];
}
for (AccessControlEntry e : acl.getAccessControlEntries()) {
acl.removeAccessControlEntry(e);
}
acl.addEntry(accessControlEntry.getPrincipal(), privileges, false);
accessControlManager.setPolicy(path, acl);

//This will not work
//accessControlList.removeAccessControlEntry(accessControlEntry);
//accessControlManager.setPolicy(path, accessControlPolicy);

jackrabbitSession.save();
}

}

}

} catch (PathNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RepositoryException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub

}


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.