5
votes

I have a Jersey app configured with Spring Security handling authentication. The jersey-spring package is providing the SpringServlet class that is registered in my web.xml as a servlet.

Authentication and all works as expected. What I'm wondering is how to have the AuthenticationExceptions (and other filter exceptions) sent through the Jersey servlet, so I can use our ExceptionMapper to process them.

Originally the SpringServlet was configured as a filter, but after doing some reading I came to understand that a servlet should be able to handle the Exceptions thrown in the filters (maybe that's an incorrect understanding). I don't notice any change in behavior after changing it to a servlet, and if I trace through the Spring Security code I can see where the HttpServletResponse is being written.

My question: Is it possible to have the Jersey servlet process exceptions thrown by the Spring Security filter?

1
Hello Nick, is it possible for you to publish a SSCCE demonstrating your own setup ?Yves Martin
Yes, I will add a small sample as soon as I get a chance.Nick Spacek

1 Answers

0
votes

How you do it depends on whether you are invoking Jersey from Spring Security, or Spring Security from Jersey.

If you are invoking Spring Security from inside the Jersey container, then you shouldn't have to do anything other than defining an exception mapper for the appropriate exception.

If you are invoking Jersey only once the client passes the Spring Security filters, then any exceptions thrown while the client request is passing through those filters will not be caught by Jersey (because the request has not yet entered the Jersey container). One way to "get" the exception into the Jersey container is to:

  1. catch the AuthenticationException in a custom authentication filter and invoke the AuthenticationFailureHandler.onAuthenticationFailure() method (passing in the exception), and make sure to break the filter chain by not invoking FilterChain.doFilter()
  2. configure your AuthenticationFailureHandler to call a Jersey resource of your design that will retrieve (and then re-throw) any exceptions generated by Spring with HttpServletRequest.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION)

There may be other ways to "get" the exception into Jersey-land, but this is one way that's worked for me in the past.