How to create a new user in Java code?

I am trying to create a user from within our Java backend.
This is what I came up with after digging through code:

UserDocument userDocument = userDocumentFactory.create(new DefaultEMailUserIdentifier(email), lastName, firstName, email);
userDocument.setPassword(password);
Role guestRole = roleRepository.findByIdent(new DefaultRoleIdentifier("guest"));
userDocument.addRole(guestRole);
UserDocument newDocument = userDocumentRepository.save(userDocument);

That seems to work (gives no error), but it’s not possible to log in with the new user. (Log in results in an “Authentication failed” error.)

The API you are using is too low level. It does not solve hashing of passwords or other properties of the user. Please use DomainUserPersister or batch operation ADD_DOCUMENT where you need to have a user document that is valid. I would suggest using this user as a template

{
  "id": "-1",
  "SystemProperties": {
    "login": "admin",
    "firstname": "ad",
    "lastname": "min",
    "email": "test.admin@<INTERNAL_LINK>",
    "password": null,
    "passwordRepeat": null,
    "roles": [
      {
        "roleIdent": "systemAdmin"
      },
      {
        "roleIdent": "admin"
      }
    ],
    "salt": null,
    "lastLoginAt": "2020-02-21T13:02:11.701+01:00",
    "failedLoginAt": "",
    "failedLoginAttempts": 0,
    "passwordChangedAt": "2222-01-01T00:00Z",
    "restorePasswordToken": "",
    "passwordTokenCreatedAt": "",
    "createdAt": "2020-02-21T13:01:43.111+01:00",
    "active": true,
    "existing": true,
    "documentId": null,
    "enforcePasswordChange": false
  },
  "CustomProperties": {
    "clientId": "CLIENT-ID"
  }
}

Thanks for the answer. I got it working.