Override Exception message for authentication when using REST

Hi All,

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

How to do it? what class that I should override ?

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.

1 Like

For more descriptive explanation at my question above , I adding snippet code that I’ve been write ,please check picture below
Screenshot%202019-02-26_08-30-03-524

So when I throw RestApiAccessDeniedException , it will catched and rethrow again in another class ? in this case

com.haulmont.restapi.auth.CubaUserAuthenticationProvider ?

Yes, you are right. It’s very easy to check, just put the breakpoint in the CubaUserAuthenticationProvider

1 Like

To be more precise, an exception thrown in your listener is first wrapped in the AurthenticationService.login(..) method which is invoked from the CubaUserAuthenticationProvider

1 Like