2

I am using Keycloak admin API to create a new user. How can I check that the given password indeed fits the realm password policy before creating the user?

I am using the following code:

Response response = usersResource.create(userRepresentation);
String userId = response.getLocation().getPath().replaceAll(".*/([^/]+)$", "$1");
UserResource userResource = usersResource.get(userId);

CredentialRepresentation passwordCred = new CredentialRepresentation();
passwordCred.setTemporary(false);
passwordCred.setType(CredentialRepresentation.PASSWORD);
passwordCred.setValue(somePassword);
userResource.resetPassword(passwordCred);

The problem with the above code is that the method "resetPassword" fails if the given password does not fit the password policy, but at this point the user has already been created in keycloak, and I have to delete it, since I have no way to "rollback".

The other option is to check is the password is OK before creating the user. But how can I do it?

Guy Hudara
  • 247
  • 4
  • 13

2 Answers2

3

You will get validation failure message as JSON Object some thing like this

{"error":"invalidPasswordMinLengthMessage","error_description":"Invalid password: minimum length 8."} 

I used following code to read the validation failure message from the ClientErrorException

public void resetUserInvalidPassword() {
        String userId = createUser("user1", "user1@localhost");

        try {
            CredentialRepresentation cred = new CredentialRepresentation();
            cred.setType(CredentialRepresentation.PASSWORD);
            cred.setValue(" ");
            cred.setTemporary(false);
            realm.users().get(userId).resetPassword(cred);
        } catch (ClientErrorException e) {

            Response response = e.getResponse();
            System.out.println(getErrorMessage(response));              
            response.close();
        }
    }
  private String getErrorMessage(Response response) {
        Object entity = response.getEntity();
        String errorMessage = "(none)";
        if (entity instanceof ErrorRepresentation)
            errorMessage = ((ErrorRepresentation) entity).getErrorMessage();
        else if (entity instanceof InputStream)
            errorMessage = new BufferedReader(new InputStreamReader((InputStream)entity)).lines().collect(Collectors.joining("\n"));
        else if (entity != null)
            errorMessage = entity.toString();
        return errorMessage;
    }
ravthiru
  • 8,878
  • 2
  • 43
  • 52
0

UserResource has the getUsers() method to find a user by username and check its attributes. If the resetPassword failed, you could find the user, apply checks if needed, and resetPassword again.

VSh
  • 438
  • 4
  • 13