I want to custom exception message when using REST service especially service related to login and authentication, because after trying extend exception class, I still get “Bad credentials” for whatever exception I intentionally made
Hi,
for login errors, the BadCredetialsException is thrown from the com.haulmont.restapi.auth.CubaUserAuthenticationProvider class:
throw new BadCredentialsException("Bad credentials");
Theoretically, you can override this bean in you project and throw an exception with any message you need. But keep in mind that a behavior of the CubaUserAuthenticationProvider may be changed and you may miss that changes in your overriden class.
Having a controller advice in your project for that case probably won’t work, because the part with getting oauth tokens is managed by the “spring security oauth” framework, and the “BadCredentialsException” thrown by the token endpoint is handled in the org.springframework.security.oauth2.provider.endpoint.TokenEndpoint class (see method annotated with @ExceptionHandler(OAuth2Exception.class)). This method is invoked before your controller advices.
To be more precise, an exception thrown in your listener is first wrapped in the AurthenticationService.login(..) method which is invoked from the CubaUserAuthenticationProvider