Paul
Paul

Reputation: 1441

keycloak: check if old password matches, if so change to another one

Java with maven dependency "keycloak-admin-cli"

I have this code:

keycloakService.findUserByEmailOrUsername( user.getKeycloakUsername() )
.ifPresent( userRepresentation -> {
    //Check for old password
    if ( userRepresentation.getCredentials() != null ) {
        for (CredentialRepresentation c : userRepresentation.getCredentials()) {
            if ( CredentialRepresentation.PASSWORD.equals( c.getType() ) ) {
                if ( userDTO.getOldpassword().equals( c.getValue() ) ) {
                    //Das alte Passwort stimmt mit dem in der Datenbank überein. Wir können updaten
                    //Neues Passwort setzen
                    CredentialRepresentation credential = new CredentialRepresentation();
                    credential.setType( CredentialRepresentation.PASSWORD );
                    credential.setValue( userDTO.getPassword() );
                    credential.setTemporary( false );
                    userRepresentation.setCredentials( Collections.singletonList( credential ) );
                } else {
                    throw new RuntimeException( "Your current password does not match", null );
                }
            }
        }
    }
} );

I checked with the debugger, and I get the correct user. userRepresentation is not null. But the credentials of the user are always null.

Also, if I only want to set a new password for the user, it does not update:

keycloakService.findUserByEmailOrUsername( user.getKeycloakUsername() )
.ifPresent( userRepresentation -> {
    CredentialRepresentation credential = new CredentialRepresentation();
    credential.setType( CredentialRepresentation.PASSWORD );
    credential.setValue( userDTO.getPassword() );
    credential.setTemporary( false );
    userRepresentation.setCredentials( Collections.singletonList( credential ) );
} );

I don't get an error message, keycloak just doesn't update.

Can anyone show me an example how I can check the old password and change it to another one? thanks

Upvotes: 3

Views: 3968

Answers (2)

Elpo Gonzalez
Elpo Gonzalez

Reputation: 31

Try using the UserResource instead of the UserRepresentation.

userResource.get(userId).credentials() instead of userRepresentation.getCredentials() should work, but it does feel more like a workaround.

As of 7/26/2021 getCredentials keeps always returning null.

Upvotes: 3

Sylvain PRAS
Sylvain PRAS

Reputation: 73

For the updating the password use :

userRessource.get(userId).resetPassword(credential);

see this example : https://gist.github.com/thomasdarimont/0c136d0b8d339b997928e9bef225f941

But for checking the actual credential, I didn't manage to check if there's one, as you say userRepresentation.getCredentials() is always null, even after reseting a new password.

Upvotes: 3

Related Questions