Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keycloak Admin API - How to check if password fits the password policy

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?

like image 933
Guy Hudara Avatar asked Oct 15 '25 18:10

Guy Hudara


1 Answers

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;
    }
like image 50
ravthiru Avatar answered Oct 17 '25 08:10

ravthiru