0

I have created a custom exception class

public class DataException extends Exception {

private final String errorCode;

private final String errorMessage;

private final HttpStatus httpStatus;

/**
 */
public DataException( String errorCode, String errorMessage, 
HttpStatus httpStatus )
{
    this.errorCode = errorCode;
    this.errorMessage = errorMessage;
    this.httpStatus = httpStatus;
}

And I am sending this exception class to the client side when an exception is thrown. I am also using Spring-Security and JWT for Authentication and Authorization process.

When a user logs in to the application by hitting endpoint /rest/login, and if the credentials are wrong, spring is throwing its exception which is going to the client side.

How to catch that exception thrown by security filter and create our User defined exception and send it to the client side?

My filter method,

 @Override
public Authentication attemptAuthentication( HttpServletRequest request, HttpServletResponse response )
{
    try
    {
        UserModel credentials = new ObjectMapper().readValue(request.getInputStream(), UserModel.class);

        return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(credentials.getEmailId(),
                credentials.getPassword(), new ArrayList<>()));
    }
    catch( IOException | AuthenticationException e )
    {
        LOGGER.error("Exception", "Invalid EmailId/Password");
        throw new BadCredentialsException("Invalid EmailId/password");
    }
}
Naanavanalla
  • 1,412
  • 2
  • 27
  • 52

1 Answers1

0

I have never found throwing Exceptions from authentication / authorization filters very useful. I simply log error , set appropriate response status & message and return null since there is no point in going any further.

AbstractAuthenticationProcessingFilter handles that null appropriately.

I have found this approach to be cleaner than throwing exceptions & then handling those because usually there are only one or two filters.

You might Follow this answer to have a dedicated filter to handle exceptions from other filters.

You can also use Access Denied Handler approach. Instead of redirecting to a page , you simply set appropriate Http status.

Sabir Khan
  • 9,826
  • 7
  • 45
  • 98