Reading and Setting Closed User Groups (CUGs) Programatically in AEM

One Black Chess Piece Separated From Red Pawn Chess Pieces
Photo by Markus Spiske from Pexels

Closed User Groups (CUGs) is the mechanism to restrict access to a resource (page or asset) and children by specifying the authorizable, either a user or a group, that can access it.

AEM provides the functionality to set closed user groups (CUGs) to a resource, normally on the page or asset properties, where you edit the user or group for each resource.

Closed user groups in AEM
Closed User Groups in AEM

There are situations when you want to add CUGs programatically and that’s what I’m going to show how to do.

CUGs API

First get the AccessControlManager object:

Session session = resolver.adaptTo(Session.class);
…
AccessControlManager acMgr = session.getAccessControlManager();

Then get the PrincipaSetPolicy for one resource:

PrincipalSetPolicy policy = null;
AccessControlPolicy[] policies = accessControlManager.getPolicies(path);

for (AccessControlPolicy plc : policies) {
    if (plc instanceof PrincipalSetPolicy) {
        policy = (PrincipalSetPolicy) plc;
    }
}

if (policy == null) {
    AccessControlPolicyIterator it = accessControlManager.getApplicablePolicies(path);
    while (it.hasNext()) {
        AccessControlPolicy plc = it.nextAccessControlPolicy();
        if (plc instanceof PrincipalSetPolicy) {
            policy = (PrincipalSetPolicy) plc;
        }
    }
}

Then add the the group to the policy and save:

policy.addPrincipals(new PrincipalImpl(principal));
acMgr.setPolicy(path, policy);
session.save();

Having set a CUG, If an unauthenticated user tries to access that page, they will see a 404 Not Found page.

What if you require authentication and want to redirect to the login page?

Authentication Requirement

authentication requirement in AEM
Authentication Requirement in AEM

AEM allows you to set that resource and children to require authentication. You can also do it programatically:

Node node = Optional.ofNullable(resourceResolver.getResource(path))
    .map(r -> r.adaptTo(
        Node.class)).orElse(null);
if (node != null && node.canAddMixin(“granite:AuthenticationRequired”)) {
    node.addMixin(“granite:AuthenticationRequired”);
    session.save();
}

What can I use this for?

With the code presented on this post, you can protect your resources programatically. For instance you can create a listener for every time a resource (page) gets created, it applies a CUG.

Any questions, please leave a comment or drop me a DM.

Leave a Reply