Search code examples
nexusnexus3

Nexus 3 | How to create (external) users using Nexus 3 APIs?


I'm trying to create external user on Nexus 3 using nexus 3 APIs. Following are the details: Posting Groovy Script using: http://localhost:8081/nexus3/service/rest/v1/script

{
    "name": "d8b3baeb-628a-43cc-9a9c-9a156f399e2",
    "type": "groovy",
    "content": "security.addUser('q018246a', '', '', '', true, 'd8b3baeb-628a-43cc-9a9c-9a156f399ae2', ['abc_test_role Developer Role']);"
}

Running Script using: http://localhost:8081/nexus3/service/rest/v1/script/d8b3baeb-628a-43cc-9a9c-9a156f399e2/run

Response:

{
    "name": "d8b3baeb-628a-43cc-9a9c-9a156f399e2",
    "result": "User{userId='q018246a', firstName='', lastName='', source='default'}"
}

Hitting though Postman, all working fine and users getting created. But through Application server it is giving Bad request.

Awkward behavior is, it's letting me create user using postman post script with blank first_name, last_name, email, password, but all these parameters are required on UI.

Another thing, It's showing source as default but how to I ensure source as LDAP?


Solution

  • I assume you're trying to map an LDAP user? If so, this will work:

    import org.sonatype.nexus.security.role.RoleIdentifier;
    import org.sonatype.nexus.security.user.User;
    
    String userId = 'someuser';
    String newRoleId = 'nx-admin'
    
    User user = security.securitySystem.getUser(userId, 'LDAP')
    
    if(user != null) {
        RoleIdentifier newRole = new RoleIdentifier('default', newRoleId);
        user.addRole(newRole)
        security.securitySystem.setUsersRoles(user.getUserId(), 'LDAP', user.getRoles());
    } else {
        log.warn("No user with ID of $userId found.")
    }