简体   繁体   中英

How to create user and group in aem6.2 programmatically with ACL permissions?

Is it possible to create Group and User in AEM6.2 by using Jackrabbit User Manager API with permissions. I have just followed below URL's but the code is throwing some exception :

  1. https://helpx.adobe.com/experience-manager/using/jackrabbit-users.html

  2. https://stackoverflow.com/questions/38259047/how-to-give-permission-all-in-aem-through-programatically

  3. ResourceResolverFactory getServiceResourceResolver throws Exception in AEM 6.1

As getAdministrativeResourceResolver(Map) method is deprecated then how can we use getServiceResourceResolver(Map) method instead.

Sharing my solution which will be helpful for others.

Following is the code using getServiceResourceResolver(Map) method for creating Group first and then User and then add user into group with ACL privileges and permission:

public void createGroupUser(SlingHttpServletRequest request) {
    String userName = request.getParameter("userName");
    String password = request.getParameter("password");
    String groupName = request.getParameter("groupName");

    Session session = null;
    ResourceResolver resourceResolver = null;
    try {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put(ResourceResolverFactory.SUBSERVICE, "datawrite");
        resourceResolver = resourceResolverFactory.getServiceResourceResolver(param);
        session = resourceResolver.adaptTo(Session.class);

        // Create UserManager Object
        final UserManager userManager = AccessControlUtil.getUserManager(session);

        // Create a Group
        Group group = null;
        if (userManager.getAuthorizable(groupName) == null) {
            group = userManager.createGroup(groupName);

            ValueFactory valueFactory = session.getValueFactory();
            Value groupNameValue = valueFactory.createValue(groupName, PropertyType.STRING);
            group.setProperty("./profile/givenName", groupNameValue);
            session.save();

            log.info("---> {} Group successfully created.", group.getID());
        } else {
            log.info("---> Group already exist..");
        }

        // Create a User
        User user = null;
        if (userManager.getAuthorizable(userName) == null) {
            user = userManager.createUser(userName, password);

            ValueFactory valueFactory = session.getValueFactory();
            Value firstNameValue = valueFactory.createValue("Arpit", PropertyType.STRING);
            user.setProperty("./profile/givenName", firstNameValue);

            Value lastNameValue = valueFactory.createValue("Bora", PropertyType.STRING);
            user.setProperty("./profile/familyName", lastNameValue);

            Value emailValue = valueFactory.createValue("arpit.p.bora@gmail.com", PropertyType.STRING);
            user.setProperty("./profile/email", emailValue);
            session.save();

            // Add User to Group
            Group addUserToGroup = (Group) (userManager.getAuthorizable(groupName));
            addUserToGroup.addMember(userManager.getAuthorizable(userName));
            session.save();

            // set Resource-based ACLs
            String nodePath = user.getPath();
            setAclPrivileges(nodePath, session);

            log.info("---> {} User successfully created and added into group.", user.getID());
        } else {
            log.info("---> User already exist..");
        }

    } catch (Exception e) {
        log.info("---> Not able to perform User Management..");
        log.info("---> Exception.." + e.getMessage());
    } finally {
        if (session != null && session.isLive()) {
            session.logout();
        }
        if (resourceResolver != null)
            resourceResolver.close();
    }
}

public static void setAclPrivileges(String path, Session session) {
    try {
        AccessControlManager aMgr = session.getAccessControlManager();

        // create a privilege set
        Privilege[] privileges = new Privilege[] { 
                aMgr.privilegeFromName(Privilege.JCR_VERSION_MANAGEMENT),
                aMgr.privilegeFromName(Privilege.JCR_MODIFY_PROPERTIES),
                aMgr.privilegeFromName(Privilege.JCR_ADD_CHILD_NODES),
                aMgr.privilegeFromName(Privilege.JCR_LOCK_MANAGEMENT),
                aMgr.privilegeFromName(Privilege.JCR_NODE_TYPE_MANAGEMENT),
                aMgr.privilegeFromName(Replicator.REPLICATE_PRIVILEGE) };

        AccessControlList acl;
        try {
            // get first applicable policy (for nodes w/o a policy)
            acl = (AccessControlList) aMgr.getApplicablePolicies(path).nextAccessControlPolicy();
        } catch (NoSuchElementException e) {
            // else node already has a policy, get that one
            acl = (AccessControlList) aMgr.getPolicies(path)[0];
        }
        // remove all existing entries
        for (AccessControlEntry e : acl.getAccessControlEntries()) {
            acl.removeAccessControlEntry(e);
        }
        // add a new one for the special "everyone" principal
        acl.addAccessControlEntry(EveryonePrincipal.getInstance(), privileges);

        // the policy must be re-set
        aMgr.setPolicy(path, acl);

        // and the session must be saved for the changes to be applied
        session.save();
    } catch (Exception e) {
        log.info("---> Not able to perform ACL Privileges..");
        log.info("---> Exception.." + e.getMessage());
    }
}

In code "datawrite" is a service mapping which is mapped with system user in "Apache Sling Service User Mapper Service" which is configurable in the OSGI configuration admin interface.

For more detail about system user check link - How to Create System User in AEM?

I am providing this code direcly from a training of an official Adobe channel, and it is based on AEM 6.1. So I assume this might be the best practice.

    private void modifyPermissions() {
    Session adminSession = null;
    try{
        adminSession = repository.loginService(null, repository.getDefaultWorkspace());

        UserManager userMgr= ((org.apache.jackrabbit.api.JackrabbitSession)adminSession).getUserManager();
        AccessControlManager accessControlManager = adminSession.getAccessControlManager();

        Authorizable denyAccess = userMgr.getAuthorizable("deny-access");

        AccessControlPolicyIterator policyIterator =
                accessControlManager.getApplicablePolicies(CONTENT_GEOMETRIXX_FR);
        AccessControlList acl;
        try{
            acl=(JackrabbitAccessControlList) policyIterator.nextAccessControlPolicy();             
        }catch(NoSuchElementException nse){
            acl=(JackrabbitAccessControlList)  accessControlManager.getPolicies(CONTENT_GEOMETRIXX_FR)[0];

        }

        Privilege[] privileges = {accessControlManager.privilegeFromName(Privilege.JCR_READ)};
        acl.addAccessControlEntry(denyAccess.getPrincipal(), privileges);
        accessControlManager.setPolicy(CONTENT_GEOMETRIXX_FR, acl);
        adminSession.save();
    }catch (RepositoryException e){
        LOGGER.error("**************************Repo Exception", e);
    }finally{
        if (adminSession != null)
            adminSession.logout();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM