March 30, 2021
Estimated Post Reading Time ~

Create a group and user using the Jackrabbit API

I was looking for a concise way to work with users and groups in Sling. Because "everything is content," it's easy to use Sling's REST API to create a user like any other node, but things get a little dicey when you want a bit more flexibility. Enter the Jackrabbit API...

private void createAuthorGroupAndUser(ResourceResolver resolver) {

  try {

    Session session = resolver.adaptTo(Session.class);

    if (session != null && session instanceof JackrabbitSession) {

      // Get our User Manager

      UserManager userManager = ((JackrabbitSession) session).getUserManager();

      ValueFactory valueFactory = session.getValueFactory();

      // Create the Authors group if it doesn't exist already.

      Authorizable authors = userManager.getAuthorizable("authors");

      if (authors == null) {

        authors = userManager.createGroup("authors");

        authors.setProperty("displayName", valueFactory.createValue("Authors"));

      }

      // Create the default author if it doesn't already exist.

      Authorizable author = userManager.getAuthorizable("author");

      if(author == null) {

        author = userManager.createUser("author", "letMeIn");

        author.setProperty("displayName", valueFactory.createValue("Default Author"));

      }

      // Add author member to authors group

      ((Group) authors).addMember(author);

      // Save our session

      session.save();

    }

  } catch (RepositoryException e) {

      LOGGER.error("Could not get the session", e);

  }

}

More Reading

Jackrabbit Wiki - User Management
Jackrabbit API - org.apache.jackrabbit.api.security.user


By aem4beginner

No comments:

Post a Comment

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