Custom User Storage Provider Message

Hello,

I’m developing a custom User Storage Provider and I need to return customized messages to the user based on the validations performed. I tried throwing exceptions, but the only message the user receives is “unknown error”.

Here’s an example of the code to illustrate what I’m trying to do:

public class CustomUserStorageProvider implements UserStorageProvider, UserLookupProvider, CredentialInputValidator, CredentialInputUpdater {
	
	//...

	@Override
	public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) {

		if (!supportsCredentialType(input.getType()) || !(input instanceof UserCredentialModel)) {
			return false;
		}
		
		// ... other validations

		if (this.service.checkExpiredPassword()) {
			// add a custom message to be shown to the user
			isvalid = false;
		}

		return isValid;
	}
}

After analyzing the Keycloak source code, I discovered that by throwing the WebApplicationException exception, the message is displayed correctly

Could you explain more about your resolution? Do you have a sample or a repository where we could have a look at your code? Because I’ve already tried throwing WebApplicationExceptions and AuthenticationFlowExceptions , and all I’m getting is a 500 error. I’m using Keycloak 18.0.0.0.

Thank you very much!

Hi guys! @davidv, you were right, actually. The thing is, the WebApplicationException (javax version for Spring 3) has to receive a Throwable in the constructor; otherwise, it’s going to respond with a 500 error. At least in the version that I’m using for keycloak(18.0.0) and spring boot(3.0). Example:

try {
    // ... code
} catch (WebApplicationException ex) {
    log.error("Authentication Error", ex);
    Throwable throwable = new Throwable(ex.getMessage());
    throw new WebApplicationException(ex.getMessage(), throwable, ex.getResponse());
}

Also, it’s important to know that the same 500 error occurs when the Response parameter is null . Yeap, were just a simple documentation and basics about exceptions! kkkk
Thank you, everyone.

1 Like