Expand my Community achievements bar.

Creeating users using serviceresourceresolver in AEM 6.5

Avatar

Level 3

Hi,

 

Can we write into /home/users using ServiceResoruceResolver in AEM 6.5? My understanding is we have to use Adminstrative session to write into /home/users but wanted to confirm.

 

Regards,

Kishore

1 Reply

Avatar

Level 7

Hi @kishored6899358 

String userID = request.getParameter("userID");
String userFirstName = request.getParameter("userFirstName");
String userLastName = request.getParameter("userLastName");
String userEmail = request.getParameter("userEmail");
String password = request.getParameter("password");

//Getting ResourceResolver and Session using System Users
Map<String, Object> param = new HashMap<>();
param.put(ResourceResolverFactory.SUBSERVICE, SYSTEM_USER);
resourceResolver = resourceResolverFactory.getServiceResourceResolver(param);
Session session = resourceResolver.adaptTo(Session.class);
assert session != null;

//Getting UserManager from ResourceResolver
UserManager userManager = resourceResolver.adaptTo(UserManager.class);
assert userManager != null;

//Creation of a new user with userID
User createdUser = null;
if (userManager.getAuthorizable(userID) == null) {
    createdUser = userManager.createUser(userID, password);

    //Setting the createdUser Profile Property
    ValueFactory valueFactory = session.getValueFactory();
    Value firstNameValue = valueFactory.createValue(userFirstName, PropertyType.STRING);
    createdUser.setProperty("./profile/givenName", firstNameValue);

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

    Value emailValue = valueFactory.createValue(userEmail, PropertyType.STRING);
    createdUser.setProperty("./profile/email", emailValue);

    session.save();
    logger.info("User successfully created with ID : {}", createdUser.getID());
} else {
        logger.info("User already exist..");
}

 

Refrences: 

https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/programmatic-user-creation... 

https://unlocklearning.in/aem-user-group-creation-and-permission-programmatically/