Expand my Community achievements bar.

create a user with user manager api from java application

Avatar

Level 1

I want to create a user with user manage api from java application.

Below is the code that i am using.

 

Repository myRepo = JcrUtils.getRepository(path);

javax.jcr.Session repoSession = myRepo.login(new SimpleCredentials("admin", "admin".toCharArray()));

org.apache.jackrabbit.api.JackrabbitSession jRabbitSession = (JackrabbitSession) repoSession;

userManager = jRabbitSession.getUserManager();

userManager.createUser(username, password);

 

But it gives below error

 

"org.apache.jackrabbit.jcr2spi.SessionImpl cannot be cast to class org.apache.jackrabbit.api.JackrabbitSession

(org.apache.jackrabbit.jcr2spi.SessionImpl and org.apache.jackrabbit.api.JackrabbitSession are in unnamed module of loader 'app')" 


Topics

Topics help categorize Community content and increase your ability to discover relevant content.

7 Replies

Avatar

Community Advisor

Hi @ParkashSi ,

You can create a user with the help of UserManager as shown below.

Note : If you face any issue to get Resource Resolver, then please check that you have correct system user, permission and user mapper service configured.

//Fetching all User Details from Servlet Parameter
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..");
}

Regards

Shiv Prakash

Avatar

Level 1

Hi @Shiv_Prakash_Patel 
Thanks for sharing the information. But I need to create a user with a Java application I am not supposed to use resource resolver.
Is there a way to solve my exception with another approach? 

Avatar

Community Advisor

Hi @ParkashSi , Yes you can achieve this using curl command. You can update this command with your respective user Id, password and AEM instance urls.

 

curl -u admin:admin -FcreateUser= -FauthorizableId=ankur-Frep:password=ankur http://localhost:4502/libs/granite/security/post/authorizables

 

You have to execute this command with your java code.

If you have standalone java project, you can refer this article - cURL in Java

If you have any maven project you can refer this article - cURL in AEM Project

Regards,

Shiv Prakash

Avatar

Level 1

Hi @Shiv_Prakash_Patel 

Thanks for sharing the information

But I don't want to change my way. I want to create a user with Jackrabbit with existing code.

Avatar

Community Advisor

Hi @ParkashSi,

Found an old thread related to this query - JackRabbitSession cannot be cast to Session

It says "JCR over RMI (Remote Method Invocation) is not full compliant with JSR-283 spec"

The JSP that you store in sling by default are given native access to the JR repo.


The author made it work by publishing the JackRabbit Ressource as a JNDI (Java Naming and Directory Interface) name and use the connection method shown below -

Rohan_Garg_0-1715349820831.png

From a .jsp running in the same JVM as JackRabbit it is now possible to obtain the JackrabbitSession by casting from a Session.

 

Other Reference Link - JCR-RMI currently doesn't support the user management extensions in Jackrabbit

Hope this helps!

 

Best Regards,
Rohan Garg

 

Avatar

Level 7

I recently came across this issue:
It’s happening because jcr2spi.SessionImpl cannot be cast to org.apache.jackrabbit.api.JackrabbitSession.

 

you should use the org.apache.sling.api.resource.ResourceResolver to get the org.apache.jackrabbit.api.security.user.UserManager.

import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.jackrabbit.api.security.user.UserManager;

@ResourceResolverFactory
private ResourceResolverFactory resolverFactory;

public void createUser(String username, String password) {
    Map<String, Object> param = new HashMap<String, Object>();
    param.put(ResourceResolverFactory.SUBSERVICE, "writeService");

    try (ResourceResolver resolver = resolverFactory.getServiceResourceResolver(param)) {
        UserManager userManager = resolver.adaptTo(UserManager.class);
        if (userManager != null) {
            userManager.createUser(username, password);
        }
    } catch (LoginException e) {
        // handle exception
    }
}

Avatar

Administrator

@ParkashSi Did you find the suggestions from users helpful? Please let us know if more information is required. Otherwise, please mark the answer as correct for posterity. If you have found out solution yourself, please share it with the community.



Kautuk Sahni